svault-ai 0.9.3

AI-aware secret access layer — enforces structured requests and detects suspicious patterns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
//! Rendering for the Svault TUI. Each screen draws into a three-row layout:
//! a header (title + status), a body, and a footer with context key hints.

use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Cell, Clear, Paragraph, Row, Table, Wrap},
    Frame,
};

use super::theme;
use super::{
    tier_label, App, ClassifyForm, CreateForm, InitForm, JudgeEditForm, JudgeEntry, JudgeForm,
    MsgKind, Screen, SecretAddForm, SecretScreen, SettingsForm, UnlockForm,
};

const CYAN: Color = theme::ACCENT;
const DIM: Color = theme::MUTED;

pub fn draw(frame: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // header
            Constraint::Min(0),    // body
            Constraint::Length(1), // status line
            Constraint::Length(3), // footer / key hints
        ])
        .split(frame.area());

    draw_header(frame, chunks[0], app.daemon_running);

    match &mut app.screen {
        Screen::List => draw_list(frame, chunks[1], &app.vaults, &mut app.list_state),
        Screen::Create(form) => draw_create(frame, chunks[1], form),
        Screen::Settings(form) => draw_settings(frame, chunks[1], form),
        Screen::Unlock(form) => draw_unlock(frame, chunks[1], form),
        Screen::Secrets(scr) => draw_secrets(frame, chunks[1], scr),
        Screen::SecretAdd(form) => draw_secret_add(frame, chunks[1], form),
        Screen::RecoveryCode(code) => draw_recovery_code(frame, chunks[1], code),
        Screen::Import(form) => draw_import(frame, chunks[1], form),
        Screen::Recover(form) => draw_recover(frame, chunks[1], form),
        Screen::Activity(scr) => draw_activity(frame, chunks[1], scr),
        Screen::Classify(form) => draw_classify(frame, chunks[1], form),
        Screen::Judge(form) => draw_judge(frame, chunks[1], form),
    }

    draw_status(frame, chunks[2], app);
    draw_footer(frame, chunks[3], app);

    // Overlays sit on top of everything when toggled.
    if app.show_help {
        draw_help(frame, chunks[1], &app.screen);
    }
    if app.confirm_quit {
        draw_quit(frame, chunks[1]);
    }
}

// ── Quit confirmation ────────────────────────────────────────────────────────────

fn draw_quit(frame: &mut Frame, area: Rect) {
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled("  Quit Svault?", theme::title())),
        Line::from(""),
        Line::from(Span::styled(
            "  enter  quit        esc / any key  stay",
            theme::label_dim(),
        )),
    ];
    let popup = centered_rect(44, 30, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Confirm ")
        .border_style(Style::default().fg(theme::WARN));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

// ── Header ─────────────────────────────────────────────────────────────────────

fn draw_header(frame: &mut Frame, area: Rect, daemon_running: bool) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme::border());
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Left: title + subtitle.
    let title = Line::from(vec![
        Span::styled(" Svault ", theme::title()),
        Span::styled("— AI-aware secret manager", theme::label_dim()),
    ]);
    frame.render_widget(Paragraph::new(title), inner);

    // Right: daemon indicator (green when running, dim when off).
    let (label, color) = if daemon_running {
        ("daemon running ", theme::OK)
    } else {
        ("daemon off ", theme::MUTED)
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(label, Style::default().fg(color))))
            .alignment(Alignment::Right),
        inner,
    );
}

// ── Status line ──────────────────────────────────────────────────────────────────

/// A single dedicated line for the most recent status message, below the body.
fn draw_status(frame: &mut Frame, area: Rect, app: &App) {
    let Some(status) = &app.status else {
        return;
    };
    let (color, prefix) = match status.kind {
        MsgKind::Ok => (theme::OK, "ok: "),
        MsgKind::Warn => (theme::WARN, "warning: "),
        MsgKind::Error => (theme::ERR, "error: "),
        MsgKind::Info => (theme::ACCENT, "note: "),
    };
    let line = Line::from(vec![
        Span::raw(" "),
        Span::styled(
            format!("{prefix}{}", status.text),
            Style::default().fg(color),
        ),
    ]);
    frame.render_widget(Paragraph::new(line), area);
}

// ── Footer ─────────────────────────────────────────────────────────────────────

