SettingsCardBodies.kt

59.4 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.SyncMode34import com.peachpasswords.sync.describeSyncOutcome35import com.peachpasswords.sync.syncIndicator36import com.peachpasswords.sync.syncIndicatorLabel37import com.peachpasswords.ui.components.SyncIndicatorDot38import com.peachpasswords.ui.theme.LocalPeachAccent39import com.peachpasswords.vault.DuressAction40import com.peachpasswords.ui.theme.peachColors41import androidx.compose.runtime.mutableStateOf42import androidx.compose.runtime.remember43import androidx.compose.runtime.rememberCoroutineScope44import androidx.compose.runtime.setValue45import androidx.compose.ui.Alignment46import androidx.compose.ui.Modifier47import androidx.compose.ui.draw.clip48import androidx.compose.ui.graphics.Color49import androidx.compose.ui.graphics.SolidColor50import androidx.compose.ui.platform.LocalContext51import androidx.compose.ui.text.TextStyle52import androidx.compose.ui.text.font.FontStyle53import androidx.compose.ui.text.input.PasswordVisualTransformation54import androidx.compose.ui.unit.Dp55import androidx.compose.ui.unit.dp56import androidx.compose.ui.unit.em57import androidx.compose.ui.unit.sp58import androidx.compose.material3.Text59import com.peachpasswords.BuildConfig60import com.peachpasswords.autofill.AutofillEnablement61import com.peachpasswords.ui.PeachNav62import com.peachpasswords.ui.components.PeachEmptyOrEndState63import com.peachpasswords.ui.components.PeachField64import com.peachpasswords.ui.sync.SyncViewModel65import com.peachpasswords.ui.theme.ACCENT_COLORS66import com.peachpasswords.ui.theme.PeachSpacing67import com.peachpasswords.ui.theme.PeachType68import com.peachpasswords.ui.updates.UpdatePhase69import com.peachpasswords.ui.updates.UpdateViewModel70import androidx.hilt.navigation.compose.hiltViewModel71import com.peachpasswords.vault.VaultSettings72import com.peachpasswords.vault.VaultSnapshot73import kotlinx.coroutines.launch74import kotlinx.coroutines.delay75import java.text.SimpleDateFormat76import java.util.Date77import java.util.Locale7879private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"8081/**82 * Body content for the active stack card. Everything is tinted with the card's83 * own foreground [fg] (the browser's `currentColor` convention), so each card's84 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,85 * canary, license activation) render their browser visual but defer the action86 * to a later phase — noted inline where that's the case.87 */88@Composable89fun CardBody(90    id: CardId,91    fg: Color,92    vm: SettingsViewModel,93    settings: VaultSettings,94    entriesCount: Int,95    onNavigate: (PeachNav) -> Unit,96) {97    when (id) {98        CardId.Appearance -> AppearanceBody(fg, vm, settings)99        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)100        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)101        CardId.Sync -> SyncBody(fg, onNavigate)102        CardId.Pro -> ProBody(fg, vm)103        CardId.Feedback -> {104            // The closest thing Peach has to an About surface, and where the brief105            // put the update entry point: version first, then the feedback form.106            AboutUpdatesBody(fg, onNavigate)107            FeedbackBody(fg, vm)108        }109    }110}111112/* ────────────────────────────  about / updates  ─────────────────────────── */113114@Composable115private fun AboutUpdatesBody(fg: Color, onNavigate: (PeachNav) -> Unit) {116    val vm: UpdateViewModel = hiltViewModel()117    val available by vm.available.collectAsState()118    val state by vm.state.collectAsState()119120    SubLabel("THIS BUILD", fg, top = 0.dp)121    RowLine(fg) {122        Name("Version", fg)123        ValueText(BuildConfig.VERSION_NAME, fg)124    }125    RowLine(fg) {126        Column(Modifier.weight(1f)) {127            Text("Updates", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)128            Text(129                when {130                    available != null -> "v${available?.version} is available"131                    state.phase == UpdatePhase.Checking -> "Checking…"132                    state.phase == UpdatePhase.UpToDate -> "You're on the latest version"133                    state.phase == UpdatePhase.Failed -> "Couldn't reach the update server"134                    else -> "Peach checks once a day and tells you when there's a new version."135                },136                color = fg.copy(alpha = 0.7f),137                fontFamily = PeachType.Body,138                fontSize = 11.sp,139                lineHeight = 16.sp,140                modifier = Modifier.padding(top = 2.dp),141            )142        }143        if (available != null) {144            SubtleButton("update", fg) { onNavigate(PeachNav.Update) }145        } else {146            SubtleButton(if (state.phase == UpdatePhase.Checking) "checking" else "check now", fg) {147                vm.check()148            }149        }150    }151}152153/* ─────────────────────────  shared row vocabulary  ───────────────────────── */154155@Composable156private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {157    Text(158        text,159        modifier = Modifier.padding(top = top, bottom = 4.dp),160        color = fg.copy(alpha = 0.58f),161        fontFamily = PeachType.Mono,162        fontSize = 8.sp,163        letterSpacing = 0.22.em,164    )165}166167@Composable168private fun RowLine(169    fg: Color,170    modifier: Modifier = Modifier,171    verticalPadding: Dp = 9.dp,172    content: @Composable RowScope.() -> Unit,173) {174    Row(175        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),176        verticalAlignment = Alignment.CenterVertically,177        horizontalArrangement = Arrangement.SpaceBetween,178        content = content,179    )180    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))181}182183@Composable184private fun RowScope.Name(text: String, fg: Color) {185    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))186}187188@Composable189private fun ValueText(text: String, fg: Color) {190    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp)191}192193@Composable194private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {195    Box(196        Modifier.clip(RoundedCornerShape(8.dp))197            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))198            .background(fg.copy(alpha = 0.08f))199            .clickable(onClick = onClick)200            .padding(horizontal = 12.dp, vertical = 6.dp),201    ) {202        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)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("MOTION", fg)280    RowLine(fg) {281        Name("Reduce motion", fg)282        SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }283    }284}285286/* ──────────────────────────────  Protection  ─────────────────────────────── */287288@Composable289private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings, onNavigate: (PeachNav) -> Unit) {290    val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")291    val current = s.autoLockMinutes ?: 0292293    SubLabel("LOCKING", fg, top = 0.dp)294    RowLine(fg) {295        Name("Auto-lock after", fg)296        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)297        SubtleButton(lockOptions[idx].second, fg) {298            val next = lockOptions[(idx + 1) % lockOptions.size].first299            vm.setAutoLockMinutes(if (next == 0) 0 else next)300        }301    }302    SubLabel("BIOMETRICS", fg)303    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity304    RowLine(fg) {305        Name("Unlock with biometrics", fg)306        Toggle(s.biometricsEnabled, fg) { on ->307            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()308        }309    }310    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)311    if (bioError != null) {312        Text(313            bioError,314            color = com.peachpasswords.ui.theme.peachColors.Breach,315            fontFamily = PeachType.Mono, fontSize = 10.sp,316            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),317        )318    }319    SubLabel("AUTOFILL", fg)320    run {321        // Read live rather than cached: the user leaves for system settings and322        // comes back, so a remembered value would show the old answer.323        val ctx = LocalContext.current324        val enabled = AutofillEnablement.isEnabled(ctx)325        RowLine(fg) {326            Column(Modifier.weight(1f)) {327                Text("Fill passwords in other apps", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)328                Text(329                    if (enabled) {330                        "Peach is your autofill service."331                    } else {332                        "Android decides which app fills passwords. Turn Peach on in system settings."333                    },334                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,335                    modifier = Modifier.padding(top = 2.dp),336                )337            }338            if (!enabled) {339                SubtleButton("enable", fg) {340                    // Straight to the autofill picker with Peach preselected;341                    // some OEM builds ship no handler, so fall back rather than342                    // dead-ending on a button that does nothing.343                    runCatching { ctx.startActivity(AutofillEnablement.requestIntent(ctx)) }344                        .onFailure { runCatching { ctx.startActivity(AutofillEnablement.fallbackIntent()) } }345                }346            } else {347                ValueText("on", fg)348            }349        }350    }351352    SubLabel("PASSKEYS", fg)353    RowLine(fg) {354        Column(Modifier.weight(1f)) {355            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)356            Text(357                "Peach can handle passkey sign-in and creation through Android Credential Manager.",358                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,359                modifier = Modifier.padding(top = 2.dp),360            )361        }362        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }363    }364    RowLine(fg) {365        Name("Status", fg)366        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)367    }368    SubLabel("RECOVERY", fg)369    RowLine(fg) {370        Column(Modifier.weight(1f)) {371            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)372            Text(373                "Keep the paper copy current before rotating sync identity or replacing devices.",374                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,375                modifier = Modifier.padding(top = 2.dp),376            )377        }378        SubtleButton("view", fg) { onNavigate(PeachNav.RecoveryView) }379    }380    SubLabel("BREACH PROTECTION", fg)381    val checkingBreaches by vm.checkingBreaches.collectAsState()382    val breachResult by vm.breachResult.collectAsState()383    RowLine(fg) {384        Name("Breach monitoring", fg)385        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }386    }387    RowLine(fg) {388        Name("Check all passwords", fg)389        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }390    }391    breachResult?.let { result ->392        RowLine(fg) {393            Name("Last check", fg)394            ValueText(result, fg)395        }396    }397398    SubLabel("MASTER PASSWORD", fg)399    ChangePasswordRow(fg, vm)400401    SubLabel("DURESS PASSWORD", fg)402    val duressIsPro by vm.isPro.collectAsState()403    if (!duressIsPro) {404        RowLine(fg) {405            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {406                Name("Duress password", fg); ProBadge(fg)407            }408            ValueText("off", fg)409        }410        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)411    } else {412        DuressSection(fg, vm)413    }414}415416@Composable417private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {418    var open by remember { mutableStateOf(false) }419    var current by remember { mutableStateOf("") }420    var next by remember { mutableStateOf("") }421    var confirm by remember { mutableStateOf("") }422    var error by remember { mutableStateOf<String?>(null) }423    var done by remember { mutableStateOf(false) }424    val scope = rememberCoroutineScope()425426    RowLine(fg) {427        Name("Master password", fg)428        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }429    }430    AnimatedVisibility(open) {431        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {432            PwField("current password", current, fg) { current = it }433            PwField("new password (min 12 chars)", next, fg) { next = it }434            PwField("confirm new password", confirm, fg) { confirm = it }435            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }436            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)437            SubtleButton("save new password", fg) {438                error = when {439                    current.isBlank() -> "enter your current password"440                    next.length < 12 -> "new password must be at least 12 characters"441                    next != confirm -> "new passwords do not match"442                    next == current -> "new password must differ from current"443                    else -> null444                }445                if (error == null) scope.launch {446                    if (vm.changePassword(current, next)) {447                        current = ""; next = ""; confirm = ""; open = false; done = true448                    } else error = "incorrect current password"449                }450            }451        }452    }453}454455@Composable456private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {457    PeachField(458        label = placeholder,459        value = value,460        onValueChange = onChange,461        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,462        visualTransformation = PasswordVisualTransformation(),463    )464}465466/* ────────────────────────────────  Vault  ───────────────────────────────── */467468@Composable469private fun VaultBody(470    fg: Color,471    vm: SettingsViewModel,472    s: VaultSettings,473    entriesCount: Int,474    onNavigate: (PeachNav) -> Unit,475) {476    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")477    val current = s.trashRetentionDays ?: 0478    val isPro by vm.isPro.collectAsState()479    val dedupCount by vm.dedupCount.collectAsState()480    val dedupRunning by vm.dedupRunning.collectAsState()481    val dedupDone by vm.dedupDone.collectAsState()482    val history by vm.vaultHistory.collectAsState()483    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()484485    SubLabel("ENTRIES", fg, top = 0.dp)486    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }487    RowLine(fg) {488        Name("Duplicates", fg)489        val done = dedupDone490        if (done != null) {491            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)492        } else {493            val count = dedupCount494            val label = when {495                dedupRunning -> "scanning..."496                count == null -> "scan"497                count == 0 -> "none found"498                else -> "$count found"499            }500            SubtleButton(label, fg) {501                if (count == null || count == 0) vm.scanDuplicates()502            }503        }504    }505    if ((dedupCount ?: 0) > 0 && dedupDone == null) {506        Column(507            Modifier.fillMaxWidth()508                .padding(top = 2.dp, bottom = 8.dp)509                .clip(RoundedCornerShape(8.dp))510                .background(fg.copy(alpha = 0.08f))511                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))512                .padding(10.dp),513            verticalArrangement = Arrangement.spacedBy(8.dp),514        ) {515            val count = dedupCount ?: 0516            Text(517                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",518                color = fg.copy(alpha = 0.82f),519                fontFamily = PeachType.Body,520                fontSize = 11.sp,521                lineHeight = 16.sp,522            )523            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {524                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }525                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }526            }527        }528    }529530    SubLabel("MAINTENANCE", fg)531    RowLine(fg) {532        Name("Trash auto-delete", fg)533        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)534        SubtleButton(trashOptions[idx].second, fg) {535            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)536        }537    }538    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }539    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }540541    SubLabel("DATA", fg)542    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }543    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }544    RowLine(fg) {545        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }546        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }547    }548    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }549550    var historyShowAll by remember { mutableStateOf(false) }551    SubLabel("VAULT HISTORY", fg)552    if (history.isEmpty()) {553        Text(554            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",555            color = fg.copy(alpha = 0.68f),556            fontFamily = PeachType.Body,557            fontSize = 11.sp,558            lineHeight = 16.sp,559            modifier = Modifier.padding(bottom = 6.dp),560        )561    } else {562        Text(563            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",564            color = fg.copy(alpha = 0.68f),565            fontFamily = PeachType.Body,566            fontSize = 11.sp,567            lineHeight = 16.sp,568            modifier = Modifier.padding(bottom = 4.dp),569        )570        history.take(if (historyShowAll) history.size else 3).forEach { snap ->571            RowLine(fg) {572                Column(Modifier.weight(1f)) {573                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)574                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)575                }576                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {577                    vm.restoreVaultSnapshot(snap.id)578                }579            }580        }581        if (history.size > 3) {582            RowLine(fg) {583                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)584                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }585            }586        }587        Text(588            "${history.size} of 5 snapshots",589            color = fg.copy(alpha = 0.58f),590            fontFamily = PeachType.Mono,591            fontSize = 10.sp,592            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),593        )594    }595596    var advancedOpen by remember { mutableStateOf(false) }597    SubLabel("ADVANCED", fg)598    RowLine(fg) {599        Name("Advanced", fg)600        SubtleButton(if (advancedOpen) "hide" else "show", fg) { advancedOpen = !advancedOpen }601    }602    if (advancedOpen) {603        RowLine(fg) {604            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)605            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }606        }607        RowLine(fg) {608            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)609            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }610        }611    }612}613614private fun snapshotSubLabel(snapshot: VaultSnapshot): String {615    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }616    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")617}618619private fun snapshotReasonLabel(reason: String): String = when (reason) {620    "local_save" -> "saved"621    "sync_received" -> "synced"622    "import" -> "imported"623    "restore" -> "restored"624    else -> reason625}626627private fun snapshotTimeLabel(savedAt: Long): String {628    val diff = System.currentTimeMillis() - savedAt629    if (diff < 60_000) return "Just now"630    if (diff < 3_600_000) return "${diff / 60_000}m ago"631    val date = Date(savedAt)632    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())633    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)634    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)635    if (today == thenDay) return "Today $time"636    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))637    if (yesterday == thenDay) return "Yesterday $time"638    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)639}640641/* ────────────────────────────────  Sync  ────────────────────────────────── */642643@Composable644private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {645    val syncVm: SyncViewModel = hiltViewModel()646    val pairedDevices by syncVm.pairedDevices.collectAsState()647    val pendingVouched by syncVm.pendingVouched.collectAsState()648    val syncStatus by syncVm.status.collectAsState()649    val configuredRelayUrl by syncVm.privateRelayUrl.collectAsState()650    val syncMode by syncVm.syncMode.collectAsState()651    val scope = rememberCoroutineScope()652    var confirmUnpair by remember { mutableStateOf<String?>(null) }653    var rotateConfirmOpen by remember { mutableStateOf(false) }654    var rotating by remember { mutableStateOf(false) }655    var rotateError by remember { mutableStateOf<String?>(null) }656    var relayUrlDraft by remember(configuredRelayUrl) { mutableStateOf(configuredRelayUrl) }657    var relayUrlStatus by remember { mutableStateOf<String?>(null) }658659    // One pairing block, two buttons. The old "Sync hub" row went to the same660    // place as "show", and the description described a LAN-code-only design661    // that no longer exists.662    SubLabel("PAIR A DEVICE", fg, top = 0.dp)663    RowLine(fg) {664        Column(Modifier.weight(1f)) {665            Row(verticalAlignment = Alignment.CenterVertically) {666                Text("Peach Sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp); ProBadge(fg)667            }668            Text(669                "End-to-end encrypted, through a relay that can read none of it.",670                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,671                modifier = Modifier.padding(top = 2.dp),672            )673        }674    }675    RowLine(fg) {676        Column(Modifier.weight(1f)) {677            Text("Show a code", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)678            Text(679                "For the other device to scan. Always use this one to pair a browser.",680                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,681                modifier = Modifier.padding(top = 2.dp),682            )683        }684        SubtleButton("show", fg) { onNavigate(PeachNav.CodePair) }685    }686    RowLine(fg) {687        Column(Modifier.weight(1f)) {688            Text("Scan a code", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)689            Text(690                "Joins that vault. Your entries are kept and the two merge; this phone's " +691                    "recovery words are replaced, and shown to you first.",692                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,693                modifier = Modifier.padding(top = 2.dp),694            )695        }696        SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }697    }698699    // The indicator light and the same claim in words, in the browser's place:700    // directly above PAIRED DEVICES. Outside the "has devices" branch on701    // purpose — a phone with nothing paired is exactly the phone whose owner702    // needs to be told why nothing is syncing.703    SubLabel("SYNC STATUS", fg)704    val indicator = syncIndicator(syncStatus, pairedDevices.size)705    RowLine(fg) {706        SyncIndicatorDot(707            indicator = indicator,708            label = syncIndicatorLabel(indicator, syncStatus),709            modifier = Modifier.padding(end = PeachSpacing.sm),710            size = 8.dp,711        )712        Text(713            describeSyncOutcome(syncStatus),714            color = fg.copy(alpha = 0.7f),715            fontFamily = PeachType.Body,716            fontSize = 11.sp,717            lineHeight = 16.sp,718            modifier = Modifier.weight(1f),719        )720        SubtleButton(if (syncStatus.syncing) "syncing..." else "sync now", fg) {721            if (!syncStatus.syncing) syncVm.syncNow()722        }723    }724725    SubLabel("PAIRED DEVICES", fg)726    if (pairedDevices.isEmpty()) {727        PeachEmptyOrEndState(728            message = "No paired devices yet.",729            detail = "Pair a nearby phone, tablet, or browser when you're ready to sync.",730            modifier = Modifier.padding(top = PeachSpacing.xs),731        )732    } else {733        pairedDevices.forEach { d ->734            RowLine(fg) {735                Column(Modifier.weight(1f)) {736                    Text(d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)737                    Text(738                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",739                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,740                        modifier = Modifier.padding(top = 2.dp),741                    )742                }743                if (confirmUnpair != d.deviceId) {744                    SubtleButton("remove", fg) { confirmUnpair = d.deviceId }745                }746            }747            // HOLE 4: revocation stops this device receiving future changes. It748            // does NOT secure the vault against it — that device may already749            // hold the recovery words, which are master-password-equivalent and750            // restore the whole vault anywhere, forever, with no sync involved.751            // Say so here rather than leaving the user falsely reassured.752            if (confirmUnpair == d.deviceId) {753                Column(Modifier.fillMaxWidth().padding(bottom = PeachSpacing.sm)) {754                    Text(755                        "Stops this device receiving future changes. It doesn't lock it " +756                            "out of what it already has - if it's lost or stolen, also " +757                            "change your master password and generate new recovery words.",758                        color = fg.copy(alpha = 0.7f),759                        fontFamily = PeachType.Body,760                        fontSize = 11.sp,761                        lineHeight = 16.sp,762                    )763                    Row(764                        modifier = Modifier.fillMaxWidth().padding(top = PeachSpacing.sm),765                        horizontalArrangement = Arrangement.End,766                    ) {767                        SubtleButton("cancel", fg) { confirmUnpair = null }768                        Spacer(Modifier.width(PeachSpacing.sm))769                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }770                    }771                }772            }773        }774    }775776    // Three named choices, not a toggle with an implied default. LAN sync is777    // retired (docs/sync-lan-retirement.md), so "no relay" now means no sync778    // rather than a peer-to-peer mode that never reliably worked. The779    // phone-as-relay-for-two-browsers mechanism went with it: browsers dial the780    // real relay directly now, so this handset has no forwarding role.781    SubLabel("HOW THIS VAULT SYNCS", fg)782    SyncModeRow(783        title = "Public relay",784        detail = "Peach's own relay. Works anywhere, nothing to set up. It never sees " +785            "your vault — everything is encrypted before it leaves this device.",786        selected = syncMode == SyncMode.PUBLIC,787        fg = fg,788    ) { syncVm.setSyncMode(SyncMode.PUBLIC) }789    SyncModeRow(790        title = "Private relay",791        detail = "Your own peach-relay, on your own domain. Same open-source code.",792        selected = syncMode == SyncMode.PRIVATE,793        fg = fg,794    ) { syncVm.setSyncMode(SyncMode.PRIVATE) }795796    if (syncMode == SyncMode.PRIVATE) {797        Text(798            "RELAY URL",799            color = fg.copy(alpha = 0.6f),800            fontFamily = PeachType.Mono,801            fontSize = 8.sp,802            letterSpacing = 0.22.em,803            modifier = Modifier.padding(top = 8.dp),804        )805        Box(806            Modifier.fillMaxWidth().padding(top = 6.dp)807                .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))808                .padding(horizontal = 12.dp, vertical = 10.dp),809        ) {810            BasicTextField(811                value = relayUrlDraft,812                onValueChange = { relayUrlDraft = it; relayUrlStatus = null },813                singleLine = true,814                textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp, color = fg),815                cursorBrush = SolidColor(fg),816                modifier = Modifier.fillMaxWidth(),817            )818        }819        // Private with no address is not the public relay. Say so here rather820        // than letting the phone sync through Peach under a private label.821        val needsRelayUrl = configuredRelayUrl.isEmpty()822        RowLine(fg) {823            val message = relayUrlStatus824                ?: if (needsRelayUrl) {825                    "Sync is paused until you enter your relay URL."826                } else {827                    "Only secure wss:// relays are accepted."828                }829            val warn = relayUrlStatus?.startsWith("Use") == true ||830                (relayUrlStatus == null && needsRelayUrl)831            ValueText(message, if (warn) peachColors.Breach else fg)832            SubtleButton("save", fg) {833                relayUrlStatus = if (syncVm.setRelayUrl(relayUrlDraft)) {834                    relayUrlDraft = syncVm.privateRelayUrl.value835                    "Saved"836                } else {837                    "Use a valid wss:// relay URL"838                }839            }840        }841    }842843    SyncModeRow(844        title = "No sync",845        detail = "This device keeps to itself. Move your vault by hand with Codex or " +846            "CSV export and import.",847        selected = syncMode == SyncMode.OFF,848        fg = fg,849    ) { syncVm.setSyncMode(SyncMode.OFF) }850851    if (pendingVouched.isNotEmpty()) {852        SubLabel("PENDING DEVICES", fg)853        pendingVouched.forEach { dev ->854            RowLine(fg) {855                Column(Modifier.weight(1f)) {856                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)857                    Text(858                        "Was added by another of your devices. Allow it to sync with this vault?",859                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,860                        modifier = Modifier.padding(top = 2.dp),861                    )862                }863                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {864                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }865                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }866                }867            }868        }869    }870871    SubLabel("RECOVERY", fg)872    if (rotateConfirmOpen) {873        Hint("This will disconnect all paired devices and your 12 recovery words will change. You'll be shown the new words next.", peachColors.Breach)874        rotateError?.let {875            Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))876        }877        Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {878            SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }879            SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {880                if (rotating) return@SubtleButton881                rotating = true882                rotateError = null883                scope.launch {884                    val ok = syncVm.rotateSyncIdentity()885                    rotating = false886                    if (ok) {887                        rotateConfirmOpen = false888                        onNavigate(PeachNav.RecoverySetup)889                    } else {890                        rotateError = "Rotation failed. Unlock your real vault and try again."891                    }892                }893            }894        }895    } else {896        RowLine(fg) {897            Column(Modifier.weight(1f)) {898                Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)899                Text(900                    "Use this if a paired device was lost or stolen. Re-keys the vault so the old device's key is useless.",901                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,902                    modifier = Modifier.padding(top = 2.dp),903                )904            }905            SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }906        }907    }908909    Hint("Sync uses the same zero-knowledge vault format as backup and restore; pairing authorizes a device, not a cloud account.", fg)910}911912private fun deviceTypeLabel(type: String?): String = when (type) {913    "android" -> "Android"914    "phone" -> "Phone"915    "tablet" -> "Tablet"916    "browser" -> "Browser"917    else -> "Device"918}919920private fun syncTimeLabel(lastSyncedAt: Long?): String {921    if (lastSyncedAt == null) return "never synced"922    val diff = System.currentTimeMillis() - lastSyncedAt923    if (diff < 60_000) return "just now"924    if (diff < 3_600_000) return "${diff / 60_000}m ago"925    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"926    return "${diff / 86_400_000}d ago"927}928929private fun isSyncStale(lastSyncedAt: Long?): Boolean =930    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L931932/* ────────────────────────────────  Pro  ─────────────────────────────────── */933934@Composable935private fun ProBody(fg: Color, vm: SettingsViewModel) {936    val ctx = LocalContext.current937    val isPro by vm.isPro.collectAsState()938    if (isPro) {939        ProActiveBody(fg, vm)940        return941    }942    val features = listOf(943        "Peach Sync" to "Encrypted · peer-to-peer",944        "Peach Codex" to "Restore from paper",945        "Passkeys" to "Zero-knowledge WebAuthn",946        "Advanced Vault Health" to "Reuse · age · exposure",947        "Canary entries" to "Detects vault compromise",948        "Duress vault" to "Decoy under coercion",949    )950    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)951    Text(952        "Everything, everywhere.",953        modifier = Modifier.padding(top = 8.dp),954        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,955    )956    Text(957        "One key unlocks every Pro feature — for the lifetime of the app.",958        modifier = Modifier.padding(top = 6.dp),959        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,960    )961    Spacer(Modifier.height(10.dp))962    features.forEachIndexed { i, (name, desc) ->963        // Compact rows (6dp vs. the shared 9dp default) — this card is the964        // tallest in the deck (6 features + price + CTA) and used to leave965        // its button with no breathing room before the fanned tab stacked966        // right beneath it in preview mode.967        RowLine(fg, verticalPadding = 6.dp) {968            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {969                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))970                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)971            }972            Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)973        }974    }975    Spacer(Modifier.height(12.dp))976    Text(977        "$39",978        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,979    )980    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)981    Spacer(Modifier.height(10.dp))982    Box(983        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))984            .background(fg.copy(alpha = 0.16f))985            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))986            .clickable {987                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }988            }989            .padding(vertical = 12.dp),990        contentAlignment = Alignment.Center,991    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }992993    // Trailing breathing room so the button clears the fanned tab stacked994    // beneath this card in preview mode, where the scrollable viewport clips995    // right around here (the license-key section below is already out of996    // view at that height).997    Spacer(Modifier.height(44.dp))998999    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1000    var key by remember { mutableStateOf("") }1001    val activating by vm.activating.collectAsState()1002    val activationError by vm.activationError.collectAsState()1003    Box(1004        Modifier.fillMaxWidth().padding(top = 6.dp)1005            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1006            .padding(horizontal = 12.dp, vertical = 10.dp),1007    ) {1008        BasicTextField(1009            value = key,1010            // NOT .uppercase() — base58 (the license payload encoding) is1011            // case-sensitive; forcing the whole string to uppercase silently1012            // corrupted every real key before it ever reached signature1013            // verification, so activation always failed with a real key.1014            onValueChange = { key = it; vm.clearActivationError() },1015            singleLine = true,1016            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),1017            cursorBrush = SolidColor(fg),1018            modifier = Modifier.fillMaxWidth(),1019            decorationBox = { inner ->1020                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)1021                inner()1022            },1023        )1024    }1025    if (activationError != null) {1026        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))1027    }1028    Spacer(Modifier.height(8.dp))1029    Box(1030        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1031            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))1032            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1033            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }1034            .padding(vertical = 12.dp),1035        contentAlignment = Alignment.Center,1036    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }1037}10381039@Composable1040private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {1041    val ctx = LocalContext.current1042    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")1043    val licenseKey by vm.licenseKey.collectAsState()1044    val issuedAt by vm.licenseIssuedAt.collectAsState()1045    var showKey by remember { mutableStateOf(false) }1046    var copied by remember { mutableStateOf(false) }1047    val scope = rememberCoroutineScope()1048    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {1049        com.peachpasswords.ui.components.PeachMark(size = 60.dp)1050    }1051    Text(1052        "Peach Pro",1053        modifier = Modifier.fillMaxWidth(),1054        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,1055        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1056    )1057    Text(1058        formatLicenseActiveSince(issuedAt),1059        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),1060        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,1061        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1062    )1063    licenseKey?.let { key ->1064        Spacer(Modifier.height(12.dp))1065        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1066        RowLine(fg) {1067            Text(1068                if (showKey) key else "************************",1069                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),1070                fontFamily = PeachType.Mono,1071                fontSize = 10.sp,1072                modifier = Modifier.weight(1f),1073            )1074            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1075                SubtleButton(if (copied) "copied" else "copy", fg) {1076                    PeachClipboard.copy(ctx, "peach license", key)1077                    copied = true1078                    scope.launch {1079                        delay(1_500)1080                        copied = false1081                    }1082                }1083                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }1084            }1085        }1086    }1087    Spacer(Modifier.height(12.dp))1088    features.forEachIndexed { i, name ->1089        RowLine(fg) {1090            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1091                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1092                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1093            }1094            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1095        }1096    }1097    Spacer(Modifier.height(12.dp))1098    Box(1099        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1100            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1101            .clickable { vm.deactivate() }1102            .padding(vertical = 12.dp),1103        contentAlignment = Alignment.Center,1104    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }1105}11061107private fun formatLicenseActiveSince(issuedAt: Long?): String {1108    if (issuedAt == null) return "Active"1109    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))1110    return "Active since $monthYear"1111}11121113/* ──────────────────────────────  Feedback  ───────────────────────────────── */11141115@OptIn(ExperimentalLayoutApi::class)1116@Composable1117private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {1118    val categories = listOf("Bug report", "Feature request", "Question", "Other")1119    var category by remember { mutableStateOf(categories[0]) }1120    var message by remember { mutableStateOf("") }1121    val state by vm.feedbackState.collectAsState()11221123    // Reset transient state when the card leaves composition so reopening starts fresh.1124    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }11251126    if (state is FeedbackState.Sent) {1127        Box(1128            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))1129                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),1130        ) {1131            Column {1132                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)1133                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))1134            }1135        }1136        return1137    }11381139    val sending = state is FeedbackState.Sending11401141    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)1142    SubLabel("TYPE", fg)1143    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1144        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }1145    }1146    SubLabel("MESSAGE", fg)1147    Box(1148        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))1149            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))1150            .padding(10.dp),1151    ) {1152        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)1153        BasicTextField(1154            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },1155            enabled = !sending,1156            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),1157            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),1158        )1159    }1160    Text(1161        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",1162        modifier = Modifier.padding(top = 6.dp),1163        color = fg.copy(alpha = 0.52f),1164        fontFamily = PeachType.Mono,1165        fontSize = 10.sp,1166        lineHeight = 14.sp,1167    )1168    Spacer(Modifier.height(8.dp))11691170    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1171        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1172        Box(1173            Modifier.clip(RoundedCornerShape(8.dp))1174                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1175                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1176                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1177                .padding(horizontal = 12.dp, vertical = 6.dp),1178        ) {1179            Text(1180                feedbackSubmitLabel(state),1181                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1182                fontFamily = PeachType.Mono, fontSize = 11.sp,1183            )1184        }1185        if (sending) {1186            CircularProgressIndicator(1187                color = LocalPeachAccent.current,1188                strokeWidth = 2.dp,1189                modifier = Modifier.size(16.dp),1190            )1191        }1192    }11931194    (state as? FeedbackState.Error)?.let { err ->1195        Text(1196            err.message,1197            modifier = Modifier.padding(top = 8.dp),1198            color = peachColors.Breach,1199            fontFamily = PeachType.Mono,1200            fontSize = 11.sp,1201            lineHeight = 15.sp,1202        )1203    }12041205    Hint("Sent anonymously · no account required", fg)1206}12071208/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */12091210@Composable1211internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1212    val configured by vm.duressConfigured.collectAsState()1213    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1214}12151216@Composable1217private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1218    Text(1219        "Duress password is active",1220        color = peachColors.HealthOk,1221        fontFamily = PeachType.Mono,1222        fontSize = 11.sp,1223        modifier = Modifier.padding(top = 6.dp),1224    )1225    Spacer(Modifier.height(8.dp))1226    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1227    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1228}12291230@Composable1231private fun DuressForm(fg: Color, vm: SettingsViewModel) {1232    var enabled by remember { mutableStateOf(false) }1233    var password by remember { mutableStateOf("") }1234    var confirm by remember { mutableStateOf("") }1235    var action by remember { mutableStateOf(DuressAction.DECOY) }1236    var error by remember { mutableStateOf<String?>(null) }1237    val scope = rememberCoroutineScope()12381239    RowLine(fg) {1240        Name("Duress password", fg)1241        Toggle(enabled, fg) { on ->1242            enabled = on1243            if (!on) { password = ""; confirm = ""; error = null }1244        }1245    }1246    Text(1247        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1248        color = fg.copy(alpha = 0.7f),1249        fontFamily = PeachType.Mono,1250        fontSize = 10.sp,1251        modifier = Modifier.padding(top = 6.dp),1252    )12531254    AnimatedVisibility(enabled) {1255        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1256            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1257            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }12581259            Text(1260                "When your duress password is entered at the lock screen, Peach will:",1261                color = fg.copy(alpha = 0.7f),1262                fontFamily = PeachType.Mono,1263                fontSize = 10.sp,1264                modifier = Modifier.padding(top = 4.dp),1265            )12661267            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1268            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }12691270            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }12711272            val canSave = password.isNotBlank() && confirm.isNotBlank()1273            DuressSaveButton("Save duress password", fg, canSave) {1274                error = when {1275                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1276                    password != confirm -> "Passwords do not match"1277                    else -> null1278                }1279                if (error == null) scope.launch {1280                    if (vm.saveDuress(password, action)) {1281                        password = ""; confirm = ""; enabled = false1282                    } else {1283                        error = "Couldn't save — the duress passphrase must differ from your real password"1284                    }1285                }1286            }1287        }1288    }1289}12901291@Composable1292private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1293    val accent = LocalPeachAccent.current1294    Row(1295        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1296        verticalAlignment = Alignment.CenterVertically,1297        horizontalArrangement = Arrangement.spacedBy(10.dp),1298    ) {1299        Box(1300            Modifier.size(16.dp).clip(CircleShape)1301                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1302            contentAlignment = Alignment.Center,1303        ) {1304            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1305        }1306        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1307    }1308}13091310@Composable1311private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1312    val accent = LocalPeachAccent.current1313    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1314    Box(1315        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1316            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1317            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1318            .let { if (enabled) it.clickable(onClick = onClick) else it }1319            .padding(vertical = 11.dp),1320        contentAlignment = Alignment.Center,1321    ) {1322        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1323    }1324}13251326@Composable1327private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1328    Box(1329        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1330            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1331            .clickable(onClick = onClick)1332            .padding(vertical = 11.dp),1333        contentAlignment = Alignment.Center,1334    ) {1335        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1336    }1337}13381339/** One choice in the three-way sync selector. */1340@Composable1341private fun SyncModeRow(1342    title: String,1343    detail: String,1344    selected: Boolean,1345    fg: Color,1346    onSelect: () -> Unit,1347) {1348    RowLine(fg, Modifier.clickable(onClick = onSelect)) {1349        Column(Modifier.weight(1f)) {1350            Text(title, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1351            Text(1352                detail,1353                color = fg.copy(alpha = 0.7f),1354                fontFamily = PeachType.Body,1355                fontSize = 11.sp,1356                lineHeight = 16.sp,1357                modifier = Modifier.padding(top = 2.dp),1358            )1359        }1360        Text(1361            if (selected) "●" else "○",1362            color = if (selected) fg else fg.copy(alpha = 0.45f),1363            fontFamily = PeachType.Mono,1364            fontSize = 14.sp,1365            modifier = Modifier.padding(start = 10.dp),1366        )1367    }1368}