peter-commander 0.8.1

A terminal file manager
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
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
use chrono::{DateTime, Local};
use ratatui::Frame;
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Widget, Wrap,
};

use crate::app::{App, Dialog, DialogKind, SettingItem, Side};
use crate::logging;
use crate::menu::{FN_KEYS, MENU_BAR};
use crate::pane::Pane;
use crate::preview::{self, PreviewContent};

pub fn draw(frame: &mut Frame, app: &mut App) {
    let root = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // menu bar
            Constraint::Min(3),    // panes
            Constraint::Length(1), // command line
            Constraint::Length(1), // F-key bar
        ])
        .split(frame.area());

    draw_menu_bar(frame, root[0], app);

    let panes = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(root[1]);

    // -2 for the pane's own top/bottom border, and 2 more for the divider +
    // status footer row when that's on (see `draw_pane`), so PgUp/PgDn page
    // by exactly what's actually visible in the file listing.
    let footer_rows = if app.pane_totals { 2 } else { 0 };
    app.pane_visible_lines = panes[0].height.saturating_sub(2 + footer_rows) as usize;
    app.left_pane_area = panes[0];
    app.right_pane_area = panes[1];

    if app.quick_view {
        match app.active {
            Side::Left => {
                app.preview_visible_lines = panes[1].height.saturating_sub(2) as usize;
                app.preview_visible_width = panes[1].width.saturating_sub(2) as usize;
                draw_pane(
                    frame,
                    panes[0],
                    &app.left,
                    !app.preview_focus,
                    &mut app.left_list_state,
                    app.classic_style,
                    app.pane_totals,
                );
                draw_preview_pane(
                    frame,
                    panes[1],
                    &app.left,
                    app.preview_focus,
                    app.preview_scroll,
                    app.classic_style,
                );
            }
            Side::Right => {
                app.preview_visible_lines = panes[0].height.saturating_sub(2) as usize;
                app.preview_visible_width = panes[0].width.saturating_sub(2) as usize;
                draw_preview_pane(
                    frame,
                    panes[0],
                    &app.right,
                    app.preview_focus,
                    app.preview_scroll,
                    app.classic_style,
                );
                draw_pane(
                    frame,
                    panes[1],
                    &app.right,
                    !app.preview_focus,
                    &mut app.right_list_state,
                    app.classic_style,
                    app.pane_totals,
                );
            }
        }
    } else {
        draw_pane(
            frame,
            panes[0],
            &app.left,
            app.active == Side::Left,
            &mut app.left_list_state,
            app.classic_style,
            app.pane_totals,
        );
        draw_pane(
            frame,
            panes[1],
            &app.right,
            app.active == Side::Right,
            &mut app.right_list_state,
            app.classic_style,
            app.pane_totals,
        );
    }

    draw_command_line(frame, root[2], app);
    draw_fn_key_bar(frame, root[3], app);

    if app.menu_open {
        draw_menu_dropdown(frame, root[0], app);
    }

    match &app.dialog {
        Dialog::Confirm { kind, items } => {
            let destination = matches!(kind, DialogKind::Copy | DialogKind::Move)
                .then(|| app.inactive_pane_ref().cwd.display().to_string());
            let summary = match items.as_slice() {
                [(name, _)] => format!("\"{name}\""),
                _ => format!("{} items", items.len()),
            };
            draw_confirm_dialog(
                frame,
                app.classic_style,
                *kind,
                &summary,
                destination.as_deref(),
                app.dialog_cancel_focused,
            );
        }
        Dialog::ConfirmOverwrite {
            items, conflicts, ..
        } => {
            let dest_dir = &app.inactive_pane_ref().cwd;
            let comparison = match conflicts.as_slice() {
                [name] => items
                    .iter()
                    .find(|(item, _)| item == name)
                    .and_then(|(_, src)| entry_summary(src).zip(entry_summary(&dest_dir.join(name)))),
                _ => None,
            };
            draw_overwrite_dialog(
                frame,
                app.classic_style,
                conflicts,
                &dest_dir.display().to_string(),
                comparison,
                app.dialog_cancel_focused,
            );
        }
        Dialog::TextInput { kind, input } => {
            draw_input_dialog(
                frame,
                app.classic_style,
                kind.title(),
                kind.prompt(),
                input,
                app.dialog_cancel_focused,
            );
        }
        Dialog::Rename { input, src } => {
            let old_name = src
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            draw_input_dialog(
                frame,
                app.classic_style,
                "Rename",
                &format!("Rename \"{old_name}\" to:"),
                input,
                app.dialog_cancel_focused,
            );
        }
        Dialog::ConfirmQuit => {
            draw_quit_dialog(frame, app.classic_style, app.dialog_cancel_focused);
        }
        Dialog::Settings { selected, .. } => {
            draw_settings_dialog(frame, app, *selected);
        }
        Dialog::None => {}
    }

    if app.help_open {
        draw_help(frame, app.help_page);
    }

    if app.logs_open {
        draw_logs(frame);
    }

    if let Some(message) = &app.error_dialog {
        draw_error_dialog(frame, message);
    }
}

/// A blocking "in your face" popup for `App::set_error` — unlike a routine
/// confirmation, an error demands a keypress to dismiss (any key, handled in
/// `main.rs`) so it can't be missed the way the log-only status line can.
fn draw_error_dialog(frame: &mut Frame, message: &str) {
    let area = frame.area();
    let inner_width = area.width.saturating_sub(4).clamp(20, 64) as usize;
    let hint = "Press any key to continue";
    let wrapped = wrap_message(message, inner_width);
    let content_width = wrapped
        .iter()
        .map(|line| line.len())
        .max()
        .unwrap_or(0)
        .max(hint.len());
    let width = (content_width as u16 + 4).min(area.width);
    let height = wrapped.len() as u16 + 4;
    let dialog_area = Rect {
        x: (area.width.saturating_sub(width)) / 2,
        y: (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };

    let block = Block::default()
        .title(" Error ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Red))
        .style(Style::default().bg(Color::Black).fg(Color::White));

    let mut lines: Vec<Line> = wrapped
        .into_iter()
        .map(|line| {
            Line::from(Span::styled(
                line,
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ))
        })
        .collect();
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        hint,
        Style::default().fg(Color::DarkGray),
    )));

    let paragraph = Paragraph::new(lines).block(block);

    draw_shadow_for(frame, dialog_area);
    frame.render_widget(Clear, dialog_area);
    frame.render_widget(paragraph, dialog_area);
}

/// Greedy word-wrap to at most `width` columns per line — good enough for
/// short error messages, no need for the full richness of a text-shaping
/// crate here.
fn wrap_message(message: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current = String::new();
    for word in message.split_whitespace() {
        if current.is_empty() {
            current.push_str(word);
        } else if current.len() + 1 + word.len() <= width {
            current.push(' ');
            current.push_str(word);
        } else {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
        }
    }
    if !current.is_empty() || lines.is_empty() {
        lines.push(current);
    }
    lines
}

const HELP_PAGE_1: &[&str] = &[
    "F1        Help          Show this screen",
    "F2        Rename        Rename selection (move within same dir)",
    "F3        View          Page selected file with $PAGER",
    "F4        Edit          Edit selected file with $EDITOR",
    "Shift+F4  New File      Create a new empty file",
    "F5        Copy          Copy selection (or marked files) to the other pane",
    "F6        Move          Move selection (or marked files) to the other pane",
    "F7        MkDir         Create a new directory",
    "F8        Delete        Delete selection or marked files (asks to confirm)",
    "F9        Menu          Open the pulldown menu",
    "F10       Quit          Quit PeterCommander (asks to confirm)",
    "",
    "Alt+F1    Left = Right   Point left pane at right pane's dir",
    "Alt+F2    Right = Left   Point right pane at left pane's dir",
    "Alt+F/O/C Menu           Jump to the File/Options/Command menu",
    "Ctrl+O    Terminal       Reveal the terminal/scrollback under panels",
    "Ctrl+Q    Quit           Same as F10, in case your terminal eats F10",
    "Ctrl+L    Show Logs      Same as F9 > Command > Show Logs",
    "Ctrl+S    Settings       Same as F9 > Options > Settings",
    "",
    "Tab       Switch the active pane",
    "Up/Down   Move the selection",
    "Home/End  Jump to the top/bottom of the listing",
    "PgUp/PgDn Move the selection by one screenful",
    "Insert    Mark/unmark the entry and move down",
];