fn draw_footer(frame: &mut Frame, area: Rect, app: &App) {
    // Each screen has a full hint and a compact fallback. On a narrow terminal
    // the single-line footer would clip the full hint from the right — losing
    // the "help" and "quit" hints entirely — so we drop to the compact form,
    // which always keeps "h/? help" discoverable. Press h or ? for the full
    // keybinding overlay.
    let (full, compact): (&str, &str) = if app.confirm_quit {
        (
            "enter  quit        esc / any key  stay",
            "enter quit  esc stay",
        )
    } else if app.show_help {
        ("any key / esc  close help", "any key  close")
    } else {
        match &app.screen {
            Screen::List => (
                "↑/↓ move   enter open   c create   u unlock   l lock   s settings   shift-J judge   v activity   e export   i import   r recover   d daemon   h/? help   q quit",
                "↑/↓ move   enter open   shift-J judge   h/? help   q quit",
            ),
            Screen::Activity(_) => ("↑/↓ scroll   esc / b back   q quit", "↑/↓ scroll   esc back"),
            Screen::Create(_) => (
                "↑/↓ field   ←/→ change   space toggle   enter next/create   esc cancel",
                "↑/↓ field   enter next   esc cancel",
            ),
            Screen::Settings(_) => (
                "↑/↓ field   ←/→ change   space toggle   enter next/save   esc cancel",
                "↑/↓ field   enter next   esc cancel",
            ),
            Screen::Unlock(_) => (
                "type passphrase   enter unlock   esc cancel",
                "enter unlock   esc cancel",
            ),
            Screen::Secrets(scr) => {
                if scr.reveal.is_some() {
                    ("space reveal/hide   esc close", "space hide   esc close")
                } else if scr.pending_delete.is_some() {
                    ("y confirm delete   n cancel", "y delete   n cancel")
                } else {
                    (
                        "↑/↓ move   enter view   a add   c classify   d delete   l lock   h/? help   esc back",
                        "↑/↓ move   enter view   c classify   h/? help   esc back",
                    )
                }
            }
            Screen::SecretAdd(_) => (
                "↑/↓ field   enter next/save   esc cancel",
                "↑/↓ field   enter save   esc cancel",
            ),
            Screen::Classify(_) => (
                "↑/↓ field   ←/→ change   space toggle   enter next/save   esc cancel",
                "↑/↓ field   enter save   esc cancel",
            ),
            Screen::Judge(form) => {
                if form.entry.is_some() {
                    (
                        "type/paste   tab move   enter confirm   esc cancel",
                        "enter confirm   esc cancel",
                    )
                } else if !form.unlocked {
                    (
                        "enter unlock / create the keyring   esc back",
                        "enter unlock   esc back",
                    )
                } else {
                    (
                        "↑/↓ move   space toggle   a add   e edit   v view   k key   d default   t test   x remove   esc back",
                        "↑/↓ move   a add   e edit   esc back",
                    )
                }
            }
            Screen::RecoveryCode(_) => (
                "press 'y' to confirm you have saved the code",
                "'y' to confirm saved",
            ),
            Screen::Import(_) => (
                "type/paste path to bundle   enter import   esc cancel",
                "enter import   esc cancel",
            ),
            Screen::Recover(_) => (
                "↑/↓ field   enter next/recover   esc cancel",
                "↑/↓ field   enter next   esc cancel",
            ),
        }
    };
    // Inner width = area minus the two vertical border columns.
    let avail = area.width.saturating_sub(2) as usize;
    let hint = if full.chars().count() <= avail {
        full
    } else {
        compact
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme::border());
    let p = Paragraph::new(Span::styled(hint, theme::hint())).block(block);
    frame.render_widget(p, area);
}

// ── Help overlay ─────────────────────────────────────────────────────────────────

