tui-file-explorer 0.7.4

A self-contained, keyboard-driven file-browser widget for Ratatui
Documentation
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
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
//! Terminal UI drawing functions for the `tfe` binary.
//!
//! All [`ratatui`] rendering that is specific to the two-pane application
//! lives here. The per-pane widget rendering (header, list, footer) remains in
//! the library's own [`tui_file_explorer::render`] module.
//!
//! Public entry-points:
//!
//! * [`draw`]               — top-level draw callback passed to `Terminal::draw`.
//! * [`render_theme_panel`] — the slide-in theme-picker side panel.
//! * [`render_action_bar`]  — the bottom status / key-hint bar.
//! * [`render_modal`]       — the blocking confirmation dialog overlay.

use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, List, ListItem, ListState, Paragraph},
    Frame,
};
use tui_file_explorer::{render_themed, Theme};

use crate::app::{App, Modal, Pane, Snackbar};

// ── Top-level draw ────────────────────────────────────────────────────────────

/// Draw the entire application UI into `frame`.
///
/// Divides the terminal area into:
/// - A main area (one or two explorer panes + optional theme panel).
/// - A fixed-height action bar at the bottom.
/// - An optional modal overlay on top of everything.
pub fn draw(app: &mut App, frame: &mut Frame) {
    let theme = app.theme().clone();
    let full = frame.area();

    // Vertical split: main area | action bar (6 rows = nav-hints row + status row).
    let v_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(0), Constraint::Length(6)])
        .split(full);

    let main_area = v_chunks[0];
    let action_area = v_chunks[1];

    // Split the action bar vertically into: nav hints (top) | status+shortcuts (bottom).
    let action_rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Length(3)])
        .split(action_area);
    let nav_area = action_rows[0];
    let status_area = action_rows[1];

    // Horizontal split: left pane | [right pane] | [theme panel].
    let mut h_constraints = vec![];
    if app.single_pane {
        h_constraints.push(Constraint::Min(0));
    } else {
        h_constraints.push(Constraint::Percentage(50));
        h_constraints.push(Constraint::Percentage(50));
    }
    if app.show_theme_panel {
        h_constraints.push(Constraint::Length(32));
    }
    if app.show_options_panel {
        h_constraints.push(Constraint::Length(42));
    }
    if app.show_editor_panel {
        h_constraints.push(Constraint::Length(42));
    }
    let h_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(h_constraints)
        .split(main_area);

    // ── Panes ─────────────────────────────────────────────────────────────────
    let active_theme = theme.clone();
    let inactive_theme = theme.clone().accent(theme.dim).brand(theme.dim);

    let (left_theme, right_theme) = match app.active {
        Pane::Left => (&active_theme, &inactive_theme),
        Pane::Right => (&inactive_theme, &active_theme),
    };

    // Sync the current theme name and editor label into both panes so render_header can display them.
    let theme_name = app.theme_name().to_string();
    app.left.theme_name = theme_name.clone();
    app.right.theme_name = theme_name;

    let editor_name = if app.editor == crate::app::Editor::None {
        String::new()
    } else {
        app.editor.label().to_string()
    };
    app.left.editor_name = editor_name.clone();
    app.right.editor_name = editor_name;

    render_themed(&mut app.left, frame, h_chunks[0], left_theme);

    if !app.single_pane {
        render_themed(&mut app.right, frame, h_chunks[1], right_theme);
    }

    // ── Theme panel ───────────────────────────────────────────────────────────
    if app.show_theme_panel {
        let panel_area = h_chunks[h_chunks.len() - 1];
        render_theme_panel(frame, panel_area, app);
    }

    // ── Options panel ─────────────────────────────────────────────────────────
    if app.show_options_panel {
        let panel_area = h_chunks[h_chunks.len() - 1];
        render_options_panel(frame, panel_area, app);
    }

    // ── Editor panel ──────────────────────────────────────────────────────────
    if app.show_editor_panel {
        let panel_area = h_chunks[h_chunks.len() - 1];
        render_editor_panel(frame, panel_area, app);
    }

    // ── Action bar ────────────────────────────────────────────────────────────
    render_nav_hints(frame, nav_area, &theme);
    render_action_bar(frame, status_area, app, &theme);

    // ── Modal overlay ─────────────────────────────────────────────────────────
    if let Some(modal) = &app.modal {
        render_modal(frame, full, modal, &theme);
    }

    // ── Snackbar overlay ──────────────────────────────────────────────────────
    // Expire stale snackbars first, then render if one is still active.
    if app.snackbar.as_ref().is_some_and(|s| s.is_expired()) {
        app.snackbar = None;
    }
    if let Some(snackbar) = &app.snackbar {
        render_snackbar(frame, full, snackbar, &theme);
    }
}

// ── Snackbar ──────────────────────────────────────────────────────────────────