const HELP_PAGE_2: &[&str] = &[
    "Type anywhere to fill the command line below the panes;",
    "Enter runs it in the active pane's directory, or opens",
    "the selected entry if the command line is empty.",
    "Esc clears the command line. Quit with F10 (or F9 > Command > Quit).",
    "",
    "F9 > Options > Settings opens the settings screen: Up/Down",
    "to move, Space to toggle a checkbox, Enter to save, Esc to cancel.",
    "",
    "F9 > Command > Show Logs shows recent status/error messages —",
    "there's no dedicated status line any more, they're logged instead.",
    "",
    "Mouse: scroll the active pane/preview, click the menu bar or an",
    "F-key tile.",
];

const HELP_FOOTER: &str = "Left/Right: switch page   Any other key: close";

fn draw_help(frame: &mut Frame, page: usize) {
    let lines_for_page = if page == 0 { HELP_PAGE_1 } else { HELP_PAGE_2 };

    // Sized from both pages combined (not just the one currently shown),
    // so the window stays the same size when switching pages instead of
    // resizing around whichever page happens to be shorter.
    let width = HELP_PAGE_1
        .iter()
        .chain(HELP_PAGE_2)
        .chain([&HELP_FOOTER])
        .map(|line| line.chars().count())
        .max()
        .unwrap_or(20) as u16
        + 4;
    let width = width.min(frame.area().width);
    let content_height = HELP_PAGE_1.len().max(HELP_PAGE_2.len()) as u16;
    let height = (content_height + 4).min(frame.area().height);

    let area = Rect {
        x: (frame.area().width.saturating_sub(width)) / 2,
        y: (frame.area().height.saturating_sub(height)) / 2,
        width,
        height,
    };

    let mut lines: Vec<Line> = lines_for_page
        .iter()
        .map(|line| Line::from(Span::styled(*line, Style::default().fg(Color::White))))
        .collect();
    // Pad the shorter page so the footer lands on the same row on both
    // pages, not just the box being the same overall size.
    lines.resize(content_height as usize, Line::from(""));
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        HELP_FOOTER,
        Style::default().fg(Color::DarkGray),
    )));

    let block = Block::default()
        .title(format!("Help — Keybindings (Page {}/2)", page + 1))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Green))
        .style(Style::default().bg(Color::Black).fg(Color::White));

    let paragraph = Paragraph::new(lines).block(block);

    frame.render_widget(Clear, area);
    frame.render_widget(paragraph, area);
}

/// Color palette for the big double-bordered dialog frame shared by every
/// modal (Copy/Move/Delete confirm, Rename, MkDir/New file, Quit). The
/// *shape* — double border, sectioned content, a `[ Button ]` row — is the
/// same in both modes; only the colors swap: `classic_style` uses the fixed
/// retro gray/teal DOS palette, otherwise everything follows the terminal's
/// own theme colors.
struct DialogPalette {
    bg: Color,
    fg: Color,
    border_fg: Color,
    field_bg: Color,
    field_fg: Color,
    button_default_bg: Color,
    button_default_fg: Color,
}

fn dialog_palette(classic_style: bool) -> DialogPalette {
    if classic_style {
        DialogPalette {
            bg: classic::DIALOG_BG,
            fg: classic::DIALOG_FG,
            border_fg: classic::DIALOG_BORDER_FG,
            field_bg: classic::HIGHLIGHT_BG,
            field_fg: classic::HIGHLIGHT_FG,
            button_default_bg: classic::HIGHLIGHT_BG,
            button_default_fg: classic::HIGHLIGHT_FG,
        }
    } else {
        DialogPalette {
            bg: Color::Black,
            fg: Color::White,
            border_fg: Color::Cyan,
            field_bg: Color::Cyan,
            field_fg: Color::Black,
            button_default_bg: Color::Cyan,
            button_default_fg: Color::Black,
        }
    }
}

/// One line of dialog content. `Field` is padded to the dialog's full inner
/// width when rendered so its background fills the whole row, like the
/// highlighted destination/input bar in classic Norton Commander dialogs;
/// `Text`/`Centered` are rendered as-is (`Centered` for the button row).
enum DialogLine<'a> {
    Text(Line<'a>),
    Field { content: Vec<Span<'a>>, fill_bg: Color },
    Centered(Line<'a>),
}

impl DialogLine<'_> {
    fn natural_width(&self) -> usize {
        match self {
            DialogLine::Text(line) | DialogLine::Centered(line) => line.width(),
            DialogLine::Field { content, .. } => {
                content.iter().map(Span::width).sum::<usize>() + 2 * DIALOG_PAD
            }
        }
    }
}

fn button_row<'a>(buttons: &[(&'a str, bool)], pal: &DialogPalette) -> DialogLine<'a> {
    let mut spans = Vec::new();
    for (idx, (label, is_default)) in buttons.iter().enumerate() {
        if idx > 0 {
            spans.push(Span::raw("   "));
        }
        let style = if *is_default {
            Style::default()
                .bg(pal.button_default_bg)
                .fg(pal.button_default_fg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(pal.fg)
        };
        spans.push(Span::styled(format!("[ {label} ]"), style));
    }
    DialogLine::Centered(Line::from(spans))
}

/// Renders `sections` stacked inside a double-bordered box, each section
/// separated by a full-width single-line divider that tees into the border
/// (`╟──────╢`) — the "big, proud" classic dialog look the whole family of
/// modals shares.
/// 1-column margin of dialog background kept between the border and the
/// content on every side (except the divider rows, which deliberately span
/// edge-to-edge to tee into the border).
const DIALOG_PAD: usize = 1;

/// A second margin of dialog background *outside* the border too, between
/// it and whatever's behind the dialog — so the border never sits flush
/// against the panes/shadow. Wider on the sides than top/bottom, matching
/// the reference look.
const OUTER_PAD_X: u16 = 2;
const OUTER_PAD_Y: u16 = 1;