fn draw_help(frame: &mut Frame, area: Rect, screen: &Screen) {
    let mut lines = vec![
        Line::from(Span::styled("  Keybindings", theme::title())),
        Line::from(""),
    ];
    let rows: &[(&str, &str)] = match screen {
        Screen::Secrets(_) => &[
            ("↑/↓ or j/k", "move selection"),
            ("enter or g", "reveal secret value"),
            ("a", "add a secret"),
            ("c", "classify (tier / scope / reason / description)"),
            ("d", "delete the selected secret"),
            ("l", "lock the vault"),
            ("h or ?", "show this help"),
            ("esc or b", "back to vault list"),
        ],
        Screen::Judge(_) => &[
            ("↑/↓", "move between rows"),
            ("enter", "unlock / create the keyring · view a judge"),
            ("space / ←→", "toggle the judge on/off (global)"),
            ("a / e", "add a judge · edit the selected judge"),
            ("v / k", "view detail · set the selected judge's API key"),
            ("d / t / x", "set default · test · remove judge"),
            ("esc", "back to vault list"),
        ],
        // Default to the list bindings — the main hub.
        _ => &[
            ("↑/↓ or j/k", "move selection"),
            ("enter", "open a vault's secrets"),
            ("c", "create a new vault"),
            ("u / l", "unlock / lock the selected vault"),
            (
                "s",
                "edit settings (description, agents, rate limit, auto-lock)",
            ),
            (
                "shift-J",
                "manage the AI judge (key, model, thresholds, test)",
            ),
            ("v", "view the activity timeline (human + agent)"),
            ("e / i", "export / import an encrypted bundle"),
            ("r", "recover a vault with its recovery code"),
            ("d", "start / stop the background daemon (Unix)"),
            ("h or ?", "show this help"),
            ("q", "quit"),
        ],
    };
    for (keys, desc) in rows {
        lines.push(Line::from(vec![
            Span::styled(format!("  {keys:<14}"), theme::label_focused()),
            Span::styled((*desc).to_string(), Style::default().fg(theme::TEXT)),
        ]));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Press any key to close.",
        theme::label_dim(),
    )));

    let popup = centered_rect(70, 70, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Help ")
        .border_style(theme::title());
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

// ── List ───────────────────────────────────────────────────────────────────────

fn draw_list(
    frame: &mut Frame,
    area: Rect,
    vaults: &[super::VaultRow],
    state: &mut ratatui::widgets::TableState,
) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Vaults ")
        .border_style(theme::border());

    if vaults.is_empty() {
        let p = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                "  No vaults yet.",
                Style::default()
                    .fg(theme::WARN)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                "  Press 'c' to create your first vault.",
                Style::default().fg(theme::TEXT),
            )),
        ])
        .block(block);
        frame.render_widget(p, area);
        return;
    }

    let header =
        Row::new(["STORAGE", "VAULT", "STATUS", "CREATED", "DESCRIPTION"]).style(theme::header());

    let rows: Vec<Row> = vaults
        .iter()
        .map(|v| {
            let (status, status_style) = if v.unlocked {
                ("unlocked", Style::default().fg(theme::OK))
            } else {
                ("locked", Style::default().fg(theme::MUTED))
            };
            let desc = if v.description.is_empty() {
                "-".to_string()
            } else {
                v.description.clone()
            };
            Row::new(vec![
                Cell::from(v.storage.clone()).style(Style::default().fg(theme::TEXT)),
                Cell::from(v.name.clone()).style(theme::title()),
                Cell::from(status).style(status_style),
                Cell::from(v.created.clone()).style(Style::default().fg(theme::MUTED)),
                Cell::from(desc).style(Style::default().fg(theme::TEXT)),
            ])
        })
        .collect();

    let widths = [
        Constraint::Length(12),
        Constraint::Length(22),
        Constraint::Length(10),
        Constraint::Length(12),
        Constraint::Min(10),
    ];

    let table = Table::new(rows, widths)
        .header(header)
        .block(block)
        .column_spacing(2)
        .row_highlight_style(theme::selected_row())
        .highlight_symbol("> ");
    frame.render_stateful_widget(table, area, state);
}

// ── Activity ───────────────────────────────────────────────────────────────────

fn draw_activity(frame: &mut Frame, area: Rect, scr: &mut super::ActivityScreen) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Activity · {} ", scr.name))
        .border_style(theme::border());

    if scr.events.is_empty() {
        let p = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                "  No activity recorded yet.",
                Style::default()
                    .fg(theme::WARN)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                "  Unlocks, reveals, edits, and agent 'get' requests will show up here.",
                Style::default().fg(theme::TEXT),
            )),
        ])
        .block(block);
        frame.render_widget(p, area);
        return;
    }

    let header = Row::new(["WHEN", "ACTOR", "VIA", "ACTION", "TARGET"]).style(theme::header());
    let rows: Vec<Row> = scr
        .events
        .iter()
        .map(|e| {
            let when = e
                .timestamp()
                .map(|t| {
                    t.with_timezone(&chrono::Local)
                        .format("%m-%d %H:%M")
                        .to_string()
                })
                .unwrap_or_else(|| e.ts.chars().take(16).collect());
            // Agents stand out in yellow; humans in the accent color.
            let actor_style = if e.actor == crate::usage::AGENT {
                Style::default().fg(theme::WARN)
            } else {
                Style::default().fg(theme::ACCENT)
            };
            let actor = format!("{} {}", e.actor, e.actor_id);
            // Surface the action came through (cli / tui / gui / mcp); older
            // events recorded before sources existed show "-".
            let via = if e.source.is_empty() {
                "-".to_string()
            } else {
                e.source.clone()
            };
            let target = e.target.clone().unwrap_or_else(|| "-".to_string());
            Row::new(vec![
                Cell::from(when).style(Style::default().fg(theme::MUTED)),
                Cell::from(actor).style(actor_style),
                Cell::from(via).style(Style::default().fg(theme::MUTED)),
                Cell::from(e.action.clone()).style(Style::default().fg(theme::TEXT)),
                Cell::from(target).style(Style::default().fg(theme::MUTED)),
            ])
        })
        .collect();

    let widths = [
        Constraint::Length(12),
        Constraint::Length(16),
        Constraint::Length(4),
        Constraint::Length(14),
        Constraint::Min(8),
    ];
    let table = Table::new(rows, widths)
        .header(header)
        .block(block)
        .column_spacing(2)
        .row_highlight_style(theme::selected_row())
        .highlight_symbol("> ");
    frame.render_stateful_widget(table, area, &mut scr.state);
}