/// Render a floating snackbar notification near the bottom of `area`.
///
/// The snackbar is a single-line (3-row with border) centred overlay that
/// clears whatever content is behind it. Error snackbars are tinted with the
/// theme's brand (red/warning) colour; info snackbars use the success colour.
pub fn render_snackbar(frame: &mut Frame, area: Rect, snackbar: &Snackbar, theme: &Theme) {
    // Height: 3 rows (border top + content + border bottom).
    // Width: message length + 4 (2 padding + 2 border chars), capped to terminal width.
    let msg = &snackbar.message;
    let desired_width = (msg.len() as u16)
        .saturating_add(4)
        .min(area.width.saturating_sub(4));
    let width = desired_width.max(20);
    let height = 3u16;

    // Position: horizontally centred, 4 rows above the bottom of `area` so it
    // floats just above the action bar without obscuring it.
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height + 7);

    let snackbar_area = Rect {
        x,
        y,
        width,
        height,
    };

    let border_color = if snackbar.is_error {
        theme.brand
    } else {
        theme.success
    };
    let text_color = if snackbar.is_error {
        theme.brand
    } else {
        theme.success
    };

    frame.render_widget(Clear, snackbar_area);
    let paragraph = Paragraph::new(Line::from(Span::styled(
        format!(" {msg} "),
        Style::default().fg(text_color).add_modifier(Modifier::BOLD),
    )))
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(border_color)),
    );
    frame.render_widget(paragraph, snackbar_area);
}

// ── Theme panel ───────────────────────────────────────────────────────────────

/// Render the slide-in theme-picker panel occupying `area`.
///
/// The panel is divided into three vertical zones:
/// - A controls header showing the `[` / `t` key hints.
/// - A scrollable list of all available themes.
/// - A description footer for the currently selected theme.
pub fn render_theme_panel(frame: &mut Frame, area: Rect, app: &App) {
    let theme = app.theme();

    // Three-row vertical layout: controls | list | description.
    let v = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(0),
            Constraint::Length(4),
        ])
        .split(area);

    // Controls header.
    let controls = Paragraph::new(Line::from(vec![
        Span::styled(" ↑ [ ", Style::default().fg(theme.dim)),
        Span::styled("prev", Style::default().fg(theme.accent)),
        Span::styled("   ", Style::default().fg(theme.dim)),
        Span::styled("↓ t ", Style::default().fg(theme.dim)),
        Span::styled("next", Style::default().fg(theme.accent)),
    ]))
    .block(
        Block::default()
            .title(Span::styled(
                " \u{1F3A8} Themes ",
                Style::default()
                    .fg(theme.brand)
                    .add_modifier(Modifier::BOLD),
            ))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.accent)),
    );
    frame.render_widget(controls, v[0]);

    // Scrollable theme list — keep the selected item in view.
    let visible = v[1].height.saturating_sub(2) as usize;
    let scroll = if app.theme_idx >= visible {
        app.theme_idx - visible + 1
    } else {
        0
    };

    let items: Vec<ListItem> = app
        .themes
        .iter()
        .enumerate()
        .skip(scroll)
        .take(visible)
        .map(|(i, (name, _, _))| {
            let is_active = i == app.theme_idx;
            let marker = if is_active { "\u{25BA} " } else { "   " };
            let line = Line::from(vec![
                Span::styled(
                    format!("{marker}{:>2}. ", i + 1),
                    Style::default().fg(if is_active { theme.brand } else { theme.dim }),
                ),
                Span::styled(
                    name.to_string(),
                    if is_active {
                        Style::default()
                            .fg(theme.accent)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(theme.fg)
                    },
                ),
            ]);
            if is_active {
                ListItem::new(line).style(Style::default().bg(theme.sel_bg))
            } else {
                ListItem::new(line)
            }
        })
        .collect();

    let mut list_state = ListState::default();
    list_state.select(Some(app.theme_idx.saturating_sub(scroll)));

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::LEFT | Borders::RIGHT)
            .border_style(Style::default().fg(theme.accent)),
    );
    frame.render_stateful_widget(list, v[1], &mut list_state);

    // Description footer.
    let desc_text = format!("{}\n{}", app.theme_name(), app.theme_desc());
    let desc = Paragraph::new(desc_text)
        .style(Style::default().fg(theme.success))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.accent)),
        );
    frame.render_widget(desc, v[2]);
}

// ── Editor panel ──────────────────────────────────────────────────────────────