fn draw_dialog_frame(
    frame: &mut Frame,
    classic_style: bool,
    title: &str,
    sections: Vec<Vec<DialogLine>>,
    min_half_screen: bool,
) {
    let pal = dialog_palette(classic_style);

    let content_width = sections
        .iter()
        .flat_map(|section| section.iter())
        .map(DialogLine::natural_width)
        .max()
        .unwrap_or(0)
        .max(title.chars().count() + 4);
    let box_width = content_width as u16 + 2 * DIALOG_PAD as u16 + 2;
    // Never narrower than half the screen, however short the content is —
    // applied to the full outer footprint, border pad included. Quit opts
    // out, staying sized to its (short) content instead.
    let min_width = if min_half_screen {
        frame.area().width / 2
    } else {
        0
    };
    let total_width = (box_width + 2 * OUTER_PAD_X)
        .max(min_width)
        .min(frame.area().width);
    let width = total_width.saturating_sub(2 * OUTER_PAD_X);
    let inner_width = width.saturating_sub(2) as usize;

    // Block's own left/right border glyph is drawn independently for every
    // row, including this one, so the divider's content can't include `╠`/
    // `╣` itself (that would double up with the border's `║`) — it's plain
    // `═` here, and the two edge cells get patched to `╠`/`╣` after the
    // paragraph is rendered, to actually tee into the border.
    let divider = Line::from(Span::styled(
        "─".repeat(inner_width),
        Style::default().fg(pal.border_fg),
    ));

    let divider_count = sections.len().saturating_sub(1);
    let content_height: usize = sections.iter().map(Vec::len).sum();
    let box_height = (content_height + divider_count + 2) as u16;
    let total_height = (box_height + 2 * OUTER_PAD_Y).min(frame.area().height);
    let height = total_height.saturating_sub(2 * OUTER_PAD_Y);

    let outer_area = Rect {
        x: (frame.area().width.saturating_sub(total_width)) / 2,
        y: (frame.area().height.saturating_sub(total_height)) / 2,
        width: total_width,
        height: total_height,
    };
    let area = Rect {
        x: outer_area.x + OUTER_PAD_X,
        y: outer_area.y + OUTER_PAD_Y,
        width,
        height,
    };

    let block = Block::default()
        .title_top(Line::from(format!(" {title} ")).centered())
        .borders(Borders::ALL)
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(pal.border_fg))
        .style(Style::default().bg(pal.bg).fg(pal.fg));

    let mut lines: Vec<Line> = Vec::new();
    let mut divider_rows: Vec<u16> = Vec::new();
    for (idx, section) in sections.into_iter().enumerate() {
        if idx > 0 {
            divider_rows.push(lines.len() as u16);
            lines.push(divider.clone());
        }
        for dialog_line in section {
            lines.push(match dialog_line {
                DialogLine::Text(mut line) => {
                    line.spans.insert(
                        0,
                        Span::styled(" ".repeat(DIALOG_PAD), Style::default().bg(pal.bg)),
                    );
                    line
                }
                DialogLine::Centered(line) => line.centered(),
                DialogLine::Field { content, fill_bg } => {
                    let content_width: usize = content.iter().map(Span::width).sum();
                    let mut spans =
                        vec![Span::styled(" ".repeat(DIALOG_PAD), Style::default().bg(pal.bg))];
                    spans.extend(content);
                    let used = DIALOG_PAD + content_width;
                    let bar_end = inner_width.saturating_sub(DIALOG_PAD);
                    if bar_end > used {
                        spans.push(Span::styled(
                            " ".repeat(bar_end - used),
                            Style::default().bg(fill_bg),
                        ));
                    }
                    Line::from(spans)
                }
            });
        }
    }

    let paragraph = Paragraph::new(lines).block(block);

    draw_shadow_for(frame, outer_area);
    frame.render_widget(Clear, outer_area);
    frame.render_widget(
        Block::default().style(Style::default().bg(pal.bg)),
        outer_area,
    );
    frame.render_widget(paragraph, area);

    // Patch the border column on each divider row into a single-line-into-
    // double-border tee (`╟`/`╢`) now that the block has drawn its own `║`
    // there — content-row index `row` sits at `area.y + 1 + row` since the
    // top border consumes row 0.
    let buf = frame.buffer_mut();
    let border_style = Style::default().fg(pal.border_fg).bg(pal.bg);
    for row in divider_rows {
        let y = area.y + 1 + row;
        if let Some(cell) = buf.cell_mut((area.x, y)) {
            cell.set_symbol("╟").set_style(border_style);
        }
        if let Some(cell) = buf.cell_mut((area.x + width.saturating_sub(1), y)) {
            cell.set_symbol("╢").set_style(border_style);
        }
    }
}

/// Copy/Move/Delete confirmation — Copy and Move also show the destination
/// (the other pane's directory, not editable) as a highlighted line.
fn draw_confirm_dialog(
    frame: &mut Frame,
    classic_style: bool,
    kind: DialogKind,
    summary: &str,
    destination: Option<&str>,
    cancel_focused: bool,
) {
    let pal = dialog_palette(classic_style);
    let verb = kind.verb();

    let message = match destination {
        Some(_) => format!("{verb} {summary} to"),
        None => format!("{verb} {summary}?"),
    };
    let mut sections = vec![vec![DialogLine::Text(Line::from(Span::styled(
        message,
        Style::default().fg(pal.fg),
    )))]];

    if let Some(dest) = destination {
        sections.push(vec![DialogLine::Field {
            content: vec![Span::styled(
                dest.to_string(),
                Style::default().bg(pal.field_bg).fg(pal.field_fg),
            )],
            fill_bg: pal.field_bg,
        }]);
    }

    sections.push(vec![button_row(
        &[(verb, !cancel_focused), ("Cancel", cancel_focused)],
        &pal,
    )]);

    draw_dialog_frame(frame, classic_style, verb, sections, true);
}

/// Size and modified time of one side of an overwrite, as the listing shows
/// them.
struct EntrySummary {
    size: String,
    modified: Option<std::time::SystemTime>,
}

fn entry_summary(path: &std::path::Path) -> Option<EntrySummary> {
    let meta = std::fs::metadata(path)
        .or_else(|_| std::fs::symlink_metadata(path))
        .ok()?;
    let size = if meta.is_dir() {
        "<DIR>".to_string()
    } else {
        format_size(meta.len())
    };
    Some(EntrySummary {
        size,
        modified: meta.modified().ok(),
    })
}

/// How many conflicting names an overwrite prompt lists before summing up
/// the rest, so a big batch doesn't grow the dialog past the screen.
const OVERWRITE_LIST_LIMIT: usize = 3;

/// Copy/Move onto items that already exist: names what's in the way and,
/// for a single item, puts both versions' size and date side by side with
/// the newer one marked, so it's clear what would be replaced.
fn draw_overwrite_dialog(
    frame: &mut Frame,
    classic_style: bool,
    conflicts: &[String],
    destination: &str,
    comparison: Option<(EntrySummary, EntrySummary)>,
    cancel_focused: bool,
) {
    let pal = dialog_palette(classic_style);
    let text = |s: String| DialogLine::Text(Line::from(Span::styled(s, Style::default().fg(pal.fg))));

    let message = match conflicts {
        [name] => format!("\"{name}\" already exists in"),
        _ => format!("{} items already exist in", conflicts.len()),
    };
    let mut sections = vec![
        vec![text(message)],
        vec![DialogLine::Field {
            content: vec![Span::styled(
                destination.to_string(),
                Style::default().bg(pal.field_bg).fg(pal.field_fg),
            )],
            fill_bg: pal.field_bg,
        }],
    ];

    let details = match comparison {
        Some((new, existing)) => {
            let is_newer = |a: &EntrySummary, b: &EntrySummary| {
                matches!((a.modified, b.modified), (Some(a), Some(b)) if a > b)
            };
            let row = |label: &str, entry: &EntrySummary, newer: bool| {
                text(format!(
                    "{label} {:>12}  {}{}",
                    entry.size,
                    format_modified(entry.modified),
                    if newer { "  (newer)" } else { "" }
                ))
            };
            vec![
                row("New:     ", &new, is_newer(&new, &existing)),
                row("Existing:", &existing, is_newer(&existing, &new)),
            ]
        }
        None => {
            let mut lines: Vec<DialogLine> = conflicts
                .iter()
                .take(OVERWRITE_LIST_LIMIT)
                .map(|name| text(name.clone()))
                .collect();
            if conflicts.len() > OVERWRITE_LIST_LIMIT {
                lines.push(text(format!(
                    "…and {} more",
                    conflicts.len() - OVERWRITE_LIST_LIMIT
                )));
            }
            lines
        }
    };
    sections.push(details);

    sections.push(vec![button_row(
        &[("Overwrite", !cancel_focused), ("Cancel", cancel_focused)],
        &pal,
    )]);

    draw_dialog_frame(frame, classic_style, "Overwrite", sections, true);
}