// ── Form rendering ───────────────────────────────────────────────────────────

fn allow_label(mode: usize, list: &str) -> String {
    match mode {
        0 => "all agents".to_string(),
        1 => "none".to_string(),
        _ => format!(
            "specific list  ({})",
            if list.is_empty() { "" } else { list }
        ),
    }
}

fn yes_no(v: bool) -> &'static str {
    if v {
        "yes"
    } else {
        "no"
    }
}

fn mask(s: &str) -> String {
    "*".repeat(s.chars().count())
}

/// Render a list of (label, value) field rows, highlighting the focused one.
/// When `caret` is set, a caret is drawn after the focused field's value so the
/// user can see exactly where typed/pasted text will land (text fields only).
fn field_lines<'a>(fields: &'a [(&'a str, String)], focus: usize, caret: bool) -> Vec<Line<'a>> {
    let mut lines = vec![Line::from("")];
    for (i, (label, value)) in fields.iter().enumerate() {
        let focused = i == focus;
        let marker = if focused { "> " } else { "  " };
        let label_style = if focused {
            theme::label_focused()
        } else {
            theme::label_dim()
        };
        let value_style = if focused {
            theme::value_focused()
        } else {
            Style::default()
        };
        let mut spans = vec![
            Span::raw(marker),
            Span::styled(format!("{label:<18}"), label_style),
            Span::styled(value.clone(), value_style),
        ];
        if focused && caret {
            // A reversed-space block reads as a solid terminal cursor, so it's
            // obvious the field is ready for typing even when it's empty.
            spans.push(Span::styled(
                " ",
                Style::default().add_modifier(Modifier::REVERSED),
            ));
        }
        lines.push(Line::from(spans));
    }
    lines
}

fn draw_create(frame: &mut Frame, area: Rect, form: &CreateForm) {
    // Order must match CreateField::ORDER.
    let fields = [
        ("Name", form.name.clone()),
        ("Description", form.description.clone()),
        (
            "Allow agent",
            allow_label(form.allow_mode, &form.allow_list),
        ),
        (
            "Agent list",
            if form.allow_list.is_empty() {
                "".into()
            } else {
                form.allow_list.clone()
            },
        ),
        ("Rate limit", form.rate_limit.clone()),
        ("Auto-lock", yes_no(form.autolock).to_string()),
        ("Auto-lock timer", form.autolock_timer.clone()),
        ("Default tier", tier_label(form.default_tier).to_string()),
        ("AI judge", yes_no(form.judge).to_string()),
        ("Passphrase", mask(&form.passphrase)),
        ("Confirm passphrase", mask(&form.confirm)),
    ];
    let mut lines = field_lines(&fields, form.focus, form.focus_is_text());
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Storage: local   Login: passphrase   (space/←→ toggles tier & judge)",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Create vault ")
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_settings(frame: &mut Frame, area: Rect, form: &SettingsForm) {
    let fields = [
        ("Description", form.description.clone()),
        (
            "Allow agent",
            allow_label(form.allow_mode, &form.allow_list),
        ),
        (
            "Agent list",
            if form.allow_list.is_empty() {
                "".into()
            } else {
                form.allow_list.clone()
            },
        ),
        ("Rate limit", form.rate_limit.clone()),
        ("Auto-lock", yes_no(form.autolock).to_string()),
        ("Auto-lock timer", form.autolock_timer.clone()),
        ("Default tier", tier_label(form.default_tier).to_string()),
        ("AI judge", yes_no(form.judge).to_string()),
    ];
    let mut lines = field_lines(&fields, form.focus, form.focus_is_text());
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Login: passphrase   (space/←→ toggles tier & judge)",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Settings · {} ", form.name))
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_secret_add(frame: &mut Frame, area: Rect, form: &SecretAddForm) {
    let fields = [
        ("Name", form.name.clone()),
        ("Value", mask(&form.value)),
        ("Scope", form.scope.clone()),
        ("Description", form.description.clone()),
        ("Tier", tier_label(form.tier).to_string()),
        ("Require reason", yes_no(form.require_reason).to_string()),
    ];
    let mut lines = field_lines(&fields, form.focus, form.focus_is_text());
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  space/←→ cycles tier & toggles require-reason",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Add secret · {} ", form.vault_name))
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_classify(frame: &mut Frame, area: Rect, form: &ClassifyForm) {
    let fields = [
        ("Scope", form.scope.clone()),
        ("Description", form.description.clone()),
        ("Tier", tier_label(form.tier).to_string()),
        ("Require reason", yes_no(form.require_reason).to_string()),
    ];
    let mut lines = field_lines(&fields, form.focus, form.focus_is_text());
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Edits the signed policy for this secret — the value is not touched.",
        Style::default().fg(DIM),
    )));
    lines.push(Line::from(Span::styled(
        "  space/←→ cycles tier & toggles require-reason",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Classify · {} ", form.secret))
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_judge(frame: &mut Frame, area: Rect, form: &JudgeForm) {
    let mut lines: Vec<Line> = Vec::new();
    if !form.created {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  No keyring yet.",
            Style::default().fg(theme::WARN),
        )));
        lines.push(Line::from(Span::styled(
            "  Press enter to create it (its own passphrase encrypts your judges + keys).",
            Style::default().fg(DIM),
        )));
    } else if !form.unlocked {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  Keyring is locked.",
            Style::default().fg(theme::WARN),
        )));
        lines.push(Line::from(Span::styled(
            "  Press enter to unlock and manage judges.",
            Style::default().fg(DIM),
        )));
    } else {
        let sel = |i: usize| if form.focus == i { ">" } else { " " };
        lines.push(Line::from(vec![
            Span::raw(format!(" {} ", sel(0))),
            Span::styled("AI judge (global)   ", Style::default().fg(theme::ACCENT)),
            Span::styled(
                yes_no(form.enabled).to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            ),
        ]));
        lines.push(Line::from(Span::styled(
            format!(
                "      default judge: {}",
                form.default_judge.as_deref().unwrap_or("(none)")
            ),
            Style::default().fg(DIM),
        )));
        lines.push(Line::from(""));
        if form.judges.is_empty() {
            lines.push(Line::from(Span::styled(
                "  No judges yet — press a to add one.",
                Style::default().fg(DIM),
            )));
        } else {
            lines.push(Line::from(Span::styled(
                format!(
                    "    {:<16} {:<24} {:>6} {:>5}  KEY",
                    "NAME", "MODEL", "ALLOW", "HIGH"
                ),
                Style::default().fg(DIM),
            )));
            for (i, j) in form.judges.iter().enumerate() {
                let focused = form.focus == i + 1;
                let mark = if focused { ">" } else { " " };
                let def = if form.default_judge.as_deref() == Some(j.name.as_str()) {
                    "*"
                } else {
                    " "
                };
                let key = if j.has_key { "set" } else { "env/none" };
                let style = if focused {
                    Style::default()
                        .fg(theme::ACCENT)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                };
                lines.push(Line::from(Span::styled(
                    format!(
                        " {}{}{:<15} {:<24} {:>6} {:>5}  {}",
                        mark, def, j.name, j.model, j.allow, j.high, key
                    ),
                    style,
                )));
            }
        }
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  space on/off   a add   e edit   v view   k key   d default   t test   x remove",
            Style::default().fg(DIM),
        )));
    }
    if let Some((kind, msg)) = &form.test_result {
        let color = match kind {
            MsgKind::Ok => theme::OK,
            MsgKind::Warn => theme::WARN,
            MsgKind::Error => theme::ERR,
            MsgKind::Info => theme::ACCENT,
        };
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  test: {msg}"),
            Style::default().fg(color),
        )));
    }
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" AI judge ")
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );

    // Sub-mode overlay on top.
    match &form.entry {
        Some(JudgeEntry::Passphrase(b)) => {
            draw_masked_popup(frame, area, " Unlock keyring ", "  Keyring passphrase", b)
        }
        Some(JudgeEntry::Key { judge, buf }) => draw_masked_popup(
            frame,
            area,
            " Set judge key ",
            &format!("  OpenRouter key for '{judge}' (sk-or-…, blank clears)"),
            buf,
        ),
        Some(JudgeEntry::Init(init)) => draw_judge_init(frame, area, init),
        Some(JudgeEntry::Edit(ed)) => draw_judge_edit(frame, area, ed),
        Some(JudgeEntry::View(name)) => draw_judge_view(frame, area, form, name),
        None => {}
    }
}