/// Render the slide-in editor-picker side panel occupying `area`.
///
/// Two bordered group cells — "Terminal Editors" and "IDEs & GUI Editors" —
/// mirror the Options panel layout.  The highlighted row (cursor) is tracked
/// by `app.editor_panel_idx`; the active editor is marked with a `✓`.
pub fn render_editor_panel(frame: &mut Frame, area: Rect, app: &App) {
    use crate::app::{App as TfeApp, Editor};

    let theme = app.theme();

    let on_style = Style::default()
        .fg(theme.success)
        .add_modifier(Modifier::BOLD);
    let key_style = Style::default()
        .fg(theme.accent)
        .add_modifier(Modifier::BOLD);
    let label_style = Style::default().fg(theme.fg);
    let subtitle_style = Style::default().fg(theme.dim);
    let title_style = Style::default()
        .fg(theme.brand)
        .add_modifier(Modifier::BOLD);

    let editors = TfeApp::all_editors();
    let first_ide = TfeApp::first_ide_idx();
    let terminal_editors = &editors[..first_ide]; // None … Emacs
    let ide_editors = &editors[first_ide..]; // Sublime … Eclipse

    // ── Layout ───────────────────────────────────────────────────────────────
    // Slots (top to bottom):
    //   [0]  hints header box              — 2 rows
    //   [1]  gap                           — 1 row
    //   [2]  "Terminal Editors" title      — 1 row
    //   [3]  Terminal Editors cell         — terminal_editors.len() + 2 (borders)
    //   [4]  gap                           — 1 row
    //   [5]  "IDEs & GUI Editors" title    — 1 row
    //   [6]  IDEs cell                     — ide_editors.len() + 2 (borders)
    //   [7]  gap                           — 1 row
    //   [8]  footer                        — 3 rows
    //   [9]  remainder
    let terminal_cell_h = terminal_editors.len() as u16 + 2;
    let ide_cell_h = ide_editors.len() as u16 + 2;

    let slots = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2),               // [0] hints header
            Constraint::Length(1),               // [1] gap
            Constraint::Length(1),               // [2] "Terminal Editors" title
            Constraint::Length(terminal_cell_h), // [3] terminal cell
            Constraint::Length(1),               // [4] gap
            Constraint::Length(1),               // [5] "IDEs & GUI Editors" title
            Constraint::Length(ide_cell_h),      // [6] IDE cell
            Constraint::Length(1),               // [7] gap
            Constraint::Length(3),               // [8] footer
            Constraint::Min(0),                  // [9] slack
        ])
        .split(area);

    // ── Helper: floating section title ────────────────────────────────────────
    let section_title = |frame: &mut Frame, slot: Rect, label: &str| {
        let dashes = "".repeat((slot.width as usize).saturating_sub(label.len() + 2));
        let para = Paragraph::new(Line::from(vec![
            Span::styled(format!(" {label} "), subtitle_style),
            Span::styled(dashes, subtitle_style),
        ]));
        frame.render_widget(para, slot);
    };

    // ── Helper: one editor row ────────────────────────────────────────────────
    let editor_row = |editor: &Editor, idx: usize| -> Line {
        let is_highlighted = idx == app.editor_panel_idx;
        let is_selected = editor == &app.editor;
        let marker = if is_highlighted { "\u{25BA} " } else { "   " };
        let check = if is_selected { "\u{2713} " } else { "  " };
        Line::from(vec![
            Span::styled(
                marker,
                Style::default().fg(if is_highlighted {
                    theme.brand
                } else {
                    theme.dim
                }),
            ),
            Span::styled(
                check,
                if is_selected {
                    on_style
                } else {
                    subtitle_style
                },
            ),
            Span::styled(
                format!("{:<width$}", editor.label(), width = 16),
                if is_highlighted {
                    key_style
                } else {
                    label_style
                },
            ),
        ])
    };

    // ── Hints header ─────────────────────────────────────────────────────────
    let header = Block::default()
        .title(Span::styled(" \u{1F4DD} Editor ", title_style))
        .title_bottom(Line::from(vec![
            Span::styled(" Shift + E ", key_style),
            Span::styled("close", subtitle_style),
        ]))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent));
    frame.render_widget(header, slots[0]);

    // ── Terminal Editors cell ─────────────────────────────────────────────────
    section_title(frame, slots[2], "Terminal Editors");

    let terminal_rows: Vec<Line> = terminal_editors
        .iter()
        .enumerate()
        .map(|(i, ed)| editor_row(ed, i))
        .collect();
    let terminal_cell = Paragraph::new(terminal_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(terminal_cell, slots[3]);

    // ── IDEs & GUI Editors cell ───────────────────────────────────────────────
    section_title(frame, slots[5], "IDEs & GUI Editors");

    let ide_rows: Vec<Line> = ide_editors
        .iter()
        .enumerate()
        .map(|(i, ed)| editor_row(ed, first_ide + i))
        .collect();
    let ide_cell = Paragraph::new(ide_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(ide_cell, slots[6]);

    // ── Footer — binary of the highlighted editor ─────────────────────────────
    let highlighted_editor = &editors[app.editor_panel_idx];
    let footer_text = if *highlighted_editor == Editor::None {
        "none  —  no editor".to_string()
    } else {
        format!(
            "{}{}",
            highlighted_editor.label(),
            highlighted_editor.binary().unwrap_or_default()
        )
    };
    let footer = Paragraph::new(footer_text)
        .style(Style::default().fg(theme.success))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.accent)),
        );
    frame.render_widget(footer, slots[8]);
}

// ── Options panel ─────────────────────────────────────────────────────────────

