SettingsCardBodies.kt

57.2 KB · raw

1package com.peachpasswords.ui.settings23import android.content.Intent4import android.net.Uri5import androidx.compose.animation.AnimatedVisibility6import androidx.compose.animation.core.animateDpAsState7import androidx.compose.foundation.background8import androidx.compose.foundation.border9import androidx.compose.foundation.clickable10import androidx.compose.foundation.layout.Arrangement11import androidx.compose.foundation.layout.Box12import androidx.compose.foundation.layout.Column13import androidx.compose.foundation.layout.FlowRow14import androidx.compose.foundation.layout.ExperimentalLayoutApi15import androidx.compose.foundation.layout.Row16import androidx.compose.foundation.layout.RowScope17import androidx.compose.foundation.layout.Spacer18import androidx.compose.foundation.layout.fillMaxWidth19import androidx.compose.foundation.layout.height20import androidx.compose.foundation.layout.padding21import androidx.compose.foundation.layout.size22import androidx.compose.foundation.layout.width23import androidx.compose.foundation.shape.CircleShape24import androidx.compose.foundation.shape.RoundedCornerShape25import androidx.compose.foundation.text.BasicTextField26import androidx.compose.runtime.Composable27import androidx.compose.material3.CircularProgressIndicator28import androidx.compose.runtime.DisposableEffect29import androidx.compose.runtime.collectAsState30import androidx.compose.runtime.getValue31import com.peachpasswords.feedback.FeedbackState32import com.peachpasswords.shared.PeachClipboard33import com.peachpasswords.sync.SyncStatus34import com.peachpasswords.ui.theme.LocalPeachAccent35import com.peachpasswords.vault.DuressAction36import com.peachpasswords.ui.theme.peachColors37import androidx.compose.runtime.mutableStateOf38import androidx.compose.runtime.remember39import androidx.compose.runtime.rememberCoroutineScope40import androidx.compose.runtime.setValue41import androidx.compose.ui.Alignment42import androidx.compose.ui.Modifier43import androidx.compose.ui.draw.clip44import androidx.compose.ui.graphics.Color45import androidx.compose.ui.graphics.SolidColor46import androidx.compose.ui.platform.LocalContext47import androidx.compose.ui.text.TextStyle48import androidx.compose.ui.text.font.FontStyle49import androidx.compose.ui.text.input.PasswordVisualTransformation50import androidx.compose.ui.unit.Dp51import androidx.compose.ui.unit.dp52import androidx.compose.ui.unit.em53import androidx.compose.ui.unit.sp54import androidx.compose.material3.Text55import com.peachpasswords.BuildConfig56import com.peachpasswords.autofill.AutofillEnablement57import com.peachpasswords.ui.PeachNav58import com.peachpasswords.ui.components.PeachEmptyOrEndState59import com.peachpasswords.ui.components.PeachField60import com.peachpasswords.ui.sync.SyncViewModel61import com.peachpasswords.ui.theme.ACCENT_COLORS62import com.peachpasswords.ui.theme.PeachSpacing63import com.peachpasswords.ui.theme.PeachType64import com.peachpasswords.ui.updates.UpdatePhase65import com.peachpasswords.ui.updates.UpdateViewModel66import androidx.hilt.navigation.compose.hiltViewModel67import com.peachpasswords.vault.VaultSettings68import com.peachpasswords.vault.VaultSnapshot69import kotlinx.coroutines.launch70import kotlinx.coroutines.delay71import java.text.SimpleDateFormat72import java.util.Date73import java.util.Locale7475private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"7677/**78 * Body content for the active stack card. Everything is tinted with the card's79 * own foreground [fg] (the browser's `currentColor` convention), so each card's80 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,81 * canary, license activation) render their browser visual but defer the action82 * to a later phase — noted inline where that's the case.83 */84@Composable85fun CardBody(86    id: CardId,87    fg: Color,88    vm: SettingsViewModel,89    settings: VaultSettings,90    entriesCount: Int,91    onNavigate: (PeachNav) -> Unit,92) {93    when (id) {94        CardId.Appearance -> AppearanceBody(fg, vm, settings)95        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)96        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)97        CardId.Sync -> SyncBody(fg, onNavigate)98        CardId.Shortcuts -> ShortcutsBody(fg)99        CardId.Pro -> ProBody(fg, vm)100        CardId.Feedback -> {101            // The closest thing Peach has to an About surface, and where the brief102            // put the update entry point: version first, then the feedback form.103            AboutUpdatesBody(fg, onNavigate)104            FeedbackBody(fg, vm)105        }106    }107}108109/* ────────────────────────────  about / updates  ─────────────────────────── */110111@Composable112private fun AboutUpdatesBody(fg: Color, onNavigate: (PeachNav) -> Unit) {113    val vm: UpdateViewModel = hiltViewModel()114    val available by vm.available.collectAsState()115    val state by vm.state.collectAsState()116117    SubLabel("THIS BUILD", fg, top = 0.dp)118    RowLine(fg) {119        Name("Version", fg)120        ValueText(BuildConfig.VERSION_NAME, fg)121    }122    RowLine(fg) {123        Column(Modifier.weight(1f)) {124            Text("Updates", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)125            Text(126                when {127                    available != null -> "v${available?.version} is available"128                    state.phase == UpdatePhase.Checking -> "Checking…"129                    state.phase == UpdatePhase.UpToDate -> "You're on the latest version"130                    state.phase == UpdatePhase.Failed -> "Couldn't reach the update server"131                    else -> "Peach checks once a day and tells you when there's a new version."132                },133                color = fg.copy(alpha = 0.7f),134                fontFamily = PeachType.Body,135                fontSize = 11.sp,136                lineHeight = 16.sp,137                modifier = Modifier.padding(top = 2.dp),138            )139        }140        if (available != null) {141            SubtleButton("update", fg) { onNavigate(PeachNav.Update) }142        } else {143            SubtleButton(if (state.phase == UpdatePhase.Checking) "checking" else "check now", fg) {144                vm.check()145            }146        }147    }148}149150/* ─────────────────────────  shared row vocabulary  ───────────────────────── */151152@Composable153private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {154    Text(155        text,156        modifier = Modifier.padding(top = top, bottom = 4.dp),157        color = fg.copy(alpha = 0.58f),158        fontFamily = PeachType.Mono,159        fontSize = 8.sp,160        letterSpacing = 0.22.em,161    )162}163164@Composable165private fun RowLine(166    fg: Color,167    modifier: Modifier = Modifier,168    verticalPadding: Dp = 9.dp,169    content: @Composable RowScope.() -> Unit,170) {171    Row(172        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),173        verticalAlignment = Alignment.CenterVertically,174        horizontalArrangement = Arrangement.SpaceBetween,175        content = content,176    )177    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))178}179180@Composable181private fun RowScope.Name(text: String, fg: Color) {182    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))183}184185@Composable186private fun ValueText(text: String, fg: Color) {187    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp)188}189190@Composable191private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {192    Box(193        Modifier.clip(RoundedCornerShape(8.dp))194            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))195            .background(fg.copy(alpha = 0.08f))196            .clickable(onClick = onClick)197            .padding(horizontal = 12.dp, vertical = 6.dp),198    ) {199        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)200    }201}202203@Composable204private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {205    val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")206    Box(207        Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))208            .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))209            .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))210            .clickable { onToggle(!on) },211    ) {212        Box(213            Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)214                .padding(start = knob - 2.dp)215                .size(14.dp).clip(CircleShape)216                .background(if (on) fg else fg.copy(alpha = 0.58f)),217        )218    }219}220221@Composable222private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {223    Box(224        Modifier.clip(RoundedCornerShape(999.dp))225            .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))226            .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)227            .clickable(onClick = onClick)228            .padding(horizontal = 12.dp, vertical = 5.dp),229    ) {230        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)231    }232}233234@Composable235private fun ProBadge(fg: Color) {236    Box(237        Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))238            .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),239    ) {240        Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)241    }242}243244@Composable245private fun Hint(text: String, fg: Color) {246    Text(247        text,248        modifier = Modifier.padding(top = 6.dp),249        color = fg.copy(alpha = 0.6f),250        fontFamily = PeachType.Display,251        fontStyle = FontStyle.Italic,252        fontSize = 11.5.sp,253        lineHeight = 16.sp,254    )255}256257/* ──────────────────────────────  Appearance  ─────────────────────────────── */258259@OptIn(ExperimentalLayoutApi::class)260@Composable261private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {262    SubLabel("THEME", fg, top = 0.dp)263    RowLine(fg) {264        Name("Theme", fg)265        val (label, next) = when (s.theme) {266            "dark" -> "Switch to light" to "light"267            else -> "Switch to dark" to "dark"268        }269        SubtleButton(label, fg) { vm.setTheme(next) }270    }271    SubLabel("ACCENT", fg)272    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {273        ACCENT_COLORS.forEach { (name, color) ->274            Box(275                Modifier.size(22.dp).clip(CircleShape).background(color)276                    .border(277                        if (s.accentColor == name) 2.dp else 1.dp,278                        if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),279                        CircleShape,280                    )281                    .clickable { vm.setAccent(name) },282            )283        }284    }285    SubLabel("TEXT SIZE", fg)286    RowLine(fg) {287        Name("Size", fg)288        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {289            Pill("Default", s.textSize == "medium", fg) { vm.setTextSize("medium") }290            Pill("Large", s.textSize == "large", fg) { vm.setTextSize("large") }291        }292    }293    SubLabel("MOTION", fg)294    RowLine(fg) {295        Name("Reduce motion", fg)296        SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }297    }298}299300/* ──────────────────────────────  Protection  ─────────────────────────────── */301302@Composable303private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings, onNavigate: (PeachNav) -> Unit) {304    val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")305    val current = s.autoLockMinutes ?: 0306307    SubLabel("LOCKING", fg, top = 0.dp)308    RowLine(fg) {309        Name("Auto-lock after", fg)310        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)311        SubtleButton(lockOptions[idx].second, fg) {312            val next = lockOptions[(idx + 1) % lockOptions.size].first313            vm.setAutoLockMinutes(if (next == 0) 0 else next)314        }315    }316    SubLabel("BIOMETRICS", fg)317    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity318    RowLine(fg) {319        Name("Unlock with biometrics", fg)320        Toggle(s.biometricsEnabled, fg) { on ->321            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()322        }323    }324    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)325    if (bioError != null) {326        Text(327            bioError,328            color = com.peachpasswords.ui.theme.peachColors.Breach,329            fontFamily = PeachType.Mono, fontSize = 10.sp,330            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),331        )332    }333    SubLabel("AUTOFILL", fg)334    run {335        // Read live rather than cached: the user leaves for system settings and336        // comes back, so a remembered value would show the old answer.337        val ctx = LocalContext.current338        val enabled = AutofillEnablement.isEnabled(ctx)339        RowLine(fg) {340            Column(Modifier.weight(1f)) {341                Text("Fill passwords in other apps", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)342                Text(343                    if (enabled) {344                        "Peach is your autofill service."345                    } else {346                        "Android decides which app fills passwords. Turn Peach on in system settings."347                    },348                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,349                    modifier = Modifier.padding(top = 2.dp),350                )351            }352            if (!enabled) {353                SubtleButton("enable", fg) {354                    // Straight to the autofill picker with Peach preselected;355                    // some OEM builds ship no handler, so fall back rather than356                    // dead-ending on a button that does nothing.357                    runCatching { ctx.startActivity(AutofillEnablement.requestIntent(ctx)) }358                        .onFailure { runCatching { ctx.startActivity(AutofillEnablement.fallbackIntent()) } }359                }360            } else {361                ValueText("on", fg)362            }363        }364    }365366    SubLabel("PASSKEYS", fg)367    RowLine(fg) {368        Column(Modifier.weight(1f)) {369            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)370            Text(371                "Peach can handle passkey sign-in and creation through Android Credential Manager.",372                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,373                modifier = Modifier.padding(top = 2.dp),374            )375        }376        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }377    }378    RowLine(fg) {379        Name("Status", fg)380        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)381    }382    SubLabel("RECOVERY", fg)383    RowLine(fg) {384        Column(Modifier.weight(1f)) {385            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)386            Text(387                "Keep the paper copy current before rotating sync identity or replacing devices.",388                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,389                modifier = Modifier.padding(top = 2.dp),390            )391        }392        SubtleButton("view", fg) { onNavigate(PeachNav.RecoveryView) }393    }394    SubLabel("BREACH PROTECTION", fg)395    val checkingBreaches by vm.checkingBreaches.collectAsState()396    val breachResult by vm.breachResult.collectAsState()397    RowLine(fg) {398        Name("Breach monitoring", fg)399        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }400    }401    RowLine(fg) {402        Name("Check all passwords", fg)403        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }404    }405    breachResult?.let { result ->406        RowLine(fg) {407            Name("Last check", fg)408            ValueText(result, fg)409        }410    }411412    SubLabel("MASTER PASSWORD", fg)413    ChangePasswordRow(fg, vm)414415    SubLabel("DURESS PASSWORD", fg)416    val duressIsPro by vm.isPro.collectAsState()417    if (!duressIsPro) {418        RowLine(fg) {419            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {420                Name("Duress password", fg); ProBadge(fg)421            }422            ValueText("off", fg)423        }424        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)425    } else {426        DuressSection(fg, vm)427    }428}429430@Composable431private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {432    var open by remember { mutableStateOf(false) }433    var current by remember { mutableStateOf("") }434    var next by remember { mutableStateOf("") }435    var confirm by remember { mutableStateOf("") }436    var error by remember { mutableStateOf<String?>(null) }437    var done by remember { mutableStateOf(false) }438    val scope = rememberCoroutineScope()439440    RowLine(fg) {441        Name("Master password", fg)442        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }443    }444    AnimatedVisibility(open) {445        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {446            PwField("current password", current, fg) { current = it }447            PwField("new password (min 12 chars)", next, fg) { next = it }448            PwField("confirm new password", confirm, fg) { confirm = it }449            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }450            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)451            SubtleButton("save new password", fg) {452                error = when {453                    current.isBlank() -> "enter your current password"454                    next.length < 12 -> "new password must be at least 12 characters"455                    next != confirm -> "new passwords do not match"456                    next == current -> "new password must differ from current"457                    else -> null458                }459                if (error == null) scope.launch {460                    if (vm.changePassword(current, next)) {461                        current = ""; next = ""; confirm = ""; open = false; done = true462                    } else error = "incorrect current password"463                }464            }465        }466    }467}468469@Composable470private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {471    PeachField(472        label = placeholder,473        value = value,474        onValueChange = onChange,475        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,476        visualTransformation = PasswordVisualTransformation(),477    )478}479480/* ────────────────────────────────  Vault  ───────────────────────────────── */481482@Composable483private fun VaultBody(484    fg: Color,485    vm: SettingsViewModel,486    s: VaultSettings,487    entriesCount: Int,488    onNavigate: (PeachNav) -> Unit,489) {490    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")491    val current = s.trashRetentionDays ?: 0492    val isPro by vm.isPro.collectAsState()493    val dedupCount by vm.dedupCount.collectAsState()494    val dedupRunning by vm.dedupRunning.collectAsState()495    val dedupDone by vm.dedupDone.collectAsState()496    val history by vm.vaultHistory.collectAsState()497    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()498499    SubLabel("ENTRIES", fg, top = 0.dp)500    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }501    RowLine(fg) {502        Name("Duplicates", fg)503        val done = dedupDone504        if (done != null) {505            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)506        } else {507            val count = dedupCount508            val label = when {509                dedupRunning -> "scanning..."510                count == null -> "scan"511                count == 0 -> "none found"512                else -> "$count found"513            }514            SubtleButton(label, fg) {515                if (count == null || count == 0) vm.scanDuplicates()516            }517        }518    }519    if ((dedupCount ?: 0) > 0 && dedupDone == null) {520        Column(521            Modifier.fillMaxWidth()522                .padding(top = 2.dp, bottom = 8.dp)523                .clip(RoundedCornerShape(8.dp))524                .background(fg.copy(alpha = 0.08f))525                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))526                .padding(10.dp),527            verticalArrangement = Arrangement.spacedBy(8.dp),528        ) {529            val count = dedupCount ?: 0530            Text(531                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",532                color = fg.copy(alpha = 0.82f),533                fontFamily = PeachType.Body,534                fontSize = 11.sp,535                lineHeight = 16.sp,536            )537            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {538                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }539                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }540            }541        }542    }543544    SubLabel("MAINTENANCE", fg)545    RowLine(fg) {546        Name("Trash auto-delete", fg)547        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)548        SubtleButton(trashOptions[idx].second, fg) {549            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)550        }551    }552    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }553    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }554555    SubLabel("DATA", fg)556    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }557    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }558    RowLine(fg) {559        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }560        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }561    }562    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }563564    var historyShowAll by remember { mutableStateOf(false) }565    SubLabel("VAULT HISTORY", fg)566    if (history.isEmpty()) {567        Text(568            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",569            color = fg.copy(alpha = 0.68f),570            fontFamily = PeachType.Body,571            fontSize = 11.sp,572            lineHeight = 16.sp,573            modifier = Modifier.padding(bottom = 6.dp),574        )575    } else {576        Text(577            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",578            color = fg.copy(alpha = 0.68f),579            fontFamily = PeachType.Body,580            fontSize = 11.sp,581            lineHeight = 16.sp,582            modifier = Modifier.padding(bottom = 4.dp),583        )584        history.take(if (historyShowAll) history.size else 3).forEach { snap ->585            RowLine(fg) {586                Column(Modifier.weight(1f)) {587                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)588                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)589                }590                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {591                    vm.restoreVaultSnapshot(snap.id)592                }593            }594        }595        if (history.size > 3) {596            RowLine(fg) {597                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)598                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }599            }600        }601        Text(602            "${history.size} of 5 snapshots",603            color = fg.copy(alpha = 0.58f),604            fontFamily = PeachType.Mono,605            fontSize = 10.sp,606            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),607        )608    }609610    var advancedOpen by remember { mutableStateOf(false) }611    SubLabel("ADVANCED", fg)612    RowLine(fg) {613        Name("Advanced", fg)614        SubtleButton(if (advancedOpen) "hide" else "show", fg) { advancedOpen = !advancedOpen }615    }616    if (advancedOpen) {617        RowLine(fg) {618            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)619            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }620        }621        RowLine(fg) {622            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)623            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }624        }625    }626}627628private fun snapshotSubLabel(snapshot: VaultSnapshot): String {629    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }630    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")631}632633private fun snapshotReasonLabel(reason: String): String = when (reason) {634    "local_save" -> "saved"635    "sync_received" -> "synced"636    "import" -> "imported"637    "restore" -> "restored"638    else -> reason639}640641private fun snapshotTimeLabel(savedAt: Long): String {642    val diff = System.currentTimeMillis() - savedAt643    if (diff < 60_000) return "Just now"644    if (diff < 3_600_000) return "${diff / 60_000}m ago"645    val date = Date(savedAt)646    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())647    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)648    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)649    if (today == thenDay) return "Today $time"650    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))651    if (yesterday == thenDay) return "Yesterday $time"652    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)653}654655/* ────────────────────────────────  Sync  ────────────────────────────────── */656657@Composable658private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {659    val syncVm: SyncViewModel = hiltViewModel()660    val pairedDevices by syncVm.pairedDevices.collectAsState()661    val pendingVouched by syncVm.pendingVouched.collectAsState()662    val syncStatus by syncVm.status.collectAsState()663    val relayEnabled by syncVm.relayEnabled.collectAsState()664    val configuredRelayUrl by syncVm.relayUrl.collectAsState()665    val lanOnly by syncVm.lanOnly.collectAsState()666    val scope = rememberCoroutineScope()667    var confirmUnpair by remember { mutableStateOf<String?>(null) }668    var rotateConfirmOpen by remember { mutableStateOf(false) }669    var rotating by remember { mutableStateOf(false) }670    var rotateError by remember { mutableStateOf<String?>(null) }671    var relayUrlDraft by remember(configuredRelayUrl) { mutableStateOf(configuredRelayUrl) }672    var relayUrlStatus by remember { mutableStateOf<String?>(null) }673674    SubLabel("PAIRING", fg, top = 0.dp)675    RowLine(fg) {676        Column(Modifier.weight(1f)) {677            Row(verticalAlignment = Alignment.CenterVertically) {678                Text("Peach Sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp); ProBadge(fg)679            }680            Text(681                "Pair devices with a code over your local network and keep encrypted vault blobs in step without a central account.",682                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,683                modifier = Modifier.padding(top = 2.dp),684            )685        }686    }687    // The whole row is the tap target — no separate "open" button (browser688    // sync-hub parity: every settings row is tappable, the chevron signals it).689    RowLine(fg, Modifier.clickable { onNavigate(PeachNav.CodePair) }) {690        Name("Sync hub", fg)691        Text("›", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 15.sp)692    }693    RowLine(fg) {694        Column(Modifier.weight(1f)) {695            Text("Pair new device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)696            Text(697                "This phone shows a code; type it into Peach in your browser.",698                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,699                modifier = Modifier.padding(top = 2.dp),700            )701        }702        SubtleButton("pair", fg) { onNavigate(PeachNav.CodePair) }703    }704705    SubLabel("PAIRED DEVICES", fg)706    if (pairedDevices.isEmpty()) {707        PeachEmptyOrEndState(708            message = "No paired devices yet.",709            detail = "Pair a nearby phone, tablet, or browser when you're ready to sync.",710            modifier = Modifier.padding(top = PeachSpacing.xs),711        )712    } else {713        pairedDevices.forEach { d ->714            RowLine(fg) {715                Column(Modifier.weight(1f)) {716                    Text(d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)717                    Text(718                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",719                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,720                        modifier = Modifier.padding(top = 2.dp),721                    )722                }723                if (confirmUnpair == d.deviceId) {724                    Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {725                        SubtleButton("cancel", fg) { confirmUnpair = null }726                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }727                    }728                } else {729                    SubtleButton("remove", fg) { confirmUnpair = d.deviceId }730                }731            }732        }733        RowLine(fg) {734            ValueText(syncFlashLabel(syncStatus), fg)735            SubtleButton(if (syncStatus == SyncStatus.Syncing) "syncing..." else "sync now", fg) {736                if (syncStatus != SyncStatus.Syncing) syncVm.syncNow()737            }738        }739    }740741    SubLabel("CONNECTION", fg)742    RowLine(fg) {743        Column(Modifier.weight(1f)) {744            Text("Use local network only (no relay)", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)745            Text(746                "Sync will only work when your devices share the same local network. " +747                    "It won't work over VPN or when your devices are in different locations.",748                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,749                modifier = Modifier.padding(top = 2.dp),750            )751        }752        Toggle(lanOnly, fg) { syncVm.setLanOnly(it) }753    }754    Text(755        "MESH RELAY URL",756        color = fg.copy(alpha = 0.6f),757        fontFamily = PeachType.Mono,758        fontSize = 8.sp,759        letterSpacing = 0.22.em,760    )761    Box(762        Modifier.fillMaxWidth().padding(top = 6.dp)763            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))764            .padding(horizontal = 12.dp, vertical = 10.dp),765    ) {766        BasicTextField(767            value = relayUrlDraft,768            onValueChange = { relayUrlDraft = it; relayUrlStatus = null },769            singleLine = true,770            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp, color = fg),771            cursorBrush = SolidColor(fg),772            modifier = Modifier.fillMaxWidth(),773        )774    }775    RowLine(fg) {776        ValueText(relayUrlStatus ?: "Only secure wss:// relays are accepted.", fg)777        SubtleButton("save", fg) {778            relayUrlStatus = if (syncVm.setRelayUrl(relayUrlDraft)) {779                relayUrlDraft = syncVm.relayUrl.value780                "Saved"781            } else {782                "Use a valid wss:// relay URL"783            }784        }785    }786787    SubLabel("RELAYING FOR PEERS", fg)788    RowLine(fg) {789        Column(Modifier.weight(1f)) {790            Text("Relay for other devices", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)791            Text(792                "Two browsers can't reach each other directly, so this phone passes their encrypted sync between them. It can't read any of it.",793                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,794                modifier = Modifier.padding(top = 2.dp),795            )796        }797        Toggle(relayEnabled, fg) { syncVm.setRelayEnabled(it) }798    }799800    if (pendingVouched.isNotEmpty()) {801        SubLabel("PENDING DEVICES", fg)802        pendingVouched.forEach { dev ->803            RowLine(fg) {804                Column(Modifier.weight(1f)) {805                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)806                    Text(807                        "Was added by another of your devices. Allow it to sync with this vault?",808                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,809                        modifier = Modifier.padding(top = 2.dp),810                    )811                }812                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {813                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }814                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }815                }816            }817        }818    }819820    SubLabel("RECOVERY", fg)821    if (rotateConfirmOpen) {822        Hint("This will disconnect all paired devices and your 12 recovery words will change. You'll be shown the new words next.", peachColors.Breach)823        rotateError?.let {824            Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))825        }826        Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {827            SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }828            SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {829                if (rotating) return@SubtleButton830                rotating = true831                rotateError = null832                scope.launch {833                    val ok = syncVm.rotateSyncIdentity()834                    rotating = false835                    if (ok) {836                        rotateConfirmOpen = false837                        onNavigate(PeachNav.RecoverySetup)838                    } else {839                        rotateError = "Rotation failed. Unlock your real vault and try again."840                    }841                }842            }843        }844    } else {845        RowLine(fg) {846            Column(Modifier.weight(1f)) {847                Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)848                Text(849                    "Use this if a paired device was lost or stolen. Re-keys the vault so the old device's key is useless.",850                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,851                    modifier = Modifier.padding(top = 2.dp),852                )853            }854            SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }855        }856    }857858    Hint("Sync uses the same zero-knowledge vault format as backup and restore; pairing authorizes a device, not a cloud account.", fg)859}860861private fun deviceTypeLabel(type: String?): String = when (type) {862    "android" -> "Android"863    "phone" -> "Phone"864    "tablet" -> "Tablet"865    "browser" -> "Browser"866    else -> "Device"867}868869private fun syncTimeLabel(lastSyncedAt: Long?): String {870    if (lastSyncedAt == null) return "never synced"871    val diff = System.currentTimeMillis() - lastSyncedAt872    if (diff < 60_000) return "just now"873    if (diff < 3_600_000) return "${diff / 60_000}m ago"874    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"875    return "${diff / 86_400_000}d ago"876}877878private fun isSyncStale(lastSyncedAt: Long?): Boolean =879    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L880881private fun syncFlashLabel(status: SyncStatus): String = when (status) {882    SyncStatus.Idle -> ""883    SyncStatus.Syncing -> "syncing..."884    SyncStatus.Offline -> "offline"885    is SyncStatus.Error -> status.message886    is SyncStatus.LastSynced -> "synced ${syncTimeLabel(status.timestamp)}"887}888889/* ──────────────────────────────  Shortcuts  ──────────────────────────────── */890891@Composable892private fun ShortcutsBody(fg: Color) {893    val bindings = listOf(894        "Copy password" to "⌘C", "Copy username" to "⌘⇧C", "Open entry" to "↵",895        "Edit entry" to "E", "New entry" to "⌘N", "Search" to "/",896    )897    SubLabel("KEYBINDINGS", fg, top = 0.dp)898    Hint("Shortcuts apply when a hardware keyboard is attached. Defaults shown below.", fg)899    Spacer(Modifier.height(8.dp))900    bindings.forEach { (label, key) ->901        RowLine(fg) {902            Name(label, fg)903            Box(904                Modifier.clip(RoundedCornerShape(4.dp)).background(fg.copy(alpha = 0.06f))905                    .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(4.dp))906                    .padding(horizontal = 7.dp, vertical = 2.dp),907            ) { Text(key, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp) }908        }909    }910}911912/* ────────────────────────────────  Pro  ─────────────────────────────────── */913914@Composable915private fun ProBody(fg: Color, vm: SettingsViewModel) {916    val ctx = LocalContext.current917    val isPro by vm.isPro.collectAsState()918    if (isPro) {919        ProActiveBody(fg, vm)920        return921    }922    val features = listOf(923        "Peach Sync" to "Encrypted · peer-to-peer",924        "Peach Codex" to "Restore from paper",925        "Passkeys" to "Zero-knowledge WebAuthn",926        "Advanced Vault Health" to "Reuse · age · exposure",927        "Canary entries" to "Detects vault compromise",928        "Duress vault" to "Decoy under coercion",929    )930    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)931    Text(932        "Everything, everywhere.",933        modifier = Modifier.padding(top = 8.dp),934        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,935    )936    Text(937        "One key unlocks every Pro feature — for the lifetime of the app.",938        modifier = Modifier.padding(top = 6.dp),939        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,940    )941    Spacer(Modifier.height(10.dp))942    features.forEachIndexed { i, (name, desc) ->943        // Compact rows (6dp vs. the shared 9dp default) — this card is the944        // tallest in the deck (6 features + price + CTA) and used to leave945        // its button with no breathing room before the fanned tab stacked946        // right beneath it in preview mode.947        RowLine(fg, verticalPadding = 6.dp) {948            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {949                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))950                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)951            }952            Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)953        }954    }955    Spacer(Modifier.height(12.dp))956    Text(957        "$39",958        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,959    )960    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)961    Spacer(Modifier.height(10.dp))962    Box(963        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))964            .background(fg.copy(alpha = 0.16f))965            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))966            .clickable {967                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }968            }969            .padding(vertical = 12.dp),970        contentAlignment = Alignment.Center,971    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }972973    // Trailing breathing room so the button clears the fanned tab stacked974    // beneath this card in preview mode, where the scrollable viewport clips975    // right around here (the license-key section below is already out of976    // view at that height).977    Spacer(Modifier.height(44.dp))978979    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)980    var key by remember { mutableStateOf("") }981    val activating by vm.activating.collectAsState()982    val activationError by vm.activationError.collectAsState()983    Box(984        Modifier.fillMaxWidth().padding(top = 6.dp)985            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))986            .padding(horizontal = 12.dp, vertical = 10.dp),987    ) {988        BasicTextField(989            value = key,990            // NOT .uppercase() — base58 (the license payload encoding) is991            // case-sensitive; forcing the whole string to uppercase silently992            // corrupted every real key before it ever reached signature993            // verification, so activation always failed with a real key.994            onValueChange = { key = it; vm.clearActivationError() },995            singleLine = true,996            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),997            cursorBrush = SolidColor(fg),998            modifier = Modifier.fillMaxWidth(),999            decorationBox = { inner ->1000                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)1001                inner()1002            },1003        )1004    }1005    if (activationError != null) {1006        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))1007    }1008    Spacer(Modifier.height(8.dp))1009    Box(1010        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1011            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))1012            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1013            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }1014            .padding(vertical = 12.dp),1015        contentAlignment = Alignment.Center,1016    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }1017}10181019@Composable1020private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {1021    val ctx = LocalContext.current1022    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")1023    val licenseKey by vm.licenseKey.collectAsState()1024    val issuedAt by vm.licenseIssuedAt.collectAsState()1025    var showKey by remember { mutableStateOf(false) }1026    var copied by remember { mutableStateOf(false) }1027    val scope = rememberCoroutineScope()1028    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {1029        com.peachpasswords.ui.components.PeachMark(size = 60.dp)1030    }1031    Text(1032        "Peach Pro",1033        modifier = Modifier.fillMaxWidth(),1034        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,1035        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1036    )1037    Text(1038        formatLicenseActiveSince(issuedAt),1039        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),1040        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,1041        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1042    )1043    licenseKey?.let { key ->1044        Spacer(Modifier.height(12.dp))1045        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1046        RowLine(fg) {1047            Text(1048                if (showKey) key else "************************",1049                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),1050                fontFamily = PeachType.Mono,1051                fontSize = 10.sp,1052                modifier = Modifier.weight(1f),1053            )1054            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1055                SubtleButton(if (copied) "copied" else "copy", fg) {1056                    PeachClipboard.copy(ctx, "peach license", key)1057                    copied = true1058                    scope.launch {1059                        delay(1_500)1060                        copied = false1061                    }1062                }1063                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }1064            }1065        }1066    }1067    Spacer(Modifier.height(12.dp))1068    features.forEachIndexed { i, name ->1069        RowLine(fg) {1070            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1071                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1072                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1073            }1074            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1075        }1076    }1077    Spacer(Modifier.height(12.dp))1078    Box(1079        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1080            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1081            .clickable { vm.deactivate() }1082            .padding(vertical = 12.dp),1083        contentAlignment = Alignment.Center,1084    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }1085}10861087private fun formatLicenseActiveSince(issuedAt: Long?): String {1088    if (issuedAt == null) return "Active"1089    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))1090    return "Active since $monthYear"1091}10921093/* ──────────────────────────────  Feedback  ───────────────────────────────── */10941095@OptIn(ExperimentalLayoutApi::class)1096@Composable1097private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {1098    val categories = listOf("Bug report", "Feature request", "Question", "Other")1099    var category by remember { mutableStateOf(categories[0]) }1100    var message by remember { mutableStateOf("") }1101    val state by vm.feedbackState.collectAsState()11021103    // Reset transient state when the card leaves composition so reopening starts fresh.1104    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }11051106    if (state is FeedbackState.Sent) {1107        Box(1108            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))1109                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),1110        ) {1111            Column {1112                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)1113                Text("Your note is in the queue. Someone will process it soon.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))1114            }1115        }1116        return1117    }11181119    val sending = state is FeedbackState.Sending11201121    Text("Help us improve Peach. Every report goes directly to our inbox.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp)1122    SubLabel("TYPE", fg)1123    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1124        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }1125    }1126    SubLabel("MESSAGE", fg)1127    Box(1128        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))1129            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))1130            .padding(10.dp),1131    ) {1132        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)1133        BasicTextField(1134            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },1135            enabled = !sending,1136            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),1137            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),1138        )1139    }1140    Text(1141        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",1142        modifier = Modifier.padding(top = 6.dp),1143        color = fg.copy(alpha = 0.52f),1144        fontFamily = PeachType.Mono,1145        fontSize = 10.sp,1146        lineHeight = 14.sp,1147    )1148    Spacer(Modifier.height(8.dp))11491150    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1151        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1152        Box(1153            Modifier.clip(RoundedCornerShape(8.dp))1154                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1155                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1156                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1157                .padding(horizontal = 12.dp, vertical = 6.dp),1158        ) {1159            Text(1160                feedbackSubmitLabel(state),1161                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1162                fontFamily = PeachType.Mono, fontSize = 11.sp,1163            )1164        }1165        if (sending) {1166            CircularProgressIndicator(1167                color = LocalPeachAccent.current,1168                strokeWidth = 2.dp,1169                modifier = Modifier.size(16.dp),1170            )1171        }1172    }11731174    (state as? FeedbackState.Error)?.let { err ->1175        Text(1176            err.message,1177            modifier = Modifier.padding(top = 8.dp),1178            color = peachColors.Breach,1179            fontFamily = PeachType.Mono,1180            fontSize = 11.sp,1181            lineHeight = 15.sp,1182        )1183    }11841185    Hint("Sent anonymously · no account required", fg)1186}11871188/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */11891190@Composable1191internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1192    val configured by vm.duressConfigured.collectAsState()1193    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1194}11951196@Composable1197private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1198    Text(1199        "Duress password is active",1200        color = peachColors.HealthOk,1201        fontFamily = PeachType.Mono,1202        fontSize = 11.sp,1203        modifier = Modifier.padding(top = 6.dp),1204    )1205    Spacer(Modifier.height(8.dp))1206    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1207    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1208}12091210@Composable1211private fun DuressForm(fg: Color, vm: SettingsViewModel) {1212    var enabled by remember { mutableStateOf(false) }1213    var password by remember { mutableStateOf("") }1214    var confirm by remember { mutableStateOf("") }1215    var action by remember { mutableStateOf(DuressAction.DECOY) }1216    var error by remember { mutableStateOf<String?>(null) }1217    val scope = rememberCoroutineScope()12181219    RowLine(fg) {1220        Name("Duress password", fg)1221        Toggle(enabled, fg) { on ->1222            enabled = on1223            if (!on) { password = ""; confirm = ""; error = null }1224        }1225    }1226    Text(1227        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1228        color = fg.copy(alpha = 0.7f),1229        fontFamily = PeachType.Mono,1230        fontSize = 10.sp,1231        modifier = Modifier.padding(top = 6.dp),1232    )12331234    AnimatedVisibility(enabled) {1235        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1236            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1237            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }12381239            Text(1240                "When your duress password is entered at the lock screen, Peach will:",1241                color = fg.copy(alpha = 0.7f),1242                fontFamily = PeachType.Mono,1243                fontSize = 10.sp,1244                modifier = Modifier.padding(top = 4.dp),1245            )12461247            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1248            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }12491250            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }12511252            val canSave = password.isNotBlank() && confirm.isNotBlank()1253            DuressSaveButton("Save duress password", fg, canSave) {1254                error = when {1255                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1256                    password != confirm -> "Passwords do not match"1257                    else -> null1258                }1259                if (error == null) scope.launch {1260                    if (vm.saveDuress(password, action)) {1261                        password = ""; confirm = ""; enabled = false1262                    } else {1263                        error = "Couldn't save — the duress passphrase must differ from your real password"1264                    }1265                }1266            }1267        }1268    }1269}12701271@Composable1272private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1273    val accent = LocalPeachAccent.current1274    Row(1275        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1276        verticalAlignment = Alignment.CenterVertically,1277        horizontalArrangement = Arrangement.spacedBy(10.dp),1278    ) {1279        Box(1280            Modifier.size(16.dp).clip(CircleShape)1281                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1282            contentAlignment = Alignment.Center,1283        ) {1284            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1285        }1286        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1287    }1288}12891290@Composable1291private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1292    val accent = LocalPeachAccent.current1293    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1294    Box(1295        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1296            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1297            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1298            .let { if (enabled) it.clickable(onClick = onClick) else it }1299            .padding(vertical = 11.dp),1300        contentAlignment = Alignment.Center,1301    ) {1302        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1303    }1304}13051306@Composable1307private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1308    Box(1309        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1310            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1311            .clickable(onClick = onClick)1312            .padding(vertical = 11.dp),1313        contentAlignment = Alignment.Center,1314    ) {1315        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1316    }1317}