/// A single masked-input popup (unlock passphrase, judge API key).
fn draw_masked_popup(frame: &mut Frame, area: Rect, title: &str, label: &str, buf: &str) {
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            label.to_string(),
            Style::default().fg(CYAN).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(vec![
            Span::raw("  > "),
            Span::styled(mask(buf), Style::default().add_modifier(Modifier::BOLD)),
            Span::styled(" ", Style::default().add_modifier(Modifier::REVERSED)),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  enter  confirm    esc  cancel",
            Style::default().fg(DIM),
        )),
    ];
    let popup = centered_rect(64, 40, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title.to_string())
        .border_style(Style::default().fg(CYAN));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

/// One labelled, focusable input row used by the judge add/edit and init popups.
fn entry_row(label: &str, value: String, focused: bool, masked: bool) -> Line<'static> {
    let cursor = if focused { ">" } else { " " };
    let shown = if masked { mask(&value) } else { value };
    let label_style = if focused {
        Style::default()
            .fg(theme::ACCENT)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(DIM)
    };
    let mut spans = vec![
        Span::raw(format!("  {cursor} ")),
        Span::styled(format!("{label:<11}"), label_style),
        Span::styled(shown, Style::default().add_modifier(Modifier::BOLD)),
    ];
    if focused {
        spans.push(Span::styled(
            " ",
            Style::default().add_modifier(Modifier::REVERSED),
        ));
    }
    Line::from(spans)
}