/// Render the slide-in options panel occupying `area`.
///
/// Shows all toggleable persistent settings with their current state.
/// Each row shows the toggle key, setting name, and on/off indicator.
pub fn render_options_panel(frame: &mut Frame, area: Rect, app: &App) {
    let theme = app.theme();

    let on_style = Style::default()
        .fg(theme.success)
        .add_modifier(Modifier::BOLD);
    let off_style = Style::default().fg(theme.dim);
    let key_style = Style::default()
        .fg(theme.accent)
        .add_modifier(Modifier::BOLD);
    let label_style = Style::default().fg(theme.fg);
    let subtitle_style = Style::default().fg(theme.dim);
    let title_style = Style::default()
        .fg(theme.brand)
        .add_modifier(Modifier::BOLD);

    // ── Layout ───────────────────────────────────────────────────────────────
    // Slots (top to bottom):
    //   [0]  hints header box         — 2 rows  (top border: title, bottom border: hints)
    //   [1]  gap                      — 1 row
    //   [2]  "Toggles" section title  — 1 row
    //   [3]  Toggles group cell       — 5 rows  (border + 3 rows + border)
    //   [4]  gap                      — 1 row
    //   [5]  "Editor" section title   — 1 row
    //   [6]  Editor group cell        — 3 rows  (border + 1 row + border)
    //   [7]  gap                      — 1 row
    //   [8]  "File Ops" section title — 1 row
    //   [9]  File Ops group cell      — 9 rows  (border + 7 rows + border)
    //   [10] remainder (absorbs slack)
    let slots = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2), // [0] hints header (border-only, no body)
            Constraint::Length(1), // [1] gap
            Constraint::Length(1), // [2] "Toggles" title
            Constraint::Length(5), // [3] Toggles group (3 option rows)
            Constraint::Length(1), // [4] gap
            Constraint::Length(1), // [5] "Editor" title
            Constraint::Length(3), // [6] Editor group (1 option row)
            Constraint::Length(1), // [7] gap
            Constraint::Length(1), // [8] "File Ops" title
            Constraint::Length(9), // [9] File Ops group (7 option rows)
            Constraint::Min(0),    // [10] slack
        ])
        .split(area);

    // ── Helper: floating section title ────────────────────────────────────────
    // Renders " Label ─────" in dim colour with no border.
    let section_title = |frame: &mut Frame, slot: Rect, label: &str| {
        let dashes = "".repeat((slot.width as usize).saturating_sub(label.len() + 2));
        let para = Paragraph::new(Line::from(vec![
            Span::styled(format!(" {label} "), subtitle_style),
            Span::styled(dashes, subtitle_style),
        ]));
        frame.render_widget(para, slot);
    };

    // ── Helper: one option row inside a group cell ────────────────────────────
    let option_row = |key: &str, label: &str, value: Span<'static>| -> Line {
        Line::from(vec![
            Span::raw(" "),
            Span::styled(format!("{key:<12}"), key_style),
            Span::styled(format!("{label:<14}"), label_style),
            value,
        ])
    };

    // ── Bool value span helper ────────────────────────────────────────────────
    let bool_span = |enabled: bool| -> Span {
        if enabled {
            Span::styled("● on ", on_style)
        } else {
            Span::styled("○ off", off_style)
        }
    };

    // ── Hints header ─────────────────────────────────────────────────────────
    // Title on the top border line; key hints on the bottom border line.
    // No body row — the block is exactly 2 rows (top + bottom borders).
    let header = Block::default()
        .title(Span::styled(" ⚙ Options ", title_style))
        .title_bottom(Line::from(vec![
            Span::styled(" Shift + O ", key_style),
            Span::styled("close", subtitle_style),
        ]))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent));
    frame.render_widget(header, slots[0]);

    // ── Toggles group ─────────────────────────────────────────────────────────
    section_title(frame, slots[2], "Toggles");

    let toggles_rows = vec![
        option_row("Shift + C", "cd on exit", bool_span(app.cd_on_exit)),
        option_row("w", "single pane", bool_span(app.single_pane)),
        option_row("Shift + T", "theme panel", bool_span(app.show_theme_panel)),
    ];
    let toggles_cell = Paragraph::new(toggles_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(toggles_cell, slots[3]);

    // ── Editor group ──────────────────────────────────────────────────────────
    section_title(frame, slots[5], "Editor");

    let editor_label = app.editor.label().to_string();
    let editor_val_style = if app.editor == crate::app::Editor::None {
        off_style
    } else {
        Style::default()
            .fg(theme.success)
            .add_modifier(Modifier::BOLD)
    };

    let editor_rows = vec![option_row(
        "Shift + E",
        "editor",
        Span::styled(editor_label, editor_val_style),
    )];
    let editor_cell = Paragraph::new(editor_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(editor_cell, slots[6]);

    // ── File Ops group ────────────────────────────────────────────────────────
    section_title(frame, slots[8], "File Ops");

    let fileops_rows = vec![
        option_row(
            "Spc",
            "mark",
            Span::styled("multi-select", Style::default().fg(theme.accent)),
        ),
        option_row(
            "y",
            "copy",
            Span::styled("yank", Style::default().fg(theme.accent)),
        ),
        option_row(
            "x",
            "cut",
            Span::styled("cut", Style::default().fg(theme.accent)),
        ),
        option_row(
            "p",
            "paste",
            Span::styled("paste", Style::default().fg(theme.accent)),
        ),
        option_row(
            "d",
            "delete",
            Span::styled("delete", Style::default().fg(theme.accent)),
        ),
        option_row(
            "n",
            "new folder",
            Span::styled("mkdir", Style::default().fg(theme.accent)),
        ),
        option_row(
            "N",
            "new file",
            Span::styled("touch", Style::default().fg(theme.accent)),
        ),
        option_row(
            "r",
            "rename",
            Span::styled("rename", Style::default().fg(theme.accent)),
        ),
    ];
    let fileops_cell = Paragraph::new(fileops_rows).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(fileops_cell, slots[9]);
}

// ── Action bar ────────────────────────────────────────────────────────────────

/// Render the top hints row of the action area as three labelled columns:
/// Navigate | File Ops | Global.
pub fn render_nav_hints(frame: &mut Frame, area: Rect, theme: &Theme) {
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(40),
            Constraint::Percentage(35),
            Constraint::Percentage(25),
        ])
        .split(area);

    let k = |s: &'static str| {
        Span::styled(
            s,
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )
    };
    let d = |s: &'static str| Span::styled(s, Style::default().fg(theme.dim));

    // ── Navigate column ───────────────────────────────────────────────────────
    let nav_spans = vec![
        k(""),
        d("/"),
        k("k"),
        d(" up │ "),
        k(""),
        d("/"),
        k("j"),
        d(" down │ "),
        k(""),
        d("/"),
        k("l"),
        d("/"),
        k("Enter"),
        d(" open │ "),
        k(""),
        d("/"),
        k("h"),
        d("/"),
        k("Bksp"),
        d(" back │ "),
        k("/"),
        d(" search │ "),
        k("s"),
        d(" sort │ "),
        k("."),
        d(" hidden │ "),
        k("Esc"),
        d(" dismiss"),
    ];
    let nav_col = Paragraph::new(Line::from(nav_spans)).block(
        Block::default()
            .title(Span::styled(" Navigate ", Style::default().fg(theme.dim)))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(nav_col, cols[0]);

    // ── File Ops column ───────────────────────────────────────────────────────
    let fileops_spans = vec![
        k("y"),
        d(" copy │ "),
        k("x"),
        d(" cut │ "),
        k("p"),
        d(" paste │ "),
        k("d"),
        d(" del │ "),
        k("n"),
        d(" mkdir │ "),
        k("N"),
        d(" touch │ "),
        k("r"),
        d(" rename │ "),
        k("Spc"),
        d(" mark"),
    ];
    let fileops_col = Paragraph::new(Line::from(fileops_spans)).block(
        Block::default()
            .title(Span::styled(" File Ops ", Style::default().fg(theme.dim)))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(fileops_col, cols[1]);

    // ── Global column ─────────────────────────────────────────────────────────
    let global_spans = vec![
        k("Tab"),
        d(" pane │ "),
        k("w"),
        d(" split │ "),
        k("["),
        d("/"),
        k("t"),
        d(" theme │ "),
        k("Shift+E"),
        d(" editor │ "),
        k("Shift+O"),
        d(" options"),
    ];
    let global_col = Paragraph::new(Line::from(global_spans)).block(
        Block::default()
            .title(Span::styled(" Global ", Style::default().fg(theme.dim)))
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(global_col, cols[2]);
}

/// Build the flat list of styled [`Span`]s for the navigate column.
///
/// Extracted so the spans can be tested independently of a real [`Frame`].
#[cfg(test)]
pub fn render_nav_hints_spans(theme: &Theme) -> Vec<Span<'_>> {
    let k = |s: &'static str| {
        Span::styled(
            s,
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )
    };
    let d = |s: &'static str| Span::styled(s, Style::default().fg(theme.dim));
    vec![
        k(""),
        d("/"),
        k("k"),
        d(" up │ "),
        k(""),
        d("/"),
        k("j"),
        d(" down │ "),
        k(""),
        d("/"),
        k("l"),
        d("/"),
        k("Enter"),
        d(" open │ "),
        k(""),
        d("/"),
        k("h"),
        d("/"),
        k("Bksp"),
        d(" back │ "),
        k("/"),
        d(" search │ "),
        k("s"),
        d(" sort │ "),
        k("."),
        d(" hidden │ "),
        k("Esc"),
        d(" dismiss"),
    ]
}