fn draw_quit_dialog(frame: &mut Frame, classic_style: bool, cancel_focused: bool) {
    let pal = dialog_palette(classic_style);
    let sections = vec![
        vec![DialogLine::Text(Line::from(Span::styled(
            "Quit PeterCommander?",
            Style::default().fg(pal.fg),
        )))],
        vec![button_row(
            &[("Quit", !cancel_focused), ("Cancel", cancel_focused)],
            &pal,
        )],
    ];
    draw_dialog_frame(frame, classic_style, "Quit", sections, false);
}

/// Rename and MkDir/New file: a label line, a highlighted editable-field
/// line showing the text typed so far (with a blinking cursor), and a
/// button row.
fn draw_input_dialog(
    frame: &mut Frame,
    classic_style: bool,
    title: &str,
    prompt: &str,
    input: &str,
    cancel_focused: bool,
) {
    let pal = dialog_palette(classic_style);
    let sections = vec![
        vec![DialogLine::Text(Line::from(Span::styled(
            prompt.to_string(),
            Style::default().fg(pal.fg),
        )))],
        vec![DialogLine::Field {
            content: vec![
                Span::styled(
                    input.to_string(),
                    Style::default().bg(pal.field_bg).fg(pal.field_fg),
                ),
                Span::styled(
                    "_",
                    Style::default()
                        .bg(pal.field_bg)
                        .fg(pal.field_fg)
                        .add_modifier(Modifier::SLOW_BLINK),
                ),
            ],
            fill_bg: pal.field_bg,
        }],
        vec![button_row(
            &[("OK", !cancel_focused), ("Cancel", cancel_focused)],
            &pal,
        )],
    ];
    draw_dialog_frame(frame, classic_style, title, sections, true);
}

const SETTINGS_HINT: &str = " \u{2190}/\u{2192}/Space: toggle   Enter: save   Esc: cancel";

/// Each setting is shown as a two-way switch — "left label [ ]----[x] right
/// label" — rather than a single generic checkbox, so both what's on and
/// what's off are named in positive language instead of one hard-to-phrase
/// boolean. The left column is padded to the widest left label so the
/// switches themselves line up in a column.
const SWITCH_TRACK: &str = "----";

fn draw_settings_dialog(frame: &mut Frame, app: &App, selected: usize) {
    let left_col_width = SettingItem::ALL
        .iter()
        .map(|item| item.left_label().chars().count())
        .max()
        .unwrap_or(0);

    let items: Vec<ListItem> = SettingItem::ALL
        .iter()
        .enumerate()
        .map(|(idx, item)| {
            let (left_box, right_box) = if app.setting_value(*item) {
                ("[ ]", "[x]")
            } else {
                ("[x]", "[ ]")
            };
            let style = if idx == selected {
                Style::default()
                    .fg(Color::White)
                    .bg(Color::Blue)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(Line::from(Span::styled(
                format!(
                    " {:<left_col_width$} {left_box}{SWITCH_TRACK}{right_box} {}",
                    item.left_label(),
                    item.right_label(),
                ),
                style,
            )))
        })
        .chain(std::iter::once(ListItem::new(Line::from(Span::styled(
            SETTINGS_HINT,
            Style::default().fg(Color::DarkGray),
        )))))
        .collect();

    let hint_len = SETTINGS_HINT.chars().count();
    let switch_width = 3 + SWITCH_TRACK.len() + 3; // "[ ]" + track + "[x]"
    let width = SettingItem::ALL
        .iter()
        .map(|item| 1 + left_col_width + 1 + switch_width + 1 + item.right_label().chars().count() + 2)
        .chain(std::iter::once(hint_len + 2))
        .max()
        .unwrap_or(20) as u16;
    // +2 for a 1-column/1-row padding between the border and the content,
    // on top of the border itself.
    let width = (width + 2).min(frame.area().width);
    let height = (SettingItem::ALL.len() as u16 + 3 + 2).min(frame.area().height);

    let area = Rect {
        x: (frame.area().width.saturating_sub(width)) / 2,
        y: (frame.area().height.saturating_sub(height)) / 2,
        width,
        height,
    };

    let block = Block::default()
        .title("Settings")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan))
        .style(Style::default().bg(Color::Black).fg(Color::White))
        .padding(Padding::uniform(1));

    frame.render_widget(Clear, area);
    frame.render_widget(List::new(items).block(block), area);
}

fn draw_menu_bar(frame: &mut Frame, area: Rect, app: &mut App) {
    app.menu_bar_tiles.clear();
    let mut x = area.x + 1; // the leading raw space
    let mut spans = Vec::new();
    spans.push(Span::raw(" "));
    for (idx, category) in MENU_BAR.iter().enumerate() {
        let is_selected = app.menu_open && idx == app.menu_category;
        let style = match (app.classic_style, is_selected) {
            (true, true) => Style::default()
                .fg(classic::MENU_BAR_SELECTED_FG)
                .bg(classic::MENU_BAR_SELECTED_BG)
                .add_modifier(Modifier::BOLD),
            (true, false) => Style::default().fg(classic::MENU_BAR_FG).bg(classic::MENU_BAR_BG),
            (false, true) => Style::default()
                .fg(Color::White)
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD),
            (false, false) => Style::default().fg(Color::Black).bg(Color::Gray),
        };
        let tile_width = category.title.len() as u16 + 2;
        app.menu_bar_tiles.push((
            Rect {
                x,
                y: area.y,
                width: tile_width,
                height: 1,
            },
            idx,
        ));
        x += tile_width;
        spans.push(Span::styled(format!(" {} ", category.title), style));
    }
    let bar_bg = if app.classic_style {
        classic::MENU_BAR_BG
    } else {
        Color::Gray
    };
    let bar = Paragraph::new(Line::from(spans)).style(Style::default().bg(bar_bg));
    frame.render_widget(bar, area);
}

/// A drop-shadow overlay. Two earlier attempts taught what doesn't work
/// here: `Modifier::DIM` only dims a cell's foreground per the ANSI spec,
/// not its background, and most of the shadow falls on blank/background
/// cells; and named colors like `Color::DarkGray` are whatever the
/// terminal's color scheme remaps them to (some dark themes map it close
/// to black, same trap as the old hardcoded `Color::White` text bug).
///
/// Where the cell underneath is a known `Color::Rgb` (true in classic
/// mode, since every classic color is an explicit RGB constant), this
/// darkens that exact color instead of replacing it — real "see-through"
/// shadow rather than a flat gray patch. For anything else (a named/Reset
/// color, i.e. following the terminal's own theme, where the actual RGB
/// isn't knowable) it falls back to a fixed dark gray fill — reverse video
/// was tried here too, but looked inconsistent against Omarchy's dynamic
/// theming, so a flat fill is the more predictable choice for that case.
struct Shadow;

/// Multiplies each RGB channel by this factor to darken it for the shadow.
const SHADOW_DARKEN_FACTOR: f32 = 0.35;
/// Flat fallback for cells whose color isn't a known RGB to darken.
const SHADOW_FALLBACK: Color = Color::Rgb(30, 30, 30);

fn darken(color: Color) -> Color {
    let Color::Rgb(r, g, b) = color else {
        return SHADOW_FALLBACK;
    };
    Color::Rgb(
        (r as f32 * SHADOW_DARKEN_FACTOR) as u8,
        (g as f32 * SHADOW_DARKEN_FACTOR) as u8,
        (b as f32 * SHADOW_DARKEN_FACTOR) as u8,
    )
}

impl Widget for Shadow {
    fn render(self, area: Rect, buf: &mut Buffer) {
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                if let Some(cell) = buf.cell_mut((x, y)) {
                    cell.set_bg(darken(cell.bg));
                    cell.set_fg(darken(cell.fg));
                }
            }
        }
    }
}

