tuisage 0.1.4

TUI application for interacting with CLI commands defined by usage specs
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
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
use std::sync::atomic::Ordering;

use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, Wrap},
    Frame,
};
use ratatui_themes::ThemeName;
use tui_term::widget::PseudoTerminal;

#[cfg(test)]
extern crate insta;

use crate::app::{flatten_command_tree, App, AppMode, FlagValue, Focus};
use crate::widgets::{
    build_help_line, panel_block, panel_title, push_edit_cursor, push_highlighted_name,
    push_selection_cursor, render_help_overlays, selection_bg, CommandPreview, HelpBar, Keybind,
    ItemContext, PanelState, SelectList, SelectListScrollState, UiColors,
};

/// Render the full UI: command panel, flag panel, arg panel, preview, help bar.
pub fn render(frame: &mut Frame, app: &mut App) {
    let palette = app.palette();
    let colors = UiColors::from_palette(&palette);

    if app.mode == AppMode::Executing {
        render_execution_view(frame, app, &colors);
        return;
    }

    let area = frame.area();

    // Top-level vertical layout:
    //   [command preview]
    //   [main content area]
    //   [help / status bar]
    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // command preview
            Constraint::Min(6),    // main content
            Constraint::Length(1), // help text
        ])
        .split(area);

    // Clear click regions each frame so they're rebuilt from current layout
    app.click_regions.clear();

    render_preview(frame, app, outer[0], &colors);
    render_main_content(frame, app, outer[1], &colors);
    render_help_bar(frame, app, outer[2], &colors);

    // Register preview area for click hit-testing
    app.click_regions.register(outer[0], Focus::Preview);

    // Render choice select overlay on top of everything
    if app.choice_select.is_some() {
        render_choice_select(frame, app, area, &colors);
    }

    // Render theme picker overlay on top of everything
    if app.theme_picker.is_some() {
        render_theme_picker(frame, app, area, &colors);
    }
}

/// Render the execution view: command at top, terminal output in middle, status at bottom.
fn render_execution_view(frame: &mut Frame, app: &App, colors: &UiColors) {
    let area = frame.area();

    // Layout: [command display] [terminal output] [status bar]
    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // command display
            Constraint::Min(4),    // terminal output
            Constraint::Length(1), // status bar
        ])
        .split(area);

    // --- Command display at top ---
    let command_display = app
        .execution
        .as_ref()
        .map(|e| e.command_display.clone())
        .unwrap_or_default();

    let cmd_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(colors.active_border))
        .title(" Command ")
        .title_style(Style::default().fg(colors.active_border).bold());

    let cmd_spans = vec![
        Span::styled("$ ", Style::default().fg(colors.command)),
        Span::styled(
            command_display,
            Style::default()
                .fg(colors.preview_cmd)
                .add_modifier(Modifier::BOLD),
        ),
    ];
    let cmd_paragraph = Paragraph::new(Line::from(cmd_spans))
        .block(cmd_block)
        .wrap(Wrap { trim: false });
    frame.render_widget(cmd_paragraph, outer[0]);

    // --- Terminal output ---
    let exited = app
        .execution
        .as_ref()
        .map(|e| e.exited.load(Ordering::Relaxed))
        .unwrap_or(false);

    let term_block = Block::default().borders(Borders::NONE);

    if let Some(ref exec) = app.execution {
        if let Ok(parser) = exec.parser.read() {
            let pseudo_term = PseudoTerminal::new(parser.screen())
                .block(term_block)
                .style(Style::default().fg(colors.preview_cmd).bg(colors.bg));
            frame.render_widget(pseudo_term, outer[1]);
        } else {
            // Fallback if lock is poisoned
            let fallback = Paragraph::new("(terminal output unavailable)")
                .block(term_block)
                .style(Style::default().fg(colors.help));
            frame.render_widget(fallback, outer[1]);
        }
    } else {
        let fallback = Paragraph::new("(no execution state)")
            .block(term_block)
            .style(Style::default().fg(colors.help));
        frame.render_widget(fallback, outer[1]);
    }

    // --- Status bar at bottom ---
    let status_text = if exited {
        let exit_code = app.execution_exit_status().unwrap_or_default();
        format!(
            " Exited ({}) — press Esc/⏎/q to close ",
            if exit_code.is_empty() {
                "unknown".to_string()
            } else {
                exit_code
            }
        )
    } else {
        " Running… (input is forwarded to the process) ".to_string()
    };

    let status_style = if exited {
        Style::default()
            .fg(colors.help)
            .add_modifier(Modifier::BOLD | Modifier::REVERSED)
    } else {
        Style::default()
            .fg(colors.command)
            .add_modifier(Modifier::BOLD | Modifier::REVERSED)
    };

    let status = Paragraph::new(status_text).style(status_style);
    frame.render_widget(status, outer[2]);
}

/// Render the main content area with panels for commands, flags, and args.
fn render_main_content(frame: &mut Frame, app: &mut App, area: Rect, colors: &UiColors) {
    // Commands tree should always be visible (shows entire tree, not just subcommands)
    let has_commands = !app.command_tree_nodes.is_empty();

    // Always show Flags and Args panes, even if empty
    if has_commands {
        // Split horizontally: commands on left, flags+args on right
        let h_split = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
            .split(area);

        render_command_list(frame, app, h_split[0], colors);

        // Always split vertically for flags and args
        let v_split = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(60), Constraint::Percentage(40)])
            .split(h_split[1]);
        render_flag_list(frame, app, v_split[0], colors);
        render_arg_list(frame, app, v_split[1], colors);
    } else {
        // No commands - still show flags and args
        let v_split = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(60), Constraint::Percentage(40)])
            .split(area);
        render_flag_list(frame, app, v_split[0], colors);
        render_arg_list(frame, app, v_split[1], colors);
    }
}

