SettingsCardBodies.kt

62.8 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.heightIn21import androidx.compose.foundation.layout.padding22import androidx.compose.foundation.layout.size23import androidx.compose.foundation.layout.width24import androidx.compose.foundation.shape.CircleShape25import androidx.compose.foundation.shape.RoundedCornerShape26import androidx.compose.foundation.text.BasicTextField27import androidx.compose.runtime.Composable28import androidx.compose.material3.CircularProgressIndicator29import androidx.compose.runtime.DisposableEffect30import androidx.compose.runtime.collectAsState31import androidx.compose.runtime.getValue32import com.peachpasswords.feedback.FeedbackState33import com.peachpasswords.shared.PeachClipboard34import com.peachpasswords.sync.SyncMode35import com.peachpasswords.sync.canShowBackgroundSyncNotification36import com.peachpasswords.sync.describeSyncOutcome37import com.peachpasswords.sync.privateRelayDraftOf38import com.peachpasswords.sync.syncIndicator39import com.peachpasswords.sync.syncIndicatorLabel40import com.peachpasswords.ui.components.SyncIndicatorDot41import com.peachpasswords.ui.theme.LocalPeachAccent42import com.peachpasswords.vault.DuressAction43import com.peachpasswords.ui.theme.peachColors44import androidx.compose.runtime.mutableStateOf45import androidx.compose.runtime.remember46import androidx.compose.runtime.rememberCoroutineScope47import androidx.compose.runtime.setValue48import androidx.compose.ui.Alignment49import androidx.compose.ui.Modifier50import androidx.compose.ui.draw.clip51import androidx.compose.ui.graphics.Color52import androidx.compose.ui.graphics.SolidColor53import androidx.compose.ui.platform.LocalContext54import androidx.compose.ui.text.TextStyle55import androidx.compose.ui.text.font.FontStyle56import androidx.compose.ui.text.input.PasswordVisualTransformation57import androidx.compose.ui.unit.Dp58import androidx.compose.ui.unit.dp59import androidx.compose.ui.unit.em60import androidx.compose.ui.unit.sp61import androidx.compose.material3.Text62import com.peachpasswords.BuildConfig63import com.peachpasswords.autofill.AutofillEnablement64import com.peachpasswords.ui.PeachNav65import com.peachpasswords.ui.components.PeachEmptyOrEndState66import com.peachpasswords.ui.components.PeachField67import com.peachpasswords.ui.pairing.BackgroundSyncDialog68import com.peachpasswords.ui.sync.SyncViewModel69import com.peachpasswords.ui.theme.ACCENT_COLORS70import com.peachpasswords.ui.theme.PeachSpacing71import com.peachpasswords.ui.theme.PeachType72import com.peachpasswords.ui.updates.UpdatePhase73import com.peachpasswords.ui.updates.UpdateViewModel74import androidx.hilt.navigation.compose.hiltViewModel75import com.peachpasswords.vault.VaultSettings76import com.peachpasswords.vault.VaultSnapshot77import kotlinx.coroutines.launch78import kotlinx.coroutines.delay79import java.text.SimpleDateFormat80import java.util.Date81import java.util.Locale8283private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"8485/**86 * Body content for the active stack card. Everything is tinted with the card's87 * own foreground [fg] (the browser's `currentColor` convention), so each card's88 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,89 * canary, license activation) render their browser visual but defer the action90 * to a later phase — noted inline where that's the case.91 */92@Composable93fun CardBody(94    id: CardId,95    fg: Color,96    vm: SettingsViewModel,97    settings: VaultSettings,98    entriesCount: Int,99    onNavigate: (PeachNav) -> Unit,100) {101    when (id) {102        CardId.Appearance -> AppearanceBody(fg, vm, settings)103        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)104        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)105        CardId.Sync -> SyncBody(fg, onNavigate)106        CardId.Pro -> ProBody(fg, vm)107        CardId.Feedback -> FeedbackBody(fg, vm)108    }109}110111/* ─────────────────────────  shared row vocabulary  ───────────────────────── */112113@Composable114private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {115    Text(116        text,117        modifier = Modifier.padding(top = top, bottom = 4.dp),118        color = fg.copy(alpha = 0.58f),119        fontFamily = PeachType.Mono,120        fontSize = 8.sp,121        letterSpacing = 0.22.em,122    )123}124125@Composable126private fun RowLine(127    fg: Color,128    modifier: Modifier = Modifier,129    verticalPadding: Dp = 9.dp,130    content: @Composable RowScope.() -> Unit,131) {132    Row(133        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),134        verticalAlignment = Alignment.CenterVertically,135        horizontalArrangement = Arrangement.SpaceBetween,136        content = content,137    )138    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))139}140141@Composable142private fun RowScope.Name(text: String, fg: Color) {143    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))144}145146@Composable147private fun ValueText(text: String, fg: Color) {148    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp)149}150151@Composable152private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {153    Box(154        Modifier.clip(RoundedCornerShape(8.dp))155            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))156            .background(fg.copy(alpha = 0.08f))157            .clickable(onClick = onClick)158            .padding(horizontal = 12.dp, vertical = 6.dp),159    ) {160        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)161    }162}163164@Composable165private fun SyncDisclosure(166    title: String,167    summary: String,168    expanded: Boolean,169    fg: Color,170    onToggle: () -> Unit,171) {172    Row(173        modifier = Modifier174            .fillMaxWidth()175            .heightIn(min = 48.dp)176            .clip(RoundedCornerShape(8.dp))177            .clickable(onClick = onToggle)178            .padding(vertical = 8.dp),179        verticalAlignment = Alignment.CenterVertically,180    ) {181        Column(Modifier.weight(1f)) {182            Text(183                title.uppercase(),184                color = fg.copy(alpha = 0.58f),185                fontFamily = PeachType.Mono,186                fontSize = 8.sp,187                letterSpacing = 0.22.em,188            )189            Text(190                summary,191                color = fg.copy(alpha = 0.7f),192                fontFamily = PeachType.Body,193                fontSize = 11.sp,194                modifier = Modifier.padding(top = 3.dp),195            )196        }197        Text(198            if (expanded) "hide" else "show",199            color = fg,200            fontFamily = PeachType.Mono,201            fontSize = 10.sp,202        )203    }204}205206@Composable207private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {208    val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")209    Box(210        Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))211            .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))212            .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))213            .clickable { onToggle(!on) },214    ) {215        Box(216            Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)217                .padding(start = knob - 2.dp)218                .size(14.dp).clip(CircleShape)219                .background(if (on) fg else fg.copy(alpha = 0.58f)),220        )221    }222}223224@Composable225private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {226    Box(227        Modifier.clip(RoundedCornerShape(999.dp))228            .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))229            .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)230            .clickable(onClick = onClick)231            .padding(horizontal = 12.dp, vertical = 5.dp),232    ) {233        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)234    }235}236237@Composable238private fun ProBadge(fg: Color) {239    Box(240        Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))241            .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),242    ) {243        Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)244    }245}246247@Composable248private fun Hint(text: String, fg: Color) {249    Text(250        text,251        modifier = Modifier.padding(top = 6.dp),252        color = fg.copy(alpha = 0.6f),253        fontFamily = PeachType.Display,254        fontStyle = FontStyle.Italic,255        fontSize = 11.5.sp,256        lineHeight = 16.sp,257    )258}259260/* ──────────────────────────────  Appearance  ─────────────────────────────── */261262@OptIn(ExperimentalLayoutApi::class)263@Composable264private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {265    SubLabel("ACCENT", fg, top = 0.dp)266    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {267        ACCENT_COLORS.forEach { (name, color) ->268            Box(269                Modifier.size(22.dp).clip(CircleShape).background(color)270                    .border(271                        if (s.accentColor == name) 2.dp else 1.dp,272                        if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),273                        CircleShape,274                    )275                    .clickable { vm.setAccent(name) },276            )277        }278    }279    SubLabel("TEXT SIZE", fg)280    RowLine(fg) {281        Name("Text size", fg)282        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {283            Pill("small", s.textSize == "small", fg) { vm.setTextSize("small") }284            Pill("medium", s.textSize == "medium", fg) { vm.setTextSize("medium") }285            Pill("large", s.textSize == "large", fg) { vm.setTextSize("large") }286        }287    }288    SubLabel("ICONS", fg)289    RowLine(fg) {290        Name("Site icons", fg)291        SubtleButton(if (s.faviconsEnabled) "On" else "Off", fg) { vm.setFaviconsEnabled(!s.faviconsEnabled) }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("Allow screenshots", fg)310        Toggle(s.allowScreenshots, fg) { vm.setAllowScreenshots(it) }311    }312    RowLine(fg) {313        Name("Auto-lock after", fg)314        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)315        SubtleButton(lockOptions[idx].second, fg) {316            val next = lockOptions[(idx + 1) % lockOptions.size].first317            vm.setAutoLockMinutes(if (next == 0) 0 else next)318        }319    }320    SubLabel("BIOMETRICS", fg)321    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity322    RowLine(fg) {323        Name("Unlock with biometrics", fg)324        Toggle(s.biometricsEnabled, fg) { on ->325            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()326        }327    }328    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)329    if (bioError != null) {330        Text(331            bioError,332            color = com.peachpasswords.ui.theme.peachColors.Breach,333            fontFamily = PeachType.Mono, fontSize = 10.sp,334            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),335        )336    }337    SubLabel("AUTOFILL", fg)338    run {339        // Read live rather than cached: the user leaves for system settings and340        // comes back, so a remembered value would show the old answer.341        val ctx = LocalContext.current342        val enabled = AutofillEnablement.isEnabled(ctx)343        RowLine(fg) {344            Column(Modifier.weight(1f)) {345                Text("Fill passwords in other apps", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)346                Text(347                    if (enabled) {348                        "Peach is your autofill service."349                    } else {350                        "Android decides which app fills passwords. Turn Peach on in system settings."351                    },352                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,353                    modifier = Modifier.padding(top = 2.dp),354                )355            }356            if (!enabled) {357                SubtleButton("enable", fg) {358                    // Straight to the autofill picker with Peach preselected;359                    // some OEM builds ship no handler, so fall back rather than360                    // dead-ending on a button that does nothing.361                    runCatching { ctx.startActivity(AutofillEnablement.requestIntent(ctx)) }362                        .onFailure { runCatching { ctx.startActivity(AutofillEnablement.fallbackIntent()) } }363                }364            } else {365                ValueText("on", fg)366            }367        }368    }369370    SubLabel("PASSKEYS", fg)371    RowLine(fg) {372        Column(Modifier.weight(1f)) {373            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)374            Text(375                "Peach can handle passkey sign-in and creation through Android Credential Manager.",376                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,377                modifier = Modifier.padding(top = 2.dp),378            )379        }380        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }381    }382    RowLine(fg) {383        Name("Status", fg)384        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)385    }386    SubLabel("RECOVERY", fg)387    RowLine(fg) {388        Column(Modifier.weight(1f)) {389            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)390            Text(391                "Keep the paper copy current before rotating sync identity or replacing devices.",392                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,393                modifier = Modifier.padding(top = 2.dp),394            )395        }396        SubtleButton("view", fg) {397            if (bioActivity != null) {398                com.peachpasswords.ui.lock.Biometrics.authenticate(399                    activity = bioActivity,400                    title = "View recovery words",401                    subtitle = "Confirm your identity to view your recovery words",402                    onSuccess = { onNavigate(PeachNav.RecoveryView) },403                )404            } else onNavigate(PeachNav.RecoveryView)405        }406    }407    SubLabel("BREACH PROTECTION", fg)408    val checkingBreaches by vm.checkingBreaches.collectAsState()409    val breachResult by vm.breachResult.collectAsState()410    RowLine(fg) {411        Name("Breach monitoring", fg)412        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }413    }414    RowLine(fg) {415        Name("Check all passwords", fg)416        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }417    }418    breachResult?.let { result ->419        RowLine(fg) {420            Name("Last check", fg)421            ValueText(result, fg)422        }423    }424425    SubLabel("MASTER PASSWORD", fg)426    ChangePasswordRow(fg, vm)427428    SubLabel("DURESS PASSWORD", fg)429    val duressIsPro by vm.isPro.collectAsState()430    if (!duressIsPro) {431        RowLine(fg) {432            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {433                Name("Duress password", fg); ProBadge(fg)434            }435            ValueText("off", fg)436        }437        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)438    } else {439        DuressSection(fg, vm)440    }441}442443@Composable444private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {445    var open by remember { mutableStateOf(false) }446    var current by remember { mutableStateOf("") }447    var next by remember { mutableStateOf("") }448    var confirm by remember { mutableStateOf("") }449    var error by remember { mutableStateOf<String?>(null) }450    var done by remember { mutableStateOf(false) }451    val scope = rememberCoroutineScope()452453    RowLine(fg) {454        Name("Master password", fg)455        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }456    }457    AnimatedVisibility(open) {458        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {459            PwField("current password", current, fg) { current = it }460            PwField("new password (min 12 chars)", next, fg) { next = it }461            PwField("confirm new password", confirm, fg) { confirm = it }462            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }463            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)464            SubtleButton("save new password", fg) {465                error = when {466                    current.isBlank() -> "enter your current password"467                    next.length < 12 -> "new password must be at least 12 characters"468                    next != confirm -> "new passwords do not match"469                    next == current -> "new password must differ from current"470                    else -> null471                }472                if (error == null) scope.launch {473                    if (vm.changePassword(current, next)) {474                        current = ""; next = ""; confirm = ""; open = false; done = true475                    } else error = "incorrect current password"476                }477            }478        }479    }480}481482@Composable483private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {484    PeachField(485        label = placeholder,486        value = value,487        onValueChange = onChange,488        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,489        visualTransformation = PasswordVisualTransformation(),490    )491}492493/* ────────────────────────────────  Vault  ───────────────────────────────── */494495@Composable496private fun UpdatesRows(fg: Color, onNavigate: (PeachNav) -> Unit) {497    val vm: UpdateViewModel = hiltViewModel()498    val available by vm.available.collectAsState()499    val state by vm.state.collectAsState()500501    RowLine(fg) {502        Name("Version", fg)503        ValueText(BuildConfig.VERSION_NAME, fg)504    }505    RowLine(fg) {506        Column(Modifier.weight(1f)) {507            Text("Updates", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)508            Text(509                when {510                    available != null -> "v${available?.version} is available"511                    state.phase == UpdatePhase.Checking -> "Checking…"512                    state.phase == UpdatePhase.UpToDate -> "You're on the latest version"513                    state.phase == UpdatePhase.Failed -> "Couldn't reach the update server"514                    else -> "Peach checks once a day and tells you when there's a new version."515                },516                color = fg.copy(alpha = 0.7f),517                fontFamily = PeachType.Body,518                fontSize = 11.sp,519                lineHeight = 16.sp,520                modifier = Modifier.padding(top = 2.dp),521            )522        }523        if (available != null) {524            SubtleButton("tap to install", fg) { onNavigate(PeachNav.Update) }525        } else {526            SubtleButton(if (state.phase == UpdatePhase.Checking) "checking" else "check for updates", fg) {527                vm.check()528            }529        }530    }531}532533@Composable534private fun VaultBody(535    fg: Color,536    vm: SettingsViewModel,537    s: VaultSettings,538    entriesCount: Int,539    onNavigate: (PeachNav) -> Unit,540) {541    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")542    val current = s.trashRetentionDays ?: 0543    val isPro by vm.isPro.collectAsState()544    val dedupCount by vm.dedupCount.collectAsState()545    val dedupRunning by vm.dedupRunning.collectAsState()546    val dedupDone by vm.dedupDone.collectAsState()547    val history by vm.vaultHistory.collectAsState()548    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()549550    SubLabel("ENTRIES", fg, top = 0.dp)551    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }552    RowLine(fg) {553        Name("Duplicates", fg)554        val done = dedupDone555        if (done != null) {556            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)557        } else {558            val count = dedupCount559            val label = when {560                dedupRunning -> "scanning..."561                count == null -> "scan"562                count == 0 -> "none found"563                else -> "$count found"564            }565            SubtleButton(label, fg) {566                if (count == null || count == 0) vm.scanDuplicates()567            }568        }569    }570    if ((dedupCount ?: 0) > 0 && dedupDone == null) {571        Column(572            Modifier.fillMaxWidth()573                .padding(top = 2.dp, bottom = 8.dp)574                .clip(RoundedCornerShape(8.dp))575                .background(fg.copy(alpha = 0.08f))576                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))577                .padding(10.dp),578            verticalArrangement = Arrangement.spacedBy(8.dp),579        ) {580            val count = dedupCount ?: 0581            Text(582                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",583                color = fg.copy(alpha = 0.82f),584                fontFamily = PeachType.Body,585                fontSize = 11.sp,586                lineHeight = 16.sp,587            )588            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {589                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }590                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }591            }592        }593    }594595    SubLabel("MAINTENANCE", fg)596    RowLine(fg) {597        Name("Trash auto-delete", fg)598        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)599        SubtleButton(trashOptions[idx].second, fg) {600            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)601        }602    }603    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }604    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }605606    SubLabel("DATA", fg)607    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }608    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }609    RowLine(fg) {610        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }611        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }612    }613    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }614615    var historyShowAll by remember { mutableStateOf(false) }616    SubLabel("UPDATES", fg)617    UpdatesRows(fg, onNavigate)618619    SubLabel("VAULT HISTORY", fg)620    if (history.isEmpty()) {621        Text(622            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",623            color = fg.copy(alpha = 0.68f),624            fontFamily = PeachType.Body,625            fontSize = 11.sp,626            lineHeight = 16.sp,627            modifier = Modifier.padding(bottom = 6.dp),628        )629    } else {630        Text(631            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",632            color = fg.copy(alpha = 0.68f),633            fontFamily = PeachType.Body,634            fontSize = 11.sp,635            lineHeight = 16.sp,636            modifier = Modifier.padding(bottom = 4.dp),637        )638        history.take(if (historyShowAll) history.size else 3).forEach { snap ->639            RowLine(fg) {640                Column(Modifier.weight(1f)) {641                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)642                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)643                }644                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {645                    vm.restoreVaultSnapshot(snap.id)646                }647            }648        }649        if (history.size > 3) {650            RowLine(fg) {651                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)652                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }653            }654        }655        Text(656            "${history.size} of 5 snapshots",657            color = fg.copy(alpha = 0.58f),658            fontFamily = PeachType.Mono,659            fontSize = 10.sp,660            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),661        )662    }663664    var advancedOpen by remember { mutableStateOf(false) }665    SubLabel("ADVANCED", fg)666    RowLine(fg) {667        Name("Advanced", fg)668        SubtleButton(if (advancedOpen) "hide" else "show", fg) { advancedOpen = !advancedOpen }669    }670    if (advancedOpen) {671        RowLine(fg) {672            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)673            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }674        }675        RowLine(fg) {676            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)677            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }678        }679    }680}681682private fun snapshotSubLabel(snapshot: VaultSnapshot): String {683    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }684    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")685}686687private fun snapshotReasonLabel(reason: String): String = when (reason) {688    "local_save" -> "saved"689    "sync_received" -> "synced"690    "import" -> "imported"691    "restore" -> "restored"692    else -> reason693}694695private fun snapshotTimeLabel(savedAt: Long): String {696    val diff = System.currentTimeMillis() - savedAt697    if (diff < 60_000) return "Just now"698    if (diff < 3_600_000) return "${diff / 60_000}m ago"699    val date = Date(savedAt)700    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())701    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)702    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)703    if (today == thenDay) return "Today $time"704    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))705    if (yesterday == thenDay) return "Yesterday $time"706    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)707}708709/* ────────────────────────────────  Sync  ────────────────────────────────── */710711@Composable712private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {713    val context = LocalContext.current714    val syncVm: SyncViewModel = hiltViewModel()715    val pairedDevices by syncVm.pairedDevices.collectAsState()716    val pendingVouched by syncVm.pendingVouched.collectAsState()717    val syncStatus by syncVm.status.collectAsState()718    val configuredRelayUrl by syncVm.privateRelayUrl.collectAsState()719    val syncMode by syncVm.syncMode.collectAsState()720    val backgroundSyncEnabled by syncVm.backgroundSyncEnabled.collectAsState()721    var notificationsAvailable by remember {722        mutableStateOf(canShowBackgroundSyncNotification(context))723    }724    var showBackgroundSyncPrompt by remember { mutableStateOf(false) }725    val scope = rememberCoroutineScope()726    var confirmUnpair by remember { mutableStateOf<String?>(null) }727    var rotateConfirmOpen by remember { mutableStateOf(false) }728    var rotating by remember { mutableStateOf(false) }729    var rotateError by remember { mutableStateOf<String?>(null) }730    var relayUrlDraft by remember(configuredRelayUrl) {731        mutableStateOf(privateRelayDraftOf(configuredRelayUrl))732    }733    var relayUrlStatus by remember { mutableStateOf<String?>(null) }734    var showConnection by remember { mutableStateOf(false) }735    var showRecovery by remember { mutableStateOf(false) }736737    SubLabel("ADD A DEVICE", fg, top = 0.dp)738    RowLine(fg) {739        Column(Modifier.weight(1f)) {740            Text("Pair a device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)741            Text(742                "Either scan a QR shown on the other device, or show this device's QR for the other one to scan.",743                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,744                modifier = Modifier.padding(top = 2.dp),745            )746        }747        // "Scan" opens the camera-driven AdoptVault flow: the phone is the748        // receiver. "Show a code" opens CodePair: the phone is the source.749        // Both are valid pairing entry points; without scan, a phone that wants750        // to join an existing browser-only vault has no path.751        SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }752        Spacer(Modifier.width(PeachSpacing.xs))753        SubtleButton("show code", fg) { onNavigate(PeachNav.CodePair) }754    }755756    SubLabel("SYNC STATUS", fg)757    val indicator = syncIndicator(syncStatus, pairedDevices.size)758    RowLine(fg) {759        SyncIndicatorDot(760            indicator = indicator,761            label = syncIndicatorLabel(indicator, syncStatus),762            modifier = Modifier.padding(end = PeachSpacing.sm),763            size = 8.dp,764        )765        Text(766            describeSyncOutcome(syncStatus),767            color = fg.copy(alpha = 0.7f),768            fontFamily = PeachType.Body,769            fontSize = 11.sp,770            lineHeight = 16.sp,771            modifier = Modifier.weight(1f),772        )773        SubtleButton(if (syncStatus.syncing) "syncing..." else "sync now", fg) {774            if (!syncStatus.syncing) syncVm.syncNow()775        }776    }777778    SubLabel("PAIRED DEVICES", fg)779    if (pairedDevices.isEmpty()) {780        PeachEmptyOrEndState(781            message = "No paired devices yet.",782            detail = "Pair a nearby phone, tablet, or browser when you're ready to sync.",783            modifier = Modifier.padding(top = PeachSpacing.xs),784        )785    } else {786        pairedDevices.forEach { d ->787            RowLine(fg) {788                Column(Modifier.weight(1f)) {789                    Text(d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)790                    Text(791                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",792                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,793                        modifier = Modifier.padding(top = 2.dp),794                    )795                }796                if (confirmUnpair != d.deviceId) {797                    SubtleButton("remove", fg) { confirmUnpair = d.deviceId }798                }799            }800            // HOLE 4: revocation stops this device receiving future changes. It801            // does NOT secure the vault against it — that device may already802            // hold the recovery words, which are master-password-equivalent and803            // restore the whole vault anywhere, forever, with no sync involved.804            // Say so here rather than leaving the user falsely reassured.805            if (confirmUnpair == d.deviceId) {806                Column(Modifier.fillMaxWidth().padding(bottom = PeachSpacing.sm)) {807                    Text(808                        "Stops this device receiving future changes. It doesn't lock it " +809                            "out of what it already has - if it's lost or stolen, also " +810                            "change your master password and generate new recovery words.",811                        color = fg.copy(alpha = 0.7f),812                        fontFamily = PeachType.Body,813                        fontSize = 11.sp,814                        lineHeight = 16.sp,815                    )816                    Row(817                        modifier = Modifier.fillMaxWidth().padding(top = PeachSpacing.sm),818                        horizontalArrangement = Arrangement.End,819                    ) {820                        SubtleButton("cancel", fg) { confirmUnpair = null }821                        Spacer(Modifier.width(PeachSpacing.sm))822                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }823                    }824                }825            }826        }827    }828829    SyncDisclosure(830        title = "Connection",831        summary = "Background sync, relay, and privacy choices",832        expanded = showConnection,833        fg = fg,834        onToggle = { showConnection = !showConnection },835    )836    if (showConnection) {837        RowLine(fg) {838            Column(Modifier.weight(1f)) {839                Text("Background sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)840                Text(841                    when {842                        backgroundSyncEnabled && !notificationsAvailable ->843                            "Action needed — Android notifications are off, so background sync is not visible."844                        backgroundSyncEnabled ->845                            "On — keeps this phone reachable for paired devices."846                        else ->847                            "Off — Peach syncs only while you are using the app."848                    },849                    color = fg.copy(alpha = 0.7f),850                    fontFamily = PeachType.Body,851                    fontSize = 11.sp,852                    lineHeight = 16.sp,853                    modifier = Modifier.padding(top = 2.dp),854                )855            }856            SubtleButton(857                if (backgroundSyncEnabled && !notificationsAvailable) "allow" else "change",858                if (backgroundSyncEnabled && !notificationsAvailable) peachColors.Breach else fg,859            ) { showBackgroundSyncPrompt = true }860        }861        SyncModeRow(862            title = "Public relay",863            detail = "Works anywhere with nothing to set up. The relay cannot read your vault.",864            selected = syncMode == SyncMode.PUBLIC,865            fg = fg,866        ) { syncVm.setSyncMode(SyncMode.PUBLIC) }867        SyncModeRow(868            title = "Private relay",869            detail = "Use your own peach-relay on your own domain.",870            selected = syncMode == SyncMode.PRIVATE,871            fg = fg,872        ) { syncVm.setSyncMode(SyncMode.PRIVATE) }873874        if (syncMode == SyncMode.PRIVATE) {875            Text(876                "RELAY URL",877                color = fg.copy(alpha = 0.6f),878                fontFamily = PeachType.Mono,879                fontSize = 8.sp,880                letterSpacing = 0.22.em,881                modifier = Modifier.padding(top = 8.dp),882            )883            Box(884                Modifier.fillMaxWidth().padding(top = 6.dp)885                    .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))886                    .padding(horizontal = 12.dp, vertical = 10.dp),887            ) {888                BasicTextField(889                    value = relayUrlDraft,890                    onValueChange = { relayUrlDraft = it; relayUrlStatus = null },891                    singleLine = true,892                    textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp, color = fg),893                    cursorBrush = SolidColor(fg),894                    modifier = Modifier.fillMaxWidth(),895                )896            }897            val needsRelayUrl = configuredRelayUrl.isEmpty()898            RowLine(fg) {899                val message = relayUrlStatus900                    ?: if (needsRelayUrl) {901                        "Sync is paused until you enter your relay URL."902                    } else {903                        "Only secure wss:// relays are accepted."904                    }905                val warn = relayUrlStatus?.startsWith("Use") == true ||906                    (relayUrlStatus == null && needsRelayUrl)907                ValueText(message, if (warn) peachColors.Breach else fg)908                SubtleButton("save", fg) {909                    relayUrlStatus = if (syncVm.setRelayUrl(relayUrlDraft)) {910                        relayUrlDraft = privateRelayDraftOf(syncVm.privateRelayUrl.value)911                        "Saved"912                    } else {913                        "Use a valid wss:// relay URL"914                    }915                }916            }917        }918919        SyncModeRow(920            title = "No sync",921            detail = "Keep this device separate and move backups by hand.",922            selected = syncMode == SyncMode.OFF,923            fg = fg,924        ) { syncVm.setSyncMode(SyncMode.OFF) }925        Hint("Pairing authorizes a device, not a cloud account.", fg)926    }927928    if (pendingVouched.isNotEmpty()) {929        SubLabel("PENDING DEVICES", fg)930        pendingVouched.forEach { dev ->931            RowLine(fg) {932                Column(Modifier.weight(1f)) {933                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)934                    Text(935                        "Was added by another device. Allow it to sync?",936                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,937                        modifier = Modifier.padding(top = 2.dp),938                    )939                }940                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {941                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }942                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }943                }944            }945        }946    }947948    SyncDisclosure(949        title = "Recovery & security",950        summary = "For a lost or stolen device",951        expanded = showRecovery,952        fg = fg,953        onToggle = { showRecovery = !showRecovery },954    )955    if (showRecovery) {956        RowLine(fg) {957            Column(Modifier.weight(1f)) {958                Text("Re-pair this device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)959                Text(960                    "Scan only when this populated vault previously trusted the source device.",961                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,962                    modifier = Modifier.padding(top = 2.dp),963                )964            }965            SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }966        }967        if (rotateConfirmOpen) {968            Hint("This disconnects every paired device and changes your 12 recovery words. You'll be shown the new words next.", peachColors.Breach)969            rotateError?.let {970                Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))971            }972            Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {973                SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }974                SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {975                    if (rotating) return@SubtleButton976                    rotating = true977                    rotateError = null978                    scope.launch {979                        val ok = syncVm.rotateSyncIdentity()980                        rotating = false981                        if (ok) {982                            rotateConfirmOpen = false983                            onNavigate(PeachNav.RecoverySetup)984                        } else {985                            rotateError = "Rotation failed. Unlock your real vault and try again."986                        }987                    }988                }989            }990        } else {991            RowLine(fg) {992                Column(Modifier.weight(1f)) {993                    Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)994                    Text(995                        "Disconnects every device and replaces the keys used for sync.",996                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,997                        modifier = Modifier.padding(top = 2.dp),998                    )999                }1000                SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }1001            }1002        }1003    }10041005    if (showBackgroundSyncPrompt) {1006        BackgroundSyncDialog { enabled ->1007            showBackgroundSyncPrompt = false1008            notificationsAvailable = canShowBackgroundSyncNotification(context)1009            syncVm.setBackgroundSyncEnabled(enabled)1010        }1011    }1012}10131014private fun deviceTypeLabel(type: String?): String = when (type) {1015    "android" -> "Android"1016    "phone" -> "Phone"1017    "tablet" -> "Tablet"1018    "browser" -> "Browser"1019    else -> "Device"1020}10211022private fun syncTimeLabel(lastSyncedAt: Long?): String {1023    if (lastSyncedAt == null) return "never synced"1024    val diff = System.currentTimeMillis() - lastSyncedAt1025    if (diff < 60_000) return "just now"1026    if (diff < 3_600_000) return "${diff / 60_000}m ago"1027    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"1028    return "${diff / 86_400_000}d ago"1029}10301031private fun isSyncStale(lastSyncedAt: Long?): Boolean =1032    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L10331034/* ────────────────────────────────  Pro  ─────────────────────────────────── */10351036@Composable1037private fun ProBody(fg: Color, vm: SettingsViewModel) {1038    val ctx = LocalContext.current1039    val isPro by vm.isPro.collectAsState()1040    if (isPro) {1041        ProActiveBody(fg, vm)1042        return1043    }1044    val features = listOf(1045        "Peach Sync" to "End-to-end encrypted",1046        "Peach Codex" to "Restore from paper",1047        "Passkeys" to "Zero-knowledge WebAuthn",1048        "Advanced Vault Health" to "Reuse · age · exposure",1049        "Canary entries" to "Detects vault compromise",1050        "Duress vault" to "Decoy under coercion",1051    )1052    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1053    Text(1054        "Everything, everywhere.",1055        modifier = Modifier.padding(top = 8.dp),1056        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,1057    )1058    Text(1059        "One key unlocks every Pro feature — for the lifetime of the app.",1060        modifier = Modifier.padding(top = 6.dp),1061        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,1062    )1063    Spacer(Modifier.height(10.dp))1064    features.forEachIndexed { i, (name, desc) ->1065        // Compact rows (6dp vs. the shared 9dp default) — this card is the1066        // tallest in the deck (6 features + price + CTA) and used to leave1067        // its button with no breathing room before the fanned tab stacked1068        // right beneath it in preview mode.1069        RowLine(fg, verticalPadding = 6.dp) {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(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1075        }1076    }1077    Spacer(Modifier.height(12.dp))1078    Text(1079        "$39",1080        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,1081    )1082    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)1083    Spacer(Modifier.height(10.dp))1084    Box(1085        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1086            .background(fg.copy(alpha = 0.16f))1087            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1088            .clickable {1089                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }1090            }1091            .padding(vertical = 12.dp),1092        contentAlignment = Alignment.Center,1093    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }10941095    // Trailing breathing room so the button clears the fanned tab stacked1096    // beneath this card in preview mode, where the scrollable viewport clips1097    // right around here (the license-key section below is already out of1098    // view at that height).1099    Spacer(Modifier.height(44.dp))11001101    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1102    var key by remember { mutableStateOf("") }1103    val activating by vm.activating.collectAsState()1104    val activationError by vm.activationError.collectAsState()1105    Box(1106        Modifier.fillMaxWidth().padding(top = 6.dp)1107            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1108            .padding(horizontal = 12.dp, vertical = 10.dp),1109    ) {1110        BasicTextField(1111            value = key,1112            // NOT .uppercase() — base58 (the license payload encoding) is1113            // case-sensitive; forcing the whole string to uppercase silently1114            // corrupted every real key before it ever reached signature1115            // verification, so activation always failed with a real key.1116            onValueChange = { key = it; vm.clearActivationError() },1117            singleLine = true,1118            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),1119            cursorBrush = SolidColor(fg),1120            modifier = Modifier.fillMaxWidth(),1121            decorationBox = { inner ->1122                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)1123                inner()1124            },1125        )1126    }1127    if (activationError != null) {1128        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))1129    }1130    Spacer(Modifier.height(8.dp))1131    Box(1132        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1133            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))1134            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1135            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }1136            .padding(vertical = 12.dp),1137        contentAlignment = Alignment.Center,1138    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }1139}11401141@Composable1142private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {1143    val ctx = LocalContext.current1144    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")1145    val licenseKey by vm.licenseKey.collectAsState()1146    val issuedAt by vm.licenseIssuedAt.collectAsState()1147    var showKey by remember { mutableStateOf(false) }1148    var copied by remember { mutableStateOf(false) }1149    val scope = rememberCoroutineScope()1150    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {1151        com.peachpasswords.ui.components.PeachMark(size = 60.dp)1152    }1153    Text(1154        "Peach Pro",1155        modifier = Modifier.fillMaxWidth(),1156        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,1157        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1158    )1159    Text(1160        formatLicenseActiveSince(issuedAt),1161        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),1162        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,1163        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1164    )1165    licenseKey?.let { key ->1166        Spacer(Modifier.height(12.dp))1167        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1168        RowLine(fg) {1169            Text(1170                if (showKey) key else "************************",1171                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),1172                fontFamily = PeachType.Mono,1173                fontSize = 10.sp,1174                modifier = Modifier.weight(1f),1175            )1176            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1177                SubtleButton(if (copied) "copied" else "copy", fg) {1178                    PeachClipboard.copy(ctx, "peach license", key)1179                    copied = true1180                    scope.launch {1181                        delay(1_500)1182                        copied = false1183                    }1184                }1185                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }1186            }1187        }1188    }1189    Spacer(Modifier.height(12.dp))1190    features.forEachIndexed { i, name ->1191        RowLine(fg) {1192            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1193                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1194                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1195            }1196            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1197        }1198    }1199    Spacer(Modifier.height(12.dp))1200    Box(1201        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1202            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1203            .clickable { vm.deactivate() }1204            .padding(vertical = 12.dp),1205        contentAlignment = Alignment.Center,1206    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }1207}12081209private fun formatLicenseActiveSince(issuedAt: Long?): String {1210    if (issuedAt == null) return "Active"1211    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))1212    return "Active since $monthYear"1213}12141215/* ──────────────────────────────  Feedback  ───────────────────────────────── */12161217@OptIn(ExperimentalLayoutApi::class)1218@Composable1219private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {1220    val categories = listOf("Bug report", "Feature request", "Question", "Other")1221    var category by remember { mutableStateOf(categories[0]) }1222    var message by remember { mutableStateOf("") }1223    val state by vm.feedbackState.collectAsState()12241225    // Reset transient state when the card leaves composition so reopening starts fresh.1226    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }12271228    if (state is FeedbackState.Sent) {1229        Box(1230            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))1231                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),1232        ) {1233            Column {1234                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)1235                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))1236            }1237        }1238        return1239    }12401241    val sending = state is FeedbackState.Sending12421243    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)1244    SubLabel("TYPE", fg)1245    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1246        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }1247    }1248    SubLabel("MESSAGE", fg)1249    Box(1250        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))1251            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))1252            .padding(10.dp),1253    ) {1254        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)1255        BasicTextField(1256            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },1257            enabled = !sending,1258            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),1259            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),1260        )1261    }1262    Text(1263        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",1264        modifier = Modifier.padding(top = 6.dp),1265        color = fg.copy(alpha = 0.52f),1266        fontFamily = PeachType.Mono,1267        fontSize = 10.sp,1268        lineHeight = 14.sp,1269    )1270    Spacer(Modifier.height(8.dp))12711272    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1273        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1274        Box(1275            Modifier.clip(RoundedCornerShape(8.dp))1276                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1277                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1278                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1279                .padding(horizontal = 12.dp, vertical = 6.dp),1280        ) {1281            Text(1282                feedbackSubmitLabel(state),1283                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1284                fontFamily = PeachType.Mono, fontSize = 11.sp,1285            )1286        }1287        if (sending) {1288            CircularProgressIndicator(1289                color = LocalPeachAccent.current,1290                strokeWidth = 2.dp,1291                modifier = Modifier.size(16.dp),1292            )1293        }1294    }12951296    (state as? FeedbackState.Error)?.let { err ->1297        Text(1298            err.message,1299            modifier = Modifier.padding(top = 8.dp),1300            color = peachColors.Breach,1301            fontFamily = PeachType.Mono,1302            fontSize = 11.sp,1303            lineHeight = 15.sp,1304        )1305    }13061307    Hint("Sent anonymously · no account required", fg)1308}13091310/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */13111312@Composable1313internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1314    val configured by vm.duressConfigured.collectAsState()1315    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1316}13171318@Composable1319private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1320    Text(1321        "Duress password is active",1322        color = peachColors.HealthOk,1323        fontFamily = PeachType.Mono,1324        fontSize = 11.sp,1325        modifier = Modifier.padding(top = 6.dp),1326    )1327    Spacer(Modifier.height(8.dp))1328    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1329    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1330}13311332@Composable1333private fun DuressForm(fg: Color, vm: SettingsViewModel) {1334    var enabled by remember { mutableStateOf(false) }1335    var password by remember { mutableStateOf("") }1336    var confirm by remember { mutableStateOf("") }1337    var action by remember { mutableStateOf(DuressAction.DECOY) }1338    var error by remember { mutableStateOf<String?>(null) }1339    val scope = rememberCoroutineScope()13401341    RowLine(fg) {1342        Name("Duress password", fg)1343        Toggle(enabled, fg) { on ->1344            enabled = on1345            if (!on) { password = ""; confirm = ""; error = null }1346        }1347    }1348    Text(1349        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1350        color = fg.copy(alpha = 0.7f),1351        fontFamily = PeachType.Mono,1352        fontSize = 10.sp,1353        modifier = Modifier.padding(top = 6.dp),1354    )13551356    AnimatedVisibility(enabled) {1357        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1358            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1359            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }13601361            Text(1362                "When your duress password is entered at the lock screen, Peach will:",1363                color = fg.copy(alpha = 0.7f),1364                fontFamily = PeachType.Mono,1365                fontSize = 10.sp,1366                modifier = Modifier.padding(top = 4.dp),1367            )13681369            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1370            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }13711372            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }13731374            val canSave = password.isNotBlank() && confirm.isNotBlank()1375            DuressSaveButton("Save duress password", fg, canSave) {1376                error = when {1377                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1378                    password != confirm -> "Passwords do not match"1379                    else -> null1380                }1381                if (error == null) scope.launch {1382                    if (vm.saveDuress(password, action)) {1383                        password = ""; confirm = ""; enabled = false1384                    } else {1385                        error = "Couldn't save — the duress passphrase must differ from your real password"1386                    }1387                }1388            }1389        }1390    }1391}13921393@Composable1394private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1395    val accent = LocalPeachAccent.current1396    Row(1397        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1398        verticalAlignment = Alignment.CenterVertically,1399        horizontalArrangement = Arrangement.spacedBy(10.dp),1400    ) {1401        Box(1402            Modifier.size(16.dp).clip(CircleShape)1403                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1404            contentAlignment = Alignment.Center,1405        ) {1406            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1407        }1408        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1409    }1410}14111412@Composable1413private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1414    val accent = LocalPeachAccent.current1415    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1416    Box(1417        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1418            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1419            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1420            .let { if (enabled) it.clickable(onClick = onClick) else it }1421            .padding(vertical = 11.dp),1422        contentAlignment = Alignment.Center,1423    ) {1424        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1425    }1426}14271428@Composable1429private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1430    Box(1431        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1432            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1433            .clickable(onClick = onClick)1434            .padding(vertical = 11.dp),1435        contentAlignment = Alignment.Center,1436    ) {1437        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1438    }1439}14401441/** One choice in the three-way sync selector. */1442@Composable1443private fun SyncModeRow(1444    title: String,1445    detail: String,1446    selected: Boolean,1447    fg: Color,1448    onSelect: () -> Unit,1449) {1450    RowLine(fg, Modifier.clickable(onClick = onSelect)) {1451        Column(Modifier.weight(1f)) {1452            Text(title, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1453            Text(1454                detail,1455                color = fg.copy(alpha = 0.7f),1456                fontFamily = PeachType.Body,1457                fontSize = 11.sp,1458                lineHeight = 16.sp,1459                modifier = Modifier.padding(top = 2.dp),1460            )1461        }1462        Text(1463            if (selected) "●" else "○",1464            color = if (selected) fg else fg.copy(alpha = 0.45f),1465            fontFamily = PeachType.Mono,1466            fontSize = 14.sp,1467            modifier = Modifier.padding(start = 10.dp),1468        )1469    }1470}