/// Draws a `Shadow` offset from `area` — call this before clearing/drawing
/// into `area` itself, so only the shadow's bottom/right sliver ends up
/// visible once the real content is drawn on top of it. The right side is
/// offset by 2 columns rather than 1 (matching classic Norton Commander):
/// terminal cells are roughly twice as tall as they are wide, so a 1-row
/// bottom shadow needs 2 columns on the right to look proportional instead
/// of lopsided.
fn draw_shadow_for(frame: &mut Frame, area: Rect) {
    let shadow_area = Rect {
        x: area.x + 1,
        y: area.y + 1,
        width: area.width + 1,
        height: area.height,
    };
    frame.render_widget(Shadow, shadow_area);
}

fn draw_menu_dropdown(frame: &mut Frame, menu_bar_area: Rect, app: &mut App) {
    // Compute the x offset of the selected category so the dropdown appears under it.
    let mut x = menu_bar_area.x + 1;
    for category in &MENU_BAR[..app.menu_category] {
        x += category.title.len() as u16 + 2;
    }

    let category = &MENU_BAR[app.menu_category];
    let row_text_width = category
        .items
        .iter()
        .map(|action| {
            let shortcut_width = action.shortcut().map_or(0, |s| s.len() + 3);
            action.label().len() + shortcut_width
        })
        .max()
        .unwrap_or(4);
    let width = (row_text_width as u16) + 4;
    let height = category.items.len() as u16 + 2;

    let area = Rect {
        x: x.min(frame.area().width.saturating_sub(width)),
        y: menu_bar_area.y + 1,
        width,
        height,
    };

    // Item rows sit 1 cell in from the block's border on every side.
    app.menu_item_tiles = (0..category.items.len())
        .map(|idx| {
            (
                Rect {
                    x: area.x + 1,
                    y: area.y + 1 + idx as u16,
                    width: area.width.saturating_sub(2),
                    height: 1,
                },
                idx,
            )
        })
        .collect();

    let items: Vec<ListItem> = category
        .items
        .iter()
        .enumerate()
        .map(|(idx, action)| {
            let is_selected = idx == app.menu_item;
            let enabled = app.action_enabled(*action);
            let style = match (app.classic_style, is_selected, enabled) {
                (true, true, _) => Style::default()
                    .fg(classic::MENU_SELECTED_ITEM_FG)
                    .bg(classic::MENU_SELECTED_ITEM_BG)
                    .add_modifier(Modifier::BOLD),
                (true, false, true) => {
                    Style::default().fg(classic::MENU_ITEM_FG).bg(classic::MENU_BG)
                }
                (true, false, false) => {
                    Style::default().fg(classic::MENU_DISABLED_FG).bg(classic::MENU_BG)
                }
                (false, true, true) => Style::default()
                    .fg(Color::White)
                    .bg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
                (false, true, false) => Style::default().fg(Color::DarkGray).bg(Color::Blue),
                (false, false, true) => Style::default().fg(Color::Black).bg(Color::Gray),
                (false, false, false) => Style::default().fg(Color::DarkGray).bg(Color::Gray),
            };
            // Classic NC shows the shortcut in white regardless of the
            // (yellow/muted) label color, but only for a plain, unselected
            // row — a selected/highlighted row is one uniform reverse-video
            // color for the whole line, same as everywhere else.
            let shortcut_style = if app.classic_style && !is_selected && enabled {
                Style::default().fg(Color::Rgb(255, 255, 255)).bg(classic::MENU_BG)
            } else {
                style
            };
            let (label_part, shortcut_part) = match action.shortcut() {
                Some(shortcut) => (
                    format!("{:<label_width$}", action.label(), label_width = row_text_width - shortcut.len()),
                    format!("{shortcut:>shortcut_width$}", shortcut_width = shortcut.len()),
                ),
                None => (format!("{:<row_text_width$}", action.label()), String::new()),
            };
            ListItem::new(Line::from(vec![
                Span::styled(" ", style),
                Span::styled(label_part, style),
                Span::styled(shortcut_part, shortcut_style),
                Span::styled(" ", style),
            ]))
        })
        .collect();

    let block = if app.classic_style {
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(classic::MENU_BORDER_FG).add_modifier(Modifier::BOLD))
            .style(Style::default().bg(classic::MENU_BG).fg(classic::MENU_ITEM_FG))
    } else {
        Block::default()
            .borders(Borders::ALL)
            .style(Style::default().bg(Color::Gray).fg(Color::Black))
    };

    draw_shadow_for(frame, area);

    frame.render_widget(Clear, area);
    frame.render_widget(List::new(items).block(block), area);
}

/// Width of a formatted date/time like "20-09-26 15:57".
const DATE_COLUMN_WIDTH: usize = 14;
/// Width the size column is right-aligned to.
const SIZE_COLUMN_WIDTH: usize = 10;
/// Above this, the size column shows megabytes instead of a raw byte count
/// — a precise byte count stops being useful reading once it's this large.
const SIZE_COLLAPSE_THRESHOLD: u64 = 100 * 1024 * 1024;

/// Inserts a comma every 3 digits, e.g. `1234567` -> `"1,234,567"`.
fn with_thousands_separators(n: u64) -> String {
    let digits = n.to_string();
    let bytes = digits.as_bytes();
    let mut result = String::with_capacity(digits.len() + digits.len() / 3);
    for (i, &byte) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i).is_multiple_of(3) {
            result.push(',');
        }
        result.push(byte as char);
    }
    result
}

/// Formats a file size for the listing: a comma-grouped byte count below
/// `SIZE_COLLAPSE_THRESHOLD`, or a comma-grouped megabyte count above it —
/// an exact byte count stops being readable/useful once a file is that big.
fn format_size(bytes: u64) -> String {
    if bytes >= SIZE_COLLAPSE_THRESHOLD {
        format!("{} MB", with_thousands_separators(bytes / (1024 * 1024)))
    } else {
        with_thousands_separators(bytes)
    }
}
/// Never shrink the name column below this, even on a very narrow pane —
/// beyond this point there just isn't a sane layout, so let the line clip
/// instead of producing a useless sliver of a name column.
const MIN_NAME_COLUMN_WIDTH: usize = 8;

/// How wide the name column should be so the full row (name + size + date)
/// exactly fills `inner_width` (the pane's content width, borders already
/// excluded) — rather than a fixed width that wastes space on a wide pane
/// or overflows on a narrow one.
fn name_column_width(inner_width: u16) -> usize {
    // 3 spaces: one before the size column, one before the date, and one
    // trailing margin after it.
    let fixed_width = SIZE_COLUMN_WIDTH + DATE_COLUMN_WIDTH + 3;
    (inner_width as usize)
        .saturating_sub(fixed_width)
        .max(MIN_NAME_COLUMN_WIDTH)
}

/// Truncates a name to fit the name column, appending an ellipsis, instead
/// of letting a long name spill into the size/date columns.
fn fit_name(name: &str, width: usize) -> String {
    let char_count = name.chars().count();
    if char_count <= width {
        format!("{name:<width$}")
    } else {
        let truncated: String = name.chars().take(width.saturating_sub(1)).collect();
        format!("{truncated}\u{2026}")
    }
}