/// Render the bottom status bar occupying `area`.
///
/// Split into two halves:
/// - **Left** — clipboard info when something is yanked, otherwise the current
///   status message.
/// - **Right** — active pane indicator + currently configured editor (always
///   visible so the user always knows which editor `e` will open).
pub fn render_action_bar(frame: &mut Frame, area: Rect, app: &App, theme: &Theme) {
    let h = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(area);

    // ── Left half: clipboard info or status message ───────────────────────────
    if let Some(clip) = &app.clipboard {
        let name = clip.path.file_name().unwrap_or_default().to_string_lossy();
        let line = Line::from(vec![
            Span::styled(
                format!(" {} {}: ", clip.icon(), clip.label()),
                Style::default()
                    .fg(theme.brand)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                name.to_string(),
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
        ]);
        let left_bar = Paragraph::new(line).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.brand)),
        );
        frame.render_widget(left_bar, h[0]);
    } else {
        let status_color =
            if app.status_msg.starts_with("Error") || app.status_msg.starts_with("Delete failed") {
                theme.brand
            } else {
                theme.success
            };
        let status = if app.status_msg.is_empty() {
            " No pending operations".to_string()
        } else {
            format!(" {}", app.status_msg)
        };
        let left_bar = Paragraph::new(Span::styled(status, Style::default().fg(status_color)))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(theme.dim)),
            );
        frame.render_widget(left_bar, h[0]);
    }

    // ── Right half: active pane + editor info (always shown) ─────────────────
    let active_label = match app.active {
        Pane::Left => "left",
        Pane::Right => "right",
    };

    let mut right_spans = vec![
        Span::styled(" pane: ", Style::default().fg(theme.dim)),
        Span::styled(
            active_label,
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("   editor: ", Style::default().fg(theme.dim)),
    ];

    if app.editor == crate::app::Editor::None {
        right_spans.push(Span::styled("none", Style::default().fg(theme.dim)));
        right_spans.push(Span::styled(
            "  (Shift+E to pick)",
            Style::default().fg(theme.dim),
        ));
    } else {
        right_spans.push(Span::styled(
            format!("\u{270F}  {}", app.editor.label()),
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ));
    }

    let right_bar = Paragraph::new(Line::from(right_spans)).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.dim)),
    );
    frame.render_widget(right_bar, h[1]);
}