/// Create-a-keyring popup: passphrase + confirm.
fn draw_judge_init(frame: &mut Frame, area: Rect, init: &InitForm) {
    let mut lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            "  Its own passphrase encrypts every judge and API key.",
            Style::default().fg(DIM),
        )),
        Line::from(""),
        entry_row("Passphrase", init.pass.clone(), init.focus == 0, true),
        entry_row("Confirm", init.confirm.clone(), init.focus == 1, true),
        Line::from(""),
    ];
    if let Some(err) = &init.error {
        lines.push(Line::from(Span::styled(
            format!("  {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    lines.push(Line::from(Span::styled(
        "  tab switch    enter create    esc cancel",
        Style::default().fg(DIM),
    )));
    let popup = centered_rect(66, 46, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Create keyring ")
        .border_style(Style::default().fg(CYAN));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

/// Add/edit-a-judge popup: name, model, url, timeout, thresholds, criteria.
fn draw_judge_edit(frame: &mut Frame, area: Rect, ed: &JudgeEditForm) {
    let title = if ed.original.is_some() {
        " Edit judge "
    } else {
        " Add judge "
    };
    let mut lines = vec![
        Line::from(""),
        entry_row("Name", ed.name.clone(), ed.focus == 0, false),
        entry_row("Model", ed.model.clone(), ed.focus == 1, false),
        entry_row("Base URL", ed.base_url.clone(), ed.focus == 2, false),
        entry_row("Timeout s", ed.timeout.clone(), ed.focus == 3, false),
        entry_row("Allow ≥", ed.allow.clone(), ed.focus == 4, false),
        entry_row("High ≥", ed.high.clone(), ed.focus == 5, false),
        entry_row("Criteria", ed.criteria.clone(), ed.focus == 6, false),
        Line::from(""),
        Line::from(Span::styled(
            "  Criteria: extra rules added to this judge's prompt (optional).",
            Style::default().fg(DIM),
        )),
        Line::from(Span::styled(
            "  Set the API key with k after saving.",
            Style::default().fg(DIM),
        )),
        Line::from(""),
    ];
    if let Some(err) = &ed.error {
        lines.push(Line::from(Span::styled(
            format!("  {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    lines.push(Line::from(Span::styled(
        "  tab/↑↓ move    enter save    esc cancel",
        Style::default().fg(DIM),
    )));
    let popup = centered_rect(72, 70, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::default().fg(CYAN));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

/// Read-only detail of one judge (includes its criteria).
fn draw_judge_view(frame: &mut Frame, area: Rect, form: &JudgeForm, name: &str) {
    let row = form.judges.iter().find(|j| j.name == name);
    let mut lines = vec![Line::from("")];
    if let Some(j) = row {
        let field = |k: &str, v: String| {
            Line::from(vec![
                Span::styled(format!("  {k:<11}"), Style::default().fg(DIM)),
                Span::styled(v, Style::default().add_modifier(Modifier::BOLD)),
            ])
        };
        let is_default = form.default_judge.as_deref() == Some(j.name.as_str());
        lines.push(field("name", j.name.clone()));
        lines.push(field(
            "default",
            if is_default { "yes" } else { "no" }.to_string(),
        ));
        lines.push(field("model", j.model.clone()));
        lines.push(field("base url", j.base_url.clone()));
        lines.push(field("timeout", format!("{}s", j.timeout_secs)));
        lines.push(field("allow ≥", j.allow.to_string()));
        lines.push(field("high ≥", j.high.to_string()));
        lines.push(field(
            "api key",
            if j.has_key { "set" } else { "env / none" }.to_string(),
        ));
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  criteria",
            Style::default().fg(DIM),
        )));
        let criteria = if j.criteria.trim().is_empty() {
            "(none)".to_string()
        } else {
            j.criteria.clone()
        };
        lines.push(Line::from(Span::styled(
            format!("  {criteria}"),
            Style::default(),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            format!("  no judge named '{name}'"),
            Style::default().fg(Color::Red),
        )));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  e edit    any other key to close",
        Style::default().fg(DIM),
    )));
    let popup = centered_rect(72, 70, area);
    frame.render_widget(Clear, popup);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Judge: {name} "))
        .border_style(Style::default().fg(CYAN));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        popup,
    );
}