fn draw_command_line(frame: &mut Frame, area: Rect, app: &App) {
    let cwd = match app.active {
        Side::Left => &app.left.cwd,
        Side::Right => &app.right.cwd,
    };
    // Once the row's background is forced to black below, the typed text
    // can't be left as Color::Reset (the terminal's own default foreground)
    // — on a light terminal theme that default is a dark color, which
    // would go invisible on a now-black background. Same lesson as the
    // earlier white-on-white pane text bug.
    // 0xAFA8AF sampled from the reference screenshot's prompt text — the
    // classic DOS "light gray" (palette color 7), not pure white.
    let typed_text_fg = if app.classic_style {
        Color::Rgb(0xAF, 0xA8, 0xAF)
    } else {
        Color::Reset
    };
    // Indented 1 column, matching the F-key bar below it — as a real
    // painted leading space rather than shrinking the render area, so
    // that column gets the row's own background instead of leaving it
    // untouched (showing whatever was underneath, e.g. the terminal's own
    // background peeking through as a stray-colored notch).
    let indent_style = if app.classic_style {
        Style::default().bg(classic::PROMPT_BG)
    } else {
        Style::default()
    };
    // The reference screenshot doesn't highlight the cwd at all — the
    // whole prompt is one uniform gray. Named `Color::Green` is also
    // exactly the kind of color a dynamically-themed terminal (e.g.
    // Omarchy) can remap to something else entirely — it showed up as
    // yellow, not green, the same lesson as every other named-color bug
    // this session.
    let cwd_fg = if app.classic_style {
        typed_text_fg
    } else {
        Color::Green
    };
    let mut spans = Vec::new();
    // The 1-column indent looks right against the terminal's own
    // background, but looks off-balance once the row has its own solid
    // blue/black backgrounds (classic mode) — skip it there.
    if !app.classic_style {
        spans.push(Span::styled(" ", indent_style));
    }
    spans.push(Span::styled(
        format!("{}> ", cwd.display()),
        Style::default().fg(cwd_fg).add_modifier(Modifier::BOLD),
    ));
    spans.push(Span::styled(&app.command_line, Style::default().fg(typed_text_fg)));
    let line = Line::from(spans);
    let paragraph = if app.classic_style {
        Paragraph::new(line).style(Style::default().bg(classic::PROMPT_BG))
    } else {
        Paragraph::new(line)
    };
    frame.render_widget(paragraph, area);
}

fn format_modified(modified: Option<std::time::SystemTime>) -> String {
    match modified {
        Some(time) => DateTime::<Local>::from(time)
            .format("%d-%m-%y %H:%M")
            .to_string(),
        None => String::new(),
    }
}

/// Fixed colors for the "Classic retro Norton Commander" setting — real
/// RGB rather than named ANSI colors, so a dynamically-themed terminal
/// (e.g. Omarchy's per-wallpaper palette) can't remap them away from the
/// intended look, the same lesson learned from the menu shadow.
mod classic {
    use ratatui::style::Color;

    pub const BG: Color = Color::Rgb(0, 0, 170);
    pub const DIR_FG: Color = Color::Rgb(255, 255, 255);
    // 0x50FFFF from the reference screenshot — a light turquoise, used for
    // both plain file text and the active pane's border.
    pub const FILE_FG: Color = Color::Rgb(0x50, 0xFF, 0xFF);
    pub const ACTIVE_BORDER_FG: Color = FILE_FG;
    pub const INACTIVE_BORDER_FG: Color = Color::Rgb(0, 170, 170);
    pub const HIGHLIGHT_BG: Color = Color::Rgb(0, 170, 170);
    pub const HIGHLIGHT_FG: Color = Color::Rgb(0, 0, 0);

    // Menu bar and dropdown — same turquoise background as the dropdown,
    // not black, with mostly-white text (a single accelerator letter is
    // yellow in the reference screenshot; not implemented yet).
    pub const MENU_BG: Color = Color::Rgb(0, 170, 170);
    pub const MENU_BAR_BG: Color = MENU_BG;
    pub const MENU_BAR_FG: Color = Color::Rgb(255, 255, 255);
    pub const MENU_BAR_SELECTED_BG: Color = Color::Rgb(255, 255, 255);
    pub const MENU_BAR_SELECTED_FG: Color = Color::Rgb(0, 0, 0);
    pub const MENU_ITEM_FG: Color = Color::Rgb(255, 255, 255);
    pub const MENU_DISABLED_FG: Color = Color::Rgb(0, 85, 85);
    pub const MENU_SELECTED_ITEM_BG: Color = Color::Rgb(0, 0, 0);
    pub const MENU_SELECTED_ITEM_FG: Color = Color::Rgb(255, 255, 255);
    pub const MENU_BORDER_FG: Color = Color::Rgb(255, 255, 255);

    // F-key bar.
    // Sampled from the reference: the F-key number is the same light gray
    // as the prompt text, not yellow.
    pub const FN_KEY_NUM_FG: Color = Color::Rgb(0xAF, 0xA8, 0xAF);
    pub const FN_KEY_NUM_BG: Color = Color::Rgb(0, 0, 0);
    pub const FN_KEY_LABEL_FG: Color = Color::Rgb(0, 0, 0);
    pub const FN_KEY_LABEL_BG: Color = Color::Rgb(0, 170, 170);

    // The command-line and status rows sit on plain black, not the pane's
    // blue — matching the original, where only the two panels are blue.
    pub const PROMPT_BG: Color = Color::Rgb(0, 0, 0);

    // Big double-bordered dialogs (Copy/Move/Delete, Rename, MkDir/New
    // file, Quit) — the classic DOS gray dialog box, not the panels' blue.
    pub const DIALOG_BG: Color = Color::Rgb(0xAF, 0xA8, 0xAF);
    pub const DIALOG_FG: Color = Color::Rgb(0, 0, 0);
    pub const DIALOG_BORDER_FG: Color = Color::Rgb(0, 0, 0);
}

/// Insert-tagged entries render in this color in both themes, so marking
/// stays visible regardless of the active palette — including on the
/// cursor row itself, where it overrides the highlight's own fg.
const MARKED_FG: Color = Color::Rgb(0xFF, 0xFF, 0x50);

