SettingsCardBodies.kt

69.0 KB · raw

1package com.peachpasswords.ui.settings23import android.content.Intent4import android.net.Uri5import androidx.compose.animation.AnimatedVisibility6import androidx.compose.animation.core.animateDpAsState7import androidx.compose.foundation.background8import androidx.compose.foundation.border9import androidx.compose.foundation.clickable10import androidx.compose.foundation.layout.Arrangement11import androidx.compose.foundation.layout.Box12import androidx.compose.foundation.layout.Column13import androidx.compose.foundation.layout.FlowRow14import androidx.compose.foundation.layout.ExperimentalLayoutApi15import androidx.compose.foundation.layout.Row16import androidx.compose.foundation.layout.RowScope17import androidx.compose.foundation.layout.Spacer18import androidx.compose.foundation.layout.fillMaxWidth19import androidx.compose.foundation.layout.height20import androidx.compose.foundation.layout.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.ChangelogPhase73import com.peachpasswords.ui.updates.UpdatePhase74import com.peachpasswords.ui.updates.UpdateViewModel75import com.peachpasswords.updates.compareVersions76import androidx.hilt.navigation.compose.hiltViewModel77import com.peachpasswords.vault.VaultSettings78import com.peachpasswords.vault.VaultSnapshot79import kotlinx.coroutines.launch80import kotlinx.coroutines.delay81import java.text.SimpleDateFormat82import java.util.Date83import java.util.Locale8485private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"8687/**88 * Body content for the active stack card. Everything is tinted with the card's89 * own foreground [fg] (the browser's `currentColor` convention), so each card's90 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,91 * canary, license activation) render their browser visual but defer the action92 * to a later phase — noted inline where that's the case.93 */94@Composable95fun CardBody(96    id: CardId,97    fg: Color,98    vm: SettingsViewModel,99    settings: VaultSettings,100    entriesCount: Int,101    onNavigate: (PeachNav) -> Unit,102) {103    when (id) {104        CardId.Appearance -> AppearanceBody(fg, vm, settings)105        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)106        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)107        CardId.Sync -> SyncBody(fg, onNavigate)108        CardId.Pro -> ProBody(fg, vm)109        CardId.Feedback -> FeedbackBody(fg, vm)110    }111}112113/* ─────────────────────────  shared row vocabulary  ───────────────────────── */114115@Composable116private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {117    Text(118        text,119        modifier = Modifier.padding(top = top, bottom = 4.dp),120        color = fg.copy(alpha = 0.58f),121        fontFamily = PeachType.Mono,122        fontSize = 8.sp,123        letterSpacing = 0.22.em,124    )125}126127/**128 * Collapsible group inside a card body: the uppercase heading row toggles its129 * rows, so busy cards can fold rarely-used sections away. Groups holding130 * dangerous or rarely-used actions start collapsed.131 */132@Composable133private fun SettingsGroup(134    label: String,135    fg: Color,136    initiallyOpen: Boolean = true,137    top: Dp = 14.dp,138    content: @Composable () -> Unit,139) {140    var open by remember { mutableStateOf(initiallyOpen) }141    Row(142        Modifier.fillMaxWidth()143            .clip(RoundedCornerShape(6.dp))144            .clickable { open = !open }145            .padding(top = top, bottom = 4.dp),146        verticalAlignment = Alignment.CenterVertically,147    ) {148        Text(149            label,150            modifier = Modifier.weight(1f),151            color = fg.copy(alpha = 0.58f),152            fontFamily = PeachType.Mono,153            fontSize = 8.sp,154            letterSpacing = 0.22.em,155        )156        Text(157            if (open) "–" else "+",158            color = fg.copy(alpha = 0.58f),159            fontFamily = PeachType.Mono,160            fontSize = 10.sp,161        )162    }163    // AnimatedVisibility stacks sibling children like a Box, so multi-row group164    // content must sit in an explicit Column or the rows overlap.165    AnimatedVisibility(visible = open) {166        Column(Modifier.fillMaxWidth()) { content() }167    }168}169170@Composable171private fun RowLine(172    fg: Color,173    modifier: Modifier = Modifier,174    verticalPadding: Dp = 9.dp,175    content: @Composable RowScope.() -> Unit,176) {177    Row(178        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),179        verticalAlignment = Alignment.CenterVertically,180        horizontalArrangement = Arrangement.SpaceBetween,181        content = content,182    )183    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))184}185186@Composable187private fun RowScope.Name(text: String, fg: Color) {188    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))189}190191@Composable192private fun ValueText(text: String, fg: Color, modifier: Modifier = Modifier) {193    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp, modifier = modifier)194}195196@Composable197private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {198    Box(199        Modifier.clip(RoundedCornerShape(8.dp))200            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))201            .background(fg.copy(alpha = 0.08f))202            .clickable(onClick = onClick)203            .padding(horizontal = 12.dp, vertical = 6.dp),204    ) {205        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp, maxLines = 1)206    }207}208209@Composable210private fun SyncDisclosure(211    title: String,212    summary: String,213    expanded: Boolean,214    fg: Color,215    onToggle: () -> Unit,216) {217    Row(218        modifier = Modifier219            .fillMaxWidth()220            .heightIn(min = 48.dp)221            .clip(RoundedCornerShape(8.dp))222            .clickable(onClick = onToggle)223            .padding(vertical = 8.dp),224        verticalAlignment = Alignment.CenterVertically,225    ) {226        Column(Modifier.weight(1f)) {227            Text(228                title.uppercase(),229                color = fg.copy(alpha = 0.58f),230                fontFamily = PeachType.Mono,231                fontSize = 8.sp,232                letterSpacing = 0.22.em,233            )234            Text(235                summary,236                color = fg.copy(alpha = 0.7f),237                fontFamily = PeachType.Body,238                fontSize = 11.sp,239                modifier = Modifier.padding(top = 3.dp),240            )241        }242        Text(243            if (expanded) "hide" else "show",244            color = fg,245            fontFamily = PeachType.Mono,246            fontSize = 10.sp,247        )248    }249}250251@Composable252private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {253    val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")254    Box(255        Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))256            .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))257            .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))258            .clickable { onToggle(!on) },259    ) {260        Box(261            Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)262                .padding(start = knob - 2.dp)263                .size(14.dp).clip(CircleShape)264                .background(if (on) fg else fg.copy(alpha = 0.58f)),265        )266    }267}268269@Composable270private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {271    Box(272        Modifier.clip(RoundedCornerShape(999.dp))273            .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))274            .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)275            .clickable(onClick = onClick)276            .padding(horizontal = 12.dp, vertical = 5.dp),277    ) {278        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)279    }280}281282@Composable283private fun ProBadge(fg: Color) {284    Box(285        Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))286            .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),287    ) {288        Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)289    }290}291292@Composable293private fun Hint(text: String, fg: Color) {294    Text(295        text,296        modifier = Modifier.padding(top = 6.dp),297        color = fg.copy(alpha = 0.6f),298        fontFamily = PeachType.Display,299        fontStyle = FontStyle.Italic,300        fontSize = 11.5.sp,301        lineHeight = 16.sp,302    )303}304305/* ──────────────────────────────  Appearance  ─────────────────────────────── */306307@OptIn(ExperimentalLayoutApi::class)308@Composable309private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {310    SubLabel("ACCENT", fg, top = 0.dp)311    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {312        ACCENT_COLORS.forEach { (name, color) ->313            Box(314                Modifier.size(22.dp).clip(CircleShape).background(color)315                    .border(316                        if (s.accentColor == name) 2.dp else 1.dp,317                        if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),318                        CircleShape,319                    )320                    .clickable { vm.setAccent(name) },321            )322        }323    }324    SubLabel("TEXT SIZE", fg)325    RowLine(fg) {326        Name("Text size", fg)327        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {328            Pill("small", s.textSize == "small", fg) { vm.setTextSize("small") }329            Pill("medium", s.textSize == "medium", fg) { vm.setTextSize("medium") }330            Pill("large", s.textSize == "large", fg) { vm.setTextSize("large") }331        }332    }333    SubLabel("ICONS", fg)334    RowLine(fg) {335        Name("Site icons", fg)336        SubtleButton(if (s.faviconsEnabled) "On" else "Off", fg) { vm.setFaviconsEnabled(!s.faviconsEnabled) }337    }338    SubLabel("MOTION", fg)339    RowLine(fg) {340        Name("Reduce motion", fg)341        SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }342    }343}344345/* ──────────────────────────────  Protection  ─────────────────────────────── */346347@Composable348private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings, onNavigate: (PeachNav) -> Unit) {349    val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")350    val current = s.autoLockMinutes ?: 0351352    SubLabel("LOCKING", fg, top = 0.dp)353    RowLine(fg) {354        Name("Allow screenshots", fg)355        Toggle(s.allowScreenshots, fg) { vm.setAllowScreenshots(it) }356    }357    RowLine(fg) {358        Name("Auto-lock after", fg)359        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)360        SubtleButton(lockOptions[idx].second, fg) {361            val next = lockOptions[(idx + 1) % lockOptions.size].first362            vm.setAutoLockMinutes(if (next == 0) 0 else next)363        }364    }365    SubLabel("BIOMETRICS", fg)366    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity367    RowLine(fg) {368        Name("Unlock with biometrics", fg)369        Toggle(s.biometricsEnabled, fg) { on ->370            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()371        }372    }373    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)374    if (bioError != null) {375        Text(376            bioError,377            color = com.peachpasswords.ui.theme.peachColors.Breach,378            fontFamily = PeachType.Mono, fontSize = 10.sp,379            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),380        )381    }382    SubLabel("AUTOFILL", fg)383    run {384        // Read live rather than cached: the user leaves for system settings and385        // comes back, so a remembered value would show the old answer.386        val ctx = LocalContext.current387        val enabled = AutofillEnablement.isEnabled(ctx)388        RowLine(fg) {389            Column(Modifier.weight(1f)) {390                Text("Fill passwords in other apps", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)391                Text(392                    if (enabled) {393                        "Peach is your autofill service."394                    } else {395                        "Android decides which app fills passwords. Turn Peach on in system settings."396                    },397                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,398                    modifier = Modifier.padding(top = 2.dp),399                )400            }401            if (!enabled) {402                SubtleButton("enable", fg) {403                    // Straight to the autofill picker with Peach preselected;404                    // some OEM builds ship no handler, so fall back rather than405                    // dead-ending on a button that does nothing.406                    runCatching { ctx.startActivity(AutofillEnablement.requestIntent(ctx)) }407                        .onFailure { runCatching { ctx.startActivity(AutofillEnablement.fallbackIntent()) } }408                }409            } else {410                ValueText("on", fg)411            }412        }413    }414415    RowLine(fg) {416        Column(Modifier.weight(1f)) {417            Text("Hide autofill previews", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)418            Text(419                "Keyboard chips and suggestion rows show only Peach until tapped — no entry names or usernames over your shoulder.",420                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,421                modifier = Modifier.padding(top = 2.dp),422            )423        }424        Toggle(s.hideAutofillPreviews, fg) { vm.setHideAutofillPreviews(it) }425    }426427    SubLabel("PASSKEYS", fg)428    RowLine(fg) {429        Column(Modifier.weight(1f)) {430            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)431            Text(432                "Peach can handle passkey sign-in and creation through Android Credential Manager.",433                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,434                modifier = Modifier.padding(top = 2.dp),435            )436        }437        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }438    }439    RowLine(fg) {440        Name("Status", fg)441        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)442    }443    SubLabel("RECOVERY", fg)444    RowLine(fg) {445        Column(Modifier.weight(1f)) {446            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)447            Text(448                "Keep the paper copy current before rotating sync identity or replacing devices.",449                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,450                modifier = Modifier.padding(top = 2.dp),451            )452        }453        SubtleButton("view", fg) {454            if (bioActivity != null) {455                com.peachpasswords.ui.lock.Biometrics.authenticate(456                    activity = bioActivity,457                    title = "View recovery words",458                    subtitle = "Confirm your identity to view your recovery words",459                    onSuccess = { onNavigate(PeachNav.RecoveryView) },460                )461            } else onNavigate(PeachNav.RecoveryView)462        }463    }464    SubLabel("BREACH PROTECTION", fg)465    val checkingBreaches by vm.checkingBreaches.collectAsState()466    val breachResult by vm.breachResult.collectAsState()467    RowLine(fg) {468        Name("Breach monitoring", fg)469        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }470    }471    RowLine(fg) {472        Name("Check all passwords", fg)473        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }474    }475    breachResult?.let { result ->476        RowLine(fg) {477            Name("Last check", fg)478            ValueText(result, fg)479        }480    }481482    SubLabel("MASTER PASSWORD", fg)483    ChangePasswordRow(fg, vm)484485    SubLabel("DURESS PASSWORD", fg)486    val duressIsPro by vm.isPro.collectAsState()487    if (!duressIsPro) {488        RowLine(fg) {489            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {490                Name("Duress password", fg); ProBadge(fg)491            }492            ValueText("off", fg)493        }494        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)495    } else {496        DuressSection(fg, vm)497    }498}499500@Composable501private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {502    var open by remember { mutableStateOf(false) }503    var current by remember { mutableStateOf("") }504    var next by remember { mutableStateOf("") }505    var confirm by remember { mutableStateOf("") }506    var error by remember { mutableStateOf<String?>(null) }507    var done by remember { mutableStateOf(false) }508    val scope = rememberCoroutineScope()509510    RowLine(fg) {511        Name("Master password", fg)512        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }513    }514    AnimatedVisibility(open) {515        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {516            PwField("current password", current, fg) { current = it }517            PwField("new password (min 12 chars)", next, fg) { next = it }518            PwField("confirm new password", confirm, fg) { confirm = it }519            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }520            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)521            SubtleButton("save new password", fg) {522                error = when {523                    current.isBlank() -> "enter your current password"524                    next.length < 12 -> "new password must be at least 12 characters"525                    next != confirm -> "new passwords do not match"526                    next == current -> "new password must differ from current"527                    else -> null528                }529                if (error == null) scope.launch {530                    if (vm.changePassword(current, next)) {531                        current = ""; next = ""; confirm = ""; open = false; done = true532                    } else error = "incorrect current password"533                }534            }535        }536    }537}538539@Composable540private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {541    PeachField(542        label = placeholder,543        value = value,544        onValueChange = onChange,545        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,546        visualTransformation = PasswordVisualTransformation(),547    )548}549550/* ────────────────────────────────  Vault  ───────────────────────────────── */551552@Composable553private fun UpdatesRows(fg: Color, onNavigate: (PeachNav) -> Unit) {554    val vm: UpdateViewModel = hiltViewModel()555    val available by vm.available.collectAsState()556    val state by vm.state.collectAsState()557    val changelog by vm.changelog.collectAsState()558    var changelogOpen by remember { mutableStateOf(false) }559560    RowLine(fg) {561        Name("Version", fg)562        ValueText(BuildConfig.VERSION_NAME, fg)563    }564    RowLine(fg) {565        Column(Modifier.weight(1f)) {566            Text("Updates", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)567            Text(568                when {569                    available != null -> "v${available?.version} is available"570                    state.phase == UpdatePhase.Checking -> "Checking…"571                    state.phase == UpdatePhase.UpToDate -> "You're on the latest version"572                    state.phase == UpdatePhase.Failed -> "Couldn't reach the update server"573                    else -> "Peach checks once a day and tells you when there's a new version."574                },575                color = fg.copy(alpha = 0.7f),576                fontFamily = PeachType.Body,577                fontSize = 11.sp,578                lineHeight = 16.sp,579                modifier = Modifier.padding(top = 2.dp),580            )581        }582        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {583            SubtleButton("changelog", fg) {584                changelogOpen = !changelogOpen585                if (changelogOpen) vm.loadChangelog()586            }587            if (available != null) {588                SubtleButton("tap to install", fg) { onNavigate(PeachNav.Update) }589            } else {590                SubtleButton(if (state.phase == UpdatePhase.Checking) "checking" else "check for updates", fg) {591                    vm.check()592                }593            }594        }595    }596    if (changelogOpen) {597        when (changelog.phase) {598            ChangelogPhase.Idle -> {}599            ChangelogPhase.Loading -> Text(600                "Loading changelog…",601                color = fg.copy(alpha = 0.68f),602                fontFamily = PeachType.Body,603                fontSize = 11.sp,604                modifier = Modifier.padding(vertical = 8.dp),605            )606            ChangelogPhase.Failed -> RowLine(fg) {607                Name("Couldn't reach the update server", fg)608                SubtleButton("retry", fg) { vm.loadChangelog() }609            }610            ChangelogPhase.Loaded -> Column(Modifier.fillMaxWidth()) {611                changelog.entries.forEachIndexed { index, entry ->612                    Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {613                        Row(verticalAlignment = Alignment.CenterVertically) {614                            Text("v${entry.version}", color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)615                            if (compareVersions(entry.version, vm.currentVersion) == 0) {616                                Text("  current", color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 9.sp)617                            }618                        }619                        Text(620                            entry.notes ?: "No notes for this release.",621                            color = fg.copy(alpha = 0.72f),622                            fontFamily = PeachType.Body,623                            fontSize = 11.sp,624                            lineHeight = 16.sp,625                            modifier = Modifier.padding(top = 3.dp),626                        )627                    }628                    if (index < changelog.entries.lastIndex) {629                        Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.08f)))630                    }631                }632            }633        }634    }635}636637@Composable638private fun VaultBody(639    fg: Color,640    vm: SettingsViewModel,641    s: VaultSettings,642    entriesCount: Int,643    onNavigate: (PeachNav) -> Unit,644) {645    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")646    val current = s.trashRetentionDays ?: 0647    val isPro by vm.isPro.collectAsState()648    val dedupCount by vm.dedupCount.collectAsState()649    val dedupRunning by vm.dedupRunning.collectAsState()650    val dedupDone by vm.dedupDone.collectAsState()651    val history by vm.vaultHistory.collectAsState()652    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()653654    SettingsGroup("ENTRIES", fg, top = 0.dp) {655    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }656    RowLine(fg) {657        Name("Duplicates", fg)658        val done = dedupDone659        if (done != null) {660            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)661        } else {662            val count = dedupCount663            val label = when {664                dedupRunning -> "scanning..."665                count == null -> "scan"666                count == 0 -> "none found"667                else -> "$count found"668            }669            SubtleButton(label, fg) {670                if (count == null || count == 0) vm.scanDuplicates()671            }672        }673    }674    if ((dedupCount ?: 0) > 0 && dedupDone == null) {675        Column(676            Modifier.fillMaxWidth()677                .padding(top = 2.dp, bottom = 8.dp)678                .clip(RoundedCornerShape(8.dp))679                .background(fg.copy(alpha = 0.08f))680                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))681                .padding(10.dp),682            verticalArrangement = Arrangement.spacedBy(8.dp),683        ) {684            val count = dedupCount ?: 0685            Text(686                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",687                color = fg.copy(alpha = 0.82f),688                fontFamily = PeachType.Body,689                fontSize = 11.sp,690                lineHeight = 16.sp,691            )692            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {693                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }694                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }695            }696        }697    }698    }699700    SettingsGroup("MAINTENANCE", fg) {701    RowLine(fg) {702        Name("Trash auto-delete", fg)703        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)704        SubtleButton(trashOptions[idx].second, fg) {705            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)706        }707    }708    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }709    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }710    }711712    SettingsGroup("DATA", fg) {713    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }714    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }715    RowLine(fg) {716        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }717        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }718    }719    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }720    }721722    SettingsGroup("UPDATES", fg) {723    UpdatesRows(fg, onNavigate)724    }725726    SettingsGroup("VAULT HISTORY", fg, initiallyOpen = false) {727    var historyShowAll by remember { mutableStateOf(false) }728    if (history.isEmpty()) {729        Text(730            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",731            color = fg.copy(alpha = 0.68f),732            fontFamily = PeachType.Body,733            fontSize = 11.sp,734            lineHeight = 16.sp,735            modifier = Modifier.padding(bottom = 6.dp),736        )737    } else {738        Text(739            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",740            color = fg.copy(alpha = 0.68f),741            fontFamily = PeachType.Body,742            fontSize = 11.sp,743            lineHeight = 16.sp,744            modifier = Modifier.padding(bottom = 4.dp),745        )746        history.take(if (historyShowAll) history.size else 3).forEach { snap ->747            RowLine(fg) {748                Column(Modifier.weight(1f)) {749                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)750                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)751                }752                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {753                    vm.restoreVaultSnapshot(snap.id)754                }755            }756        }757        if (history.size > 3) {758            RowLine(fg) {759                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)760                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }761            }762        }763        Text(764            "${history.size} of 5 snapshots",765            color = fg.copy(alpha = 0.58f),766            fontFamily = PeachType.Mono,767            fontSize = 10.sp,768            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),769        )770    }771    }772773    SettingsGroup("ADVANCED", fg, initiallyOpen = false) {774        RowLine(fg) {775            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)776            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }777        }778        RowLine(fg) {779            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)780            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }781        }782    }783}784785private fun snapshotSubLabel(snapshot: VaultSnapshot): String {786    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }787    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")788}789790private fun snapshotReasonLabel(reason: String): String = when (reason) {791    "local_save" -> "saved"792    "sync_received" -> "synced"793    "import" -> "imported"794    "restore" -> "restored"795    else -> reason796}797798private fun snapshotTimeLabel(savedAt: Long): String {799    val diff = System.currentTimeMillis() - savedAt800    if (diff < 60_000) return "Just now"801    if (diff < 3_600_000) return "${diff / 60_000}m ago"802    val date = Date(savedAt)803    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())804    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)805    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)806    if (today == thenDay) return "Today $time"807    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))808    if (yesterday == thenDay) return "Yesterday $time"809    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)810}811812/* ────────────────────────────────  Sync  ────────────────────────────────── */813814@Composable815private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {816    val context = LocalContext.current817    val syncVm: SyncViewModel = hiltViewModel()818    val pairedDevices by syncVm.pairedDevices.collectAsState()819    val pendingVouched by syncVm.pendingVouched.collectAsState()820    val syncStatus by syncVm.status.collectAsState()821    val configuredRelayUrl by syncVm.privateRelayUrl.collectAsState()822    val syncMode by syncVm.syncMode.collectAsState()823    val backgroundSyncEnabled by syncVm.backgroundSyncEnabled.collectAsState()824    var notificationsAvailable by remember {825        mutableStateOf(canShowBackgroundSyncNotification(context))826    }827    var showBackgroundSyncPrompt by remember { mutableStateOf(false) }828    val scope = rememberCoroutineScope()829    var confirmUnpair by remember { mutableStateOf<String?>(null) }830    var renamingDeviceId by remember { mutableStateOf<String?>(null) }831    var renameDraft by remember { mutableStateOf("") }832    var rotateConfirmOpen by remember { mutableStateOf(false) }833    var rotating by remember { mutableStateOf(false) }834    var rotateError by remember { mutableStateOf<String?>(null) }835    var relayUrlDraft by remember(configuredRelayUrl) {836        mutableStateOf(privateRelayDraftOf(configuredRelayUrl))837    }838    var relayUrlStatus by remember { mutableStateOf<String?>(null) }839    var showConnection by remember { mutableStateOf(false) }840    var showRecovery by remember { mutableStateOf(false) }841842    SubLabel("ADD A DEVICE", fg, top = 0.dp)843    RowLine(fg) {844        Column(Modifier.weight(1f)) {845            Text("Pair a device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)846            Text(847                "Either scan a QR shown on the other device, or show this device's QR for the other one to scan.",848                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,849                modifier = Modifier.padding(top = 2.dp),850            )851        }852        // "Scan" opens the camera-driven AdoptVault flow: the phone is the853        // receiver. "Show a code" opens CodePair: the phone is the source.854        // Both are valid pairing entry points; without scan, a phone that wants855        // to join an existing browser-only vault has no path.856        SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }857        Spacer(Modifier.width(PeachSpacing.xs))858        SubtleButton("show code", fg) { onNavigate(PeachNav.CodePair) }859    }860861    SubLabel("SYNC STATUS", fg)862    val indicator = syncIndicator(syncStatus, pairedDevices.size)863    RowLine(fg) {864        SyncIndicatorDot(865            indicator = indicator,866            label = syncIndicatorLabel(indicator, syncStatus),867            modifier = Modifier.padding(end = PeachSpacing.sm),868            size = 8.dp,869        )870        Text(871            describeSyncOutcome(syncStatus),872            color = fg.copy(alpha = 0.7f),873            fontFamily = PeachType.Body,874            fontSize = 11.sp,875            lineHeight = 16.sp,876            modifier = Modifier.weight(1f),877        )878        SubtleButton(if (syncStatus.syncing) "syncing..." else "sync now", fg) {879            if (!syncStatus.syncing) syncVm.syncNow()880        }881    }882883    SubLabel("PAIRED DEVICES", fg)884    if (pairedDevices.isEmpty()) {885        PeachEmptyOrEndState(886            message = "No paired devices yet.",887            detail = "Pair a nearby phone, tablet, or browser when you're ready to sync.",888            modifier = Modifier.padding(top = PeachSpacing.xs),889        )890    } else {891        pairedDevices.forEach { d ->892            RowLine(fg) {893                Column(Modifier.weight(1f)) {894                    if (renamingDeviceId == d.deviceId) {895                        Box(896                            Modifier.fillMaxWidth()897                                .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))898                                .padding(horizontal = 10.dp, vertical = 8.dp),899                        ) {900                            BasicTextField(901                                value = renameDraft,902                                onValueChange = { renameDraft = it.take(64) },903                                singleLine = true,904                                textStyle = TextStyle(fontFamily = PeachType.Body, fontSize = 13.sp, color = fg),905                                cursorBrush = SolidColor(fg),906                                modifier = Modifier.fillMaxWidth(),907                            )908                        }909                    } else {910                        Text(d.localAlias ?: d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)911                    }912                    Text(913                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",914                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,915                        modifier = Modifier.padding(top = 2.dp),916                    )917                }918                if (confirmUnpair != d.deviceId) {919                    if (renamingDeviceId == d.deviceId) {920                        SubtleButton("cancel", fg) { renamingDeviceId = null }921                        Spacer(Modifier.width(PeachSpacing.xs))922                        SubtleButton("save", fg) {923                            if (renameDraft.isNotBlank()) {924                                syncVm.renameDevice(d.deviceId, renameDraft)925                                renamingDeviceId = null926                            }927                        }928                    } else {929                        SubtleButton("rename", fg) {930                            renameDraft = d.localAlias ?: d.deviceName ?: ""931                            renamingDeviceId = d.deviceId932                        }933                    }934                    if (renamingDeviceId != d.deviceId) {935                        Spacer(Modifier.width(PeachSpacing.xs))936                        SubtleButton("remove", fg) { confirmUnpair = d.deviceId }937                    }938                }939            }940            // HOLE 4: revocation stops this device receiving future changes. It941            // does NOT secure the vault against it — that device may already942            // hold the recovery words, which are master-password-equivalent and943            // restore the whole vault anywhere, forever, with no sync involved.944            // Say so here rather than leaving the user falsely reassured.945            if (confirmUnpair == d.deviceId) {946                Column(Modifier.fillMaxWidth().padding(bottom = PeachSpacing.sm)) {947                    Text(948                        "Stops this device receiving future changes. It doesn't lock it " +949                            "out of what it already has - if it's lost or stolen, also " +950                            "change your master password and generate new recovery words.",951                        color = fg.copy(alpha = 0.7f),952                        fontFamily = PeachType.Body,953                        fontSize = 11.sp,954                        lineHeight = 16.sp,955                    )956                    Row(957                        modifier = Modifier.fillMaxWidth().padding(top = PeachSpacing.sm),958                        horizontalArrangement = Arrangement.End,959                    ) {960                        SubtleButton("cancel", fg) { confirmUnpair = null }961                        Spacer(Modifier.width(PeachSpacing.sm))962                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }963                    }964                }965            }966        }967    }968969    SyncDisclosure(970        title = "Connection",971        summary = "Background sync, relay, and privacy choices",972        expanded = showConnection,973        fg = fg,974        onToggle = { showConnection = !showConnection },975    )976    if (showConnection) {977        RowLine(fg) {978            Column(Modifier.weight(1f)) {979                Text("Background sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)980                Text(981                    when {982                        backgroundSyncEnabled && !notificationsAvailable ->983                            "Action needed — Android notifications are off, so background sync is not visible."984                        backgroundSyncEnabled ->985                            "On — keeps this phone reachable for paired devices."986                        else ->987                            "Off — Peach syncs only while you are using the app."988                    },989                    color = fg.copy(alpha = 0.7f),990                    fontFamily = PeachType.Body,991                    fontSize = 11.sp,992                    lineHeight = 16.sp,993                    modifier = Modifier.padding(top = 2.dp),994                )995            }996            SubtleButton(997                if (backgroundSyncEnabled && !notificationsAvailable) "allow" else "change",998                if (backgroundSyncEnabled && !notificationsAvailable) peachColors.Breach else fg,999            ) { showBackgroundSyncPrompt = true }1000        }1001        SyncModeRow(1002            title = "Public relay",1003            detail = "Works anywhere with nothing to set up. The relay cannot read your vault.",1004            selected = syncMode == SyncMode.PUBLIC,1005            fg = fg,1006        ) { syncVm.setSyncMode(SyncMode.PUBLIC) }1007        SyncModeRow(1008            title = "Private relay",1009            detail = "Use your own peach-relay on your own domain.",1010            selected = syncMode == SyncMode.PRIVATE,1011            fg = fg,1012        ) { syncVm.setSyncMode(SyncMode.PRIVATE) }10131014        if (syncMode == SyncMode.PRIVATE) {1015            Text(1016                "RELAY URL",1017                color = fg.copy(alpha = 0.6f),1018                fontFamily = PeachType.Mono,1019                fontSize = 8.sp,1020                letterSpacing = 0.22.em,1021                modifier = Modifier.padding(top = 8.dp),1022            )1023            Box(1024                Modifier.fillMaxWidth().padding(top = 6.dp)1025                    .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1026                    .padding(horizontal = 12.dp, vertical = 10.dp),1027            ) {1028                BasicTextField(1029                    value = relayUrlDraft,1030                    onValueChange = { relayUrlDraft = it; relayUrlStatus = null },1031                    singleLine = true,1032                    textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp, color = fg),1033                    cursorBrush = SolidColor(fg),1034                    modifier = Modifier.fillMaxWidth(),1035                )1036            }1037            val needsRelayUrl = configuredRelayUrl.isEmpty()1038            RowLine(fg) {1039                val message = relayUrlStatus1040                    ?: if (needsRelayUrl) {1041                        "Sync is paused until you enter your relay URL."1042                    } else {1043                        "Only secure wss:// relays are accepted."1044                    }1045                val warn = relayUrlStatus?.startsWith("Use") == true ||1046                    (relayUrlStatus == null && needsRelayUrl)1047                ValueText(message, if (warn) peachColors.Breach else fg, Modifier.weight(1f))1048                Spacer(Modifier.width(PeachSpacing.xs))1049                SubtleButton("save", fg) {1050                    relayUrlStatus = if (syncVm.setRelayUrl(relayUrlDraft)) {1051                        relayUrlDraft = privateRelayDraftOf(syncVm.privateRelayUrl.value)1052                        "Saved"1053                    } else {1054                        "Use a valid wss:// relay URL"1055                    }1056                }1057            }1058        }10591060        SyncModeRow(1061            title = "No sync",1062            detail = "Keep this device separate and move backups by hand.",1063            selected = syncMode == SyncMode.OFF,1064            fg = fg,1065        ) { syncVm.setSyncMode(SyncMode.OFF) }1066        Hint("Pairing authorizes a device, not a cloud account.", fg)1067    }10681069    if (pendingVouched.isNotEmpty()) {1070        SubLabel("PENDING DEVICES", fg)1071        pendingVouched.forEach { dev ->1072            RowLine(fg) {1073                Column(Modifier.weight(1f)) {1074                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1075                    Text(1076                        "Was added by another device. Allow it to sync?",1077                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1078                        modifier = Modifier.padding(top = 2.dp),1079                    )1080                }1081                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1082                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }1083                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }1084                }1085            }1086        }1087    }10881089    SyncDisclosure(1090        title = "Recovery & security",1091        summary = "For a lost or stolen device",1092        expanded = showRecovery,1093        fg = fg,1094        onToggle = { showRecovery = !showRecovery },1095    )1096    if (showRecovery) {1097        RowLine(fg) {1098            Column(Modifier.weight(1f)) {1099                Text("Re-pair this device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1100                Text(1101                    "Scan only when this populated vault previously trusted the source device.",1102                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1103                    modifier = Modifier.padding(top = 2.dp),1104                )1105            }1106            SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }1107        }1108        if (rotateConfirmOpen) {1109            Hint("This disconnects every paired device and changes your 12 recovery words. You'll be shown the new words next.", peachColors.Breach)1110            rotateError?.let {1111                Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))1112            }1113            Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {1114                SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }1115                SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {1116                    if (rotating) return@SubtleButton1117                    rotating = true1118                    rotateError = null1119                    scope.launch {1120                        val ok = syncVm.rotateSyncIdentity()1121                        rotating = false1122                        if (ok) {1123                            rotateConfirmOpen = false1124                            onNavigate(PeachNav.RecoverySetup)1125                        } else {1126                            rotateError = "Rotation failed. Unlock your real vault and try again."1127                        }1128                    }1129                }1130            }1131        } else {1132            RowLine(fg) {1133                Column(Modifier.weight(1f)) {1134                    Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1135                    Text(1136                        "Disconnects every device and replaces the keys used for sync.",1137                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1138                        modifier = Modifier.padding(top = 2.dp),1139                    )1140                }1141                SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }1142            }1143        }1144    }11451146    if (showBackgroundSyncPrompt) {1147        BackgroundSyncDialog { enabled ->1148            showBackgroundSyncPrompt = false1149            notificationsAvailable = canShowBackgroundSyncNotification(context)1150            syncVm.setBackgroundSyncEnabled(enabled)1151        }1152    }1153}11541155private fun deviceTypeLabel(type: String?): String = when (type) {1156    "android" -> "Android"1157    "phone" -> "Phone"1158    "tablet" -> "Tablet"1159    "browser" -> "Browser"1160    else -> "Device"1161}11621163private fun syncTimeLabel(lastSyncedAt: Long?): String {1164    if (lastSyncedAt == null) return "never synced"1165    val diff = System.currentTimeMillis() - lastSyncedAt1166    if (diff < 60_000) return "just now"1167    if (diff < 3_600_000) return "${diff / 60_000}m ago"1168    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"1169    return "${diff / 86_400_000}d ago"1170}11711172private fun isSyncStale(lastSyncedAt: Long?): Boolean =1173    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L11741175/* ────────────────────────────────  Pro  ─────────────────────────────────── */11761177@Composable1178private fun ProBody(fg: Color, vm: SettingsViewModel) {1179    val ctx = LocalContext.current1180    val isPro by vm.isPro.collectAsState()1181    if (isPro) {1182        ProActiveBody(fg, vm)1183        return1184    }1185    val features = listOf(1186        "Peach Sync" to "End-to-end encrypted",1187        "Peach Codex" to "Restore from paper",1188        "Passkeys" to "Zero-knowledge WebAuthn",1189        "Advanced Vault Health" to "Reuse · age · exposure",1190        "Canary entries" to "Detects vault compromise",1191        "Duress vault" to "Decoy under coercion",1192    )1193    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1194    Text(1195        "Everything, everywhere.",1196        modifier = Modifier.padding(top = 8.dp),1197        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,1198    )1199    Text(1200        "One key unlocks every Pro feature — for the lifetime of the app.",1201        modifier = Modifier.padding(top = 6.dp),1202        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,1203    )1204    Spacer(Modifier.height(10.dp))1205    features.forEachIndexed { i, (name, desc) ->1206        // Compact rows (6dp vs. the shared 9dp default) — this card is the1207        // tallest in the deck (6 features + price + CTA) and used to leave1208        // its button with no breathing room before the fanned tab stacked1209        // right beneath it in preview mode.1210        RowLine(fg, verticalPadding = 6.dp) {1211            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1212                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1213                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1214            }1215            Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1216        }1217    }1218    Spacer(Modifier.height(12.dp))1219    Text(1220        "$39",1221        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,1222    )1223    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)1224    Spacer(Modifier.height(10.dp))1225    Box(1226        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1227            .background(fg.copy(alpha = 0.16f))1228            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1229            .clickable {1230                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }1231            }1232            .padding(vertical = 12.dp),1233        contentAlignment = Alignment.Center,1234    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }12351236    // Trailing breathing room so the button clears the fanned tab stacked1237    // beneath this card in preview mode, where the scrollable viewport clips1238    // right around here (the license-key section below is already out of1239    // view at that height).1240    Spacer(Modifier.height(44.dp))12411242    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1243    var key by remember { mutableStateOf("") }1244    val activating by vm.activating.collectAsState()1245    val activationError by vm.activationError.collectAsState()1246    Box(1247        Modifier.fillMaxWidth().padding(top = 6.dp)1248            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1249            .padding(horizontal = 12.dp, vertical = 10.dp),1250    ) {1251        BasicTextField(1252            value = key,1253            // NOT .uppercase() — base58 (the license payload encoding) is1254            // case-sensitive; forcing the whole string to uppercase silently1255            // corrupted every real key before it ever reached signature1256            // verification, so activation always failed with a real key.1257            onValueChange = { key = it; vm.clearActivationError() },1258            singleLine = true,1259            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),1260            cursorBrush = SolidColor(fg),1261            modifier = Modifier.fillMaxWidth(),1262            decorationBox = { inner ->1263                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)1264                inner()1265            },1266        )1267    }1268    if (activationError != null) {1269        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))1270    }1271    Spacer(Modifier.height(8.dp))1272    Box(1273        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1274            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))1275            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1276            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }1277            .padding(vertical = 12.dp),1278        contentAlignment = Alignment.Center,1279    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }1280}12811282@Composable1283private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {1284    val ctx = LocalContext.current1285    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")1286    val licenseKey by vm.licenseKey.collectAsState()1287    val issuedAt by vm.licenseIssuedAt.collectAsState()1288    var showKey by remember { mutableStateOf(false) }1289    var copied by remember { mutableStateOf(false) }1290    val scope = rememberCoroutineScope()1291    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {1292        com.peachpasswords.ui.components.PeachMark(size = 60.dp)1293    }1294    Text(1295        "Peach Pro",1296        modifier = Modifier.fillMaxWidth(),1297        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,1298        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1299    )1300    Text(1301        formatLicenseActiveSince(issuedAt),1302        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),1303        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,1304        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1305    )1306    licenseKey?.let { key ->1307        Spacer(Modifier.height(12.dp))1308        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1309        RowLine(fg) {1310            Text(1311                if (showKey) key else "************************",1312                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),1313                fontFamily = PeachType.Mono,1314                fontSize = 10.sp,1315                modifier = Modifier.weight(1f),1316            )1317            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1318                SubtleButton(if (copied) "copied" else "copy", fg) {1319                    PeachClipboard.copy(ctx, "peach license", key)1320                    copied = true1321                    scope.launch {1322                        delay(1_500)1323                        copied = false1324                    }1325                }1326                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }1327            }1328        }1329    }1330    Spacer(Modifier.height(12.dp))1331    features.forEachIndexed { i, name ->1332        RowLine(fg) {1333            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1334                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1335                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1336            }1337            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1338        }1339    }1340    Spacer(Modifier.height(12.dp))1341    Box(1342        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1343            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1344            .clickable { vm.deactivate() }1345            .padding(vertical = 12.dp),1346        contentAlignment = Alignment.Center,1347    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }1348}13491350private fun formatLicenseActiveSince(issuedAt: Long?): String {1351    if (issuedAt == null) return "Active"1352    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))1353    return "Active since $monthYear"1354}13551356/* ──────────────────────────────  Feedback  ───────────────────────────────── */13571358@OptIn(ExperimentalLayoutApi::class)1359@Composable1360private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {1361    val categories = listOf("Bug report", "Feature request", "Question", "Other")1362    var category by remember { mutableStateOf(categories[0]) }1363    var message by remember { mutableStateOf("") }1364    val state by vm.feedbackState.collectAsState()13651366    // Reset transient state when the card leaves composition so reopening starts fresh.1367    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }13681369    if (state is FeedbackState.Sent) {1370        Box(1371            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))1372                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),1373        ) {1374            Column {1375                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)1376                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))1377            }1378        }1379        return1380    }13811382    val sending = state is FeedbackState.Sending13831384    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)1385    SubLabel("TYPE", fg)1386    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1387        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }1388    }1389    SubLabel("MESSAGE", fg)1390    Box(1391        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))1392            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))1393            .padding(10.dp),1394    ) {1395        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)1396        BasicTextField(1397            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },1398            enabled = !sending,1399            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),1400            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),1401        )1402    }1403    Text(1404        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",1405        modifier = Modifier.padding(top = 6.dp),1406        color = fg.copy(alpha = 0.52f),1407        fontFamily = PeachType.Mono,1408        fontSize = 10.sp,1409        lineHeight = 14.sp,1410    )1411    Spacer(Modifier.height(8.dp))14121413    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1414        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1415        Box(1416            Modifier.clip(RoundedCornerShape(8.dp))1417                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1418                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1419                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1420                .padding(horizontal = 12.dp, vertical = 6.dp),1421        ) {1422            Text(1423                feedbackSubmitLabel(state),1424                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1425                fontFamily = PeachType.Mono, fontSize = 11.sp,1426            )1427        }1428        if (sending) {1429            CircularProgressIndicator(1430                color = LocalPeachAccent.current,1431                strokeWidth = 2.dp,1432                modifier = Modifier.size(16.dp),1433            )1434        }1435    }14361437    (state as? FeedbackState.Error)?.let { err ->1438        Text(1439            err.message,1440            modifier = Modifier.padding(top = 8.dp),1441            color = peachColors.Breach,1442            fontFamily = PeachType.Mono,1443            fontSize = 11.sp,1444            lineHeight = 15.sp,1445        )1446    }14471448    Hint("Sent anonymously · no account required", fg)1449}14501451/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */14521453@Composable1454internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1455    val configured by vm.duressConfigured.collectAsState()1456    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1457}14581459@Composable1460private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1461    Text(1462        "Duress password is active",1463        color = peachColors.HealthOk,1464        fontFamily = PeachType.Mono,1465        fontSize = 11.sp,1466        modifier = Modifier.padding(top = 6.dp),1467    )1468    Spacer(Modifier.height(8.dp))1469    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1470    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1471}14721473@Composable1474private fun DuressForm(fg: Color, vm: SettingsViewModel) {1475    var enabled by remember { mutableStateOf(false) }1476    var password by remember { mutableStateOf("") }1477    var confirm by remember { mutableStateOf("") }1478    var action by remember { mutableStateOf(DuressAction.DECOY) }1479    var error by remember { mutableStateOf<String?>(null) }1480    val scope = rememberCoroutineScope()14811482    RowLine(fg) {1483        Name("Duress password", fg)1484        Toggle(enabled, fg) { on ->1485            enabled = on1486            if (!on) { password = ""; confirm = ""; error = null }1487        }1488    }1489    Text(1490        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1491        color = fg.copy(alpha = 0.7f),1492        fontFamily = PeachType.Mono,1493        fontSize = 10.sp,1494        modifier = Modifier.padding(top = 6.dp),1495    )14961497    AnimatedVisibility(enabled) {1498        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1499            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1500            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }15011502            Text(1503                "When your duress password is entered at the lock screen, Peach will:",1504                color = fg.copy(alpha = 0.7f),1505                fontFamily = PeachType.Mono,1506                fontSize = 10.sp,1507                modifier = Modifier.padding(top = 4.dp),1508            )15091510            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1511            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }15121513            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }15141515            val canSave = password.isNotBlank() && confirm.isNotBlank()1516            DuressSaveButton("Save duress password", fg, canSave) {1517                error = when {1518                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1519                    password != confirm -> "Passwords do not match"1520                    else -> null1521                }1522                if (error == null) scope.launch {1523                    if (vm.saveDuress(password, action)) {1524                        password = ""; confirm = ""; enabled = false1525                    } else {1526                        error = "Couldn't save — the duress passphrase must differ from your real password"1527                    }1528                }1529            }1530        }1531    }1532}15331534@Composable1535private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1536    val accent = LocalPeachAccent.current1537    Row(1538        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1539        verticalAlignment = Alignment.CenterVertically,1540        horizontalArrangement = Arrangement.spacedBy(10.dp),1541    ) {1542        Box(1543            Modifier.size(16.dp).clip(CircleShape)1544                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1545            contentAlignment = Alignment.Center,1546        ) {1547            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1548        }1549        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1550    }1551}15521553@Composable1554private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1555    val accent = LocalPeachAccent.current1556    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1557    Box(1558        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1559            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1560            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1561            .let { if (enabled) it.clickable(onClick = onClick) else it }1562            .padding(vertical = 11.dp),1563        contentAlignment = Alignment.Center,1564    ) {1565        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1566    }1567}15681569@Composable1570private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1571    Box(1572        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1573            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1574            .clickable(onClick = onClick)1575            .padding(vertical = 11.dp),1576        contentAlignment = Alignment.Center,1577    ) {1578        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1579    }1580}15811582/** One choice in the three-way sync selector. */1583@Composable1584private fun SyncModeRow(1585    title: String,1586    detail: String,1587    selected: Boolean,1588    fg: Color,1589    onSelect: () -> Unit,1590) {1591    RowLine(fg, Modifier.clickable(onClick = onSelect)) {1592        Column(Modifier.weight(1f)) {1593            Text(title, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1594            Text(1595                detail,1596                color = fg.copy(alpha = 0.7f),1597                fontFamily = PeachType.Body,1598                fontSize = 11.sp,1599                lineHeight = 16.sp,1600                modifier = Modifier.padding(top = 2.dp),1601            )1602        }1603        Text(1604            if (selected) "●" else "○",1605            color = if (selected) fg else fg.copy(alpha = 0.45f),1606            fontFamily = PeachType.Mono,1607            fontSize = 14.sp,1608            modifier = Modifier.padding(start = 10.dp),1609        )1610    }1611}