svault-ai 0.6.0

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
//! 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, List, ListItem, Paragraph, Row, Table, Wrap},
    Frame,
};

use super::theme;
use super::{
    App, CreateForm, 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),
    }

    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   v activity   e export   i import   r recover   d daemon   h/? help   q quit",
                "↑/↓ move   enter open   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   d delete   l lock   h/? help   esc back",
                        "↑/↓ move   enter view   h/? help   esc back",
                    )
                }
            }
            Screen::SecretAdd(_) => (
                "↑/↓ field   enter next/save   esc cancel",
                "↑/↓ field   enter save   esc cancel",
            ),
            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"),
            ("d", "delete the selected secret"),
            ("l", "lock the vault"),
            ("h or ?", "show this help"),
            ("esc or b", "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)",
            ),
            ("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()),
        ("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   (more options coming soon)",
        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()),
    ];
    let mut lines = field_lines(&fields, form.focus, form.focus_is_text());
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Login: passphrase   (more options coming soon)",
        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))];
    let mut lines = field_lines(&fields, form.focus, true);
    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_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 {
        let items: Vec<ListItem> = scr
            .secrets
            .iter()
            .map(|n| ListItem::new(Span::styled(n.clone(), Style::default().fg(CYAN))))
            .collect();
        let list = List::new(items)
            .block(block)
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED))
            .highlight_symbol("> ");
        frame.render_stateful_widget(list, area, &mut scr.list_state);
    }

    // Reveal modal.
    if let Some(reveal) = &scr.reveal {
        let value = if reveal.masked {
            mask(&reveal.value)
        } else {
            reveal.value.clone()
        };
        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]
}