fn draw_pane(
    frame: &mut Frame,
    area: Rect,
    pane: &Pane,
    is_active: bool,
    list_state: &mut ListState,
    classic_style: bool,
    show_totals: bool,
) {
    let border_style = if classic_style {
        let fg = if is_active {
            classic::ACTIVE_BORDER_FG
        } else {
            classic::INACTIVE_BORDER_FG
        };
        Style::default().fg(fg).add_modifier(Modifier::BOLD)
    } else if is_active {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };

    // The title is just the pane's own directory — it used to fold in the
    // selected entry's name too, which meant it changed on every Up/Down
    // press. That per-selection detail now lives in the status footer
    // below instead, where it belongs with the rest of the file info.
    let title = pane.cwd.to_string_lossy().to_string();

    // -2 for the pane's own left/right border.
    let name_width = name_column_width(area.width.saturating_sub(2));

    let items: Vec<ListItem> = pane
        .entries
        .iter()
        .enumerate()
        .map(|(idx, entry)| {
            let is_marked = pane.marked.contains(&entry.name);
            let fg = if is_marked {
                MARKED_FG
            } else if entry.is_dir {
                if classic_style { classic::DIR_FG } else { Color::Cyan }
            } else if entry.is_executable {
                // Classic mode treats executables exactly like directories
                // (same white, bold) rather than a distinct green — the
                // size/date columns already tell them apart.
                if classic_style { classic::DIR_FG } else { Color::Green }
            } else if classic_style {
                classic::FILE_FG
            } else {
                // Not White: this renders straight onto the terminal's own
                // background with no contrasting box behind it, so it must
                // follow the terminal's default foreground instead of
                // assuming a dark theme (a hardcoded white was invisible on
                // light-background terminals).
                Color::Reset
            };
            let bold = is_marked || entry.is_dir || entry.is_executable;

            // The cursor row's highlight is baked in per-item (instead of
            // going through `List::highlight_style`, which would apply one
            // fixed fg to every row) so a marked entry keeps its yellow text
            // instead of being swallowed by the highlight's own fg when
            // it's also under the cursor.
            let style = if is_active && idx == pane.selected {
                let bg = if classic_style { classic::HIGHLIGHT_BG } else { Color::Blue };
                let cursor_fg = if is_marked {
                    fg
                } else if classic_style {
                    classic::HIGHLIGHT_FG
                } else {
                    Color::White
                };
                Style::default()
                    .bg(bg)
                    .fg(cursor_fg)
                    .add_modifier(Modifier::BOLD)
            } else {
                let mut style = Style::default().fg(fg);
                if bold {
                    style = style.add_modifier(Modifier::BOLD);
                }
                style
            };

            let date = format_modified(entry.modified);
            let size_label = if entry.is_dir {
                if classic_style { "<DIR>".to_string() } else { String::new() }
            } else {
                format_size(entry.size)
            };
            let name = fit_name(&entry.name, name_width);
            let label = format!("{name} {size_label:>SIZE_COLUMN_WIDTH$} {date} ");
            ListItem::new(Line::from(Span::styled(label, style)))
        })
        .collect();

    let mut block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(border_style);
    if classic_style {
        block = block.style(Style::default().bg(classic::BG));
    }

    let status_text = show_totals.then(|| match pane.marked_summary() {
        Some((count, bytes)) => format!(
            "{} bytes in {count} selected file{}",
            with_thousands_separators(bytes),
            if count == 1 { "" } else { "s" }
        ),
        // Nothing marked: show the cursor's entry — name, size, date —
        // instead, now that the title above no longer does. Falls back to
        // plain totals for "..", which has none of those to show.
        // Lined up under the listing's own Name/Size/Date columns (same
        // widths as each row above), instead of just running the three
        // together against the left edge.
        None => match pane.selected_entry() {
            Some(entry) if entry.name != ".." => {
                let size = if entry.is_dir {
                    if classic_style { "<DIR>".to_string() } else { String::new() }
                } else {
                    format_size(entry.size)
                };
                let date = format_modified(entry.modified);
                let name = fit_name(&entry.name, name_width);
                format!("{name} {size:>SIZE_COLUMN_WIDTH$} {date}")
            }
            _ => {
                let (files, dirs) = pane.totals();
                format!("{files} files, {dirs} dirs")
            }
        },
    });

    // A real last row (plus a divider above it) inside the border, instead
    // of the old `title_bottom` approach that wrote the status straight
    // onto the border line itself — that crowded the last listed entry
    // right up against it, unlike the top, where the ".." entry already
    // gives the path title some breathing room below it.
    let inner = block.inner(area);
    let footer_rows = if inner.height >= 2 { 2 } else { 0 };
    let (list_area, show_footer) = match &status_text {
        Some(_) if footer_rows > 0 => (
            Rect {
                height: inner.height - footer_rows,
                ..inner
            },
            true,
        ),
        _ => (inner, false),
    };

    frame.render_widget(block, area);

    // The cursor row's highlight is already baked into its `ListItem`
    // style above (so a marked entry can keep its own fg there), so `List`
    // itself doesn't need a `highlight_style` patched on top.
    let list = List::new(items);

    // Always keep the selection tracked (not just while active) so the
    // persisted `list_state`'s scroll offset stays correct for this pane
    // even while the other pane has focus; the `is_active` check above is
    // what actually hides the highlight when inactive.
    list_state.select(Some(pane.selected));

    frame.render_stateful_widget(list, list_area, list_state);

    if show_footer {
        let divider_y = list_area.y + list_area.height;
        let status_y = divider_y + 1;
        frame.render_widget(
            Paragraph::new("─".repeat(inner.width as usize)).style(border_style),
            Rect {
                x: inner.x,
                y: divider_y,
                width: inner.width,
                height: 1,
            },
        );
        let is_marked_summary = pane.marked_summary().is_some();
        let status_style = if is_marked_summary {
            Style::default().fg(MARKED_FG).add_modifier(Modifier::BOLD)
        } else {
            border_style
        };
        // Centered for the marked-files summary (a standalone sentence);
        // the per-entry line stays left-aligned so it lines up with the
        // listing's own Name/Size/Date columns above it.
        let status_paragraph = Paragraph::new(status_text.unwrap_or_default())
            .style(status_style)
            .alignment(if is_marked_summary {
                Alignment::Center
            } else {
                Alignment::Left
            });
        frame.render_widget(
            status_paragraph,
            Rect {
                x: inner.x,
                y: status_y,
                width: inner.width,
                height: 1,
            },
        );

        // Tee the divider into the pane's own left/right border, matching
        // the dialogs' section separators.
        let buf = frame.buffer_mut();
        if let Some(cell) = buf.cell_mut((area.x, divider_y)) {
            cell.set_symbol("├").set_style(border_style);
        }
        if let Some(cell) = buf.cell_mut((area.x + area.width.saturating_sub(1), divider_y)) {
            cell.set_symbol("┤").set_style(border_style);
        }
    }
}

/// Quick-view: renders a live preview of `source`'s selected entry, in
/// place of the opposite pane's own listing (Ctrl+Q). `focused` is whether
/// Tab has moved scroll focus onto this pane; `scroll` is how many lines of
/// a text preview are skipped from the top.
fn draw_preview_pane(
    frame: &mut Frame,
    area: Rect,
    source: &Pane,
    focused: bool,
    scroll: usize,
    classic_style: bool,
) {
    let title = match source.selected_entry() {
        Some(entry) if entry.name != ".." => {
            source.cwd.join(&entry.name).to_string_lossy().to_string()
        }
        _ => source.cwd.to_string_lossy().to_string(),
    };

    let border_style = if classic_style {
        let fg = if focused {
            classic::ACTIVE_BORDER_FG
        } else {
            classic::INACTIVE_BORDER_FG
        };
        Style::default().fg(fg).add_modifier(Modifier::BOLD)
    } else if focused {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };

    let mut block = Block::default()
        .title(format!("Preview: {title}"))
        .borders(Borders::ALL)
        .border_style(border_style);
    if classic_style {
        block = block
            .style(Style::default().bg(classic::BG).fg(classic::FILE_FG));
    }

    // For everything except Text, the scroll offset is applied by
    // skipping whole (never-wrapped) entries up front. Text is different:
    // it's word-wrapped, so a scroll offset in *logical* lines would be
    // wrong once a long line spans multiple visual rows — instead all
    // lines are kept and `paragraph_scroll` is handed to Ratatui's own
    // `.scroll()`, which operates in post-wrap visual rows.
    let mut paragraph_scroll: u16 = 0;
    let lines: Vec<Line> = match preview::build_preview(source) {
        PreviewContent::Empty => Vec::new(),
        PreviewContent::Directory(entries) => entries
            .into_iter()
            .skip(scroll)
            .map(|entry| {
                let style = if entry.is_dir {
                    let fg = if classic_style { classic::DIR_FG } else { Color::Cyan };
                    Style::default().fg(fg).add_modifier(Modifier::BOLD)
                } else if classic_style {
                    Style::default().fg(classic::FILE_FG)
                } else {
                    Style::default().fg(Color::Reset)
                };
                Line::from(Span::styled(entry.name, style))
            })
            .collect(),
        PreviewContent::Binary(size) => vec![Line::from(Span::styled(
            format!("<Binary file> ({size} bytes)"),
            Style::default().fg(Color::DarkGray),
        ))],
        PreviewContent::Error(err) => vec![Line::from(Span::styled(
            format!("Cannot preview: {err}"),
            Style::default().fg(Color::Red),
        ))],
        PreviewContent::Text(text_lines) => {
            paragraph_scroll = scroll as u16;
            text_lines.into_iter().map(Line::from).collect()
        }
    };

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false })
        .scroll((paragraph_scroll, 0));
    frame.render_widget(paragraph, area);
}