fn draw_recovery_code(frame: &mut Frame, area: Rect, code: &str) {
    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            "  Recovery code",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            format!("    {code}"),
            Style::default().fg(CYAN).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  This is the ONLY time this code is shown — it is not stored in plaintext.",
            Style::default().fg(Color::Yellow),
        )),
        Line::from(Span::styled(
            "  Save it in a password manager (or on paper, offline). It is the only way",
            Style::default().fg(DIM),
        )),
        Line::from(Span::styled(
            "  back in if you lose your passphrase — then run 'svault recover'.",
            Style::default().fg(DIM),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  Press 'y' to confirm you have saved it.",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )),
    ];
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Save your recovery code ")
        .border_style(Style::default().fg(Color::Yellow));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_import(frame: &mut Frame, area: Rect, form: &super::ImportForm) {
    let fields = [("Bundle path", form.path.clone())];
    let mut lines = field_lines(&fields, 0, true);
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Path to a .svault-export.json file created by 'svault export'.",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Import vault ")
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_recover(frame: &mut Frame, area: Rect, form: &super::RecoverForm) {
    // The recovery code is shown as typed (not masked): the user is copying it
    // from paper or a password manager, so visible text prevents silent typos.
    let fields = [
        ("Recovery code", form.code.clone()),
        ("New passphrase", mask(&form.new_pass)),
        ("Confirm passphrase", mask(&form.confirm)),
    ];
    let mut lines = field_lines(&fields, form.focus, true);
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Resets a lost passphrase. The recovery code stays the same.",
        Style::default().fg(DIM),
    )));
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  error: {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Recover · {} ", form.name))
        .border_style(Style::default().fg(DIM));
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

// ── Unlock ─────────────────────────────────────────────────────────────────────

fn draw_unlock(frame: &mut Frame, area: Rect, form: &UnlockForm) {
    let mut lines = vec![
        Line::from(""),
        Line::from(vec![
            Span::raw("  Passphrase for "),
            Span::styled(
                form.name.clone(),
                Style::default().fg(CYAN).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::raw("  > "),
            Span::styled(
                mask(&form.passphrase),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::styled(" ", Style::default().add_modifier(Modifier::REVERSED)),
        ]),
    ];
    if let Some(err) = &form.error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  {err}"),
            Style::default().fg(Color::Red),
        )));
    }
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Unlock ")
        .border_style(Style::default().fg(DIM));
    frame.render_widget(Paragraph::new(lines).block(block), area);
}

// ── Secrets ────────────────────────────────────────────────────────────────────

