SettingsCardBodies.kt

79.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.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.material3.AlertDialog30import androidx.compose.runtime.DisposableEffect31import androidx.compose.runtime.collectAsState32import androidx.compose.runtime.getValue33import com.peachpasswords.feedback.FeedbackState34import com.peachpasswords.shared.PeachClipboard35import com.peachpasswords.sync.LEGACY_ACTIVE36import com.peachpasswords.sync.REPAIRING37import com.peachpasswords.sync.RESET_CONFIRMED38import com.peachpasswords.sync.RESET_REQUIRED39import com.peachpasswords.sync.SyncMode40import com.peachpasswords.sync.UNKNOWN_STATE41import com.peachpasswords.sync.V2_ACTIVE42import com.peachpasswords.sync.V2_ANCHOR43import com.peachpasswords.sync.canShowBackgroundSyncNotification44import com.peachpasswords.sync.describeSyncOutcome45import com.peachpasswords.sync.privateRelayDraftOf46import com.peachpasswords.sync.syncIndicator47import com.peachpasswords.sync.syncIndicatorLabel48import com.peachpasswords.ui.components.SyncIndicatorDot49import com.peachpasswords.ui.theme.LocalPeachAccent50import com.peachpasswords.vault.DuressAction51import com.peachpasswords.ui.theme.peachColors52import androidx.compose.runtime.mutableStateOf53import androidx.compose.runtime.remember54import androidx.compose.runtime.rememberCoroutineScope55import androidx.compose.runtime.setValue56import androidx.compose.ui.Alignment57import androidx.compose.ui.Modifier58import androidx.compose.ui.draw.clip59import androidx.compose.ui.graphics.Color60import androidx.compose.ui.graphics.SolidColor61import androidx.compose.ui.platform.LocalContext62import androidx.compose.ui.text.TextStyle63import androidx.compose.ui.text.font.FontStyle64import androidx.compose.ui.text.input.PasswordVisualTransformation65import androidx.compose.ui.text.input.KeyboardType66import androidx.compose.ui.unit.Dp67import androidx.compose.ui.unit.dp68import androidx.compose.ui.unit.em69import androidx.compose.ui.unit.sp70import androidx.compose.material3.Text71import com.peachpasswords.BuildConfig72import com.peachpasswords.autofill.AutofillEnablement73import com.peachpasswords.ui.PeachNav74import com.peachpasswords.ui.components.PeachEmptyOrEndState75import com.peachpasswords.ui.components.PeachField76import com.peachpasswords.ui.pairing.BackgroundSyncDialog77import com.peachpasswords.ui.sync.SyncViewModel78import com.peachpasswords.ui.theme.ACCENT_COLORS79import com.peachpasswords.ui.theme.PeachSpacing80import com.peachpasswords.ui.theme.PeachType81import com.peachpasswords.ui.updates.ChangelogPhase82import com.peachpasswords.ui.updates.UpdatePhase83import com.peachpasswords.ui.updates.UpdateViewModel84import com.peachpasswords.updates.compareVersions85import androidx.hilt.navigation.compose.hiltViewModel86import com.peachpasswords.vault.VaultSettings87import com.peachpasswords.vault.VaultSnapshot88import com.peachpasswords.vault.faviconsAllowed89import kotlinx.coroutines.launch90import kotlinx.coroutines.delay91import java.text.SimpleDateFormat92import java.util.Date93import java.util.Locale9495private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"9697internal const val FAVICON_DISCLOSURE_TEXT =98    "Peach requests site icons from DuckDuckGo. Turning this on discloses your full vault domain inventory to DuckDuckGo as icons are requested."99100/**101 * Body content for the active stack card. Everything is tinted with the card's102 * own foreground [fg] (the browser's `currentColor` convention), so each card's103 * rows inherit its palette. Rows whose backend doesn't exist yet (duress,104 * canary, license activation) render their browser visual but defer the action105 * to a later phase — noted inline where that's the case.106 */107@Composable108fun CardBody(109    id: CardId,110    fg: Color,111    vm: SettingsViewModel,112    settings: VaultSettings,113    entriesCount: Int,114    onNavigate: (PeachNav) -> Unit,115) {116    when (id) {117        CardId.Appearance -> AppearanceBody(fg, vm, settings)118        CardId.Protection -> ProtectionBody(fg, vm, settings, onNavigate)119        CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)120        CardId.Sync -> SyncBody(fg, onNavigate)121        CardId.Pro -> ProBody(fg, vm)122        CardId.Feedback -> FeedbackBody(fg, vm)123    }124}125126/* ─────────────────────────  shared row vocabulary  ───────────────────────── */127128@Composable129private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {130    Text(131        text,132        modifier = Modifier.padding(top = top, bottom = 4.dp),133        color = fg.copy(alpha = 0.58f),134        fontFamily = PeachType.Mono,135        fontSize = 8.sp,136        letterSpacing = 0.22.em,137    )138}139140/**141 * Collapsible group inside a card body: the uppercase heading row toggles its142 * rows, so busy cards can fold rarely-used sections away. Groups holding143 * dangerous or rarely-used actions start collapsed.144 */145@Composable146private fun SettingsGroup(147    label: String,148    fg: Color,149    initiallyOpen: Boolean = true,150    top: Dp = 14.dp,151    content: @Composable () -> Unit,152) {153    var open by remember { mutableStateOf(initiallyOpen) }154    Row(155        Modifier.fillMaxWidth()156            .clip(RoundedCornerShape(6.dp))157            .clickable { open = !open }158            .padding(top = top, bottom = 4.dp),159        verticalAlignment = Alignment.CenterVertically,160    ) {161        Text(162            label,163            modifier = Modifier.weight(1f),164            color = fg.copy(alpha = 0.58f),165            fontFamily = PeachType.Mono,166            fontSize = 8.sp,167            letterSpacing = 0.22.em,168        )169        Text(170            if (open) "–" else "+",171            color = fg.copy(alpha = 0.58f),172            fontFamily = PeachType.Mono,173            fontSize = 10.sp,174        )175    }176    // AnimatedVisibility stacks sibling children like a Box, so multi-row group177    // content must sit in an explicit Column or the rows overlap.178    AnimatedVisibility(visible = open) {179        Column(Modifier.fillMaxWidth()) { content() }180    }181}182183@Composable184private fun RowLine(185    fg: Color,186    modifier: Modifier = Modifier,187    verticalPadding: Dp = 9.dp,188    content: @Composable RowScope.() -> Unit,189) {190    Row(191        Modifier.fillMaxWidth().then(modifier).padding(vertical = verticalPadding),192        verticalAlignment = Alignment.CenterVertically,193        horizontalArrangement = Arrangement.SpaceBetween,194        content = content,195    )196    Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))197}198199@Composable200private fun RowScope.Name(text: String, fg: Color) {201    Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))202}203204@Composable205private fun ValueText(text: String, fg: Color, modifier: Modifier = Modifier) {206    Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp, modifier = modifier)207}208209@Composable210private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {211    Box(212        Modifier.clip(RoundedCornerShape(8.dp))213            .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))214            .background(fg.copy(alpha = 0.08f))215            .clickable(onClick = onClick)216            .padding(horizontal = 12.dp, vertical = 6.dp),217    ) {218        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp, maxLines = 1)219    }220}221222@Composable223private fun SyncDisclosure(224    title: String,225    summary: String,226    expanded: Boolean,227    fg: Color,228    onToggle: () -> Unit,229) {230    Row(231        modifier = Modifier232            .fillMaxWidth()233            .heightIn(min = 48.dp)234            .clip(RoundedCornerShape(8.dp))235            .clickable(onClick = onToggle)236            .padding(vertical = 8.dp),237        verticalAlignment = Alignment.CenterVertically,238    ) {239        Column(Modifier.weight(1f)) {240            Text(241                title.uppercase(),242                color = fg.copy(alpha = 0.58f),243                fontFamily = PeachType.Mono,244                fontSize = 8.sp,245                letterSpacing = 0.22.em,246            )247            Text(248                summary,249                color = fg.copy(alpha = 0.7f),250                fontFamily = PeachType.Body,251                fontSize = 11.sp,252                modifier = Modifier.padding(top = 3.dp),253            )254        }255        Text(256            if (expanded) "hide" else "show",257            color = fg,258            fontFamily = PeachType.Mono,259            fontSize = 10.sp,260        )261    }262}263264@Composable265private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {266    val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")267    Box(268        Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))269            .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))270            .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))271            .clickable { onToggle(!on) },272    ) {273        Box(274            Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)275                .padding(start = knob - 2.dp)276                .size(14.dp).clip(CircleShape)277                .background(if (on) fg else fg.copy(alpha = 0.58f)),278        )279    }280}281282@Composable283private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {284    Box(285        Modifier.clip(RoundedCornerShape(999.dp))286            .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))287            .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)288            .clickable(onClick = onClick)289            .padding(horizontal = 12.dp, vertical = 5.dp),290    ) {291        Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)292    }293}294295@Composable296private fun ProBadge(fg: Color) {297    Box(298        Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))299            .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),300    ) {301        Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)302    }303}304305@Composable306private fun Hint(text: String, fg: Color) {307    Text(308        text,309        modifier = Modifier.padding(top = 6.dp),310        color = fg.copy(alpha = 0.6f),311        fontFamily = PeachType.Display,312        fontStyle = FontStyle.Italic,313        fontSize = 11.5.sp,314        lineHeight = 16.sp,315    )316}317318/* ──────────────────────────────  Appearance  ─────────────────────────────── */319320@OptIn(ExperimentalLayoutApi::class)321@Composable322private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {323    var showFaviconDisclosure by remember { mutableStateOf(false) }324    SubLabel("ACCENT", fg, top = 0.dp)325    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {326        ACCENT_COLORS.forEach { (name, color) ->327            Box(328                Modifier.size(22.dp).clip(CircleShape).background(color)329                    .border(330                        if (s.accentColor == name) 2.dp else 1.dp,331                        if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),332                        CircleShape,333                    )334                    .clickable { vm.setAccent(name) },335            )336        }337    }338    SubLabel("TEXT SIZE", fg)339    RowLine(fg) {340        Name("Text size", fg)341        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {342            Pill("small", s.textSize == "small", fg) { vm.setTextSize("small") }343            Pill("medium", s.textSize == "medium", fg) { vm.setTextSize("medium") }344            Pill("large", s.textSize == "large", fg) { vm.setTextSize("large") }345        }346    }347    SubLabel("UI SCALE", fg)348    RowLine(fg) {349        Name("Large-screen sizing", fg)350        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {351            Pill("compact", s.uiScale == "compact", fg) { vm.setUiScale("compact") }352            Pill("auto", s.uiScale == "auto", fg) { vm.setUiScale("auto") }353            Pill("large", s.uiScale == "large", fg) { vm.setUiScale("large") }354        }355    }356    Hint("Auto keeps foldables roomy while preventing tablet controls from inflating.", fg)357    SubLabel("ICONS", fg)358    RowLine(fg) {359        Name("Site icons", fg)360        val siteIconsAllowed = faviconsAllowed(s)361        SubtleButton(if (siteIconsAllowed) "On" else "Off", fg) {362            if (siteIconsAllowed) vm.setFaviconsEnabled(false) else showFaviconDisclosure = true363        }364    }365    if (showFaviconDisclosure) {366        AlertDialog(367            onDismissRequest = { showFaviconDisclosure = false },368            title = { Text("Enable site icons?", color = fg, fontFamily = PeachType.Body) },369            text = { Text(FAVICON_DISCLOSURE_TEXT, color = fg, fontFamily = PeachType.Body) },370            confirmButton = {371                SubtleButton("Enable", fg) {372                    showFaviconDisclosure = false373                    vm.setFaviconsEnabled(true)374                }375            },376            dismissButton = {377                SubtleButton("Cancel", fg) { showFaviconDisclosure = false }378            },379        )380    }381    SubLabel("MOTION", fg)382    RowLine(fg) {383        Name("Reduce motion", fg)384        SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }385    }386}387388/* ──────────────────────────────  Protection  ─────────────────────────────── */389390@Composable391private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings, onNavigate: (PeachNav) -> Unit) {392    val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")393    val current = s.autoLockMinutes ?: 0394    val pinEnabled by vm.pinEnabled.collectAsState()395    var pinOpen by remember { mutableStateOf(false) }396    var pinRemovalOpen by remember { mutableStateOf(false) }397    var pinMaster by remember { mutableStateOf("") }398    var pin by remember { mutableStateOf("") }399    var pinConfirm by remember { mutableStateOf("") }400    var pinRemovalMaster by remember { mutableStateOf("") }401    var pinError by remember { mutableStateOf<String?>(null) }402    val pinScope = rememberCoroutineScope()403404    SubLabel("LOCKING", fg, top = 0.dp)405    RowLine(fg) {406        Name("Allow screenshots", fg)407        Toggle(s.allowScreenshots, fg) { vm.setAllowScreenshots(it) }408    }409    RowLine(fg) {410        Name("Auto-lock after", fg)411        val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)412        SubtleButton(lockOptions[idx].second, fg) {413            val next = lockOptions[(idx + 1) % lockOptions.size].first414            vm.setAutoLockMinutes(if (next == 0) 0 else next)415        }416    }417    SubLabel("PIN UNLOCK", fg)418    RowLine(fg) {419        Name("Unlock with PIN", fg)420        Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {421            ValueText(if (pinEnabled) "enabled" else "off", fg)422            SubtleButton(if (pinEnabled) "change" else "set", fg) {423                pin = ""424                pinConfirm = ""425                pinMaster = ""426                pinError = null427                pinOpen = !pinOpen428            }429        }430    }431    if (pinEnabled) {432        RowLine(fg) {433            Name("Remove PIN unlock", fg)434            SubtleButton("turn off", fg) {435                pinRemovalMaster = ""436                pinError = null437                pinRemovalOpen = !pinRemovalOpen438            }439        }440    }441    AnimatedVisibility(pinRemovalOpen) {442        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {443            PeachField(444                label = "master password",445                value = pinRemovalMaster,446                onValueChange = { pinRemovalMaster = it; pinError = null },447                keyboardType = KeyboardType.Password,448                visualTransformation = PasswordVisualTransformation(),449            )450            pinError?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }451            SubtleButton("remove PIN", fg) {452                pinScope.launch {453                    val error = vm.disablePin(pinRemovalMaster)454                    if (error == null) {455                        pinRemovalMaster = ""456                        pinRemovalOpen = false457                    } else {458                        pinError = error459                    }460                }461            }462        }463    }464    AnimatedVisibility(pinOpen) {465        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {466            PeachField(467                label = "master password",468                value = pinMaster,469                onValueChange = { pinMaster = it; pinError = null },470                keyboardType = KeyboardType.Password,471                visualTransformation = PasswordVisualTransformation(),472            )473            PeachField(474                label = "new PIN (4–12 digits)",475                value = pin,476                onValueChange = { pin = it.filter(Char::isDigit).take(12); pinError = null },477                keyboardType = KeyboardType.NumberPassword,478                visualTransformation = PasswordVisualTransformation(),479            )480            PeachField(481                label = "confirm PIN",482                value = pinConfirm,483                onValueChange = { pinConfirm = it.filter(Char::isDigit).take(12); pinError = null },484                keyboardType = KeyboardType.NumberPassword,485                visualTransformation = PasswordVisualTransformation(),486            )487            pinError?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }488            SubtleButton("save PIN", fg) {489                pinError = if (pin != pinConfirm) "PINs do not match" else null490                if (pinError == null) pinScope.launch {491                    val error = vm.savePin(pinMaster, pin)492                    if (error == null) {493                        pinMaster = ""494                        pin = ""495                        pinConfirm = ""496                        pinOpen = false497                    } else {498                        pinError = error499                    }500                }501            }502        }503    }504    SubLabel("BIOMETRICS", fg)505    val bioActivity = LocalContext.current as? androidx.fragment.app.FragmentActivity506    RowLine(fg) {507        Name("Unlock with biometrics", fg)508        Toggle(s.biometricsEnabled, fg) { on ->509            if (on && bioActivity != null) vm.enableBiometrics(bioActivity) else vm.disableBiometrics()510        }511    }512    val bioError = com.peachpasswords.ui.lock.Biometrics.statusMessage(LocalContext.current)513    if (bioError != null) {514        Text(515            bioError,516            color = com.peachpasswords.ui.theme.peachColors.Breach,517            fontFamily = PeachType.Mono, fontSize = 10.sp,518            modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 4.dp),519        )520    }521    SubLabel("AUTOFILL", fg)522    run {523        // Read live rather than cached: the user leaves for system settings and524        // comes back, so a remembered value would show the old answer.525        val ctx = LocalContext.current526        val enabled = AutofillEnablement.isEnabled(ctx)527        RowLine(fg) {528            Column(Modifier.weight(1f)) {529                Text("Fill passwords in other apps", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)530                Text(531                    if (enabled) {532                        "Peach is your autofill service."533                    } else {534                        "Android decides which app fills passwords. Turn Peach on in system settings."535                    },536                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,537                    modifier = Modifier.padding(top = 2.dp),538                )539            }540            if (!enabled) {541                SubtleButton("enable", fg) {542                    // Straight to the autofill picker with Peach preselected;543                    // some OEM builds ship no handler, so fall back rather than544                    // dead-ending on a button that does nothing.545                    runCatching { ctx.startActivity(AutofillEnablement.requestIntent(ctx)) }546                        .onFailure { runCatching { ctx.startActivity(AutofillEnablement.fallbackIntent()) } }547                }548            } else {549                ValueText("on", fg)550            }551        }552    }553554    RowLine(fg) {555        Column(Modifier.weight(1f)) {556            Text("Hide autofill previews", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)557            Text(558                "Keyboard chips and suggestion rows show only Peach until tapped — no entry names or usernames over your shoulder.",559                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,560                modifier = Modifier.padding(top = 2.dp),561            )562        }563        Toggle(s.hideAutofillPreviews, fg) { vm.setHideAutofillPreviews(it) }564    }565566    SubLabel("PASSKEYS", fg)567    RowLine(fg) {568        Column(Modifier.weight(1f)) {569            Text("Credential provider", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)570            Text(571                "Peach can handle passkey sign-in and creation through Android Credential Manager.",572                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,573                modifier = Modifier.padding(top = 2.dp),574            )575        }576        Toggle(s.passkeyProviderEnabled, fg) { vm.setPasskeyProviderEnabled(it) }577    }578    RowLine(fg) {579        Name("Status", fg)580        ValueText(if (s.passkeyProviderEnabled) "enabled" else "off", fg)581    }582    SubLabel("RECOVERY", fg)583    RowLine(fg) {584        Column(Modifier.weight(1f)) {585            Text("View recovery words", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)586            Text(587                "Keep the paper copy current before rotating sync identity or replacing devices.",588                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,589                modifier = Modifier.padding(top = 2.dp),590            )591        }592        SubtleButton("view", fg) {593            if (bioActivity != null) {594                com.peachpasswords.ui.lock.Biometrics.authenticate(595                    activity = bioActivity,596                    title = "View recovery words",597                    subtitle = "Confirm your identity to view your recovery words",598                    onSuccess = { onNavigate(PeachNav.RecoveryView) },599                )600            } else onNavigate(PeachNav.RecoveryView)601        }602    }603    SubLabel("BREACH PROTECTION", fg)604    val checkingBreaches by vm.checkingBreaches.collectAsState()605    val breachResult by vm.breachResult.collectAsState()606    RowLine(fg) {607        Name("Breach monitoring", fg)608        Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }609    }610    RowLine(fg) {611        Name("Check all passwords", fg)612        SubtleButton(if (checkingBreaches) "checking..." else "run", fg) { vm.checkAllBreaches() }613    }614    breachResult?.let { result ->615        RowLine(fg) {616            Name("Last check", fg)617            ValueText(result, fg)618        }619    }620621    SubLabel("MASTER PASSWORD", fg)622    ChangePasswordRow(fg, vm)623624    SubLabel("DURESS PASSWORD", fg)625    val duressIsPro by vm.isPro.collectAsState()626    if (!duressIsPro) {627        RowLine(fg) {628            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {629                Name("Duress password", fg); ProBadge(fg)630            }631            ValueText("off", fg)632        }633        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)634    } else {635        DuressSection(fg, vm)636    }637}638639@Composable640private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {641    var open by remember { mutableStateOf(false) }642    var current by remember { mutableStateOf("") }643    var next by remember { mutableStateOf("") }644    var confirm by remember { mutableStateOf("") }645    var error by remember { mutableStateOf<String?>(null) }646    var done by remember { mutableStateOf(false) }647    val scope = rememberCoroutineScope()648649    RowLine(fg) {650        Name("Master password", fg)651        SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }652    }653    AnimatedVisibility(open) {654        Column(Modifier.fillMaxWidth().padding(top = PeachSpacing.sm), verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {655            PwField("current password", current, fg) { current = it }656            PwField("new password (min 12 chars)", next, fg) { next = it }657            PwField("confirm new password", confirm, fg) { confirm = it }658            error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }659            if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)660            SubtleButton("save new password", fg) {661                error = when {662                    current.isBlank() -> "enter your current password"663                    next.length < 12 -> "new password must be at least 12 characters"664                    next != confirm -> "new passwords do not match"665                    next == current -> "new password must differ from current"666                    else -> null667                }668                if (error == null) scope.launch {669                    if (vm.changePassword(current, next)) {670                        current = ""; next = ""; confirm = ""; open = false; done = true671                    } else error = "incorrect current password"672                }673            }674        }675    }676}677678@Composable679private fun PwField(placeholder: String, value: String, @Suppress("UNUSED_PARAMETER") fg: Color, onChange: (String) -> Unit) {680    PeachField(681        label = placeholder,682        value = value,683        onValueChange = onChange,684        keyboardType = androidx.compose.ui.text.input.KeyboardType.Password,685        visualTransformation = PasswordVisualTransformation(),686    )687}688689/* ────────────────────────────────  Vault  ───────────────────────────────── */690691@Composable692private fun UpdatesRows(fg: Color, onNavigate: (PeachNav) -> Unit) {693    val vm: UpdateViewModel = hiltViewModel()694    val available by vm.available.collectAsState()695    val state by vm.state.collectAsState()696    val changelog by vm.changelog.collectAsState()697    var changelogOpen by remember { mutableStateOf(false) }698699    RowLine(fg) {700        Name("Version", fg)701        ValueText(BuildConfig.VERSION_NAME, fg)702    }703    RowLine(fg) {704        Column(Modifier.weight(1f)) {705            Text("Updates", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)706            Text(707                when {708                    available != null -> "v${available?.version} is available"709                    state.phase == UpdatePhase.Checking -> "Checking…"710                    state.phase == UpdatePhase.UpToDate -> "You're on the latest version"711                    state.phase == UpdatePhase.Failed -> "Couldn't reach the update server"712                    else -> "Peach checks once a day and tells you when there's a new version."713                },714                color = fg.copy(alpha = 0.7f),715                fontFamily = PeachType.Body,716                fontSize = 11.sp,717                lineHeight = 16.sp,718                modifier = Modifier.padding(top = 2.dp),719            )720        }721        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {722            SubtleButton("changelog", fg) {723                changelogOpen = !changelogOpen724                if (changelogOpen) vm.loadChangelog()725            }726            if (available != null) {727                SubtleButton("tap to install", fg) { onNavigate(PeachNav.Update) }728            } else {729                SubtleButton(if (state.phase == UpdatePhase.Checking) "checking" else "check for updates", fg) {730                    vm.check()731                }732            }733        }734    }735    if (changelogOpen) {736        when (changelog.phase) {737            ChangelogPhase.Idle -> {}738            ChangelogPhase.Loading -> Text(739                "Loading changelog…",740                color = fg.copy(alpha = 0.68f),741                fontFamily = PeachType.Body,742                fontSize = 11.sp,743                modifier = Modifier.padding(vertical = 8.dp),744            )745            ChangelogPhase.Failed -> RowLine(fg) {746                Name("Couldn't reach the update server", fg)747                SubtleButton("retry", fg) { vm.loadChangelog() }748            }749            ChangelogPhase.Loaded -> Column(Modifier.fillMaxWidth()) {750                changelog.entries.forEachIndexed { index, entry ->751                    Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {752                        Row(verticalAlignment = Alignment.CenterVertically) {753                            Text("v${entry.version}", color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)754                            if (compareVersions(entry.version, vm.currentVersion) == 0) {755                                Text("  current", color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 9.sp)756                            }757                        }758                        Text(759                            entry.notes ?: "No notes for this release.",760                            color = fg.copy(alpha = 0.72f),761                            fontFamily = PeachType.Body,762                            fontSize = 11.sp,763                            lineHeight = 16.sp,764                            modifier = Modifier.padding(top = 3.dp),765                        )766                    }767                    if (index < changelog.entries.lastIndex) {768                        Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.08f)))769                    }770                }771            }772        }773    }774}775776@Composable777private fun VaultBody(778    fg: Color,779    vm: SettingsViewModel,780    s: VaultSettings,781    entriesCount: Int,782    onNavigate: (PeachNav) -> Unit,783) {784    val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")785    val current = s.trashRetentionDays ?: 0786    val isPro by vm.isPro.collectAsState()787    val dedupCount by vm.dedupCount.collectAsState()788    val dedupRunning by vm.dedupRunning.collectAsState()789    val dedupDone by vm.dedupDone.collectAsState()790    val history by vm.vaultHistory.collectAsState()791    val restoringSnapshotId by vm.restoringSnapshotId.collectAsState()792793    SettingsGroup("ENTRIES", fg, top = 0.dp) {794    RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }795    RowLine(fg) {796        Name("Duplicates", fg)797        val done = dedupDone798        if (done != null) {799            ValueText(if (done == 0) "already clean" else "removed $done", com.peachpasswords.ui.theme.peachColors.SyncOk)800        } else {801            val count = dedupCount802            val label = when {803                dedupRunning -> "scanning..."804                count == null -> "scan"805                count == 0 -> "none found"806                else -> "$count found"807            }808            SubtleButton(label, fg) {809                if (count == null || count == 0) vm.scanDuplicates()810            }811        }812    }813    if ((dedupCount ?: 0) > 0 && dedupDone == null) {814        Column(815            Modifier.fillMaxWidth()816                .padding(top = 2.dp, bottom = 8.dp)817                .clip(RoundedCornerShape(8.dp))818                .background(fg.copy(alpha = 0.08f))819                .border(1.dp, fg.copy(alpha = 0.18f), RoundedCornerShape(8.dp))820                .padding(10.dp),821            verticalArrangement = Arrangement.spacedBy(8.dp),822        ) {823            val count = dedupCount ?: 0824            Text(825                "$count duplicate ${if (count == 1) "entry" else "entries"} found. The newest copy of each will be kept; older duplicates will be moved to trash.",826                color = fg.copy(alpha = 0.82f),827                fontFamily = PeachType.Body,828                fontSize = 11.sp,829                lineHeight = 16.sp,830            )831            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {832                SubtleButton("cancel", fg) { vm.cancelDuplicateRemoval() }833                SubtleButton(if (dedupRunning) "removing..." else "remove duplicates", fg) { vm.removeDuplicates() }834            }835        }836    }837    }838839    SettingsGroup("MAINTENANCE", fg) {840    RowLine(fg) {841        Name("Trash auto-delete", fg)842        val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)843        SubtleButton(trashOptions[idx].second, fg) {844            vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)845        }846    }847    RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }848    RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }849    }850851    SettingsGroup("DATA", fg) {852    RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }853    RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }854    RowLine(fg) {855        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); if (!isPro) ProBadge(fg) }856        SubtleButton(if (isPro) "open" else "Pro", fg) { if (isPro) onNavigate(PeachNav.CodexGenerate) }857    }858    RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }859    }860861    SettingsGroup("UPDATES", fg) {862    UpdatesRows(fg, onNavigate)863    }864865    SettingsGroup("VAULT HISTORY", fg, initiallyOpen = false) {866    var historyShowAll by remember { mutableStateOf(false) }867    if (history.isEmpty()) {868        Text(869            "No snapshots yet. Peach saves automatically before every change — saves, syncs, and imports.",870            color = fg.copy(alpha = 0.68f),871            fontFamily = PeachType.Body,872            fontSize = 11.sp,873            lineHeight = 16.sp,874            modifier = Modifier.padding(bottom = 6.dp),875        )876    } else {877        Text(878            "Restoring locks your vault. Unlock with the password that encrypted that snapshot to confirm.",879            color = fg.copy(alpha = 0.68f),880            fontFamily = PeachType.Body,881            fontSize = 11.sp,882            lineHeight = 16.sp,883            modifier = Modifier.padding(bottom = 4.dp),884        )885        history.take(if (historyShowAll) history.size else 3).forEach { snap ->886            RowLine(fg) {887                Column(Modifier.weight(1f)) {888                    Text(snapshotTimeLabel(snap.savedAt), color = fg, fontFamily = PeachType.Body, fontSize = 12.sp)889                    Text(snapshotSubLabel(snap), color = fg.copy(alpha = 0.62f), fontFamily = PeachType.Mono, fontSize = 10.sp)890                }891                SubtleButton(if (restoringSnapshotId == snap.id) "..." else "restore", fg) {892                    vm.restoreVaultSnapshot(snap.id)893                }894            }895        }896        if (history.size > 3) {897            RowLine(fg) {898                Name(if (historyShowAll) "show less" else "${history.size - 3} older", fg)899                SubtleButton(if (historyShowAll) "hide" else "show", fg) { historyShowAll = !historyShowAll }900            }901        }902        Text(903            "${history.size} of 5 snapshots",904            color = fg.copy(alpha = 0.58f),905            fontFamily = PeachType.Mono,906            fontSize = 10.sp,907            modifier = Modifier.padding(top = 2.dp, bottom = 6.dp),908        )909    }910    }911912    SettingsGroup("ADVANCED", fg, initiallyOpen = false) {913        RowLine(fg) {914            Name("Replace vault from backup", com.peachpasswords.ui.theme.peachColors.SyncBusy)915            SubtleButton("open", com.peachpasswords.ui.theme.peachColors.SyncBusy) { onNavigate(PeachNav.Import) }916        }917        RowLine(fg) {918            Name("Destroy vault", com.peachpasswords.ui.theme.peachColors.Breach)919            SubtleButton("destroy", com.peachpasswords.ui.theme.peachColors.Breach) { onNavigate(PeachNav.Panic) }920        }921    }922}923924private fun snapshotSubLabel(snapshot: VaultSnapshot): String {925    val count = snapshot.entryCount?.let { "up to $it ${if (it == 1) "entry" else "entries"}" }926    return listOfNotNull(count, snapshotReasonLabel(snapshot.reason)).joinToString(" · ")927}928929private fun snapshotReasonLabel(reason: String): String = when (reason) {930    "local_save" -> "saved"931    "sync_received" -> "synced"932    "import" -> "imported"933    "restore" -> "restored"934    else -> reason935}936937private fun snapshotTimeLabel(savedAt: Long): String {938    val diff = System.currentTimeMillis() - savedAt939    if (diff < 60_000) return "Just now"940    if (diff < 3_600_000) return "${diff / 60_000}m ago"941    val date = Date(savedAt)942    val today = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())943    val thenDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date)944    val time = SimpleDateFormat("h:mm a", Locale.getDefault()).format(date)945    if (today == thenDay) return "Today $time"946    val yesterday = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date(System.currentTimeMillis() - 86_400_000))947    if (yesterday == thenDay) return "Yesterday $time"948    return SimpleDateFormat("MMM d h:mm a", Locale.getDefault()).format(date)949}950951/* ────────────────────────────────  Sync  ────────────────────────────────── */952953/**954 * The §11 migration copy. It must never imply that old peers keep working: the955 * whole point of the reset is that they cannot.956 */957private const val SECURE_RESET_DISCLOSURE =958    "Peach will archive this device's old Sync trust and start the new Sync generation. " +959        "Every other device must be updated first, then re-paired with this one — they will " +960        "not continue on their own. Your vault and your recovery words are not changed."961962private fun secureResetHeadline(state: String): String = when (state) {963    LEGACY_ACTIVE -> "Legacy Sync generation"964    RESET_REQUIRED -> "Reset required"965    RESET_CONFIRMED -> "Reset not completed"966    V2_ANCHOR, REPAIRING -> "Not re-paired"967    V2_ACTIVE -> "New Sync generation"968    UNKNOWN_STATE -> "Sync generation unreadable"969    else -> "Sync generation"970}971972private fun secureResetDetail(state: String): String = when (state) {973    LEGACY_ACTIVE ->974        "This device still holds the old Sync trust. Resetting retires it for good: update " +975            "Peach on every other device, then re-pair each one."976    RESET_REQUIRED ->977        "Sync is stopped until the reset completes. Update Peach on every other device, then " +978            "reset this one and re-pair each device."979    RESET_CONFIRMED ->980        "The reset did not finish. Nothing was lost — the old trust is archived. Try again."981    V2_ANCHOR, REPAIRING ->982        "This device anchors the new Sync generation and is not re-paired yet. Pair each device " +983            "again; until then it keeps its own vault and cannot sync."984    V2_ACTIVE ->985        "This device is on the new Sync generation. Each device is re-paired individually."986    UNKNOWN_STATE ->987        "This device's Sync generation can't be read, so sync is stopped. Reinstall or contact support."988    else -> "Sync state is unavailable."989}990991@Composable992private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {993    val context = LocalContext.current994    val syncVm: SyncViewModel = hiltViewModel()995    val pairedDevices by syncVm.pairedDevices.collectAsState()996    val pendingVouched by syncVm.pendingVouched.collectAsState()997    val syncStatus by syncVm.status.collectAsState()998    val configuredRelayUrl by syncVm.privateRelayUrl.collectAsState()999    val syncMode by syncVm.syncMode.collectAsState()1000    val backgroundSyncEnabled by syncVm.backgroundSyncEnabled.collectAsState()1001    var notificationsAvailable by remember {1002        mutableStateOf(canShowBackgroundSyncNotification(context))1003    }1004    var showBackgroundSyncPrompt by remember { mutableStateOf(false) }1005    val scope = rememberCoroutineScope()1006    var confirmUnpair by remember { mutableStateOf<String?>(null) }1007    var renamingDeviceId by remember { mutableStateOf<String?>(null) }1008    var renameDraft by remember { mutableStateOf("") }1009    var rotateConfirmOpen by remember { mutableStateOf(false) }1010    var rotating by remember { mutableStateOf(false) }1011    var rotateError by remember { mutableStateOf<String?>(null) }1012    var relayUrlDraft by remember(configuredRelayUrl) {1013        mutableStateOf(privateRelayDraftOf(configuredRelayUrl))1014    }1015    var relayUrlStatus by remember { mutableStateOf<String?>(null) }1016    var showConnection by remember { mutableStateOf(false) }1017    var showRecovery by remember { mutableStateOf(false) }10181019    SubLabel("SECURE SYNC RESET", fg)1020    val generation by syncVm.generationState.collectAsState()1021    var resetOpen by remember { mutableStateOf(false) }1022    var resetPassword by remember { mutableStateOf("") }1023    var resetError by remember { mutableStateOf<String?>(null) }1024    var resetting by remember { mutableStateOf(false) }1025    val resetOffered = generation.state == LEGACY_ACTIVE ||1026        generation.state == RESET_REQUIRED ||1027        generation.state == RESET_CONFIRMED10281029    RowLine(fg) {1030        Column(Modifier.weight(1f)) {1031            Text(secureResetHeadline(generation.state), color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1032            Text(1033                secureResetDetail(generation.state),1034                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1035                modifier = Modifier.padding(top = 2.dp),1036            )1037            resetError?.let {1038                Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 2.dp))1039            }1040        }1041        if (resetOffered) {1042            SubtleButton("reset sync", fg) {1043                resetError = null1044                resetPassword = ""1045                resetOpen = true1046            }1047        }1048    }10491050    if (resetOpen) {1051        AlertDialog(1052            onDismissRequest = { if (!resetting) resetOpen = false },1053            title = { Text("Reset Sync on this device?", color = fg, fontFamily = PeachType.Body) },1054            text = {1055                Column(verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {1056                    Text(1057                        SECURE_RESET_DISCLOSURE,1058                        color = fg.copy(alpha = 0.8f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,1059                    )1060                    PwField("master password", resetPassword, fg) { resetPassword = it }1061                }1062            },1063            confirmButton = {1064                SubtleButton(if (resetting) "resetting..." else "reset", peachColors.Breach) {1065                    if (!resetting) scope.launch {1066                        resetting = true1067                        resetError = syncVm.confirmReset(resetPassword)1068                        resetPassword = ""1069                        resetting = false1070                        if (resetError == null) resetOpen = false1071                    }1072                }1073            },1074            dismissButton = {1075                SubtleButton("cancel", fg) { if (!resetting) resetOpen = false }1076            },1077        )1078    }10791080    SubLabel("ADD A DEVICE", fg, top = 0.dp)1081    RowLine(fg) {1082        Column(Modifier.weight(1f)) {1083            Text("Pair a device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1084            Text(1085                "Either scan a QR shown on the other device, or show this device's QR for the other one to scan.",1086                color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1087                modifier = Modifier.padding(top = 2.dp),1088            )1089        }1090        // "Scan" opens the camera-driven AdoptVault flow: the phone is the1091        // receiver. "Show a code" opens CodePair: the phone is the source.1092        // Both are valid pairing entry points; without scan, a phone that wants1093        // to join an existing browser-only vault has no path.1094        SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }1095        Spacer(Modifier.width(PeachSpacing.xs))1096        SubtleButton("show code", fg) { onNavigate(PeachNav.CodePair) }1097    }10981099    SubLabel("SYNC STATUS", fg)1100    val indicator = syncIndicator(syncStatus, pairedDevices.size)1101    RowLine(fg) {1102        SyncIndicatorDot(1103            indicator = indicator,1104            label = syncIndicatorLabel(indicator, syncStatus),1105            modifier = Modifier.padding(end = PeachSpacing.sm),1106            size = 8.dp,1107        )1108        Text(1109            describeSyncOutcome(syncStatus),1110            color = fg.copy(alpha = 0.7f),1111            fontFamily = PeachType.Body,1112            fontSize = 11.sp,1113            lineHeight = 16.sp,1114            modifier = Modifier.weight(1f),1115        )1116        SubtleButton(if (syncStatus.syncing) "syncing..." else "sync now", fg) {1117            if (!syncStatus.syncing) syncVm.syncNow()1118        }1119    }11201121    SubLabel("PAIRED DEVICES", fg)1122    if (pairedDevices.isEmpty()) {1123        PeachEmptyOrEndState(1124            message = "No paired devices yet.",1125            detail = "Pair a nearby phone, tablet, or browser when you're ready to sync.",1126            modifier = Modifier.padding(top = PeachSpacing.xs),1127        )1128    } else {1129        pairedDevices.forEach { d ->1130            RowLine(fg) {1131                Column(Modifier.weight(1f)) {1132                    if (renamingDeviceId == d.deviceId) {1133                        Box(1134                            Modifier.fillMaxWidth()1135                                .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1136                                .padding(horizontal = 10.dp, vertical = 8.dp),1137                        ) {1138                            BasicTextField(1139                                value = renameDraft,1140                                onValueChange = { renameDraft = it.take(64) },1141                                singleLine = true,1142                                textStyle = TextStyle(fontFamily = PeachType.Body, fontSize = 13.sp, color = fg),1143                                cursorBrush = SolidColor(fg),1144                                modifier = Modifier.fillMaxWidth(),1145                            )1146                        }1147                    } else {1148                        Text(d.localAlias ?: d.deviceName ?: d.deviceId, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1149                    }1150                    Text(1151                        "${deviceTypeLabel(d.deviceType)} · ${syncTimeLabel(d.lastSyncedAt)}${if (isSyncStale(d.lastSyncedAt)) " · not seen recently" else ""}",1152                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1153                        modifier = Modifier.padding(top = 2.dp),1154                    )1155                }1156                if (confirmUnpair != d.deviceId) {1157                    if (renamingDeviceId == d.deviceId) {1158                        SubtleButton("cancel", fg) { renamingDeviceId = null }1159                        Spacer(Modifier.width(PeachSpacing.xs))1160                        SubtleButton("save", fg) {1161                            if (renameDraft.isNotBlank()) {1162                                syncVm.renameDevice(d.deviceId, renameDraft)1163                                renamingDeviceId = null1164                            }1165                        }1166                    } else {1167                        SubtleButton("rename", fg) {1168                            renameDraft = d.localAlias ?: d.deviceName ?: ""1169                            renamingDeviceId = d.deviceId1170                        }1171                    }1172                    if (renamingDeviceId != d.deviceId) {1173                        Spacer(Modifier.width(PeachSpacing.xs))1174                        SubtleButton("remove", fg) { confirmUnpair = d.deviceId }1175                    }1176                }1177            }1178            // HOLE 4: revocation stops this device receiving future changes. It1179            // does NOT secure the vault against it — that device may already1180            // hold the recovery words, which are master-password-equivalent and1181            // restore the whole vault anywhere, forever, with no sync involved.1182            // Say so here rather than leaving the user falsely reassured.1183            if (confirmUnpair == d.deviceId) {1184                Column(Modifier.fillMaxWidth().padding(bottom = PeachSpacing.sm)) {1185                    Text(1186                        "Stops this device receiving future changes. It doesn't lock it " +1187                            "out of what it already has - if it's lost or stolen, also " +1188                            "change your master password and generate new recovery words.",1189                        color = fg.copy(alpha = 0.7f),1190                        fontFamily = PeachType.Body,1191                        fontSize = 11.sp,1192                        lineHeight = 16.sp,1193                    )1194                    Row(1195                        modifier = Modifier.fillMaxWidth().padding(top = PeachSpacing.sm),1196                        horizontalArrangement = Arrangement.End,1197                    ) {1198                        SubtleButton("cancel", fg) { confirmUnpair = null }1199                        Spacer(Modifier.width(PeachSpacing.sm))1200                        SubtleButton("remove", peachColors.Breach) { syncVm.unpairDevice(d.deviceId); confirmUnpair = null }1201                    }1202                }1203            }1204        }1205    }12061207    SyncDisclosure(1208        title = "Connection",1209        summary = "Background sync, relay, and privacy choices",1210        expanded = showConnection,1211        fg = fg,1212        onToggle = { showConnection = !showConnection },1213    )1214    if (showConnection) {1215        RowLine(fg) {1216            Column(Modifier.weight(1f)) {1217                Text("Background sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1218                Text(1219                    when {1220                        backgroundSyncEnabled && !notificationsAvailable ->1221                            "Action needed — Android notifications are off, so background sync is not visible."1222                        backgroundSyncEnabled ->1223                            "On — keeps this phone reachable for paired devices."1224                        else ->1225                            "Off — Peach syncs only while you are using the app."1226                    },1227                    color = fg.copy(alpha = 0.7f),1228                    fontFamily = PeachType.Body,1229                    fontSize = 11.sp,1230                    lineHeight = 16.sp,1231                    modifier = Modifier.padding(top = 2.dp),1232                )1233            }1234            SubtleButton(1235                if (backgroundSyncEnabled && !notificationsAvailable) "allow" else "change",1236                if (backgroundSyncEnabled && !notificationsAvailable) peachColors.Breach else fg,1237            ) { showBackgroundSyncPrompt = true }1238        }1239        SyncModeRow(1240            title = "Public relay",1241            detail = "Works anywhere with nothing to set up. The relay cannot read your vault.",1242            selected = syncMode == SyncMode.PUBLIC,1243            fg = fg,1244        ) { syncVm.setSyncMode(SyncMode.PUBLIC) }1245        SyncModeRow(1246            title = "Private relay",1247            detail = "Use your own peach-relay on your own domain.",1248            selected = syncMode == SyncMode.PRIVATE,1249            fg = fg,1250        ) { syncVm.setSyncMode(SyncMode.PRIVATE) }12511252        if (syncMode == SyncMode.PRIVATE) {1253            Text(1254                "RELAY URL",1255                color = fg.copy(alpha = 0.6f),1256                fontFamily = PeachType.Mono,1257                fontSize = 8.sp,1258                letterSpacing = 0.22.em,1259                modifier = Modifier.padding(top = 8.dp),1260            )1261            Box(1262                Modifier.fillMaxWidth().padding(top = 6.dp)1263                    .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1264                    .padding(horizontal = 12.dp, vertical = 10.dp),1265            ) {1266                BasicTextField(1267                    value = relayUrlDraft,1268                    onValueChange = { relayUrlDraft = it; relayUrlStatus = null },1269                    singleLine = true,1270                    textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 11.sp, color = fg),1271                    cursorBrush = SolidColor(fg),1272                    modifier = Modifier.fillMaxWidth(),1273                )1274            }1275            val needsRelayUrl = configuredRelayUrl.isEmpty()1276            RowLine(fg) {1277                val message = relayUrlStatus1278                    ?: if (needsRelayUrl) {1279                        "Sync is paused until you enter your relay URL."1280                    } else {1281                        "Only secure wss:// relays are accepted."1282                    }1283                val warn = relayUrlStatus?.startsWith("Use") == true ||1284                    (relayUrlStatus == null && needsRelayUrl)1285                ValueText(message, if (warn) peachColors.Breach else fg, Modifier.weight(1f))1286                Spacer(Modifier.width(PeachSpacing.xs))1287                SubtleButton("save", fg) {1288                    relayUrlStatus = if (syncVm.setRelayUrl(relayUrlDraft)) {1289                        relayUrlDraft = privateRelayDraftOf(syncVm.privateRelayUrl.value)1290                        "Saved"1291                    } else {1292                        "Use a valid wss:// relay URL"1293                    }1294                }1295            }1296        }12971298        SyncModeRow(1299            title = "No sync",1300            detail = "Keep this device separate and move backups by hand.",1301            selected = syncMode == SyncMode.OFF,1302            fg = fg,1303        ) { syncVm.setSyncMode(SyncMode.OFF) }1304        Hint("Pairing authorizes a device, not a cloud account.", fg)1305    }13061307    if (pendingVouched.isNotEmpty()) {1308        SubLabel("PENDING DEVICES", fg)1309        pendingVouched.forEach { dev ->1310            RowLine(fg) {1311                Column(Modifier.weight(1f)) {1312                    Text(dev.deviceName, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1313                    Text(1314                        "Was added by another device. Allow it to sync?",1315                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1316                        modifier = Modifier.padding(top = 2.dp),1317                    )1318                }1319                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1320                    SubtleButton("Allow", fg) { syncVm.confirmVouchedDevice(dev.deviceId) }1321                    SubtleButton("Reject", fg) { syncVm.rejectVouchedDevice(dev.deviceId) }1322                }1323            }1324        }1325    }13261327    SyncDisclosure(1328        title = "Recovery & security",1329        summary = "For a lost or stolen device",1330        expanded = showRecovery,1331        fg = fg,1332        onToggle = { showRecovery = !showRecovery },1333    )1334    if (showRecovery) {1335        RowLine(fg) {1336            Column(Modifier.weight(1f)) {1337                Text("Re-pair this device", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1338                Text(1339                    "Scan only when this populated vault previously trusted the source device.",1340                    color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1341                    modifier = Modifier.padding(top = 2.dp),1342                )1343            }1344            SubtleButton("scan", fg) { onNavigate(PeachNav.AdoptVault) }1345        }1346        if (rotateConfirmOpen) {1347            Hint("This disconnects every paired device and changes your 12 recovery words. You'll be shown the new words next.", peachColors.Breach)1348            rotateError?.let {1349                Text(it, color = peachColors.Breach, fontFamily = PeachType.Body, fontSize = 11.sp, modifier = Modifier.padding(top = 6.dp))1350            }1351            Row(Modifier.padding(top = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {1352                SubtleButton("cancel", fg) { if (!rotating) rotateConfirmOpen = false }1353                SubtleButton(if (rotating) "rotating..." else "Rotate sync identity", peachColors.Breach) {1354                    if (rotating) return@SubtleButton1355                    rotating = true1356                    rotateError = null1357                    scope.launch {1358                        val ok = syncVm.rotateSyncIdentity()1359                        rotating = false1360                        if (ok) {1361                            rotateConfirmOpen = false1362                            onNavigate(PeachNav.RecoverySetup)1363                        } else {1364                            rotateError = "Rotation failed. Unlock your real vault and try again."1365                        }1366                    }1367                }1368            }1369        } else {1370            RowLine(fg) {1371                Column(Modifier.weight(1f)) {1372                    Text("Rotate sync identity", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1373                    Text(1374                        "Disconnects every device and replaces the keys used for sync.",1375                        color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1376                        modifier = Modifier.padding(top = 2.dp),1377                    )1378                }1379                SubtleButton("rotate", peachColors.Breach) { rotateError = null; rotateConfirmOpen = true }1380            }1381        }1382    }13831384    if (showBackgroundSyncPrompt) {1385        BackgroundSyncDialog { enabled ->1386            showBackgroundSyncPrompt = false1387            notificationsAvailable = canShowBackgroundSyncNotification(context)1388            syncVm.setBackgroundSyncEnabled(enabled)1389        }1390    }1391}13921393private fun deviceTypeLabel(type: String?): String = when (type) {1394    "android" -> "Android"1395    "phone" -> "Phone"1396    "tablet" -> "Tablet"1397    "browser" -> "Browser"1398    else -> "Device"1399}14001401private fun syncTimeLabel(lastSyncedAt: Long?): String {1402    if (lastSyncedAt == null) return "never synced"1403    val diff = System.currentTimeMillis() - lastSyncedAt1404    if (diff < 60_000) return "just now"1405    if (diff < 3_600_000) return "${diff / 60_000}m ago"1406    if (diff < 86_400_000) return "${diff / 3_600_000}h ago"1407    return "${diff / 86_400_000}d ago"1408}14091410private fun isSyncStale(lastSyncedAt: Long?): Boolean =1411    lastSyncedAt != null && System.currentTimeMillis() - lastSyncedAt > 7L * 24L * 60L * 60L * 1000L14121413/* ────────────────────────────────  Pro  ─────────────────────────────────── */14141415@Composable1416private fun ProBody(fg: Color, vm: SettingsViewModel) {1417    val ctx = LocalContext.current1418    val isPro by vm.isPro.collectAsState()1419    if (isPro) {1420        ProActiveBody(fg, vm)1421        return1422    }1423    val features = listOf(1424        "Peach Sync" to "End-to-end encrypted",1425        "Peach Codex" to "Restore from paper",1426        "Passkeys" to "Zero-knowledge WebAuthn",1427        "Advanced Vault Health" to "Reuse · age · exposure",1428        "Canary entries" to "Detects vault compromise",1429        "Duress vault" to "Decoy under coercion",1430    )1431    Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1432    Text(1433        "Everything, everywhere.",1434        modifier = Modifier.padding(top = 8.dp),1435        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,1436    )1437    Text(1438        "One key unlocks every Pro feature — for the lifetime of the app.",1439        modifier = Modifier.padding(top = 6.dp),1440        color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,1441    )1442    Spacer(Modifier.height(10.dp))1443    features.forEachIndexed { i, (name, desc) ->1444        // Compact rows (6dp vs. the shared 9dp default) — this card is the1445        // tallest in the deck (6 features + price + CTA) and used to leave1446        // its button with no breathing room before the fanned tab stacked1447        // right beneath it in preview mode.1448        RowLine(fg, verticalPadding = 6.dp) {1449            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1450                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1451                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1452            }1453            Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1454        }1455    }1456    Spacer(Modifier.height(12.dp))1457    Text(1458        "$39",1459        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,1460    )1461    Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)1462    Spacer(Modifier.height(10.dp))1463    Box(1464        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1465            .background(fg.copy(alpha = 0.16f))1466            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1467            .clickable {1468                runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }1469            }1470            .padding(vertical = 12.dp),1471        contentAlignment = Alignment.Center,1472    ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }14731474    // Trailing breathing room so the button clears the fanned tab stacked1475    // beneath this card in preview mode, where the scrollable viewport clips1476    // right around here (the license-key section below is already out of1477    // view at that height).1478    Spacer(Modifier.height(44.dp))14791480    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1481    var key by remember { mutableStateOf("") }1482    val activating by vm.activating.collectAsState()1483    val activationError by vm.activationError.collectAsState()1484    Box(1485        Modifier.fillMaxWidth().padding(top = 6.dp)1486            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))1487            .padding(horizontal = 12.dp, vertical = 10.dp),1488    ) {1489        BasicTextField(1490            value = key,1491            // NOT .uppercase() — base58 (the license payload encoding) is1492            // case-sensitive; forcing the whole string to uppercase silently1493            // corrupted every real key before it ever reached signature1494            // verification, so activation always failed with a real key.1495            onValueChange = { key = it; vm.clearActivationError() },1496            singleLine = true,1497            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),1498            cursorBrush = SolidColor(fg),1499            modifier = Modifier.fillMaxWidth(),1500            decorationBox = { inner ->1501                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)1502                inner()1503            },1504        )1505    }1506    if (activationError != null) {1507        Text(activationError!!, color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))1508    }1509    Spacer(Modifier.height(8.dp))1510    Box(1511        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1512            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))1513            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1514            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }1515            .padding(vertical = 12.dp),1516        contentAlignment = Alignment.Center,1517    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }1518}15191520@Composable1521private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {1522    val ctx = LocalContext.current1523    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")1524    val licenseKey by vm.licenseKey.collectAsState()1525    val issuedAt by vm.licenseIssuedAt.collectAsState()1526    var showKey by remember { mutableStateOf(false) }1527    var copied by remember { mutableStateOf(false) }1528    val scope = rememberCoroutineScope()1529    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {1530        com.peachpasswords.ui.components.PeachMark(size = 60.dp)1531    }1532    Text(1533        "Peach Pro",1534        modifier = Modifier.fillMaxWidth(),1535        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,1536        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1537    )1538    Text(1539        formatLicenseActiveSince(issuedAt),1540        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),1541        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,1542        textAlign = androidx.compose.ui.text.style.TextAlign.Center,1543    )1544    licenseKey?.let { key ->1545        Spacer(Modifier.height(12.dp))1546        Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)1547        RowLine(fg) {1548            Text(1549                if (showKey) key else "************************",1550                color = fg.copy(alpha = if (showKey) 0.82f else 0.58f),1551                fontFamily = PeachType.Mono,1552                fontSize = 10.sp,1553                modifier = Modifier.weight(1f),1554            )1555            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {1556                SubtleButton(if (copied) "copied" else "copy", fg) {1557                    PeachClipboard.copy(ctx, "peach license", key)1558                    copied = true1559                    scope.launch {1560                        delay(1_500)1561                        copied = false1562                    }1563                }1564                SubtleButton(if (showKey) "hide" else "reveal", fg) { showKey = !showKey }1565            }1566        }1567    }1568    Spacer(Modifier.height(12.dp))1569    features.forEachIndexed { i, name ->1570        RowLine(fg) {1571            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {1572                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))1573                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1574            }1575            Text("unlocked", color = com.peachpasswords.ui.theme.peachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)1576        }1577    }1578    Spacer(Modifier.height(12.dp))1579    Box(1580        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))1581            .border(1.dp, com.peachpasswords.ui.theme.peachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))1582            .clickable { vm.deactivate() }1583            .padding(vertical = 12.dp),1584        contentAlignment = Alignment.Center,1585    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }1586}15871588private fun formatLicenseActiveSince(issuedAt: Long?): String {1589    if (issuedAt == null) return "Active"1590    val monthYear = SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format(Date(issuedAt))1591    return "Active since $monthYear"1592}15931594/* ──────────────────────────────  Feedback  ───────────────────────────────── */15951596@OptIn(ExperimentalLayoutApi::class)1597@Composable1598private fun FeedbackBody(fg: Color, vm: SettingsViewModel) {1599    val categories = listOf("Bug report", "Feature request", "Question", "Other")1600    var category by remember { mutableStateOf(categories[0]) }1601    var message by remember { mutableStateOf("") }1602    val state by vm.feedbackState.collectAsState()16031604    // Reset transient state when the card leaves composition so reopening starts fresh.1605    DisposableEffect(Unit) { onDispose { vm.resetFeedback() } }16061607    if (state is FeedbackState.Sent) {1608        Box(1609            Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))1610                .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),1611        ) {1612            Column {1613                Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)1614                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))1615            }1616        }1617        return1618    }16191620    val sending = state is FeedbackState.Sending16211622    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)1623    SubLabel("TYPE", fg)1624    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1625        categories.forEach { cat -> Pill(cat, category == cat, fg) { if (!sending) category = cat } }1626    }1627    SubLabel("MESSAGE", fg)1628    Box(1629        Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))1630            .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))1631            .padding(10.dp),1632    ) {1633        if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)1634        BasicTextField(1635            value = message, onValueChange = { message = it.take(MAX_FEEDBACK_MESSAGE_LENGTH) },1636            enabled = !sending,1637            textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),1638            cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),1639        )1640    }1641    Text(1642        "Version ${BuildConfig.VERSION_NAME} · will be included automatically",1643        modifier = Modifier.padding(top = 6.dp),1644        color = fg.copy(alpha = 0.52f),1645        fontFamily = PeachType.Mono,1646        fontSize = 10.sp,1647        lineHeight = 14.sp,1648    )1649    Spacer(Modifier.height(8.dp))16501651    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {1652        val canSend = !sending && sanitizeFeedbackMessage(message).isNotBlank()1653        Box(1654            Modifier.clip(RoundedCornerShape(8.dp))1655                .border(1.dp, fg.copy(alpha = if (canSend) 0.28f else 0.14f), RoundedCornerShape(8.dp))1656                .background(fg.copy(alpha = if (canSend) 0.08f else 0.04f))1657                .clickable(enabled = canSend) { vm.sendFeedback(category, message) }1658                .padding(horizontal = 12.dp, vertical = 6.dp),1659        ) {1660            Text(1661                feedbackSubmitLabel(state),1662                color = fg.copy(alpha = if (canSend) 1f else 0.4f),1663                fontFamily = PeachType.Mono, fontSize = 11.sp,1664            )1665        }1666        if (sending) {1667            CircularProgressIndicator(1668                color = LocalPeachAccent.current,1669                strokeWidth = 2.dp,1670                modifier = Modifier.size(16.dp),1671            )1672        }1673    }16741675    (state as? FeedbackState.Error)?.let { err ->1676        Text(1677            err.message,1678            modifier = Modifier.padding(top = 8.dp),1679            color = peachColors.Breach,1680            fontFamily = PeachType.Mono,1681            fontSize = 11.sp,1682            lineHeight = 15.sp,1683        )1684    }16851686    Hint("Sent anonymously · no account required", fg)1687}16881689/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */16901691@Composable1692internal fun DuressSection(fg: Color, vm: SettingsViewModel) {1693    val configured by vm.duressConfigured.collectAsState()1694    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)1695}16961697@Composable1698private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {1699    Text(1700        "Duress password is active",1701        color = peachColors.HealthOk,1702        fontFamily = PeachType.Mono,1703        fontSize = 11.sp,1704        modifier = Modifier.padding(top = 6.dp),1705    )1706    Spacer(Modifier.height(8.dp))1707    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }1708    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)1709}17101711@Composable1712private fun DuressForm(fg: Color, vm: SettingsViewModel) {1713    var enabled by remember { mutableStateOf(false) }1714    var password by remember { mutableStateOf("") }1715    var confirm by remember { mutableStateOf("") }1716    var action by remember { mutableStateOf(DuressAction.DECOY) }1717    var error by remember { mutableStateOf<String?>(null) }1718    val scope = rememberCoroutineScope()17191720    RowLine(fg) {1721        Name("Duress password", fg)1722        Toggle(enabled, fg) { on ->1723            enabled = on1724            if (!on) { password = ""; confirm = ""; error = null }1725        }1726    }1727    Text(1728        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",1729        color = fg.copy(alpha = 0.7f),1730        fontFamily = PeachType.Mono,1731        fontSize = 10.sp,1732        modifier = Modifier.padding(top = 6.dp),1733    )17341735    AnimatedVisibility(enabled) {1736        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {1737            PwField("DURESS PASSPHRASE", password, fg) { password = it; error = null }1738            PwField("CONFIRM DURESS PASSPHRASE", confirm, fg) { confirm = it; error = null }17391740            Text(1741                "When your duress password is entered at the lock screen, Peach will:",1742                color = fg.copy(alpha = 0.7f),1743                fontFamily = PeachType.Mono,1744                fontSize = 10.sp,1745                modifier = Modifier.padding(top = 4.dp),1746            )17471748            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }1749            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }17501751            error?.let { Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }17521753            val canSave = password.isNotBlank() && confirm.isNotBlank()1754            DuressSaveButton("Save duress password", fg, canSave) {1755                error = when {1756                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"1757                    password != confirm -> "Passwords do not match"1758                    else -> null1759                }1760                if (error == null) scope.launch {1761                    if (vm.saveDuress(password, action)) {1762                        password = ""; confirm = ""; enabled = false1763                    } else {1764                        error = "Couldn't save — the duress passphrase must differ from your real password"1765                    }1766                }1767            }1768        }1769    }1770}17711772@Composable1773private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {1774    val accent = LocalPeachAccent.current1775    Row(1776        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),1777        verticalAlignment = Alignment.CenterVertically,1778        horizontalArrangement = Arrangement.spacedBy(10.dp),1779    ) {1780        Box(1781            Modifier.size(16.dp).clip(CircleShape)1782                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),1783            contentAlignment = Alignment.Center,1784        ) {1785            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))1786        }1787        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)1788    }1789}17901791@Composable1792private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {1793    val accent = LocalPeachAccent.current1794    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)1795    Box(1796        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1797            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))1798            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))1799            .let { if (enabled) it.clickable(onClick = onClick) else it }1800            .padding(vertical = 11.dp),1801        contentAlignment = Alignment.Center,1802    ) {1803        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)1804    }1805}18061807@Composable1808private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {1809    Box(1810        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))1811            .border(1.dp, peachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))1812            .clickable(onClick = onClick)1813            .padding(vertical = 11.dp),1814        contentAlignment = Alignment.Center,1815    ) {1816        Text(label, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)1817    }1818}18191820/** One choice in the three-way sync selector. */1821@Composable1822private fun SyncModeRow(1823    title: String,1824    detail: String,1825    selected: Boolean,1826    fg: Color,1827    onSelect: () -> Unit,1828) {1829    RowLine(fg, Modifier.clickable(onClick = onSelect)) {1830        Column(Modifier.weight(1f)) {1831            Text(title, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1832            Text(1833                detail,1834                color = fg.copy(alpha = 0.7f),1835                fontFamily = PeachType.Body,1836                fontSize = 11.sp,1837                lineHeight = 16.sp,1838                modifier = Modifier.padding(top = 2.dp),1839            )1840        }1841        Text(1842            if (selected) "●" else "○",1843            color = if (selected) fg else fg.copy(alpha = 0.45f),1844            fontFamily = PeachType.Mono,1845            fontSize = 14.sp,1846            modifier = Modifier.padding(start = 10.dp),1847        )1848    }1849}