/// Command > Show Logs: reads the tail of the log file fresh each draw
/// (simple, and the file is small enough that this is cheap) and shows as
/// many of the most recent lines as fit.
fn draw_logs(frame: &mut Frame) {
    let width = frame.area().width.saturating_sub(4).max(20);
    let height = frame.area().height.saturating_sub(4).max(3);
    let area = Rect {
        x: (frame.area().width.saturating_sub(width)) / 2,
        y: (frame.area().height.saturating_sub(height)) / 2,
        width,
        height,
    };

    let visible_rows = height.saturating_sub(2) as usize; // minus the block's borders
    let all_lines = std::fs::read_to_string(logging::log_path()).unwrap_or_default();
    let mut lines: Vec<&str> = all_lines.lines().collect();
    let total = lines.len();
    if total > visible_rows {
        lines = lines.split_off(total - visible_rows);
    }
    let shown: Vec<Line> = if lines.is_empty() {
        vec![Line::from(Span::styled(
            "(no log entries yet)",
            Style::default().fg(Color::DarkGray),
        ))]
    } else {
        lines
            .iter()
            .map(|line| Line::from(Span::styled(*line, Style::default().fg(Color::White))))
            .collect()
    };

    let block = Block::default()
        .title(format!("Logs — last {} lines — press any key to close", shown.len()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Green))
        .style(Style::default().bg(Color::Black).fg(Color::White));

    frame.render_widget(Clear, area);
    frame.render_widget(Paragraph::new(shown).block(block), area);
}

fn draw_fn_key_bar(frame: &mut Frame, area: Rect, app: &mut App) {
    // Same reasoning as draw_command_line: the 1-column indent and the
    // gaps between tiles are real painted spaces (styled with the row's
    // background), not just skipped/unshrunk area — otherwise those
    // columns show whatever was underneath instead of matching the row.
    let gap_style = if app.classic_style {
        Style::default().bg(classic::PROMPT_BG)
    } else {
        Style::default()
    };
    // Same as draw_command_line: the leading indent looks off-balance once
    // the row has its own solid background (classic mode), so skip it there.
    let indent = if app.classic_style { 0u16 } else { 1u16 };

    // Spread the tiles evenly across the full width instead of packing them
    // to the left; on a narrow terminal the tail simply gets clipped, same
    // as before. A 1-column gap between tiles (not before F1) needs
    // reserving len-1 columns up front.
    let gaps = FN_KEYS.len() as u16 - 1;
    let usable = area.width.saturating_sub(indent + gaps);
    let base_width = usable / FN_KEYS.len() as u16;
    let remainder = (usable % FN_KEYS.len() as u16) as usize;

    // Integer division always leaves 0-9 leftover columns; rather than
    // stranding them as blank padding after the last tile, hand one extra
    // column each to the `remainder` tiles with the longest label text —
    // those already have the least slack, so widening them first keeps the
    // row looking evenly balanced instead of the growth being arbitrary.
    let mut widen_first: Vec<usize> = (0..FN_KEYS.len()).collect();
    widen_first.sort_by_key(|&i| std::cmp::Reverse(FN_KEYS[i].label.len()));
    let mut tile_widths = vec![base_width; FN_KEYS.len()];
    for &i in widen_first.iter().take(remainder) {
        tile_widths[i] += 1;
    }

    app.fn_key_tiles.clear();
    let mut x = area.x + indent;
    let mut spans = if indent > 0 {
        vec![Span::styled(" ", gap_style)]
    } else {
        Vec::new()
    };
    for (idx, fn_key) in FN_KEYS.iter().enumerate() {
        if idx > 0 {
            spans.push(Span::styled(" ", gap_style));
            x += 1;
        }
        app.fn_key_tiles.push((
            Rect {
                x,
                y: area.y,
                width: tile_widths[idx],
                height: 1,
            },
            fn_key.action,
        ));
        x += tile_widths[idx];

        let (num_fg, num_bg, label_fg, label_bg) = if app.classic_style {
            (
                classic::FN_KEY_NUM_FG,
                classic::FN_KEY_NUM_BG,
                classic::FN_KEY_LABEL_FG,
                classic::FN_KEY_LABEL_BG,
            )
        } else {
            (Color::Yellow, Color::Black, Color::Black, Color::Cyan)
        };
        spans.push(Span::styled(
            fn_key.key,
            Style::default().fg(num_fg).bg(num_bg).add_modifier(Modifier::BOLD),
        ));
        let label_width = tile_widths[idx].saturating_sub(fn_key.key.len() as u16) as usize;
        spans.push(Span::styled(
            format!("{:<label_width$}", fn_key.label),
            Style::default().fg(label_fg).bg(label_bg),
        ));
    }
    let bar = Paragraph::new(Line::from(spans));
    frame.render_widget(bar, area);
}

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

    #[test]
    fn thousands_separators_are_inserted_every_3_digits() {
        assert_eq!(with_thousands_separators(0), "0");
        assert_eq!(with_thousands_separators(42), "42");
        assert_eq!(with_thousands_separators(999), "999");
        assert_eq!(with_thousands_separators(1000), "1,000");
        assert_eq!(with_thousands_separators(1_234_567), "1,234,567");
    }

    #[test]
    fn size_below_threshold_shows_a_comma_grouped_byte_count() {
        assert_eq!(format_size(0), "0");
        assert_eq!(format_size(1_234_567), "1,234,567");
        assert_eq!(format_size(SIZE_COLLAPSE_THRESHOLD - 1), "104,857,599");
    }

    #[test]
    fn size_at_or_above_threshold_collapses_to_megabytes() {
        assert_eq!(format_size(SIZE_COLLAPSE_THRESHOLD), "100 MB");
        assert_eq!(format_size(250 * 1024 * 1024), "250 MB");
        assert_eq!(format_size(2_000 * 1024 * 1024), "2,000 MB");
    }

    #[test]
    fn short_name_is_padded_not_truncated() {
        let result = fit_name("short.txt", 10);
        assert_eq!(result, "short.txt ");
        assert_eq!(result.chars().count(), 10);
    }

    #[test]
    fn long_name_is_truncated_with_ellipsis() {
        let result = fit_name("this_is_a_very_long_filename.txt", 10);
        assert_eq!(result.chars().count(), 10);
        assert!(result.ends_with('\u{2026}'));
        assert!(result.starts_with("this_is_a"));
    }

    #[test]
    fn menu_dropdown_shadow_survives_to_final_buffer() {
        use crate::app::App;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = App::new().unwrap();
        // Deterministic regardless of whatever's actually saved on disk —
        // App::new() loads real persisted settings, and classic_style
        // changes what color the shadow darkens to.
        app.classic_style = false;
        app.open_menu();

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| draw(frame, &mut app)).unwrap();

        let buf = terminal.backend().buffer();

        // Recompute the same area/shadow_area the real code computes, to
        // find a cell that should be shadow-only (outside the dropdown's
        // own area, inside shadow_area).
        let category = &MENU_BAR[0];
        let row_text_width = category
            .items
            .iter()
            .map(|action| {
                let shortcut_width = action.shortcut().map_or(0, |s| s.len() + 3);
                action.label().len() + shortcut_width
            })
            .max()
            .unwrap_or(4);
        let width = (row_text_width as u16) + 4;
        let height = category.items.len() as u16 + 2;
        let area = Rect {
            x: 1,
            y: 1,
            width,
            height,
        };
        let shadow_only_x = area.x + area.width; // one past the dropdown's right edge
        let shadow_only_y = area.y + 1;

        let cell = &buf[(shadow_only_x, shadow_only_y)];
        // Non-classic mode: the cell underneath is a named/Reset color, so
        // the shadow falls back to a flat dark gray fill.
        assert_eq!(cell.bg, Color::Rgb(30, 30, 30));
    }

    #[test]
    fn exact_width_name_is_unchanged() {
        let result = fit_name("1234567890", 10);
        assert_eq!(result, "1234567890");
    }
}