fn draw_secrets(frame: &mut Frame, area: Rect, scr: &mut SecretScreen) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Secrets · {} (unlocked) ", scr.name))
        .border_style(Style::default().fg(DIM));

    if scr.secrets.is_empty() {
        let p = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                "  No secrets yet.",
                Style::default()
                    .fg(theme::WARN)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                "  Press 'a' to add one.",
                Style::default().fg(theme::TEXT),
            )),
        ])
        .block(block);
        frame.render_widget(p, area);
    } else {
        // Each row shows the secret's name next to the policy classification
        // (tier/scope/require-reason/description) that gates an agent `get`.
        let header =
            Row::new(["SECRET", "TIER", "SCOPE", "REASON?", "DESCRIPTION"]).style(theme::header());
        let rows: Vec<Row> = scr
            .secrets
            .iter()
            .map(|n| {
                let rule = scr.classifications.get(n);
                let (tier, tier_style) = match rule.map(|r| r.tier) {
                    Some(crate::policy::Tier::High) => ("high", Style::default().fg(theme::ERR)),
                    Some(crate::policy::Tier::Medium) => {
                        ("medium", Style::default().fg(theme::WARN))
                    }
                    Some(crate::policy::Tier::Low) => ("low", Style::default().fg(theme::OK)),
                    None => ("unset", Style::default().fg(theme::MUTED)),
                };
                let scope = rule
                    .map(|r| r.scope.clone())
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| "-".to_string());
                let reason = match rule.map(|r| r.require_reason) {
                    Some(true) => "yes",
                    _ => "-",
                };
                let desc = rule
                    .map(|r| r.description.clone())
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| "-".to_string());
                Row::new(vec![
                    Cell::from(n.clone()).style(Style::default().fg(CYAN)),
                    Cell::from(tier).style(tier_style),
                    Cell::from(scope).style(Style::default().fg(theme::TEXT)),
                    Cell::from(reason).style(Style::default().fg(theme::MUTED)),
                    Cell::from(desc).style(Style::default().fg(theme::MUTED)),
                ])
            })
            .collect();
        let widths = [
            Constraint::Length(22),
            Constraint::Length(8),
            Constraint::Length(12),
            Constraint::Length(8),
            Constraint::Min(10),
        ];
        let table = Table::new(rows, widths)
            .header(header)
            .block(block)
            .column_spacing(2)
            .row_highlight_style(theme::selected_row())
            .highlight_symbol("> ");
        frame.render_stateful_widget(table, area, &mut scr.list_state);
    }

    // Reveal modal.
    if let Some(reveal) = &scr.reveal {
        let value = if reveal.masked {
            mask(&reveal.value)
        } else {
            reveal.value.to_string()
        };
        let lines = vec![
            Line::from(""),
            Line::from(vec![
                Span::raw("  "),
                Span::styled(
                    reveal.name.clone(),
                    Style::default().fg(CYAN).add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(""),
            Line::from(Span::styled(
                format!("  {value}"),
                Style::default().add_modifier(Modifier::BOLD),
            )),
            Line::from(""),
            Line::from(Span::styled(
                if reveal.masked {
                    "  (hidden — press space to reveal)"
                } else {
                    "  (press space to hide)"
                },
                Style::default().fg(DIM),
            )),
        ];
        let popup = centered_rect(60, 40, area);
        frame.render_widget(Clear, popup);
        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Secret value ")
            .border_style(Style::default().fg(CYAN));
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .wrap(Wrap { trim: false }),
            popup,
        );
    }

    // Delete confirmation modal.
    if let Some(name) = &scr.pending_delete {
        let lines = vec![
            Line::from(""),
            Line::from(vec![
                Span::raw("  Delete secret "),
                Span::styled(
                    name.clone(),
                    Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                ),
                Span::raw("?"),
            ]),
            Line::from(""),
            Line::from(Span::styled(
                "  y = delete    n / esc = cancel",
                Style::default().fg(DIM),
            )),
        ];
        let popup = centered_rect(50, 30, area);
        frame.render_widget(Clear, popup);
        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Confirm delete ")
            .border_style(Style::default().fg(Color::Red));
        frame.render_widget(
            Paragraph::new(lines)
                .block(block)
                .alignment(Alignment::Left),
            popup,
        );
    }
}

/// Center a rectangle taking `pct_x`% width and `pct_y`% height of `area`.
fn centered_rect(pct_x: u16, pct_y: u16, area: Rect) -> Rect {
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - pct_y) / 2),
            Constraint::Percentage(pct_y),
            Constraint::Percentage((100 - pct_y) / 2),
        ])
        .split(area);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - pct_x) / 2),
            Constraint::Percentage(pct_x),
            Constraint::Percentage((100 - pct_x) / 2),
        ])
        .split(vertical[1])[1]
}