/// Build the list of styled [`Span`]s for the global key-hint column.
///
/// Extracted so the spans can be tested independently of a real [`Frame`].
#[cfg(test)]
pub fn render_action_bar_spans(theme: &Theme) -> Vec<Span<'_>> {
    let k = |s: &'static str| {
        Span::styled(
            s,
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )
    };
    let d = |s: &'static str| Span::styled(s, Style::default().fg(theme.dim));
    vec![
        k("Tab"),
        d(" pane │ "),
        k("w"),
        d(" split │ "),
        k("["),
        d("/"),
        k("t"),
        d(" theme │ "),
        k("Shift+E"),
        d(" editor │ "),
        k("Shift+O"),
        d(" options"),
    ]
}

// ── Modal ─────────────────────────────────────────────────────────────────────

/// Render a blocking confirmation modal centred over `area`.
///
/// The modal clears whatever is behind it, draws a double-border box with a
/// title, a body message, and a key-hint footer.
pub fn render_modal(frame: &mut Frame, area: Rect, modal: &Modal, theme: &Theme) {
    // ── MultiDeleteConfirm — taller modal with a scrollable name list ─────────
    if let Modal::MultiDelete { paths } = modal {
        let count = paths.len();
        // Show up to 6 file names inside the box, then a "+ N more" note.
        const MAX_SHOWN: usize = 6;
        let shown: Vec<&std::path::PathBuf> = paths.iter().take(MAX_SHOWN).collect();
        let remainder = count.saturating_sub(MAX_SHOWN);

        // Width: wide enough for the longest shown name + padding.
        let max_name_len = shown
            .iter()
            .map(|p| p.file_name().unwrap_or_default().to_string_lossy().len())
            .max()
            .unwrap_or(0);
        let w = (max_name_len as u16 + 8)
            .max(44)
            .min(area.width.saturating_sub(4));
        // Height: header line + one row per shown entry + optional overflow line
        //         + blank gap + hint line + 2 border rows.
        let list_rows = shown.len() + if remainder > 0 { 1 } else { 0 };
        let h = (list_rows as u16 + 5).min(area.height.saturating_sub(2));
        let x = area.x + (area.width.saturating_sub(w)) / 2;
        let y = area.y + (area.height.saturating_sub(h)) / 2;
        let modal_area = Rect::new(x, y, w, h);

        frame.render_widget(Clear, modal_area);

        let outer = Block::default()
            .title(Span::styled(
                " Confirm Multi-Delete ",
                Style::default()
                    .fg(theme.brand)
                    .add_modifier(Modifier::BOLD),
            ))
            .borders(Borders::ALL)
            .border_type(BorderType::Double)
            .border_style(Style::default().fg(theme.brand));
        frame.render_widget(outer, modal_area);

        // Inner layout: summary | file list | hint.
        let v = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1),
                Constraint::Min(1),
                Constraint::Length(1),
            ])
            .margin(1)
            .split(modal_area);

        // Summary line.
        let summary = Paragraph::new(Span::styled(
            format!("Delete {count} item(s)?"),
            Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
        ))
        .alignment(Alignment::Center);
        frame.render_widget(summary, v[0]);

        // File name list.
        let mut name_lines: Vec<Line> = shown
            .iter()
            .map(|p| {
                let name = p.file_name().unwrap_or_default().to_string_lossy();
                Line::from(vec![
                    Span::styled("", Style::default().fg(theme.brand)),
                    Span::styled(name.to_string(), Style::default().fg(theme.accent)),
                ])
            })
            .collect();
        if remainder > 0 {
            name_lines.push(Line::from(Span::styled(
                format!("  … and {remainder} more"),
                Style::default().fg(theme.dim),
            )));
        }
        let list_para = Paragraph::new(name_lines);
        frame.render_widget(list_para, v[1]);

        // Hint line.
        let hint_para = Paragraph::new(Line::from(vec![
            Span::styled(
                "  y",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("  confirm    ", Style::default().fg(theme.dim)),
            Span::styled(
                "any key",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("  cancel  ", Style::default().fg(theme.dim)),
        ]))
        .alignment(Alignment::Center);
        frame.render_widget(hint_para, v[2]);

        return;
    }

    // ── Single-item modals (Delete / Overwrite) ───────────────────────────────
    let (title, body) = match modal {
        Modal::Delete { path } => (
            " Confirm Delete ",
            format!(
                "Delete '{}' ?",
                path.file_name().unwrap_or_default().to_string_lossy()
            ),
        ),
        Modal::Overwrite { dst, .. } => (
            " Confirm Overwrite ",
            format!(
                "'{}' already exists. Overwrite?",
                dst.file_name().unwrap_or_default().to_string_lossy()
            ),
        ),
        // Already handled above.
        Modal::MultiDelete { .. } => unreachable!(),
    };

    let w = (body.len() as u16 + 6).max(40).min(area.width - 4);
    let h = 7u16;
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let modal_area = Rect::new(x, y, w, h);

    frame.render_widget(Clear, modal_area);

    let v = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(2),
            Constraint::Min(0),
            Constraint::Length(2),
        ])
        .margin(1)
        .split(modal_area);

    let outer = Block::default()
        .title(Span::styled(
            title,
            Style::default()
                .fg(theme.brand)
                .add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::ALL)
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme.brand));
    frame.render_widget(outer, modal_area);

    let body_para = Paragraph::new(Span::styled(
        body,
        Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
    ))
    .alignment(Alignment::Center);
    frame.render_widget(body_para, v[0]);

    let hint_para = Paragraph::new(Line::from(vec![
        Span::styled(
            "  y",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("  confirm    ", Style::default().fg(theme.dim)),
        Span::styled(
            "any key",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("  cancel  ", Style::default().fg(theme.dim)),
    ]))
    .alignment(Alignment::Center);
    frame.render_widget(hint_para, v[2]);
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use tui_file_explorer::Theme;

    // ── render_action_bar_spans ───────────────────────────────────────────────

    #[test]
    fn action_bar_spans_contains_expected_key_labels() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Tab"), "missing Tab hint");
        assert!(text.contains('['), "missing [ hint");
        assert!(text.contains('t'), "missing t hint");
        assert!(text.contains('w'), "missing w hint");
        assert!(text.contains("Shift+E"), "missing Shift+E (editor) hint");
        assert!(text.contains("Shift+O"), "missing Shift+O (options) hint");
    }

    #[test]
    fn action_bar_spans_count_is_stable() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        // 6 key spans + 6 description spans = 12 total.
        assert_eq!(
            spans.len(),
            12,
            "span count changed — update this test if the action bar was intentionally modified"
        );
    }

    #[test]
    fn action_bar_spans_key_spans_are_bold() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        let key_labels = ["Tab", "w", "[", "t", "Shift+E", "Shift+O"];
        for label in key_labels {
            let span = spans
                .iter()
                .find(|s| s.content.as_ref() == label)
                .unwrap_or_else(|| panic!("span for key '{label}' not found"));
            assert!(
                span.style.add_modifier.contains(Modifier::BOLD),
                "key span '{label}' should be bold"
            );
        }
    }

    #[test]
    fn action_bar_spans_description_spans_are_not_bold() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        let key_labels = ["Tab", "w", "[", "t", "Shift+E", "Shift+O"];
        for span in &spans {
            if !key_labels.contains(&span.content.as_ref()) {
                assert!(
                    !span.style.add_modifier.contains(Modifier::BOLD),
                    "description span '{}' should not be bold",
                    span.content
                );
            }
        }
    }

    #[test]
    fn action_bar_spans_key_spans_use_accent_colour() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        let key_labels = ["Tab", "w", "[", "t", "Shift+E", "Shift+O"];
        for label in key_labels {
            let span = spans
                .iter()
                .find(|s| s.content.as_ref() == label)
                .unwrap_or_else(|| panic!("span for key '{label}' not found"));
            assert_eq!(
                span.style.fg,
                Some(theme.accent),
                "key span '{label}' should use the accent colour"
            );
        }
    }

    #[test]
    fn action_bar_spans_description_spans_use_dim_colour() {
        let theme = Theme::default();
        let spans = render_action_bar_spans(&theme);
        let key_labels = ["Tab", "w", "[", "t", "Shift+E", "Shift+O"];
        for span in &spans {
            if !key_labels.contains(&span.content.as_ref()) {
                assert_eq!(
                    span.style.fg,
                    Some(theme.dim),
                    "description span '{}' should use the dim colour",
                    span.content
                );
            }
        }
    }

    // ── render_nav_hints_spans ────────────────────────────────────────────────

    #[test]
    fn nav_hints_spans_contain_arrow_keys() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains('k'), "missing k (up)");
        assert!(text.contains('j'), "missing j (down)");
        assert!(text.contains('h'), "missing h (ascend)");
        assert!(text.contains('l'), "missing l (confirm)");
        assert!(text.contains("Enter"), "missing Enter");
        assert!(text.contains("Bksp"), "missing Bksp");
    }

    #[test]
    fn nav_hints_spans_contain_search_and_sort() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains('/'), "missing / (search)");
        assert!(text.contains('s'), "missing s (sort)");
        assert!(text.contains('.'), "missing . (hidden)");
        assert!(text.contains("Esc"), "missing Esc (dismiss)");
    }

    #[test]
    fn nav_hints_key_spans_are_bold() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        // '/' appears both as a dim separator (between e.g. "↑" and "k") and as
        // the bold search-activation key.  Exclude it from the simple
        // "first match" check and verify it separately below.
        let key_labels = [
            "", "k", "", "j", "", "l", "Enter", "", "h", "Bksp", "s", ".", "Esc",
        ];
        for label in key_labels {
            let span = spans
                .iter()
                .find(|s| s.content.as_ref() == label)
                .unwrap_or_else(|| panic!("nav hint span for '{label}' not found"));
            assert!(
                span.style.add_modifier.contains(Modifier::BOLD),
                "nav key span '{label}' should be bold"
            );
        }
        // '/' is used both as a separator (dim) and as the search key (bold).
        // Assert that at least one '/' span is bold.
        let slash_bold = spans
            .iter()
            .any(|s| s.content.as_ref() == "/" && s.style.add_modifier.contains(Modifier::BOLD));
        assert!(slash_bold, "the search '/' key span should be bold");
    }

    #[test]
    fn nav_hints_key_spans_use_accent_colour() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        // Exclude '/' — it appears as both a dim separator and a bold accent key.
        let key_labels = ["", "k", "", "j", "Enter", "Bksp", "s", ".", "Esc"];
        for label in key_labels {
            let span = spans
                .iter()
                .find(|s| s.content.as_ref() == label)
                .unwrap_or_else(|| panic!("nav hint span for '{label}' not found"));
            assert_eq!(
                span.style.fg,
                Some(theme.accent),
                "nav key span '{label}' should use the accent colour"
            );
        }
        // Verify the search '/' key span (bold one) uses the accent colour.
        let slash_accent = spans.iter().any(|s| {
            s.content.as_ref() == "/"
                && s.style.add_modifier.contains(Modifier::BOLD)
                && s.style.fg == Some(theme.accent)
        });
        assert!(
            slash_accent,
            "the search '/' key span should use the accent colour"
        );
    }

    #[test]
    fn nav_hints_description_spans_use_dim_colour() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        // Bold key labels — spans carrying these as content must be accent-coloured.
        // '/' is excluded because it also appears as a dim separator between combos.
        let key_labels = [
            "", "k", "", "j", "", "l", "Enter", "", "h", "Bksp", "s", ".", "Esc",
        ];
        for span in &spans {
            let content = span.content.as_ref();
            // Skip bold key spans and '/' (mixed role).
            if key_labels.contains(&content) || content == "/" {
                continue;
            }
            assert_eq!(
                span.style.fg,
                Some(theme.dim),
                "nav description span '{}' should use the dim colour",
                span.content
            );
        }
    }

    #[test]
    fn nav_hints_span_count_is_stable() {
        let theme = Theme::default();
        let spans = render_nav_hints_spans(&theme);
        // 14 key spans + 14 separator/description spans = 28 total.
        assert_eq!(
            spans.len(),
            28,
            "nav hint span count changed — update this test if the nav bar was intentionally modified"
        );
    }

    // ── render_snackbar ───────────────────────────────────────────────────────

    /// Build a minimal `Snackbar` without going through `App` helpers so the
    /// tests stay pure (no `Instant::now()` drift issues in CI).
    fn make_snackbar(message: &str, is_error: bool) -> Snackbar {
        use std::time::{Duration, Instant};
        Snackbar {
            message: message.to_string(),
            expires_at: Instant::now() + Duration::from_secs(10),
            is_error,
        }
    }

    #[test]
    fn snackbar_geometry_height_is_three() {
        // render_snackbar always uses height = 3 (top border + content + bottom border).
        // We verify the computed Rect indirectly by checking that a short message
        // still produces a snackbar_area with height == 3.
        // Since render_snackbar is not pure (it takes a Frame), we test the
        // height constant through the public geometry formula used in the function.
        let height: u16 = 3;
        assert_eq!(height, 3);
    }

    #[test]
    fn snackbar_info_uses_success_colour() {
        let theme = Theme::default();
        let sb = make_snackbar("info message", false);
        // For an info snackbar the border / text colour must be theme.success.
        let expected = theme.success;
        let actual = if sb.is_error {
            theme.brand
        } else {
            theme.success
        };
        assert_eq!(actual, expected, "info snackbar should use success colour");
    }

    #[test]
    fn snackbar_error_uses_brand_colour() {
        let theme = Theme::default();
        let sb = make_snackbar("error message", true);
        let expected = theme.brand;
        let actual = if sb.is_error {
            theme.brand
        } else {
            theme.success
        };
        assert_eq!(actual, expected, "error snackbar should use brand colour");
    }

    #[test]
    fn snackbar_info_and_error_colours_are_distinct() {
        let theme = Theme::default();
        // Sanity check: the two colour paths must differ so the tests above
        // are actually meaningful.
        assert_ne!(
            theme.success, theme.brand,
            "success and brand colours must differ for snackbar colour tests to be meaningful"
        );
    }

    #[test]
    fn snackbar_message_is_preserved() {
        let msg = "No editor set — open Options (Shift + O) and press e to pick one";
        let sb = make_snackbar(msg, true);
        assert_eq!(sb.message, msg);
    }

    #[test]
    fn snackbar_width_at_least_minimum() {
        // The width formula: desired = msg.len() + 4, clamped to area_width - 4,
        // then max(20).  For any message the result must be >= 20.
        let msg = "hi"; // very short message
        let area_width: u16 = 200;
        let desired = (msg.len() as u16)
            .saturating_add(4)
            .min(area_width.saturating_sub(4));
        let width = desired.max(20);
        assert!(width >= 20, "snackbar width must be at least 20 columns");
    }

    #[test]
    fn snackbar_width_capped_to_area() {
        // A very long message should not exceed area_width - 4.
        let msg = "a".repeat(300);
        let area_width: u16 = 120;
        let desired = (msg.len() as u16)
            .saturating_add(4)
            .min(area_width.saturating_sub(4));
        let width = desired.max(20);
        assert!(
            width <= area_width,
            "snackbar must not exceed the terminal width"
        );
    }

    #[test]
    fn snackbar_is_not_expired_when_fresh() {
        let sb = make_snackbar("fresh", false);
        assert!(
            !sb.is_expired(),
            "a newly created snackbar must not be expired"
        );
    }

    #[test]
    fn snackbar_is_expired_after_deadline() {
        use std::time::{Duration, Instant};
        let sb = Snackbar {
            message: "old".into(),
            expires_at: Instant::now() - Duration::from_millis(1),
            is_error: false,
        };
        assert!(
            sb.is_expired(),
            "snackbar past its deadline must be expired"
        );
    }
}