SettingsCardBodies.kt

51.0 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.ui.PeachNav57import com.peachpasswords.ui.components.PeachEmptyOrEndState58import com.peachpasswords.ui.components.PeachField59import com.peachpasswords.ui.sync.SyncViewModel60import com.peachpasswords.ui.theme.ACCENT_COLORS61import com.peachpasswords.ui.theme.PeachSpacing62import com.peachpasswords.ui.theme.PeachType63import androidx.hilt.navigation.compose.hiltViewModel64import com.peachpasswords.vault.VaultSettings65import com.peachpasswords.vault.VaultSnapshot66import kotlinx.coroutines.launch67import kotlinx.coroutines.delay68import java.text.SimpleDateFormat69import java.util.Date70import java.util.Locale7172private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"7374/**75 * Body content for the active stack card. Everything is tinted with the card's76 * own foreground [fg] (the browser's `currentColor` convention), so each card's77 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,78 * canary, license activation) render their browser visual but defer the action79 * to a later phase — noted inline where that's the case.80 */81@Composable82fun CardBody(83    id: CardId,84    fg: Color,85    vm: SettingsViewModel,86    settings: VaultSettings,87    entriesCount: Int,88    onNavigate: (PeachNav) -> Unit,89) {90    when (id) {91        CardId.Appearance -> AppearanceBody(fg, vm, settings)92        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)93        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)94        CardId.Sync -> SyncBody(fg, onNavigate)95        CardId.Shortcuts -> ShortcutsBody(fg)96        CardId.Pro -> ProBody(fg, vm)97        CardId.Feedback -> FeedbackBody(fg, vm)98    }99}100101/* ─────────────────────────  shared row vocabulary  ───────────────────────── */102103@Composable104private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {105    Text(106        text,107        modifier = Modifier.padding(top = top, bottom = 4.dp),108        color = fg.copy(alpha = 0.58f),109        fontFamily = PeachType.Mono,110        fontSize = 8.sp,111        letterSpacing = 0.22.em,112    )113}114115@Composable116private fun RowLine(117    fg: Color,118    modifier: Modifier = Modifier,119    verticalPadding: Dp = 9.dp,120    content: @Composable RowScope.() -> Unit,121) {122    Row(123        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),124        verticalAlignment = Alignment.CenterVertically,125        horizontalArrangement = Arrangement.SpaceBetween,126        content = content,127    )128    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))129}130131@Composable132private fun RowScope.Name(text: String, fg: Color) {133    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))134}135136@Composable137private fun ValueText(text: String, fg: Color) {138    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp)139}140141@Composable142private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {143    Box(144        Modifier.clip(RoundedCornerShape(8.dp))145            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))146            .background(fg.copy(alpha = 0.08f))147            .clickable(onClick = onClick)148            .padding(horizontal = 12.dp, vertical = 6.dp),149    ) {150        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)151    }152}153154@Composable155private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {156    val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")157    Box(158        Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))159            .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))160            .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))161            .clickable { onToggle(!on) },162    ) {163        Box(164            Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)165                .padding(start = knob - 2.dp)166                .size(14.dp).clip(CircleShape)167                .background(if (on) fg else fg.copy(alpha = 0.58f)),168        )169    }170}171172@Composable173private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {174    Box(175        Modifier.clip(RoundedCornerShape(999.dp))176            .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))177            .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)178            .clickable(onClick = onClick)179            .padding(horizontal = 12.dp, vertical = 5.dp),180    ) {181        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)182    }183}184185@Composable186private fun ProBadge(fg: Color) {187    Box(188        Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))189            .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),190    ) {191        Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)192    }193}194195@Composable196private fun Hint(text: String, fg: Color) {197    Text(198        text,199        modifier = Modifier.padding(top = 6.dp),200        color = fg.copy(alpha = 0.6f),201        fontFamily = PeachType.Display,202        fontStyle = FontStyle.Italic,203        fontSize = 11.5.sp,204        lineHeight = 16.sp,205    )206}207208/* ──────────────────────────────  Appearance  ─────────────────────────────── */209210@OptIn(ExperimentalLayoutApi::class)211@Composable212private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {213    SubLabel("THEME", fg, top = 0.dp)214    RowLine(fg) {215        Name("Theme", fg)216        val (label, next) = when (s.theme) {217            "dark" -> "Switch to light" to "light"218            else -> "Switch to dark" to "dark"219        }220        SubtleButton(label, fg) { vm.setTheme(next) }221    }222    SubLabel("ACCENT", fg)223    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {224        ACCENT_COLORS.forEach { (name, color) ->225            Box(226                Modifier.size(22.dp).clip(CircleShape).background(color)227                    .border(228                        if (s.accentColor == name) 2.dp else 1.dp,229                        if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),230                        CircleShape,231                    )232                    .clickable { vm.setAccent(name) },233            )234        }235    }236    SubLabel("TEXT SIZE", fg)237    RowLine(fg) {238        Name("Size", fg)239        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {240            Pill("Default", s.textSize == "medium", fg) { vm.setTextSize("medium") }241            Pill("Large", s.textSize == "large", fg) { vm.setTextSize("large") }242        }243    }244    SubLabel("MOTION", fg)245    RowLine(fg) {246        Name("Reduce motion", fg)247        SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }248    }249}250251/* ──────────────────────────────  Protection  ─────────────────────────────── */252253@Composable254private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings, onNavigate: (PeachNav) -> Unit) {255    val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")256    val current = s.autoLockMinutes ?: 0257258    SubLabel("LOCKING", fg, top = 0.dp)259    RowLine(fg) {260        Name("Auto-lock after", fg)261        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)262        SubtleButton(lockOptions[idx].second, fg) {263            val next = lockOptions[(idx + 1) % lockOptions.size].first264            vm.setAutoLockMinutes(if (next == 0) 0 else next)265        }266    }267    SubLabel("BIOMETRICS", fg)268    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity269    RowLine(fg) {270        Name("Unlock with biometrics", fg)271        Toggle(s.biometricsEnabled, fg) { on ->272            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()273        }274    }275    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)276    if (bioError != null) {277        Text(278            bioError,279            color = com.peachpasswords.ui.theme.peachColors.Breach,280            fontFamily = PeachType.Mono, fontSize = 10.sp,281            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),282        )283    }284    SubLabel("PASSKEYS", fg)285    RowLine(fg) {286        Column(Modifier.weight(1f)) {287            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)288            Text(289                "Peach can handle passkey sign-in and creation through Android Credential Manager.",290                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,291                modifier = Modifier.padding(top = 2.dp),292            )293        }294        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }295    }296    RowLine(fg) {297        Name("Status", fg)298        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)299    }300    SubLabel("RECOVERY", fg)301    RowLine(fg) {302        Column(Modifier.weight(1f)) {303            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)304            Text(305                "Keep the paper copy current before rotating sync identity or replacing devices.",306                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,307                modifier = Modifier.padding(top = 2.dp),308            )309        }310        SubtleButton("view", fg) { onNavigate(PeachNav.RecoveryView) }311    }312    SubLabel("BREACH PROTECTION", fg)313    val checkingBreaches by vm.checkingBreaches.collectAsState()314    val breachResult by vm.breachResult.collectAsState()315    RowLine(fg) {316        Name("Breach monitoring", fg)317        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }318    }319    RowLine(fg) {320        Name("Check all passwords", fg)321        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }322    }323    breachResult?.let { result ->324        RowLine(fg) {325            Name("Last check", fg)326            ValueText(result, fg)327        }328    }329330    SubLabel("MASTER PASSWORD", fg)331    ChangePasswordRow(fg, vm)332333    SubLabel("DURESS PASSWORD", fg)334    val duressIsPro by vm.isPro.collectAsState()335    if (!duressIsPro) {336        RowLine(fg) {337            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {338                Name("Duress password", fg); ProBadge(fg)339            }340            ValueText("off", fg)341        }342        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)343    } else {344        DuressSection(fg, vm)345    }346}347348@Composable349private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {350    var open by remember { mutableStateOf(false) }351    var current by remember { mutableStateOf("") }352    var next by remember { mutableStateOf("") }353    var confirm by remember { mutableStateOf("") }354    var error by remember { mutableStateOf<String?>(null) }355    var done by remember { mutableStateOf(false) }356    val scope = rememberCoroutineScope()357358    RowLine(fg) {359        Name("Master password", fg)360        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }361    }362    AnimatedVisibility(open) {363        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {364            PwField("current password", current, fg) { current = it }365            PwField("new password (min 12 chars)", next, fg) { next = it }366            PwField("confirm new password", confirm, fg) { confirm = it }367            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }368            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)369            SubtleButton("save new password", fg) {370                error = when {371                    current.isBlank() -> "enter your current password"372                    next.length < 12 -> "new password must be at least 12 characters"373                    next != confirm -> "new passwords do not match"374                    next == current -> "new password must differ from current"375                    else -> null376                }377                if (error == null) scope.launch {378                    if (vm.changePassword(current, next)) {379                        current = ""; next = ""; confirm = ""; open = false; done = true380                    } else error = "incorrect current password"381                }382            }383        }384    }385}386387@Composable388private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {389    PeachField(390        label = placeholder,391        value = value,392        onValueChange = onChange,393        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,394        visualTransformation = PasswordVisualTransformation(),395    )396}397398/* ────────────────────────────────  Vault  ───────────────────────────────── */399400@Composable401private fun VaultBody(402    fg: Color,403    vm: SettingsViewModel,404    s: VaultSettings,405    entriesCount: Int,406    onNavigate: (PeachNav) -> Unit,407) {408    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")409    val current = s.trashRetentionDays ?: 0410    val isPro by vm.isPro.collectAsState()411    val dedupCount by vm.dedupCount.collectAsState()412    val dedupRunning by vm.dedupRunning.collectAsState()413    val dedupDone by vm.dedupDone.collectAsState()414    val history by vm.vaultHistory.collectAsState()415    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()416417    SubLabel("ENTRIES", fg, top = 0.dp)418    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }419    RowLine(fg) {420        Name("Duplicates", fg)421        val done = dedupDone422        if (done != null) {423            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)424        } else {425            val count = dedupCount426            val label = when {427                dedupRunning -> "scanning..."428                count == null -> "scan"429                count == 0 -> "none found"430                else -> "$count found"431            }432            SubtleButton(label, fg) {433                if (count == null || count == 0) vm.scanDuplicates()434            }435        }436    }437    if ((dedupCount ?: 0) > 0 && dedupDone == null) {438        Column(439            Modifier.fillMaxWidth()440                .padding(top = 2.dp, bottom = 8.dp)441                .clip(RoundedCornerShape(8.dp))442                .background(fg.copy(alpha = 0.08f))443                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))444                .padding(10.dp),445            verticalArrangement = Arrangement.spacedBy(8.dp),446        ) {447            val count = dedupCount ?: 0448            Text(449                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",450                color = fg.copy(alpha = 0.82f),451                fontFamily = PeachType.Body,452                fontSize = 11.sp,453                lineHeight = 16.sp,454            )455            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {456                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }457                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }458            }459        }460    }461462    SubLabel("MAINTENANCE", fg)463    RowLine(fg) {464        Name("Trash auto-delete", fg)465        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)466        SubtleButton(trashOptions[idx].second, fg) {467            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)468        }469    }470    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }471    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }472473    SubLabel("DATA", fg)474    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }475    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }476    RowLine(fg) {477        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }478        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }479    }480    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }481482    var historyShowAll by remember { mutableStateOf(false) }483    SubLabel("VAULT HISTORY", fg)484    if (history.isEmpty()) {485        Text(486            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",487            color = fg.copy(alpha = 0.68f),488            fontFamily = PeachType.Body,489            fontSize = 11.sp,490            lineHeight = 16.sp,491            modifier = Modifier.padding(bottom = 6.dp),492        )493    } else {494        Text(495            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",496            color = fg.copy(alpha = 0.68f),497            fontFamily = PeachType.Body,498            fontSize = 11.sp,499            lineHeight = 16.sp,500            modifier = Modifier.padding(bottom = 4.dp),501        )502        history.take(if (historyShowAll) history.size else 3).forEach { snap ->503            RowLine(fg) {504                Column(Modifier.weight(1f)) {505                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)506                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)507                }508                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {509                    vm.restoreVaultSnapshot(snap.id)510                }511            }512        }513        if (history.size > 3) {514            RowLine(fg) {515                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)516                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }517            }518        }519        Text(520            "${history.size} of 5 snapshots",521            color = fg.copy(alpha = 0.58f),522            fontFamily = PeachType.Mono,523            fontSize = 10.sp,524            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),525        )526    }527528    var advancedOpen by remember { mutableStateOf(false) }529    SubLabel("ADVANCED", fg)530    RowLine(fg) {531        Name("Advanced", fg)532        SubtleButton(if (advancedOpen) "hide" else "show", fg) { advancedOpen = !advancedOpen }533    }534    if (advancedOpen) {535        RowLine(fg) {536            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)537            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }538        }539        RowLine(fg) {540            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)541            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }542        }543    }544}545546private fun snapshotSubLabel(snapshot: VaultSnapshot): String {547    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }548    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")549}550551private fun snapshotReasonLabel(reason: String): String = when (reason) {552    "local_save" -> "saved"553    "sync_received" -> "synced"554    "import" -> "imported"555    "restore" -> "restored"556    else -> reason557}558559private fun snapshotTimeLabel(savedAt: Long): String {560    val diff = System.currentTimeMillis() - savedAt561    if (diff < 60_000) return "Just now"562    if (diff < 3_600_000) return "${diff / 60_000}m ago"563    val date = Date(savedAt)564    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())565    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)566    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)567    if (today == thenDay) return "Today $time"568    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))569    if (yesterday == thenDay) return "Yesterday $time"570    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)571}572573/* ────────────────────────────────  Sync  ────────────────────────────────── */574575@Composable576private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {577    val syncVm: SyncViewModel = hiltViewModel()578    val pairedDevices by syncVm.pairedDevices.collectAsState()579    val pendingVouched by syncVm.pendingVouched.collectAsState()580    val syncStatus by syncVm.status.collectAsState()581    val scope = rememberCoroutineScope()582    var confirmUnpair by remember { mutableStateOf<String?>(null) }583    var rotateConfirmOpen by remember { mutableStateOf(false) }584    var rotating by remember { mutableStateOf(false) }585    var rotateError by remember { mutableStateOf<String?>(null) }586587    SubLabel("PAIRING", fg, top = 0.dp)588    RowLine(fg) {589        Column(Modifier.weight(1f)) {590            Row(verticalAlignment = Alignment.CenterVertically) {591                Text("Peach Sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp); ProBadge(fg)592            }593            Text(594                "Pair nearby devices by chirp and keep encrypted vault blobs in step without a central account.",595                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,596                modifier = Modifier.padding(top = 2.dp),597            )598        }599    }600    // The whole row is the tap target — no separate "open" button (browser601    // sync-hub parity: every settings row is tappable, the chevron signals it).602    RowLine(fg, Modifier.clickable { onNavigate(PeachNav.ChirpPair) }) {603        Name("Sync hub", fg)604        Text("›", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 15.sp)605    }606    RowLine(fg) {607        Column(Modifier.weight(1f)) {608            Text("Pair new device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)609            Text(610                "Add a phone, another browser, or your desktop sync helper.",611                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,612                modifier = Modifier.padding(top = 2.dp),613            )614        }615        SubtleButton("pair", fg) { onNavigate(PeachNav.ChirpPair) }616    }617618    SubLabel("PAIRED DEVICES", fg)619    if (pairedDevices.isEmpty()) {620        PeachEmptyOrEndState(621            message = "No paired devices yet.",622            detail = "Pair a nearby phone, browser, or desktop helper when you're ready to sync.",623            modifier = Modifier.padding(top = PeachSpacing.xs),624        )625    } else {626        pairedDevices.forEach { d ->627            RowLine(fg) {628                Column(Modifier.weight(1f)) {629                    Text(d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)630                    Text(631                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",632                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,633                        modifier = Modifier.padding(top = 2.dp),634                    )635                }636                if (confirmUnpair == d.deviceId) {637                    Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {638                        SubtleButton("cancel", fg) { confirmUnpair = null }639                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }640                    }641                } else {642                    SubtleButton("remove", fg) { confirmUnpair = d.deviceId }643                }644            }645        }646        RowLine(fg) {647            ValueText(syncFlashLabel(syncStatus), fg)648            SubtleButton(if (syncStatus == SyncStatus.Syncing) "syncing..." else "sync now", fg) {649                if (syncStatus != SyncStatus.Syncing) syncVm.syncNow()650            }651        }652    }653654    if (pendingVouched.isNotEmpty()) {655        SubLabel("PENDING DEVICES", fg)656        pendingVouched.forEach { dev ->657            RowLine(fg) {658                Column(Modifier.weight(1f)) {659                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)660                    Text(661                        "Was added by another of your devices. Allow it to sync with this vault?",662                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,663                        modifier = Modifier.padding(top = 2.dp),664                    )665                }666                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {667                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }668                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }669                }670            }671        }672    }673674    SubLabel("RECOVERY", fg)675    if (rotateConfirmOpen) {676        Hint("This will disconnect all paired devices and your 12 recovery words will change. You'll be shown the new words next.", peachColors.Breach)677        rotateError?.let {678            Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))679        }680        Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {681            SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }682            SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {683                if (rotating) return@SubtleButton684                rotating = true685                rotateError = null686                scope.launch {687                    val ok = syncVm.rotateSyncIdentity()688                    rotating = false689                    if (ok) {690                        rotateConfirmOpen = false691                        onNavigate(PeachNav.RecoverySetup)692                    } else {693                        rotateError = "Rotation failed. Unlock your real vault and try again."694                    }695                }696            }697        }698    } else {699        RowLine(fg) {700            Column(Modifier.weight(1f)) {701                Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)702                Text(703                    "Use this if a paired device was lost or stolen. Re-keys the vault so the old device's key is useless.",704                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,705                    modifier = Modifier.padding(top = 2.dp),706                )707            }708            SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }709        }710    }711712    Hint("Sync uses the same zero-knowledge vault format as backup and restore; pairing authorizes a device, not a cloud account.", fg)713}714715private fun deviceTypeLabel(type: String?): String = when (type) {716    "android" -> "Android"717    "phone" -> "Phone"718    "tablet" -> "Tablet"719    "desktop" -> "Desktop"720    "browser" -> "Browser"721    else -> "Device"722}723724private fun syncTimeLabel(lastSyncedAt: Long?): String {725    if (lastSyncedAt == null) return "never synced"726    val diff = System.currentTimeMillis() - lastSyncedAt727    if (diff < 60_000) return "just now"728    if (diff < 3_600_000) return "${diff / 60_000}m ago"729    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"730    return "${diff / 86_400_000}d ago"731}732733private fun isSyncStale(lastSyncedAt: Long?): Boolean =734    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L735736private fun syncFlashLabel(status: SyncStatus): String = when (status) {737    SyncStatus.Idle -> ""738    SyncStatus.Syncing -> "syncing..."739    SyncStatus.Offline -> "offline"740    is SyncStatus.Error -> status.message741    is SyncStatus.LastSynced -> "synced ${syncTimeLabel(status.timestamp)}"742}743744/* ──────────────────────────────  Shortcuts  ──────────────────────────────── */745746@Composable747private fun ShortcutsBody(fg: Color) {748    val bindings = listOf(749        "Copy password" to "⌘C", "Copy username" to "⌘⇧C", "Open entry" to "↵",750        "Edit entry" to "E", "New entry" to "⌘N", "Search" to "/",751    )752    SubLabel("KEYBINDINGS", fg, top = 0.dp)753    Hint("Shortcuts apply when a hardware keyboard is attached. Defaults shown below.", fg)754    Spacer(Modifier.height(8.dp))755    bindings.forEach { (label, key) ->756        RowLine(fg) {757            Name(label, fg)758            Box(759                Modifier.clip(RoundedCornerShape(4.dp)).background(fg.copy(alpha = 0.06f))760                    .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(4.dp))761                    .padding(horizontal = 7.dp, vertical = 2.dp),762            ) { Text(key, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp) }763        }764    }765}766767/* ────────────────────────────────  Pro  ─────────────────────────────────── */768769@Composable770private fun ProBody(fg: Color, vm: SettingsViewModel) {771    val ctx = LocalContext.current772    val isPro by vm.isPro.collectAsState()773    if (isPro) {774        ProActiveBody(fg, vm)775        return776    }777    val features = listOf(778        "Peach Sync" to "Encrypted · peer-to-peer",779        "Peach Codex" to "Restore from paper",780        "Passkeys" to "Zero-knowledge WebAuthn",781        "Advanced Vault Health" to "Reuse · age · exposure",782        "Canary entries" to "Detects vault compromise",783        "Duress vault" to "Decoy under coercion",784    )785    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)786    Text(787        "Everything, everywhere.",788        modifier = Modifier.padding(top = 8.dp),789        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,790    )791    Text(792        "One key unlocks every Pro feature — for the lifetime of the app.",793        modifier = Modifier.padding(top = 6.dp),794        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,795    )796    Spacer(Modifier.height(10.dp))797    features.forEachIndexed { i, (name, desc) ->798        // Compact rows (6dp vs. the shared 9dp default) — this card is the799        // tallest in the deck (6 features + price + CTA) and used to leave800        // its button with no breathing room before the fanned tab stacked801        // right beneath it in preview mode.802        RowLine(fg, verticalPadding = 6.dp) {803            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {804                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))805                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)806            }807            Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)808        }809    }810    Spacer(Modifier.height(12.dp))811    Text(812        "$39",813        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,814    )815    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)816    Spacer(Modifier.height(10.dp))817    Box(818        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))819            .background(fg.copy(alpha = 0.16f))820            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))821            .clickable {822                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }823            }824            .padding(vertical = 12.dp),825        contentAlignment = Alignment.Center,826    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }827828    // Trailing breathing room so the button clears the fanned tab stacked829    // beneath this card in preview mode, where the scrollable viewport clips830    // right around here (the license-key section below is already out of831    // view at that height).832    Spacer(Modifier.height(44.dp))833834    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)835    var key by remember { mutableStateOf("") }836    val activating by vm.activating.collectAsState()837    val activationError by vm.activationError.collectAsState()838    Box(839        Modifier.fillMaxWidth().padding(top = 6.dp)840            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))841            .padding(horizontal = 12.dp, vertical = 10.dp),842    ) {843        BasicTextField(844            value = key,845            // NOT .uppercase() — base58 (the license payload encoding) is846            // case-sensitive; forcing the whole string to uppercase silently847            // corrupted every real key before it ever reached signature848            // verification, so activation always failed with a real key.849            onValueChange = { key = it; vm.clearActivationError() },850            singleLine = true,851            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),852            cursorBrush = SolidColor(fg),853            modifier = Modifier.fillMaxWidth(),854            decorationBox = { inner ->855                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)856                inner()857            },858        )859    }860    if (activationError != null) {861        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))862    }863    Spacer(Modifier.height(8.dp))864    Box(865        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))866            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))867            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))868            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }869            .padding(vertical = 12.dp),870        contentAlignment = Alignment.Center,871    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }872}873874@Composable875private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {876    val ctx = LocalContext.current877    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")878    val licenseKey by vm.licenseKey.collectAsState()879    val issuedAt by vm.licenseIssuedAt.collectAsState()880    var showKey by remember { mutableStateOf(false) }881    var copied by remember { mutableStateOf(false) }882    val scope = rememberCoroutineScope()883    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {884        com.peachpasswords.ui.components.PeachMark(size = 60.dp)885    }886    Text(887        "Peach Pro",888        modifier = Modifier.fillMaxWidth(),889        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,890        textAlign = androidx.compose.ui.text.style.TextAlign.Center,891    )892    Text(893        formatLicenseActiveSince(issuedAt),894        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),895        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,896        textAlign = androidx.compose.ui.text.style.TextAlign.Center,897    )898    licenseKey?.let { key ->899        Spacer(Modifier.height(12.dp))900        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)901        RowLine(fg) {902            Text(903                if (showKey) key else "************************",904                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),905                fontFamily = PeachType.Mono,906                fontSize = 10.sp,907                modifier = Modifier.weight(1f),908            )909            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {910                SubtleButton(if (copied) "copied" else "copy", fg) {911                    PeachClipboard.copy(ctx, "peach license", key)912                    copied = true913                    scope.launch {914                        delay(1_500)915                        copied = false916                    }917                }918                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }919            }920        }921    }922    Spacer(Modifier.height(12.dp))923    features.forEachIndexed { i, name ->924        RowLine(fg) {925            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {926                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))927                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)928            }929            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)930        }931    }932    Spacer(Modifier.height(12.dp))933    Box(934        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))935            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))936            .clickable { vm.deactivate() }937            .padding(vertical = 12.dp),938        contentAlignment = Alignment.Center,939    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }940}941942private fun formatLicenseActiveSince(issuedAt: Long?): String {943    if (issuedAt == null) return "Active"944    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))945    return "Active since $monthYear"946}947948/* ──────────────────────────────  Feedback  ───────────────────────────────── */949950@OptIn(ExperimentalLayoutApi::class)951@Composable952private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {953    val categories = listOf("Bug report", "Feature request", "Question", "Other")954    var category by remember { mutableStateOf(categories[0]) }955    var message by remember { mutableStateOf("") }956    val state by vm.feedbackState.collectAsState()957958    // Reset transient state when the card leaves composition so reopening starts fresh.959    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }960961    if (state is FeedbackState.Sent) {962        Box(963            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))964                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),965        ) {966            Column {967                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)968                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))969            }970        }971        return972    }973974    val sending = state is FeedbackState.Sending975976    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)977    SubLabel("TYPE", fg)978    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {979        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }980    }981    SubLabel("MESSAGE", fg)982    Box(983        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))984            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))985            .padding(10.dp),986    ) {987        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)988        BasicTextField(989            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },990            enabled = !sending,991            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),992            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),993        )994    }995    Text(996        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",997        modifier = Modifier.padding(top = 6.dp),998        color = fg.copy(alpha = 0.52f),999        fontFamily = PeachType.Mono,1000        fontSize = 10.sp,1001        lineHeight = 14.sp,1002    )1003    Spacer(Modifier.height(8.dp))10041005    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1006        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1007        Box(1008            Modifier.clip(RoundedCornerShape(8.dp))1009                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1010                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1011                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1012                .padding(horizontal = 12.dp, vertical = 6.dp),1013        ) {1014            Text(1015                feedbackSubmitLabel(state),1016                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1017                fontFamily = PeachType.Mono, fontSize = 11.sp,1018            )1019        }1020        if (sending) {1021            CircularProgressIndicator(1022                color = LocalPeachAccent.current,1023                strokeWidth = 2.dp,1024                modifier = Modifier.size(16.dp),1025            )1026        }1027    }10281029    (state as? FeedbackState.Error)?.let { err ->1030        Text(1031            err.message,1032            modifier = Modifier.padding(top = 8.dp),1033            color = peachColors.Breach,1034            fontFamily = PeachType.Mono,1035            fontSize = 11.sp,1036            lineHeight = 15.sp,1037        )1038    }10391040    Hint("Sent anonymously · no account required", fg)1041}10421043/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */10441045@Composable1046internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1047    val configured by vm.duressConfigured.collectAsState()1048    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1049}10501051@Composable1052private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1053    Text(1054        "Duress password is active",1055        color = peachColors.HealthOk,1056        fontFamily = PeachType.Mono,1057        fontSize = 11.sp,1058        modifier = Modifier.padding(top = 6.dp),1059    )1060    Spacer(Modifier.height(8.dp))1061    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1062    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1063}10641065@Composable1066private fun DuressForm(fg: Color, vm: SettingsViewModel) {1067    var enabled by remember { mutableStateOf(false) }1068    var password by remember { mutableStateOf("") }1069    var confirm by remember { mutableStateOf("") }1070    var action by remember { mutableStateOf(DuressAction.DECOY) }1071    var error by remember { mutableStateOf<String?>(null) }1072    val scope = rememberCoroutineScope()10731074    RowLine(fg) {1075        Name("Duress password", fg)1076        Toggle(enabled, fg) { on ->1077            enabled = on1078            if (!on) { password = ""; confirm = ""; error = null }1079        }1080    }1081    Text(1082        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1083        color = fg.copy(alpha = 0.7f),1084        fontFamily = PeachType.Mono,1085        fontSize = 10.sp,1086        modifier = Modifier.padding(top = 6.dp),1087    )10881089    AnimatedVisibility(enabled) {1090        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1091            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1092            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }10931094            Text(1095                "When your duress password is entered at the lock screen, Peach will:",1096                color = fg.copy(alpha = 0.7f),1097                fontFamily = PeachType.Mono,1098                fontSize = 10.sp,1099                modifier = Modifier.padding(top = 4.dp),1100            )11011102            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1103            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }11041105            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }11061107            val canSave = password.isNotBlank() && confirm.isNotBlank()1108            DuressSaveButton("Save duress password", fg, canSave) {1109                error = when {1110                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1111                    password != confirm -> "Passwords do not match"1112                    else -> null1113                }1114                if (error == null) scope.launch {1115                    if (vm.saveDuress(password, action)) {1116                        password = ""; confirm = ""; enabled = false1117                    } else {1118                        error = "Couldn't save — the duress passphrase must differ from your real password"1119                    }1120                }1121            }1122        }1123    }1124}11251126@Composable1127private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1128    val accent = LocalPeachAccent.current1129    Row(1130        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1131        verticalAlignment = Alignment.CenterVertically,1132        horizontalArrangement = Arrangement.spacedBy(10.dp),1133    ) {1134        Box(1135            Modifier.size(16.dp).clip(CircleShape)1136                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1137            contentAlignment = Alignment.Center,1138        ) {1139            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1140        }1141        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1142    }1143}11441145@Composable1146private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1147    val accent = LocalPeachAccent.current1148    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1149    Box(1150        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1151            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1152            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1153            .let { if (enabled) it.clickable(onClick = onClick) else it }1154            .padding(vertical = 11.dp),1155        contentAlignment = Alignment.Center,1156    ) {1157        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1158    }1159}11601161@Composable1162private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1163    Box(1164        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1165            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1166            .clickable(onClick = onClick)1167            .padding(vertical = 11.dp),1168        contentAlignment = Alignment.Center,1169    ) {1170        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1171    }1172}