/// Render the command tree panel using the TreeView widget.
fn render_command_list(frame: &mut Frame, app: &mut App, area: Rect, colors: &UiColors) {
    // Register area for click hit-testing
    app.click_regions.register(area, Focus::Commands);

    let ps = {
        let base = PanelState::from_app(app, Focus::Commands, colors);
        let scores = if !base.filter_text.is_empty() {
            app.compute_tree_match_scores()
        } else {
            std::collections::HashMap::new()
        };
        base.with_scores(scores)
    };

    // Flatten the tree for display
    let flat_commands = flatten_command_tree(&app.command_tree_nodes);

    let title = panel_title("Commands", &ps);
    let block = panel_block(title, &ps);

    // Calculate inner height for scroll offset (area minus borders)
    let inner_height = area.height.saturating_sub(2) as usize;
    app.ensure_visible(Focus::Commands, inner_height);

    // Get selected index
    let selected_index = app.command_index();

    // Get hovered index for this panel (only when focused)
    let hovered_index = if ps.is_focused { app.hovered_index(Focus::Commands) } else { None };

    // Build list items with indentation markers
    let mut help_entries: Vec<(usize, Line<'static>)> = Vec::new();
    let items: Vec<ListItem> = flat_commands
        .iter()
        .enumerate()
        .map(|(i, cmd)| {
            let is_selected = i == selected_index;
            let is_hovered = hovered_index == Some(i) && !is_selected;
            let ctx = ItemContext::new(&cmd.id, is_selected, &ps);

            let mut spans = Vec::new();

            // Selection cursor
            push_selection_cursor(&mut spans, is_selected, colors);

            // Depth-based indentation with vertical line prefix
            if cmd.depth > 0 {
                let indent = "  ".repeat(cmd.depth - 1);
                spans.push(Span::styled(indent, Style::default().fg(colors.help)));
                spans.push(Span::styled("", Style::default().fg(colors.help)));
            }

            // Command name (with aliases)
            let name_text = if !cmd.aliases.is_empty() {
                format!("{} ({})", cmd.name, cmd.aliases.join(", "))
            } else {
                cmd.name.clone()
            };

            push_highlighted_name(
                &mut spans,
                &name_text,
                colors.command,
                &ctx,
                &ps,
                colors,
            );

            // Collect help text for overlay rendering
            if let Some(help) = &cmd.help {
                help_entries.push((i, build_help_line(help, &ctx, &ps, colors)));
            }

            let mut item = ListItem::new(Line::from(spans));
            if is_selected {
                item = item.style(selection_bg(false, colors));
            } else if is_hovered {
                item = item.style(Style::default().bg(colors.hover_bg));
            }
            item
        })
        .collect();

    let selected_index = app.command_index();
    let mut state = ListState::default()
        .with_selected(if ps.is_focused {
            Some(selected_index)
        } else {
            None
        })
        .with_offset(app.command_scroll());

    let list = List::new(items).block(block);
    frame.render_stateful_widget(list, area, &mut state);

    // Scrollbar
    render_panel_scrollbar(frame, area, flat_commands.len(), app.command_scroll(), colors);

    // Render right-aligned help text overlays (no padding on Commands panel)
    let inner = area.inner(ratatui::layout::Margin::new(1, 1));
    render_help_overlays(frame.buffer_mut(), &help_entries, app.command_scroll(), inner);
}
fn render_flag_list(frame: &mut Frame, app: &mut App, area: Rect, colors: &UiColors) {
    // Register area for click hit-testing
    app.click_regions.register(area, Focus::Flags);

    let ps = {
        let base = PanelState::from_app(app, Focus::Flags, colors);
        let scores = if !base.filter_text.is_empty() {
            app.compute_flag_match_scores()
        } else {
            std::collections::HashMap::new()
        };
        base.with_scores(scores)
    };

    // Compute index for scroll visibility
    let flag_index = app.flag_index();

    let title = panel_title("Flags", &ps);
    let block = panel_block(title, &ps);

    // Calculate inner height for scroll offset
    let inner_height = area.height.saturating_sub(2) as usize;
    app.ensure_visible(Focus::Flags, inner_height);

    // Re-fetch data after mutable borrow ends
    let flags = app.visible_flags();

    // Pre-compute default values for each flag so we can show "(default)" indicator
    let flag_defaults: Vec<Option<String>> =
        flags.iter().map(|f| f.default.first().cloned()).collect();

    // Pre-compute negate column positions for mouse hit-testing.
    // Layout per row: border(1) + cursor(2) + indicator(2) + flag_display + optional [G](4) + optional *(2) + " / "(3) = negate start
    let inner_left = area.x + 1; // past left border
    let negate_cols: std::collections::HashMap<usize, u16> = flags
        .iter()
        .enumerate()
        .filter(|(_, flag)| flag.negate.is_some())
        .map(|(i, flag)| {
            let display_len = flag_display_string(flag).len() as u16;
            let mut col = inner_left + 2 + 2 + display_len;
            if flag.global {
                col += 4; // " [G]"
            }
            if flag.required {
                col += 2; // " *"
            }
            col += 3; // " / "
            (i, col)
        })
        .collect();
    drop(flags); // release borrow so we can mutate app
    app.flag_negate_cols = negate_cols;

    let flags = app.visible_flags();
    let flag_values = app.current_flag_values();

    // Get hovered index for this panel (only when focused)
    let hovered_index = if ps.is_focused { app.hovered_index(Focus::Flags) } else { None };

    let mut help_entries: Vec<(usize, Line<'static>)> = Vec::new();
    let items: Vec<ListItem> = flags
        .iter()
        .enumerate()
        .map(|(i, flag)| {
            let is_selected = ps.is_focused && i == flag_index;
            let is_hovered = hovered_index == Some(i) && !is_selected;
            let is_editing = is_selected && app.editing;
            let value = flag_values.iter().find(|(n, _)| n == &flag.name);
            let default_val = flag_defaults.get(i).and_then(|d| d.as_ref());

            let ctx = ItemContext::new(&flag.name, is_selected, &ps);

            let mut spans = Vec::new();

            // Selection cursor indicator
            push_selection_cursor(&mut spans, is_selected, colors);

            // Checkbox / toggle indicator using checkmark style (✓/○)
            let indicator = match value.map(|(_, v)| v) {
                Some(FlagValue::Bool(true)) => Span::styled(
                    "",
                    Style::default().fg(colors.arg).add_modifier(Modifier::BOLD),
                ),
                Some(FlagValue::Bool(false)) => {
                    Span::styled("", Style::default().fg(colors.help))
                }
                Some(FlagValue::NegBool(None)) => {
                    Span::styled("", Style::default().fg(colors.help))
                }
                Some(FlagValue::NegBool(Some(true))) => Span::styled(
                    "",
                    Style::default().fg(colors.arg).add_modifier(Modifier::BOLD),
                ),
                Some(FlagValue::NegBool(Some(false))) => Span::styled(
                    "",
                    Style::default()
                        .fg(colors.required)
                        .add_modifier(Modifier::BOLD),
                ),
                Some(FlagValue::Count(n)) => {
                    if *n > 0 {
                        Span::styled(format!("[{}] ", n), Style::default().fg(colors.count))
                    } else {
                        Span::styled("[0] ", Style::default().fg(colors.help))
                    }
                }
                Some(FlagValue::String(s)) => {
                    if s.is_empty() {
                        Span::styled("[·] ", Style::default().fg(colors.help))
                    } else {
                        Span::styled("[•] ", Style::default().fg(colors.arg))
                    }
                }
                None => Span::styled("", Style::default().fg(colors.help)),
            };
            spans.push(indicator);

            // Flag display (short + long) with highlighting
            let flag_display = flag_display_string(flag);

            // When the negate flag is explicitly active, subdue the positive name
            let is_negated = matches!(value.map(|(_, v)| v), Some(FlagValue::NegBool(Some(false))));
            let flag_name_color = if is_negated { colors.help } else { colors.flag };

            push_highlighted_name(
                &mut spans,
                &flag_display,
                flag_name_color,
                &ctx,
                &ps,
                colors,
            );

            // Global indicator
            if flag.global {
                let global_style = if !ctx.is_match && !ps.match_scores.is_empty() {
                    Style::default().fg(colors.help).add_modifier(Modifier::DIM)
                } else {
                    Style::default().fg(colors.help)
                };
                spans.push(Span::styled(" [G]", global_style));
            }

            // Required indicator
            if flag.required {
                let required_style = if !ctx.is_match && !ps.match_scores.is_empty() {
                    Style::default().fg(colors.help).add_modifier(Modifier::DIM)
                } else {
                    Style::default().fg(colors.required)
                };
                spans.push(Span::styled(" *", required_style));
            }

            // Negate indicator for negatable flags
            if let Some(ref negate) = flag.negate {
                let dim = !ctx.is_match && !ps.match_scores.is_empty();
                // The " / " separator is always subdued
                let sep_style = if dim {
                    Style::default().fg(colors.help).add_modifier(Modifier::DIM)
                } else {
                    Style::default().fg(colors.help)
                };
                spans.push(Span::styled(" / ", sep_style));
                // The negate string is highlighted when the flag is in the negated state
                let negate_style = if is_negated {
                    if dim {
                        Style::default().fg(colors.flag).add_modifier(Modifier::DIM)
                    } else {
                        Style::default().fg(colors.flag)
                    }
                } else if dim {
                    Style::default().fg(colors.help).add_modifier(Modifier::DIM)
                } else {
                    Style::default().fg(colors.help)
                };
                spans.push(Span::styled(negate.clone(), negate_style));
            }

            // Value display for string flags
            if let Some((_, FlagValue::String(s))) = value {
                spans.push(Span::styled(" = ", Style::default().fg(colors.help)));

                // Check if the choice select box is open for this flag
                let is_choice_selecting = app.choice_select.as_ref().is_some_and(|cs| {
                    cs.source_panel == Focus::Flags && cs.source_index == i
                });

                if is_choice_selecting || is_editing {
                    // Show the edit cursor — when choice selecting, the text input is also active
                    let before_cursor = app.edit_input.text_before_cursor();
                    let after_cursor = app.edit_input.text_after_cursor();
                    push_edit_cursor(&mut spans, before_cursor, after_cursor, colors);
                } else if s.is_empty() {
                    // Show choices hint or default
                    if let Some(ref arg) = flag.arg {
                        if let Some(ref choices) = arg.choices {
                            let hint = choices.choices.join("|");
                            spans.push(Span::styled(
                                format!("<{}>", hint),
                                Style::default().fg(colors.choice),
                            ));
                        } else {
                            spans.push(Span::styled(
                                format!("<{}>", arg.name),
                                Style::default().fg(colors.default_val),
                            ));
                        }
                    }
                } else {
                    spans.push(Span::styled(s.to_string(), Style::default().fg(colors.value)));
                    // Show "(default)" if value matches the spec default
                    if let Some(def) = default_val {
                        if s == def {
                            spans.push(Span::styled(
                                " (default)",
                                Style::default().fg(colors.default_val).italic(),
                            ));
                        }
                    }
                }
            }

            // Collect help text for overlay rendering
            if let Some(help) = &flag.help {
                help_entries.push((i, build_help_line(help, &ctx, &ps, colors)));
            }

            let line = Line::from(spans);
            let mut item = ListItem::new(line);
            if is_selected {
                item = item.style(selection_bg(is_editing, colors));
            } else if is_hovered {
                item = item.style(Style::default().bg(colors.hover_bg));
            }
            item
        })
        .collect();

    let total_flags = flags.len();
    let mut state = ListState::default()
        .with_selected(if ps.is_focused { Some(flag_index) } else { None })
        .with_offset(app.flag_scroll());
    let list = List::new(items).block(block);
    frame.render_stateful_widget(list, area, &mut state);

    // Scrollbar
    render_panel_scrollbar(frame, area, total_flags, app.flag_scroll(), colors);

    // Render right-aligned help text overlays (2 = border + horizontal padding)
    let inner = area.inner(ratatui::layout::Margin::new(1, 1));
    render_help_overlays(frame.buffer_mut(), &help_entries, app.flag_scroll(), inner);
}

fn render_arg_list(frame: &mut Frame, app: &mut App, area: Rect, colors: &UiColors) {
    // Register area for click hit-testing
    app.click_regions.register(area, Focus::Args);

    let ps = {
        let base = PanelState::from_app(app, Focus::Args, colors);
        let scores = if !base.filter_text.is_empty() {
            app.compute_arg_match_scores()
        } else {
            std::collections::HashMap::new()
        };
        base.with_scores(scores)
    };

    let arg_index = app.arg_index();

    let title = panel_title("Arguments", &ps);
    let block = panel_block(title, &ps);

    // Calculate inner height for scroll offset (must happen before borrowing app.arg_values)
    let inner_height = area.height.saturating_sub(2) as usize;
    app.ensure_visible(Focus::Args, inner_height);

    // Get hovered index for this panel (only when focused)
    let hovered_index = if ps.is_focused { app.hovered_index(Focus::Args) } else { None };

    let mut help_entries: Vec<(usize, Line<'static>)> = Vec::new();
    let items: Vec<ListItem> = app
        .arg_values
        .iter()
        .enumerate()
        .map(|(i, arg_val)| {
            let is_selected = ps.is_focused && i == arg_index;
            let is_hovered = hovered_index == Some(i) && !is_selected;
            let is_editing = is_selected && app.editing;

            let ctx = ItemContext::new(&arg_val.name, is_selected, &ps);

            let mut spans = Vec::new();

            // Selection cursor indicator
            push_selection_cursor(&mut spans, is_selected, colors);

            // Required/optional indicator
            if arg_val.required {
                spans.push(Span::styled("", Style::default().fg(colors.required)));
            } else {
                spans.push(Span::styled("", Style::default().fg(colors.help)));
            }

            // Arg name with highlighting
            let bracket = if arg_val.required { "<>" } else { "[]" };
            let arg_display = format!("{}{}{}", &bracket[..1], arg_val.name, &bracket[1..]);

            push_highlighted_name(
                &mut spans,
                &arg_display,
                colors.arg,
                &ctx,
                &ps,
                colors,
            );

            // Value display
            spans.push(Span::styled(" = ", Style::default().fg(colors.help)));

            // Check if the choice select box is open for this arg
            let is_choice_selecting = app.choice_select.as_ref().is_some_and(|cs| {
                cs.source_panel == Focus::Args && cs.source_index == i
            });

            if is_choice_selecting || is_editing {
                // Show the edit cursor — when choice selecting, the text input is also active
                let before_cursor = app.edit_input.text_before_cursor();
                let after_cursor = app.edit_input.text_after_cursor();
                push_edit_cursor(&mut spans, before_cursor, after_cursor, colors);
            } else if arg_val.value.is_empty() {
                if !arg_val.choices.is_empty() {
                    let hint = arg_val.choices.join("|");
                    spans.push(Span::styled(
                        format!("<{}>", hint),
                        Style::default().fg(colors.choice),
                    ));
                } else {
                    spans.push(Span::styled(
                        "(empty)",
                        Style::default().fg(colors.default_val),
                    ));
                }
            } else {
                spans.push(Span::styled(
                    arg_val.value.clone(),
                    Style::default().fg(colors.value),
                ));
            }

            // Show choices if arg has them and we're not editing (and not choice-selecting)
            if !arg_val.choices.is_empty() && !arg_val.value.is_empty() && !is_editing && !is_choice_selecting {
                spans.push(Span::styled(
                    format!(" [{}]", arg_val.choices.join("|")),
                    Style::default().fg(colors.choice),
                ));
            }

            // Collect help text for overlay rendering
            if let Some(ref help) = arg_val.help {
                if !help.is_empty() {
                    help_entries.push((i, build_help_line(help, &ctx, &ps, colors)));
                }
            }

            let line = Line::from(spans);
            let mut item = ListItem::new(line);
            if is_selected {
                item = item.style(selection_bg(is_editing, colors));
            } else if is_hovered {
                item = item.style(Style::default().bg(colors.hover_bg));
            }
            item
        })
        .collect();

    let total_args = app.arg_values.len();
    let mut state = ListState::default()
        .with_selected(if ps.is_focused { Some(arg_index) } else { None })
        .with_offset(app.arg_scroll());
    let list = List::new(items).block(block);
    frame.render_stateful_widget(list, area, &mut state);

    // Scrollbar
    render_panel_scrollbar(frame, area, total_args, app.arg_scroll(), colors);

    // Render right-aligned help text overlays (2 = border + horizontal padding)
    let inner = area.inner(ratatui::layout::Margin::new(1, 1));
    render_help_overlays(frame.buffer_mut(), &help_entries, app.arg_scroll(), inner);
}

/// Render a vertical scrollbar on the right side of a panel if content overflows.
fn render_panel_scrollbar(
    frame: &mut Frame,
    area: Rect,
    total_items: usize,
    scroll_offset: usize,
    colors: &UiColors,
) {
    let inner_height = area.height.saturating_sub(2) as usize; // minus top/bottom borders
    if total_items <= inner_height || inner_height == 0 {
        return;
    }
    let inner = area.inner(ratatui::layout::Margin::new(0, 1));
    let mut scrollbar_state = ScrollbarState::new(total_items.saturating_sub(inner_height))
        .position(scroll_offset);
    let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
        .begin_symbol(None)
        .end_symbol(None)
        .track_symbol(Some(""))
        .thumb_symbol("")
        .track_style(Style::default().fg(colors.inactive_border))
        .thumb_style(Style::default().fg(colors.active_border));
    frame.render_stateful_widget(scrollbar, inner, &mut scrollbar_state);
}

/// Render the choice select box as an overlay.
fn render_choice_select(frame: &mut Frame, app: &mut App, terminal_area: Rect, colors: &UiColors) {
    let Some(ref cs) = app.choice_select else {
        return;
    };

    // Extract values before calling filtered_choices (which borrows app)
    let source_panel = cs.source_panel;
    let source_index = cs.source_index;
    let value_column = cs.value_column;
    let selected_index = cs.selected_index;

    let filtered = app.filtered_choices();

    // Determine the panel area and item position
    let panel_area = match source_panel {
        Focus::Flags => app
            .click_regions
            .regions()
            .iter()
            .find(|r| r.data == Focus::Flags)
            .map(|r| r.area),
        Focus::Args => app
            .click_regions
            .regions()
            .iter()
            .find(|r| r.data == Focus::Args)
            .map(|r| r.area),
        _ => None,
    };

    let Some(panel_area) = panel_area else {
        return;
    };

    // Calculate the y position of the item within the panel
    let scroll_offset = match source_panel {
        Focus::Flags => app.flag_scroll(),
        Focus::Args => app.arg_scroll(),
        _ => 0,
    };

    let inner_y = panel_area.y + 1; // skip border
    let item_y = inner_y + (source_index as u16).saturating_sub(scroll_offset as u16);

    // Position the overlay one row BELOW the item
    let overlay_y = item_y + 1;

    // Calculate dimensions
    let max_choice_len = filtered
        .iter()
        .map(|(_, c)| c.chars().count())
        .max()
        .unwrap_or(10) as u16;
    let max_visible = 10u16;
    
    // Calculate available space below the item (to bottom of terminal, minus 1 for help bar)
    let space_below = terminal_area.height.saturating_sub(overlay_y).saturating_sub(1);
    
    // Adjust visible count to fit available space (account for bottom border)
    let max_items_that_fit = space_below.saturating_sub(1).max(1); // at least 1 item
    let visible_count = if filtered.is_empty() {
        1
    } else {
        (filtered.len() as u16).min(max_visible).min(max_items_that_fit)
    };
    let overlay_height = visible_count + 1; // bottom border only

    // Collect labels and descriptions for the SelectList widget
    let labels: Vec<String> = filtered.iter().map(|(_, c)| c.clone()).collect();
    let descs: Vec<Option<String>> = filtered
        .iter()
        .map(|(orig_idx, _)| app.choice_description(*orig_idx).map(|s| s.to_string()))
        .collect();

    // Account for description width in overlay sizing
    let max_desc_len = descs
        .iter()
        .map(|d| d.as_ref().map(|s| s.chars().count() + 2).unwrap_or(0))
        .max()
        .unwrap_or(0) as u16;
    let overlay_width =
        (max_choice_len + max_desc_len + 4).min(terminal_area.width.saturating_sub(2));

    // Position x one character left of value column to align with text output
    let overlay_x = (panel_area.x + value_column.saturating_sub(1))
        .min(terminal_area.width.saturating_sub(overlay_width));

    // Clamp to terminal bounds
    let overlay_y = overlay_y.min(terminal_area.height.saturating_sub(overlay_height));

    let overlay_rect = Rect::new(overlay_x, overlay_y, overlay_width, overlay_height);

    // Store overlay_rect for mouse hit-testing
    if let Some(ref mut cs) = app.choice_select {
        cs.overlay_rect = Some(overlay_rect);
    }

    // Compute hover index for the select overlay
    let hovered_index = app.mouse_position.and_then(|(col, row)| {
        let inner_top = overlay_rect.y; // no top border
        let inner_bottom = overlay_rect.y + overlay_rect.height.saturating_sub(1);
        if col >= overlay_rect.x && col < overlay_rect.x + overlay_rect.width
            && row >= inner_top && row < inner_bottom
        {
            let scroll_offset = app.choice_select.as_ref().map_or(0, |cs| cs.scroll_offset);
            let idx = (row - inner_top) as usize + scroll_offset;
            if idx < filtered.len() { Some(idx) } else { None }
        } else {
            None
        }
    });

    let widget = SelectList::new(
        String::new(),
        &labels,
        selected_index,
        colors.choice,
        colors.choice,
        colors,
    )
    .with_descriptions(&descs)
    .with_borders(Borders::LEFT | Borders::RIGHT | Borders::BOTTOM)
    .with_hovered(hovered_index);
    let mut scroll_state = SelectListScrollState::default();
    frame.render_stateful_widget(widget, overlay_rect, &mut scroll_state);

    // Store scroll state for mouse handling
    if let Some(ref mut cs) = app.choice_select {
        cs.scroll_offset = scroll_state.scroll_offset;
        cs.visible_items = scroll_state.visible_items;
    }
}

/// Render the theme picker overlay, positioned above the help bar, right-aligned.
fn render_theme_picker(frame: &mut Frame, app: &mut App, terminal_area: Rect, colors: &UiColors) {
    let Some(ref tp) = app.theme_picker else {
        return;
    };
    let selected_index = tp.selected_index;
    let all = ThemeName::all();

    // Dimensions
    let max_name_len = all
        .iter()
        .map(|t| t.display_name().len())
        .max()
        .unwrap_or(10) as u16;
    let overlay_width = max_name_len + 6; // "▶ " prefix (2) + padding (2) + borders (2)
    let num_themes = all.len() as u16;
    let overlay_height = (num_themes + 2).min(terminal_area.height.saturating_sub(2)); // +2 for borders

    // Position: right-aligned, above the help bar (last row)
    let overlay_x = terminal_area
        .right()
        .saturating_sub(overlay_width)
        .max(terminal_area.x);
    let help_bar_y = terminal_area.bottom().saturating_sub(1);
    let overlay_y = help_bar_y.saturating_sub(overlay_height).max(terminal_area.y);

    let overlay_rect = Rect::new(overlay_x, overlay_y, overlay_width, overlay_height);

    // Store overlay_rect for mouse hit-testing
    if let Some(ref mut tp) = app.theme_picker {
        tp.overlay_rect = Some(overlay_rect);
    }

    // Collect labels for the SelectList widget
    let labels: Vec<String> = all.iter().map(|t| t.display_name().to_string()).collect();

    let widget = SelectList::new(
        " Theme ".to_string(),
        &labels,
        Some(selected_index),
        colors.choice,
        colors.value,
        colors,
    )
    .with_cursor();
    frame.render_widget(widget, overlay_rect);
}

fn render_help_bar(frame: &mut Frame, app: &mut App, area: Rect, colors: &UiColors) {
    let keybinds: &[Keybind] = if app.is_theme_picking() {
        &[
            Keybind { key: "↑↓", desc: "navigate" },
            Keybind { key: "", desc: "confirm" },
            Keybind { key: "Esc", desc: "cancel" },
        ]
    } else if app.is_choosing() {
        &[
            Keybind { key: "↑↓", desc: "select" },
            Keybind { key: "", desc: "confirm" },
            Keybind { key: "Esc", desc: "keep text" },
        ]
    } else if app.editing {
        &[
            Keybind { key: "", desc: "confirm" },
            Keybind { key: "Esc", desc: "cancel" },
        ]
    } else if app.filtering {
        &[
            Keybind { key: "", desc: "apply" },
            Keybind { key: "Esc", desc: "clear" },
            Keybind { key: "↑↓", desc: "navigate" },
        ]
    } else if app.filter_active() {
        &[
            Keybind { key: "↑↓/jk", desc: "next match" },
            Keybind { key: "/", desc: "new filter" },
            Keybind { key: "Esc", desc: "clear filter" },
        ]
    } else {
        match app.focus() {
            Focus::Commands => &[
                Keybind { key: "↑↓", desc: "navigate" },
                Keybind { key: "", desc: "next" },
                Keybind { key: "/", desc: "filter" },
                Keybind { key: "^r", desc: "run" },
                Keybind { key: "q", desc: "quit" },
            ],
            Focus::Flags => &[
                Keybind { key: "⏎/Space", desc: "toggle" },
                Keybind { key: "↑↓", desc: "navigate" },
                Keybind { key: "", desc: "next" },
                Keybind { key: "/", desc: "filter" },
                Keybind { key: "^r", desc: "run" },
                Keybind { key: "q", desc: "quit" },
            ],
            Focus::Args => &[
                Keybind { key: "", desc: "edit" },
                Keybind { key: "↑↓", desc: "navigate" },
                Keybind { key: "", desc: "next" },
                Keybind { key: "/", desc: "filter" },
                Keybind { key: "^r", desc: "run" },
                Keybind { key: "q", desc: "quit" },
            ],
            Focus::Preview => &[
                Keybind { key: "", desc: "run" },
                Keybind { key: "", desc: "next" },
                Keybind { key: "q", desc: "quit" },
            ],
        }
    };

    let theme_display = app.theme_name.display_name();
    let widget = HelpBar::new(keybinds, theme_display, colors);

    // Store the theme indicator rect for mouse click detection
    app.theme_indicator_rect = Some(widget.theme_indicator_rect(area));

    frame.render_widget(widget, area);
}

/// Render the command preview bar at the bottom with colorized parts.
fn render_preview(frame: &mut Frame, app: &App, area: Rect, colors: &UiColors) {
    let is_focused = app.focus() == Focus::Preview;
    let command = app.build_command();
    let bin = if app.spec.bin.is_empty() {
        &app.spec.name
    } else {
        &app.spec.bin
    };

    let widget = CommandPreview::new(&command, bin, &app.command_path, is_focused, colors);
    frame.render_widget(widget, area);
}

/// Format a flag's display string (e.g., "-f, --force" or "--verbose").
fn flag_display_string(flag: &usage::SpecFlag) -> String {
    let mut parts = Vec::new();
    for s in &flag.short {
        parts.push(format!("-{s}"));
    }
    for l in &flag.long {
        parts.push(format!("--{l}"));
    }
    if parts.is_empty() {
        flag.name.clone()
    } else {
        parts.join(", ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::FlagValue;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::{backend::TestBackend, Terminal};
    use ratatui_themes::ThemeName;

    fn sample_spec() -> usage::Spec {
        let input = include_str!("../fixtures/sample.usage.kdl");
        input
            .parse::<usage::Spec>()
            .expect("Failed to parse sample spec")
    }

    /// Parse a custom usage spec string into a Spec for targeted tests.
    fn parse_spec(input: &str) -> usage::Spec {
        input.parse::<usage::Spec>().expect("Failed to parse spec")
    }

    fn render_to_string(app: &mut App, width: u16, height: u16) -> String {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|frame| render(frame, app)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let mut output = String::new();
        for y in 0..buffer.area.height {
            for x in 0..buffer.area.width {
                let cell = &buffer[(x, y)];
                output.push_str(cell.symbol());
            }
            // Trim trailing whitespace per line for cleaner snapshots
            let trimmed = output.trim_end();
            output = trimmed.to_string();
            output.push('\n');
        }
        output
    }

    // ── Snapshot tests ──────────────────────────────────────────────────

    #[test]
    fn snapshot_root_view() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_config_subcommands() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["config"]);
        // Expand config to show its subcommands
        app.command_tree_state.expand("config");
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_deploy_leaf() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_run_command() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["run"]);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_flags_toggled() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Toggle --rollback (find its index)
        app.set_focus(Focus::Flags);
        let flag_values = app.current_flag_values();
        let rollback_idx = flag_values
            .iter()
            .position(|(n, _)| n == "rollback")
            .unwrap();
        app.set_flag_index(rollback_idx);
        // Toggle it
        let fidx = app.flag_index();
        let vals = app.current_flag_values_mut();
        if let Some((_, FlagValue::Bool(ref mut b))) = vals.get_mut(fidx) {
            *b = true;
        }

        // Set --tag value
        let tag_idx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "tag")
            .unwrap();
        app.set_flag_index(tag_idx);
        let fidx = app.flag_index();
        let vals = app.current_flag_values_mut();
        if let Some((_, FlagValue::String(ref mut s))) = vals.get_mut(fidx) {
            *s = "v1.2.3".to_string();
        }

        // Set arg <environment> = prod
        app.arg_values[0].value = "prod".to_string();

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_editing_arg() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["init"]);

        // Focus on args and start editing
        app.set_focus(Focus::Args);
        app.set_arg_index(0);
        app.start_editing();
        app.edit_input.set_text("my-project");
        app.arg_values[0].value = "my-project".to_string();

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_filter_active() {
        let mut app = App::new(sample_spec());

        // Activate filter mode
        let slash = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char('/'),
            crossterm::event::KeyModifiers::NONE,
        );
        app.handle_key(slash);

        // Type "pl" to filter - this will trigger auto-select
        for c in "pl".chars() {
            let key = crossterm::event::KeyEvent::new(
                crossterm::event::KeyCode::Char(c),
                crossterm::event::KeyModifiers::NONE,
            );
            app.handle_key(key);
        }

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_preview_focused() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["run"]);

        app.arg_values[0].value = "lint".to_string();
        app.set_focus(Focus::Preview);

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_deep_navigation() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["plugin", "install"]);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_choice_select_open() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);
        app.set_focus(Focus::Args);
        app.set_arg_index(0); // <environment> with choices dev, staging, prod

        // Open the choice select box
        let enter = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Enter,
            crossterm::event::KeyModifiers::NONE,
        );
        app.handle_key(enter);
        assert!(app.is_choosing());

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_choice_select_filtered() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);
        app.set_focus(Focus::Args);
        app.set_arg_index(0);

        // Open the choice select box
        let enter = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Enter,
            crossterm::event::KeyModifiers::NONE,
        );
        app.handle_key(enter);

        // Type "st" to filter
        for c in "st".chars() {
            let key = crossterm::event::KeyEvent::new(
                crossterm::event::KeyCode::Char(c),
                crossterm::event::KeyModifiers::NONE,
            );
            app.handle_key(key);
        }

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    // ── Minimal spec tests ──────────────────────────────────────────────

    #[test]
    fn snapshot_simple_flags_only() {
        let spec = parse_spec(
            r#"
bin "mytool"
flag "-v --verbose" help="Verbose output"
flag "-f --force" help="Force operation"
flag "--dry-run" help="Show what would happen"
arg "<input>" help="Input file"
arg "[output]" help="Output file"
        "#,
        );
        let mut app = App::new(spec);
        let output = render_to_string(&mut app, 80, 20);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_choices_flag() {
        let spec = parse_spec(
            r#"
bin "mycli"
cmd "format" help="Format code" {
    flag "--style <style>" help="Code style" {
        arg "<style>" {
            choices "compact" "expanded" "default"
        }
    }
    arg "<file>" help="File to format"
}
        "#,
        );
        let mut app = App::new(spec);
        app.navigate_to_command(&["format"]);
        let output = render_to_string(&mut app, 80, 20);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_no_subcommands() {
        let spec = parse_spec(
            r#"
bin "simple"
about "A simple tool"
arg "<file>" help="File to process"
flag "-o --output <path>" help="Output path"
        "#,
        );
        let mut app = App::new(spec);
        let output = render_to_string(&mut app, 80, 20);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_count_flag_incremented() {
        let spec = parse_spec(
            r#"
bin "mycli"
flag "-v --verbose" help="Increase verbosity" count=#true
flag "-q --quiet" help="Quiet mode"
        "#,
        );
        let mut app = App::new(spec);
        // Increment verbose 3 times
        let key = app.command_path.join(" ");
        if let Some(flags) = app.flag_values.get_mut(&key) {
            for (name, value) in flags.iter_mut() {
                if name == "verbose" {
                    *value = FlagValue::Count(3);
                }
            }
        }
        let output = render_to_string(&mut app, 80, 20);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_flag_filter_active() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Focus on flags and start filtering
        app.set_focus(Focus::Flags);
        app.filtering = true;
        app.filter_input.set_text("roll");

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_flag_filter_verbose() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Focus on flags and filter for "verb" (should match --verbose)
        app.set_focus(Focus::Flags);
        app.filtering = true;
        app.filter_input.set_text("verb");

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_flag_filter_selected_item() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Focus on flags and filter for "tag" (matches --tag)
        app.set_focus(Focus::Flags);
        app.filtering = true;
        app.filter_input.set_text("tag");

        // Move selection to the matching flag (tag is at index 0)
        app.flag_list_state.selected_index = 0;

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    // ── Theme-specific snapshot tests ───────────────────────────────────

    #[test]
    fn snapshot_nord_theme() {
        let mut app = App::with_theme(sample_spec(), ThemeName::Nord);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_catppuccin_mocha_theme() {
        let mut app = App::with_theme(sample_spec(), ThemeName::CatppuccinMocha);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_tokyo_night_theme() {
        let mut app = App::with_theme(sample_spec(), ThemeName::TokyoNight);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_gruvbox_dark_theme() {
        let mut app = App::with_theme(sample_spec(), ThemeName::GruvboxDark);
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    // ── Assertion-based rendering tests ─────────────────────────────────

    #[test]
    fn test_render_root() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 100, 30);
        assert!(output.contains("mycli"));
        assert!(output.contains("init"));
        assert!(output.contains("config"));
        assert!(output.contains("run"));
        assert!(output.contains("deploy"));
        assert!(output.contains("Command"));
    }

    #[test]
    fn test_render_with_subcommand() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["config"]);
        // Expand config to show children in the tree
        app.command_tree_state.expand("config");

        let output = render_to_string(&mut app, 100, 30);
        assert!(output.contains("config"));
        assert!(output.contains("set"));
        assert!(output.contains("get"));
        assert!(output.contains("list"));
        assert!(output.contains("remove"));
    }

    #[test]
    fn test_render_leaf_command() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        let output = render_to_string(&mut app, 100, 30);
        assert!(output.contains("Flags"));
        assert!(output.contains("Arguments"));
        assert!(output.contains("environment"));
    }

    #[test]
    fn test_render_flag_display() {
        let flag = usage::SpecFlag {
            name: "verbose".to_string(),
            short: vec!['v'],
            long: vec!["verbose".to_string()],
            ..Default::default()
        };
        assert_eq!(flag_display_string(&flag), "-v, --verbose");

        let flag2 = usage::SpecFlag {
            name: "force".to_string(),
            short: vec!['f'],
            long: vec!["force".to_string()],
            ..Default::default()
        };
        assert_eq!(flag_display_string(&flag2), "-f, --force");

        let flag3 = usage::SpecFlag {
            name: "json".to_string(),
            short: vec![],
            long: vec!["json".to_string()],
            ..Default::default()
        };
        assert_eq!(flag_display_string(&flag3), "--json");
    }

    #[test]
    fn test_render_command_preview_shows_built_command() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["init"]);

        app.arg_values[0].value = "hello".to_string();

        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("mycli init hello"));
    }

    #[test]
    fn test_render_aliases_shown() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["config"]);
        // Expand config to show children with aliases
        app.command_tree_state.expand("config");

        let output = render_to_string(&mut app, 100, 30);
        // "set" has alias "add", "list" has alias "ls", "remove" has alias "rm"
        assert!(output.contains("add"));
        assert!(output.contains("ls"));
        assert!(output.contains("rm"));
    }

    #[test]
    fn test_render_global_flag_indicator() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 100, 30);
        // Global flags should show [G] indicator
        assert!(output.contains("[G]"));
    }

    #[test]
    fn test_render_required_arg_indicator() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        let output = render_to_string(&mut app, 100, 24);
        // Required args should be shown with <> brackets
        assert!(output.contains("<environment>"));
    }

    #[test]
    fn test_render_choices_display() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        let output = render_to_string(&mut app, 100, 24);
        // Choices should be displayed
        assert!(output.contains("dev"));
        assert!(output.contains("staging"));
        assert!(output.contains("prod"));
    }

    // ── Keyboard interaction rendering tests ────────────────────────────

    #[test]
    fn test_render_after_flag_toggle() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Focus flags and toggle yes flag
        app.set_focus(Focus::Flags);
        let flag_values = app.current_flag_values();
        let yes_idx = flag_values.iter().position(|(n, _)| n == "yes").unwrap();
        app.set_flag_index(yes_idx);

        // Toggle via space key
        app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        // After toggling, should show checkmark indicator
        assert!(output.contains(""));
        // Preview should include --yes
        assert!(output.contains("--yes"));
    }

    #[test]
    fn test_render_narrow_terminal() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 60, 16);
        // Should still render without panicking
        assert!(output.contains("mycli"));
        assert!(output.contains("Commands"));
    }

    // ── Theme cycling tests ─────────────────────────────────────────────

    #[test]
    fn test_theme_cycling() {
        let mut app = App::new(sample_spec());
        assert_eq!(app.theme_name, ThemeName::Dracula);

        app.next_theme();
        assert_eq!(app.theme_name, ThemeName::OneDarkPro);

        app.next_theme();
        assert_eq!(app.theme_name, ThemeName::Nord);

        app.prev_theme();
        assert_eq!(app.theme_name, ThemeName::OneDarkPro);
    }

    #[test]
    fn test_theme_key_binding() {
        let mut app = App::new(sample_spec());
        assert_eq!(app.theme_name, ThemeName::Dracula);

        // T opens the theme picker instead of cycling
        let key = KeyEvent::new(KeyCode::Char('T'), KeyModifiers::NONE);
        app.handle_key(key);
        assert!(app.is_theme_picking(), "T should open theme picker");
        assert_eq!(app.theme_name, ThemeName::Dracula, "Theme should not change yet");
    }

    #[test]
    fn test_theme_name_displayed_in_status_bar() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("Dracula"));
    }

    #[test]
    fn test_with_theme_constructor() {
        let app = App::with_theme(sample_spec(), ThemeName::Nord);
        assert_eq!(app.theme_name, ThemeName::Nord);
        assert_eq!(app.palette().accent, ThemeName::Nord.palette().accent);
    }

    // ── Command path visibility tests ───────────────────────────────────

    #[test]
    fn test_binary_name_visible_in_preview() {
        let mut app = App::new(sample_spec());
        let output = render_to_string(&mut app, 100, 24);
        // The binary name should be visible in the command preview
        assert!(output.contains("mycli"));
    }

    #[test]
    fn test_command_path_visible_in_ui() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["config"]);

        let output = render_to_string(&mut app, 100, 24);
        // Both mycli (in preview) and config (in tree + preview) should be visible
        assert!(output.contains("mycli"));
        assert!(output.contains("config"));
    }

    // ── Colorized preview tests ─────────────────────────────────────────

    #[test]
    fn test_preview_shows_flags_and_args() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Set flag and arg values
        let fidx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "tag")
            .unwrap();
        app.set_flag_index(fidx);
        let vals = app.current_flag_values_mut();
        if let Some((_, FlagValue::String(ref mut s))) = vals.get_mut(fidx) {
            *s = "latest".to_string();
        }
        app.arg_values[0].value = "prod".to_string();

        let output = render_to_string(&mut app, 100, 24);
        // Preview should contain the full colorized command
        assert!(output.contains("mycli"));
        assert!(output.contains("deploy"));
        assert!(output.contains("--tag"));
        assert!(output.contains("latest"));
        assert!(output.contains("prod"));
    }

    #[test]
    fn test_preview_focused_shows_run_indicator() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Preview);
        let output = render_to_string(&mut app, 100, 24);
        // Focused preview uses ▶ prefix instead of $
        assert!(output.contains(""));
    }

    #[test]
    fn test_preview_unfocused_shows_dollar() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        let output = render_to_string(&mut app, 100, 24);
        // Unfocused preview uses $ prefix
        assert!(output.contains("$ mycli"));
    }

    // ── Panel count display tests ───────────────────────────────────────

    #[test]
    fn test_focused_panel_shows_title() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        app.command_tree_state.selected_index = 2;
        app.sync_command_path_from_tree();
        let output = render_to_string(&mut app, 100, 24);
        // Panel headers no longer show counts
        assert!(output.contains("Commands"));
    }

    #[test]
    fn test_unfocused_panel_shows_title() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        let output = render_to_string(&mut app, 100, 24);
        // Unfocused panels just show their name, no counts
        assert!(output.contains("Flags"));
        // Arguments panel only shown when the selected command has args
        // Navigate to init which has args
        app.navigate_to_command(&["init"]);
        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("Arguments"));
    }

    #[test]
    fn test_selection_cursor_visible() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        let output = render_to_string(&mut app, 100, 24);
        // Selected item should have ▶ cursor
        assert!(output.contains(""));
    }

    #[test]
    fn test_filter_shows_query_in_title() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        app.set_focus(Focus::Flags);
        app.filtering = true;
        app.filter_input.set_text("roll");

        let output = render_to_string(&mut app, 100, 24);
        // Should show filter query in title with emoji and query text
        // Note: there appears to be extra spacing after emoji in terminal rendering
        assert!(
            output.contains("Flags 🔍") && output.contains("roll"),
            "Expected 'Flags 🔍' and 'roll' in output"
        );
    }

    #[test]
    fn test_filter_mode_shows_slash_immediately() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        app.filtering = true;
        // No text typed yet — filter_input is empty

        let output = render_to_string(&mut app, 100, 24);
        // Title should show the magnifying glass emoji even with an empty query
        assert!(
            output.contains("Commands 🔍"),
            "Panel title should show '🔍' immediately when filter mode is activated, got:\n{output}"
        );
    }

    #[test]
    fn test_filter_mode_shows_slash_in_flags_panel() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);
        app.set_focus(Focus::Flags);
        app.filtering = true;
        // No text typed yet

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("Flags 🔍"),
            "Flags title should show '🔍' immediately when filter mode is activated, got:\n{output}"
        );
    }

    // ── Unicode checkbox tests ──────────────────────────────────────────

    #[test]
    fn test_checked_flag_shows_checked_box() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Toggle rollback flag on
        app.set_focus(Focus::Flags);
        let fidx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "rollback")
            .unwrap();
        app.set_flag_index(fidx);
        let vals = app.current_flag_values_mut();
        if let Some((_, FlagValue::Bool(ref mut b))) = vals.get_mut(fidx) {
            *b = true;
        }

        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains(""));
    }

    #[test]
    fn test_unchecked_flag_shows_empty_box() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        let output = render_to_string(&mut app, 100, 24);
        // Unchecked boolean flags should show ○
        assert!(output.contains(""));
    }

    // ── Theme visual consistency tests ──────────────────────────────────

    #[test]
    fn test_all_themes_render_without_panic() {
        for theme in ThemeName::all() {
            let mut app = App::with_theme(sample_spec(), *theme);
            app.navigate_to_command(&["deploy"]);

            // Should render without panicking for any theme
            let output = render_to_string(&mut app, 100, 24);
            assert!(
                output.contains("mycli"),
                "Theme {:?} failed to render binary name",
                theme
            );
            assert!(
                output.contains("deploy"),
                "Theme {:?} failed to render subcommand",
                theme
            );
            assert!(
                output.contains(theme.display_name()),
                "Theme {:?} name not shown in status bar",
                theme
            );
        }
    }

    #[test]
    fn test_light_theme_renders() {
        // Test a light theme to ensure we handle light backgrounds
        let mut app = App::with_theme(sample_spec(), ThemeName::CatppuccinLatte);
        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("mycli"));
        assert!(output.contains("Catppuccin Latte"));
    }

    #[test]
    fn test_ui_colors_from_palette_consistency() {
        // Verify UiColors derives correctly from different palettes
        let dracula_palette = ThemeName::Dracula.palette();
        let nord_palette = ThemeName::Nord.palette();

        let dracula_colors = super::UiColors::from_palette(&dracula_palette);
        let nord_colors = super::UiColors::from_palette(&nord_palette);

        // command uses info color, which should differ between themes
        assert_eq!(dracula_colors.command, dracula_palette.info);
        assert_eq!(nord_colors.command, nord_palette.info);

        // flag uses warning color
        assert_eq!(dracula_colors.flag, dracula_palette.warning);
        assert_eq!(nord_colors.flag, nord_palette.warning);

        // required uses error color
        assert_eq!(dracula_colors.required, dracula_palette.error);
        assert_eq!(nord_colors.required, nord_palette.error);
    }

    // ── Phase 10: UX Bug Fix Tests ──────────────────────────────────────

    #[test]
    fn test_checkmark_style_checked() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        // Toggle --rollback on
        app.set_focus(Focus::Flags);
        let fidx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "rollback")
            .unwrap();
        app.set_flag_index(fidx);
        let vals = app.current_flag_values_mut();
        if let Some((_, FlagValue::Bool(ref mut b))) = vals.get_mut(fidx) {
            *b = true;
        }

        let output = render_to_string(&mut app, 100, 24);
        // Checked flags should use checkmark ✓ (not ☑)
        assert!(
            output.contains(''),
            "Checked flag should show ✓ checkmark symbol"
        );
        assert!(
            !output.contains(''),
            "Should NOT use small ☑ symbol anymore"
        );
    }

    #[test]
    fn test_checkmark_style_unchecked() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);

        let output = render_to_string(&mut app, 100, 24);
        // Unchecked flags should use ○ (not ☐)
        assert!(
            output.contains(''),
            "Unchecked flag should show ○ circle symbol"
        );
        assert!(
            !output.contains(''),
            "Should NOT use small ☐ symbol anymore"
        );
    }

    #[test]
    fn test_prominent_selection_caret() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Commands);
        let output = render_to_string(&mut app, 100, 24);
        // Selected item should have prominent ▶ cursor (not thin ▸)
        assert!(
            output.contains(''),
            "Selection caret should be the prominent ▶ triangle"
        );
        // The old thin ▸ should only appear as a subcommand indicator, not as a selection caret
        // (subcommand indicator "▸" is still used for has-children indicator)
    }

    #[test]
    fn test_prominent_caret_in_flags_panel() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["deploy"]);
        app.set_focus(Focus::Flags);

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains(''),
            "Flags panel should use prominent ▶ caret for selected item"
        );
    }

    #[test]
    fn test_prominent_caret_in_args_panel() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["run"]);
        app.set_focus(Focus::Args);

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains(''),
            "Args panel should use prominent ▶ caret for selected item"
        );
    }

    #[test]
    fn test_count_flag_decrement_renders() {
        let mut app = App::new(sample_spec());
        app.set_focus(Focus::Flags);

        // Find verbose (count flag)
        let fidx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "verbose")
            .unwrap();
        app.set_flag_index(fidx);

        // Increment to 3
        for _ in 0..3 {
            app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));
        }

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("[3]"),
            "Count flag at 3 should show [3] in the UI"
        );

        // Decrement via backspace
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("[2]"),
            "After backspace, count flag should show [2]"
        );

        // Decrement to zero
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("[0]"), "Count flag at 0 should show [0]");

        // One more backspace — should stay at 0
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(output.contains("[0]"), "Count flag should not go below 0");
    }

    #[test]
    fn test_editing_arg_then_switching_does_not_bleed() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["run"]);

        // Focus on args and edit <task>
        app.set_focus(Focus::Args);
        app.set_arg_index(0);
        app.start_editing();
        // Type via handle_key which calls sync_edit_to_value internally
        for c in ['h', 'e', 'l', 'l', 'o'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));
        }

        // Render while editing first arg
        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("hello"),
            "Editing first arg should show 'hello'"
        );

        // Finish editing and switch to second arg
        app.finish_editing();
        app.set_arg_index(1);

        // Render: second arg should NOT show 'hello'
        let output = render_to_string(&mut app, 100, 24);
        // The second arg row should show (empty) not 'hello'
        // Split output into lines, find the line with [args...]
        let args_line = output.lines().find(|l| l.contains("args")).unwrap_or("");
        assert!(
            !args_line.contains("hello"),
            "Second arg should not contain text from first arg. Line: {}",
            args_line
        );
    }

    #[test]
    fn test_count_flag_preview_after_decrement() {
        let mut app = App::new(sample_spec());
        // Stay at root where verbose flag is
        app.set_focus(Focus::Flags);

        let fidx = app
            .current_flag_values()
            .iter()
            .position(|(n, _)| n == "verbose")
            .unwrap();
        app.set_flag_index(fidx);

        // Increment to 2
        app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));
        app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("-vv"),
            "Preview should show -vv for count 2"
        );

        // Decrement to 1
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("-v") && !output.contains("-vv"),
            "Preview should show -v for count 1"
        );

        // Decrement to 0
        app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));

        let output = render_to_string(&mut app, 100, 24);
        assert!(
            !output.contains("-v ") && !output.contains("-vv"),
            "Preview should not contain -v when count is 0"
        );
    }

    #[test]
    fn test_cursor_position_in_editing() {
        let mut app = App::new(sample_spec());
        app.navigate_to_command(&["init"]);
        app.set_focus(Focus::Args);
        app.set_arg_index(0);
        app.start_editing();

        // Type "hello"
        app.edit_input.insert_char('h');
        app.edit_input.insert_char('e');
        app.edit_input.insert_char('l');
        app.edit_input.insert_char('l');
        app.edit_input.insert_char('o');

        // Render with cursor at end
        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("hello▎"),
            "Should show cursor at end of text"
        );

        // Move cursor to beginning
        app.edit_input.move_home();
        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("▎hello"),
            "Should show cursor at beginning of text"
        );

        // Move cursor to middle
        app.edit_input.move_right();
        app.edit_input.move_right();
        let output = render_to_string(&mut app, 100, 24);
        assert!(
            output.contains("he▎llo"),
            "Should show cursor in middle of text"
        );
    }

    // ── Theme picker rendering tests ────────────────────────────────────

    #[test]
    fn snapshot_theme_picker_open() {
        let mut app = App::new(sample_spec());
        app.open_theme_picker();
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_theme_picker_navigated() {
        let mut app = App::new(sample_spec());
        app.open_theme_picker();

        // Navigate down to Nord (index 2)
        let down = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
        app.handle_key(down);
        app.handle_key(down);

        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn test_theme_picker_shows_all_themes() {
        let mut app = App::new(sample_spec());
        app.open_theme_picker();
        let output = render_to_string(&mut app, 100, 24);

        // All theme display names should appear in the overlay
        for theme in ThemeName::all() {
            assert!(
                output.contains(theme.display_name()),
                "Theme picker should show '{}' but output was:\n{}",
                theme.display_name(),
                output
            );
        }
    }

    #[test]
    fn test_theme_picker_help_bar_shows_picker_keybinds() {
        let mut app = App::new(sample_spec());
        app.open_theme_picker();
        let output = render_to_string(&mut app, 100, 24);

        assert!(
            output.contains("⏎ confirm") && output.contains("Esc cancel"),
            "Help bar should show theme picker keybinds"
        );
    }

    #[test]
    fn test_theme_picker_previews_theme() {
        let mut app = App::new(sample_spec());
        app.open_theme_picker();

        // Navigate to Nord
        let down = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
        app.handle_key(down);
        app.handle_key(down);

        let output = render_to_string(&mut app, 100, 24);
        // The help bar should show [Nord] since theme_name changed to preview
        assert!(
            output.contains("[Nord]"),
            "Theme indicator should show the previewed theme"
        );
    }

    #[test]
    fn test_theme_indicator_rect_set_after_render() {
        let mut app = App::new(sample_spec());
        assert!(app.theme_indicator_rect.is_none());
        let _output = render_to_string(&mut app, 100, 24);
        assert!(
            app.theme_indicator_rect.is_some(),
            "theme_indicator_rect should be set after rendering"
        );
    }

    #[test]
    fn snapshot_commands_scrollbar() {
        // Use sample spec which has 15 commands (when flat)
        // Render in a small height (12 lines) to force scrolling
        let mut app = App::new(sample_spec());
        // Navigate down to show scrollbar thumb moved from top
        let down = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Down,
            crossterm::event::KeyModifiers::NONE,
        );
        for _ in 0..7 {
            app.handle_key(down);
        }
        let output = render_to_string(&mut app, 100, 12);
        insta::assert_snapshot!(output);
    }

    #[test]
    fn snapshot_select_scrollbar() {
        // Create a spec with many static choices to test scrollbar
        let spec_text = r#"
name "test"
bin "test"
cmd "test" {
    arg "<item>" {
        choices "opt01" "opt02" "opt03" "opt04" "opt05" "opt06" "opt07" "opt08" "opt09" "opt10" "opt11" "opt12" "opt13" "opt14" "opt15"
    }
}
        "#;
        let mut app = App::new(parse_spec(spec_text));
        
        // Focus on Args and open the select box
        app.set_focus(Focus::Args);
        let enter = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Enter,
            crossterm::event::KeyModifiers::NONE,
        );
        app.handle_key(enter);
        
        // Navigate down in the select to show scrollbar thumb moved from top
        let down = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Down,
            crossterm::event::KeyModifiers::NONE,
        );
        for _ in 0..5 {
            app.handle_key(down);
        }
        let output = render_to_string(&mut app, 100, 24);
        insta::assert_snapshot!(output);
    }
}