turboreview 0.1.2

A terminal code-review tool for git: review working-tree changes and commits, stage files, leave line comments, and hand off to an AI agent.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
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
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Wrap,
};
use ratatui::Frame;

use crate::app::{App, CommentRow, InputState, LineKind, Pane, Section, Status, ViewMode};
use crate::comments::CommentStatus;
use crate::highlight::highlight_code;
use crate::theme::Palette;
use crate::tree::RowKind;

fn status_letter(status: Status, pal: &Palette) -> (&'static str, ratatui::style::Color) {
    match status {
        Status::Added => ("A", pal.tick),
        Status::Modified => ("M", pal.yellow),
        Status::Deleted => ("D", pal.red),
        Status::Renamed => ("R", pal.blue),
        Status::Other => (" ", pal.accent_dim),
    }
}

fn gutter(dl: &crate::app::DiffLine) -> String {
    let n = dl.new_lineno.or(dl.old_lineno);
    match n {
        Some(n) => format!("{:>4} ", n),
        None => "     ".to_string(),
    }
}

/// Word-wrap `text` to `width` columns. Each `\n`-delimited source line is wrapped
/// independently; words longer than `width` are hard-split. An empty source line
/// yields one empty visual line, so blank lines are preserved. `width` is clamped
/// to at least 1. Returns the visual lines (no trailing newline).
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    let width = width.max(1);
    let mut out = Vec::new();
    for src_line in text.split('\n') {
        if src_line.is_empty() {
            out.push(String::new());
            continue;
        }
        let mut cur = String::new();
        let mut cur_len = 0usize; // in chars
        for word in src_line.split(' ') {
            let wlen = word.chars().count();
            // Hard-split a word longer than the full width.
            if wlen > width {
                if cur_len > 0 {
                    out.push(std::mem::take(&mut cur));
                    cur_len = 0;
                }
                let mut chunk = String::new();
                for ch in word.chars() {
                    if chunk.chars().count() == width {
                        out.push(std::mem::take(&mut chunk));
                    }
                    chunk.push(ch);
                }
                if !chunk.is_empty() {
                    cur = chunk;
                    cur_len = cur.chars().count();
                }
                continue;
            }
            // +1 for the joining space when cur is non-empty.
            let needed = if cur_len == 0 {
                wlen
            } else {
                cur_len + 1 + wlen
            };
            if needed > width {
                out.push(std::mem::take(&mut cur));
                cur = word.to_string();
                cur_len = wlen;
            } else {
                if cur_len > 0 {
                    cur.push(' ');
                    cur_len += 1;
                }
                cur.push_str(word);
                cur_len += wlen;
            }
        }
        out.push(cur);
    }
    out
}

/// One visual row in side-by-side mode. A `header` (hunk) row spans the full
/// width and ignores left/right. Otherwise `left`/`right` hold the diff indices
/// shown on the old/new sides (`None` = a blank cell).
#[derive(Debug, Clone, PartialEq, Eq)]
struct RowPair {
    header: Option<usize>,
    left: Option<usize>,
    right: Option<usize>,
}

/// Pair a unified `diff` into side-by-side rows. Context lines map to one row
/// with the same index on both sides. A run of Del lines immediately followed by
/// a run of Add lines is zipped position-wise (the shorter side padded blank).
/// Hunk lines become full-width header rows.
fn pair_diff_rows(diff: &[crate::app::DiffLine]) -> Vec<RowPair> {
    let mut rows = Vec::new();
    let mut i = 0;
    while i < diff.len() {
        match diff[i].kind {
            LineKind::Hunk => {
                rows.push(RowPair {
                    header: Some(i),
                    left: None,
                    right: None,
                });
                i += 1;
            }
            LineKind::Context => {
                rows.push(RowPair {
                    header: None,
                    left: Some(i),
                    right: Some(i),
                });
                i += 1;
            }
            LineKind::Del | LineKind::Add => {
                // Gather the maximal run of Dels, then the maximal run of Adds.
                let dels_start = i;
                while i < diff.len() && diff[i].kind == LineKind::Del {
                    i += 1;
                }
                let dels: Vec<usize> = (dels_start..i).collect();
                let adds_start = i;
                while i < diff.len() && diff[i].kind == LineKind::Add {
                    i += 1;
                }
                let adds: Vec<usize> = (adds_start..i).collect();
                let n = dels.len().max(adds.len());
                for k in 0..n {
                    rows.push(RowPair {
                        header: None,
                        left: dels.get(k).copied(),
                        right: adds.get(k).copied(),
                    });
                }
            }
        }
    }
    rows
}

pub fn render(frame: &mut Frame, app: &App) {
    // The bottom status row only exists when it has something to show — a search
    // input line or a transient message. Otherwise the panes use the full height
    // (no empty padding line), since the "? help" hint lives in the diff border.
    let want_status = app.search_input.is_some() || app.status_msg.is_some();
    let status_h = if want_status { 1 } else { 0 };
    let outer = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(status_h)])
        .split(frame.area());

    let main_area = outer[0];
    let comment_pct: u16 = 28;

    if app.show_files && app.show_comments {
        // Three columns: [Files | Diff | Comments]
        // Ensure middle (diff) is at least 20%
        let diff_pct = 100u16
            .saturating_sub(app.file_pane_pct)
            .saturating_sub(comment_pct)
            .max(20);
        let actual_files_pct = 100u16.saturating_sub(diff_pct).saturating_sub(comment_pct);
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(actual_files_pct),
                Constraint::Percentage(diff_pct),
                Constraint::Percentage(comment_pct),
            ])
            .split(main_area);
        match app.view {
            ViewMode::Changes => render_files(frame, app, panes[0]),
            ViewMode::Commits if app.open_commit.is_none() => render_commits(frame, app, panes[0]),
            ViewMode::Commits => render_files(frame, app, panes[0]),
        }
        render_diff(frame, app, panes[1]);
        render_comment_list(frame, app, panes[2]);
    } else if !app.show_files && app.show_comments {
        // Two columns: [Diff | Comments]
        let diff_pct = 100u16.saturating_sub(comment_pct).max(20);
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(diff_pct),
                Constraint::Percentage(comment_pct),
            ])
            .split(main_area);
        render_diff(frame, app, panes[0]);
        render_comment_list(frame, app, panes[1]);
    } else if app.show_files {
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(app.file_pane_pct),
                Constraint::Percentage(100 - app.file_pane_pct),
            ])
            .split(main_area);
        match app.view {
            ViewMode::Changes => render_files(frame, app, panes[0]),
            ViewMode::Commits if app.open_commit.is_none() => render_commits(frame, app, panes[0]),
            ViewMode::Commits => render_files(frame, app, panes[0]),
        }
        render_diff(frame, app, panes[1]);
    } else {
        render_diff(frame, app, main_area);
    }
    if status_h > 0 {
        render_status(frame, app, outer[1]);
    }
    if let Some(input) = &app.input {
        render_input_modal(frame, app, input);
    }
    if app.show_help {
        render_help_modal(frame, app);
    }
}

fn focused_border(app: &App, pane: Pane) -> Style {
    let pal = app.palette();
    if app.focus == pane {
        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(pal.accent_dim)
    }
}

fn status_color(status: CommentStatus, pal: &Palette) -> ratatui::style::Color {
    match status {
        CommentStatus::Open => pal.accent,
        CommentStatus::NeedsInfo => pal.yellow,
        CommentStatus::Wontfix => pal.red,
        CommentStatus::Resolved => pal.tick,
    }
}

fn render_comment_list(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let count = app.comments.items.len();
    let title = format!(" Comments ({}) ", count);

    let rows = app.comment_rows();
    let items: Vec<ListItem> = rows
        .iter()
        .map(|row| match row {
            CommentRow::Header(status, cnt) => {
                let label = format!("{} ({})", status.label(), cnt);
                let line = Line::from(Span::styled(
                    label,
                    Style::default()
                        .fg(status_color(*status, &pal))
                        .add_modifier(Modifier::BOLD),
                ));
                ListItem::new(line)
            }
            CommentRow::Item(i) => {
                let c = &app.comments.items[*i];
                let basename = c.file.file_name().and_then(|n| n.to_str()).unwrap_or("");
                let first_line = c.text.lines().next().unwrap_or("");
                let max_text = area.width.saturating_sub(20) as usize;
                let text_display = if first_line.chars().count() > max_text && max_text > 3 {
                    format!(
                        "{}",
                        first_line
                            .chars()
                            .take(max_text.saturating_sub(1))
                            .collect::<String>()
                    )
                } else {
                    first_line.to_string()
                };
                let line = Line::from(vec![
                    Span::styled(
                        format!("  {}:{} ", basename, c.line),
                        Style::default().fg(pal.accent_dim),
                    ),
                    Span::raw(text_display),
                ]);
                ListItem::new(line)
            }
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Comments))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );

    let mut state = ListState::default();
    if !rows.is_empty() {
        state.select(Some(app.comment_selected));
    }
    frame.render_stateful_widget(list, area, &mut state);
}

fn render_files(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let items: Vec<ListItem> = app
        .rows
        .iter()
        .map(|row| {
            let indent = "  ".repeat(row.depth);
            match &row.kind {
                RowKind::Header { section, count } => {
                    let label = match section {
                        Section::Unstaged => format!("{}▌ Unstaged ({})", indent, count),
                        Section::Staged => format!("{}▌ Staged ({})", indent, count),
                        Section::Commit => {
                            let short = app.open_commit_short().unwrap_or("commit");
                            format!("{}▌ Commit {} ({})", indent, short, count)
                        }
                    };
                    let line = Line::from(Span::styled(
                        label,
                        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
                    ));
                    ListItem::new(line)
                }
                RowKind::Dir { collapsed, .. } => {
                    let glyph = if *collapsed { "" } else { "" };
                    let text = format!("{}{} {}", indent, glyph, row.name);
                    ListItem::new(Line::from(text))
                }
                RowKind::File {
                    section,
                    file_index,
                } => {
                    let files = app.section_files(*section);
                    let fc = &files[*file_index];
                    let file_path = &fc.path;
                    let (mark, mark_style) = if app.is_reviewed_path(file_path) {
                        ("", Style::default().fg(pal.tick))
                    } else {
                        ("", Style::default().fg(pal.accent_dim))
                    };
                    let (letter, letter_color) = status_letter(fc.status, &pal);
                    let icon = crate::icons::icon_for(file_path);
                    let line = Line::from(vec![
                        Span::raw(indent),
                        Span::styled(format!("{} ", letter), Style::default().fg(letter_color)),
                        Span::styled(mark, mark_style),
                        Span::raw(format!("{} {}", icon, row.name)),
                    ]);
                    ListItem::new(line)
                }
            }
        })
        .collect();
    let title = if app.in_commit_detail() {
        let short = app.open_commit_short().unwrap_or("commit");
        format!(" Changes  Commits ▸ {} ", short)
    } else if app.hide_reviewed {
        " [Changes] Commits  (hiding reviewed) ".to_string()
    } else {
        " [Changes] Commits ".to_string()
    };
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Files))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );
    let mut state = ListState::default();
    state.select(Some(app.selected));
    frame.render_stateful_widget(list, area, &mut state);
}

fn render_commits(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let mut items: Vec<ListItem> = app
        .commits
        .iter()
        .map(|ci| {
            // Reserve room for hash + author/date + diff stats so the summary
            // truncates instead of overflowing.
            let max_summary = area.width.saturating_sub(48) as usize;
            let summary = if ci.summary.chars().count() > max_summary && max_summary > 3 {
                format!(
                    "{}",
                    ci.summary.chars().take(max_summary - 1).collect::<String>()
                )
            } else {
                ci.summary.clone()
            };
            let mut spans = vec![
                Span::styled(format!("{} ", ci.short), Style::default().fg(pal.yellow)),
                Span::raw(summary),
                Span::styled(
                    format!("{} {}", ci.author, ci.time),
                    Style::default().fg(pal.accent_dim),
                ),
            ];
            // Diff stats: "· N files +ins -del" (green/red), or a placeholder
            // while the stat is still being computed for this row.
            match app.commit_stats.get(&ci.id) {
                Some(s) => {
                    spans.push(Span::styled(
                        format!(" · {} files ", s.files),
                        Style::default().fg(pal.accent_dim),
                    ));
                    spans.push(Span::styled(
                        format!("+{}", s.insertions),
                        Style::default().fg(pal.tick),
                    ));
                    spans.push(Span::styled(
                        format!(" -{}", s.deletions),
                        Style::default().fg(pal.red),
                    ));
                }
                None => spans.push(Span::styled(
                    " · …",
                    Style::default().fg(pal.accent_dim),
                )),
            }
            ListItem::new(Line::from(spans))
        })
        .collect();

    // Footer hint when the page may have been truncated (more history available).
    if !app.commits.is_empty() && app.commits.len() == app.commit_limit {
        items.push(ListItem::new(Line::from(Span::styled(
            "  … press L to load more",
            Style::default()
                .fg(pal.accent_dim)
                .add_modifier(Modifier::ITALIC),
        ))));
    }

    let title = " Changes [Commits] ";
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Files))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );
    let mut state = ListState::default();
    state.select(if app.commits.is_empty() {
        None
    } else {
        Some(app.selected_commit)
    });
    frame.render_stateful_widget(list, area, &mut state);
}

/// Keep the cursor visible at the bottom of the viewport (default diff scrolling).
fn diff_scroll_start_follow(cursor: usize, page: usize, rh: &impl Fn(usize) -> usize) -> usize {
    if page == 0 {
        return cursor;
    }
    let mut start = cursor;
    let mut used = rh(cursor);
    while start > 0 {
        let h = rh(start - 1);
        if used + h > page {
            break;
        }
        used += h;
        start -= 1;
    }
    start
}

/// Place the cursor near the vertical center, or near the top when the cursor is early.
fn diff_scroll_start_center(cursor: usize, page: usize, rh: &impl Fn(usize) -> usize) -> usize {
    if page == 0 {
        return cursor;
    }
    let cursor_h = rh(cursor);
    let above_target = page.saturating_sub(cursor_h) / 2;
    let mut start = cursor;
    let mut above_used = 0;
    while start > 0 {
        let h = rh(start - 1);
        if above_used + h > above_target {
            break;
        }
        above_used += h;
        start -= 1;
    }
    start
}

/// Number of rendered lines an inline comment box occupies for `wrap_w` columns:
/// 1 (top) + wrapped text + (response ? 1 blank + wrapped response : 0) + 1 (bottom).
fn comment_box_height(c: &crate::comments::Comment, wrap_w: usize) -> usize {
    let text_lines = wrap_text(&c.text, wrap_w).len().max(1);
    let response_lines = match c.response.as_deref() {
        Some(r) if !r.trim().is_empty() => 1 + wrap_text(r, response_wrap_w(wrap_w)).len(),
        _ => 0,
    };
    1 + text_lines + response_lines + 1
}

/// Wrap width for the response block. The response prefix `"    │ ↳ response: "`
/// is 18 columns vs the body prefix `"    │ "` (6 columns), so response text has
/// 12 fewer columns than the body. Continuation lines align to the same start.
/// `wrap_w` is the body wrap width (= inner_w - 6).
fn response_wrap_w(wrap_w: usize) -> usize {
    wrap_w.saturating_sub(RESPONSE_PREFIX_W - BODY_PREFIX_W).max(1)
}

/// Visible width of the body line prefix `"    │ "`.
const BODY_PREFIX_W: usize = 6;
/// Right-side breathing room: wrap comment text this many columns short of the
/// pane edge so text doesn't butt against the border.
const RIGHT_PAD: usize = 2;
/// Visible width of the response first-line prefix `"    │ ↳ response: "`.
const RESPONSE_PREFIX_W: usize = 18;

/// Push an inline comment box (top border, wrapped text, optional response,
/// bottom border) into `result`, honoring the remaining `page` budget. Shared by
/// the unified and side-by-side diff renderers.
fn push_comment_box(
    result: &mut Vec<Line<'static>>,
    rendered_rows: &mut usize,
    page: usize,
    c: &crate::comments::Comment,
    wrap_w: usize,
    pal: &Palette,
) {
    let border_color = if c.stale {
        pal.yellow
    } else {
        match c.status {
            // Open: a subtle dim frame so the header/body colors stand out.
            CommentStatus::Open => pal.accent_dim,
            CommentStatus::Resolved => pal.tick,
            CommentStatus::Wontfix => pal.red,
            CommentStatus::NeedsInfo => pal.yellow,
        }
    };
    let border_style = Style::default()
        .fg(border_color)
        .add_modifier(Modifier::ITALIC | Modifier::DIM);
    let body_style = Style::default()
        .fg(pal.accent)
        .add_modifier(Modifier::ITALIC);

    // Top border line with status badge
    if *rendered_rows < page {
        let mut top_label = if c.stale {
            format!("    ╭─ ⚠ outdated · {}", c.status.label())
        } else {
            match c.status {
                CommentStatus::Open => "    ╭─ comment".to_string(),
                CommentStatus::Resolved => "    ╭─ ✓ resolved".to_string(),
                CommentStatus::Wontfix => "    ╭─ ✗ wontfix".to_string(),
                CommentStatus::NeedsInfo => "    ╭─ ? needs-info".to_string(),
            }
        };
        // Last-edit timestamp (UTC) + relative age. 0 = legacy comment, no stamp.
        if c.updated > 0 {
            top_label.push_str(&format!(
                " · {} ({})",
                crate::git::format_datetime(c.updated),
                crate::git::relative_time(c.updated, crate::storage::now_secs())
            ));
        }
        result.push(Line::from(Span::styled(top_label, border_style)));
        *rendered_rows += 1;
    }
    // Body lines (reviewer's comment text), wrapped to the box width.
    for comment_line in wrap_text(&c.text, wrap_w) {
        if *rendered_rows >= page {
            break;
        }
        let prefix = Span::styled("", border_style);
        let body = Span::styled(comment_line, body_style);
        result.push(Line::from(vec![prefix, body]));
        *rendered_rows += 1;
    }
    // Response block (only when response is present AND non-empty after trim)
    if c.response
        .as_deref()
        .map_or(false, |r| !r.trim().is_empty())
    {
        let resp = c.response.as_deref().unwrap();
        if *rendered_rows < page {
            result.push(Line::from(Span::styled("", border_style)));
            *rendered_rows += 1;
        }
        let mut first = true;
        for resp_line in wrap_text(resp, response_wrap_w(wrap_w)) {
            if *rendered_rows >= page {
                break;
            }
            // "    │ " is the border; the rest (label + text) uses body color.
            let border = Span::styled("", border_style);
            let text = if first {
                first = false;
                // "↳ response: " label + text, aligned to 18 cols total prefix.
                Span::styled(format!("↳ response: {}", resp_line), body_style)
            } else {
                // Align continuation under the first response char.
                Span::styled(format!("            {}", resp_line), body_style)
            };
            result.push(Line::from(vec![border, text]));
            *rendered_rows += 1;
        }
    }
    // Bottom border line
    if *rendered_rows < page {
        result.push(Line::from(Span::styled("    ╰─", border_style)));
        *rendered_rows += 1;
    }
}

/// Build the rendered lines for side-by-side (split) diff mode. Old lines sit on
/// the left half, new lines on the right, separated by a vertical bar. Cursor row
/// (whichever side holds `diff_cursor`) is highlighted full-row; search matches
/// tint their cell; hunk headers span the full width; inline comment boxes render
/// full width under their row.
fn build_split_lines(app: &App, area: Rect, ext: &str) -> Vec<Line<'static>> {
    let pal = app.palette();
    let page = area.height.saturating_sub(2) as usize;
    let inner_w = area.width.saturating_sub(2) as usize; // minus borders
    // Two columns + a 1-char separator between them.
    let sep_w = 1usize;
    let cell_w = inner_w.saturating_sub(sep_w) / 2;
    let gutter_w = 5usize; // matches `gutter()` width
    let text_w = cell_w.saturating_sub(gutter_w).max(1);
    let wrap_w = inner_w.saturating_sub(BODY_PREFIX_W + RIGHT_PAD).max(1); // indent "    │ " + right pad

    let pairs = pair_diff_rows(&app.diff);
    // Which paired row holds the cursor — its header (hunk), left, or right cell.
    let cur = Some(app.diff_cursor);
    let cursor_row = pairs
        .iter()
        .position(|p| p.header == cur || p.left == cur || p.right == cur)
        .unwrap_or(0);

    // Rendered height of a paired row = 1 + comment box for each distinct side
    // with a comment. Context rows have left==right; count that box only once.
    let row_height = |pi: usize| -> usize {
        let p = &pairs[pi];
        let mut h = 1;
        let right = if p.right == p.left { None } else { p.right };
        for side in [p.left, right] {
            if let Some(di) = side {
                if let Some(c) = app.comment_for(&app.diff[di]) {
                    h += comment_box_height(c, wrap_w);
                }
            }
        }
        h
    };

    let start = if app.history_active() {
        diff_scroll_start_center(cursor_row, page, &row_height)
    } else {
        diff_scroll_start_follow(cursor_row, page, &row_height)
    };

    // Render one cell (gutter + text), padded/truncated to `cell_w`, with the
    // appropriate background. `di` None => a blank cell.
    let render_cell = |di: Option<usize>, is_cursor_row: bool| -> Vec<Span<'static>> {
        let Some(di) = di else {
            // Blank cell: pad to cell width.
            let bg = if is_cursor_row {
                Style::default().bg(pal.selected_bg)
            } else {
                Style::default()
            };
            return vec![Span::styled(" ".repeat(cell_w), bg)];
        };
        let dl = &app.diff[di];
        let comment = app.comment_for(dl);
        let gutter_fg = match comment {
            Some(c) if c.stale => pal.yellow,
            Some(_) => pal.accent,
            None => pal.accent_dim,
        };
        let bg = match dl.kind {
            LineKind::Add => Some(pal.add_bg),
            LineKind::Del => Some(pal.del_bg),
            _ => None,
        };
        let cell_bg = if is_cursor_row { Some(pal.selected_bg) } else { bg };
        let gutter_style = {
            let mut s = Style::default().fg(gutter_fg);
            if let Some(b) = cell_bg {
                s = s.bg(b);
            }
            s
        };
        // Text, horizontally scrolled then truncated to text width, syntax-highlighted.
        let shifted: String = dl
            .text
            .chars()
            .skip(app.diff_hscroll)
            .take(text_w)
            .collect();
        let visible = shifted.chars().count();
        let pad = text_w.saturating_sub(visible);
        // Search tint applies to the whole cell when matched (not on cursor row).
        let search_hit = app.search.as_ref().map_or(false, |s| {
            !is_cursor_row && dl.text.to_lowercase().contains(&s.query)
        });
        let mut text_spans: Vec<Span<'static>> = highlight_code(&shifted, ext, app.theme);
        for sp in text_spans.iter_mut() {
            if is_cursor_row {
                sp.style = sp.style.bg(pal.selected_bg);
            } else if search_hit {
                sp.style = sp.style.bg(pal.accent_dim);
            } else if let Some(b) = cell_bg {
                sp.style = sp.style.bg(b);
            }
            if !is_cursor_row && dl.kind == LineKind::Context {
                sp.style = sp.style.add_modifier(Modifier::DIM);
            }
        }
        // Pad the cell to full width so backgrounds fill the column.
        let pad_style = {
            let mut s = Style::default();
            if is_cursor_row {
                s = s.bg(pal.selected_bg);
            } else if let Some(b) = cell_bg {
                s = s.bg(b);
            }
            s
        };
        let mut spans = vec![Span::styled(gutter(dl), gutter_style)];
        spans.extend(text_spans);
        spans.push(Span::styled(" ".repeat(pad), pad_style));
        spans
    };

    // A row is highlighted when any of its diff indices fall in the visual-select
    // range (collapses to the single cursor row when nothing is selected).
    let (sel_lo, sel_hi) = app.select_range();
    let in_sel = |di: Option<usize>| matches!(di, Some(i) if i >= sel_lo && i <= sel_hi);

    let mut result: Vec<Line<'static>> = Vec::new();
    let mut rendered_rows = 0usize;
    for p in pairs.iter().skip(start) {
        if rendered_rows >= page {
            break;
        }
        let is_cursor_row = in_sel(p.header) || in_sel(p.left) || in_sel(p.right);

        // Hunk header: full width.
        if let Some(hi) = p.header {
            let shifted: String = app.diff[hi].text.chars().skip(app.diff_hscroll).collect();
            let mut style = Style::default().fg(pal.hunk);
            if is_cursor_row {
                style = style.bg(pal.selected_bg);
            }
            result.push(Line::from(Span::styled(shifted, style)));
            rendered_rows += 1;
            continue;
        }

        // Two cells + separator.
        let mut spans = render_cell(p.left, is_cursor_row);
        let sep_style = if is_cursor_row {
            Style::default().fg(pal.accent_dim).bg(pal.selected_bg)
        } else {
            Style::default().fg(pal.accent_dim)
        };
        spans.push(Span::styled("", sep_style));
        spans.extend(render_cell(p.right, is_cursor_row));
        result.push(Line::from(spans));
        rendered_rows += 1;

        // Inline comment box(es) full-width under the row. For a context row,
        // left and right are the SAME diff index — render its box once.
        let right = if p.right == p.left { None } else { p.right };
        for side in [p.left, right] {
            if let Some(di) = side {
                if let Some(c) = app.comment_for(&app.diff[di]) {
                    push_comment_box(&mut result, &mut rendered_rows, page, c, wrap_w, &pal);
                }
            }
        }
    }
    result
}

fn render_diff(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let ext = app
        .selected_path()
        .and_then(|p| p.extension())
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_string();

    let ctx_label = if app.full_file {
        "full file".to_string()
    } else {
        format!("ctx {}", app.context_lines)
    };
    let title = if let Some(commit) = app.history_current_commit() {
        let h = app.history.as_ref().unwrap();
        format!(
            " {} @ {} ({}/{}) — {} ",
            h.file.display(),
            commit.short,
            h.idx,
            h.commits.len(),
            commit.summary,
        )
    } else {
        app.selected_path()
            .map(|p| format!(" Diff: {} ({}) ", p.display(), ctx_label))
            .unwrap_or_else(|| " Diff ".to_string())
    };

    let lines: Vec<Line> = if app.view == ViewMode::Commits && app.open_commit.is_none() {
        vec![Line::from(Span::styled(
            "Press Enter to open commit  ·  [/] switch view",
            Style::default().fg(pal.placeholder),
        ))]
    } else if app.diff.is_empty() {
        vec![Line::from(Span::styled(
            "No changes",
            Style::default().fg(pal.placeholder),
        ))]
    } else if app.split_diff {
        build_split_lines(app, area, &ext)
    } else {
        let page = area.height.saturating_sub(2) as usize;

        // Inline comment box body is indented by "    │ " (6 columns). Wrap comment and
        // response text to the remaining inner width, less RIGHT_PAD, so long comments
        // don't overflow or butt against the pane border.
        let inner_w = area.width.saturating_sub(2) as usize; // minus the diff pane borders
        let wrap_w = inner_w.saturating_sub(BODY_PREFIX_W + RIGHT_PAD).max(1);

        // Compute the rendered height (diff line + its inline comment box lines) for a
        // given diff index, so we can scroll in rendered-line space and guarantee the
        // cursor line AND its comment are always visible. Wrapped text height must match
        // the body/response render below or scrolling drifts.
        // comment box: 1 (top) + wrapped text + (if response: 1 blank + wrapped response) + 1 (bottom)
        let rendered_height = |i: usize| -> usize {
            let dl = &app.diff[i];
            let comment_lines = app
                .comment_for(dl)
                .map(|c| {
                    let text_lines = wrap_text(&c.text, wrap_w).len().max(1);
                    let response_lines = match c.response.as_deref() {
                        Some(r) if !r.trim().is_empty() => {
                            1 + wrap_text(r, response_wrap_w(wrap_w)).len() // 1 blank separator + wrapped response
                        }
                        _ => 0,
                    };
                    1 + text_lines + response_lines + 1 // top + text + [blank+response] + bottom
                })
                .unwrap_or(0);
            1 + comment_lines
        };

        // History overlay: center the cursor line. Otherwise: cursor at viewport bottom.
        let start = if app.history_active() {
            diff_scroll_start_center(app.diff_cursor, page, &rendered_height)
        } else {
            diff_scroll_start_follow(app.diff_cursor, page, &rendered_height)
        };

        let (sel_lo, sel_hi) = app.select_range();
        let mut result: Vec<Line> = Vec::new();
        let mut rendered_rows: usize = 0;
        for (idx, dl) in app.diff.iter().enumerate().skip(start) {
            if rendered_rows >= page {
                break;
            }
            // Highlight the whole visual-select range (collapses to the single
            // cursor line when nothing is selected).
            let is_cursor = idx >= sel_lo && idx <= sel_hi;
            let bg = match dl.kind {
                LineKind::Add => Some(pal.add_bg),
                LineKind::Del => Some(pal.del_bg),
                _ => None,
            };
            if dl.kind == LineKind::Hunk {
                let shifted: String = dl.text.chars().skip(app.diff_hscroll).collect();
                let mut span = Span::styled(shifted, Style::default().fg(pal.hunk));
                if is_cursor {
                    span.style = span.style.bg(pal.selected_bg);
                }
                result.push(Line::from(span));
                rendered_rows += 1;
                continue;
            }
            // Gutter: YELLOW for stale-commented lines, ACCENT for normal commented, ACCENT_DIM otherwise.
            let comment = app.comment_for(dl);
            let gutter_fg = match comment {
                Some(c) if c.stale => pal.yellow,
                Some(_) => pal.accent,
                None => pal.accent_dim,
            };
            let gutter_style = if is_cursor {
                Style::default().fg(gutter_fg).bg(pal.selected_bg)
            } else {
                Style::default().fg(gutter_fg)
            };
            let gutter_span = Span::styled(gutter(dl), gutter_style);
            let shifted: String = dl.text.chars().skip(app.diff_hscroll).collect();
            let mut spans: Vec<Span> = highlight_code(&shifted, &ext, app.theme);
            if is_cursor {
                for s in spans.iter_mut() {
                    s.style = s.style.bg(pal.selected_bg);
                }
            } else {
                if let Some(bg) = bg {
                    for s in spans.iter_mut() {
                        s.style = s.style.bg(bg);
                    }
                }
                if dl.kind == LineKind::Context {
                    for s in spans.iter_mut() {
                        s.style = s.style.add_modifier(Modifier::DIM);
                    }
                }
            }
            // Search: tint the background of lines that match the active query.
            if let Some(s) = app.search.as_ref() {
                if !is_cursor && dl.text.to_lowercase().contains(&s.query) {
                    for sp in spans.iter_mut() {
                        sp.style = sp.style.bg(pal.accent_dim);
                    }
                }
            }
            let mut all_spans = Vec::with_capacity(1 + spans.len());
            all_spans.push(gutter_span);
            all_spans.extend(spans);
            result.push(Line::from(all_spans));
            rendered_rows += 1;

            // Enhancement 5a: Inline comment box with box-drawing chars.
            // Normal:  ╭─ comment  /  │ <line>...  /  ╰─
            // Stale:   ╭─ ⚠ outdated · <status> (yellow) / │ <line>... / ╰─
            // Status badge colors: resolved=TICK, wontfix=RED, needs_info=YELLOW, open=ACCENT_DIM
            // Response: blank line + ↳ response: <text> lines, shown below body
            // The top + body lines + optional response + bottom are all counted toward budget.
            if let Some(c) = comment {
                push_comment_box(&mut result, &mut rendered_rows, page, c, wrap_w, &pal);
            }
        }
        result
    };

    let para = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(focused_border(app, Pane::Diff))
            .title(title)
            // Help hint sits in the bottom-right of the diff pane's border.
            .title_bottom(
                Line::from(Span::styled(
                    " ? help ",
                    Style::default().fg(pal.accent_dim),
                ))
                .right_aligned(),
            ),
    );
    frame.render_widget(para, area);
}

fn render_status(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    // While the search input line is open, it owns the status row.
    if let Some(buf) = app.search_input.as_ref() {
        let text = format!("/{}\u{2588}", buf); // trailing block as a cursor
        let para = Paragraph::new(text).style(Style::default().fg(pal.accent));
        frame.render_widget(para, area);
        return;
    }
    // Transient status message only; the "? for help" hint lives in the diff pane's
    // bottom-right border (see render_diff).
    let text = app.status_msg.clone().unwrap_or_default();
    let para = Paragraph::new(text).style(Style::default().fg(pal.accent_dim));
    frame.render_widget(para, area);
}

/// Compute a centered Rect using percentages of the given area.
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let margin_v = (100u16.saturating_sub(percent_y)) / 2;
    let margin_h = (100u16.saturating_sub(percent_x)) / 2;
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(margin_v),
            Constraint::Percentage(percent_y),
            Constraint::Percentage(margin_v),
        ])
        .split(area);
    let horizontal = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(margin_h),
            Constraint::Percentage(percent_x),
            Constraint::Percentage(margin_h),
        ])
        .split(vertical[1]);
    horizontal[1]
}

fn render_input_modal(frame: &mut Frame, app: &App, input: &InputState) {
    let pal = app.palette();
    let area = centered_rect(60, 40, frame.area());
    frame.render_widget(Clear, area);
    let title = format!(
        " Comment line {} (Ctrl-S save · Esc cancel) ",
        input.target_line
    );
    // Append a cursor block indicator to the buffer text.
    let display_text = format!("{}", input.buffer);
    // Enhancement 5b: rounded border, accent color, horizontal padding for clearer text field.
    let para = Paragraph::new(display_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(pal.accent))
                .padding(Padding::horizontal(1))
                .title(title),
        )
        .wrap(Wrap { trim: false });
    frame.render_widget(para, area);
}

/// Keybindings grouped by category for the help overlay. Each group is a
/// (title, &[(key, description)]) pair rendered as a labelled section.
const HELP_SECTIONS: &[(&str, &[(&str, &str)])] = &[
    (
        "Navigation",
        &[
            ("Tab", "switch focus (Files/Diff/Comments)"),
            ("j/k, ↑/↓", "move selection / cursor"),
            ("J/K, ⇧↑/⇧↓", "jump (fast scroll)"),
            ("gg / G", "top / bottom"),
            (
                "Enter",
                "open file diff / open commit / fold dir / jump to comment",
            ),
            ("Esc", "back / focus files"),
            ("[ / ]", "switch Changes/Commits view"),
        ],
    ),
    (
        "Diff view",
        &[
            ("h/l, ←/→", "scroll diff horizontally"),
            ("+/-", "context lines (±5, + at max → full file)"),
            ("F", "full-file diff toggle"),
            ("v", "side-by-side / unified diff"),
            ("y", "copy line / selection to clipboard"),
            ("V", "visual select (move, then y to copy, Esc cancels)"),
        ],
    ),
    (
        "History & search",
        &[
            ("H", "file-history overlay for the current file diff"),
            ("{ / }", "older / newer revision (in history overlay)"),
            ("/", "search within the diff"),
            ("n / N", "next / previous search match"),
        ],
    ),
    (
        "Layout",
        &[
            ("a", "fold/unfold all directories"),
            ("z", "hide/show file pane"),
            ("< / >", "resize file pane"),
            ("C", "toggle comment-list pane"),
        ],
    ),
    (
        "Review",
        &[
            ("c", "comment on line"),
            ("s", "stage / unstage file"),
            ("Space", "toggle reviewed"),
            ("R", "hide reviewed files"),
        ],
    ),
    (
        "App",
        &[
            ("r", "refresh"),
            ("T", "toggle light / dark theme"),
            ("?", "this help"),
            ("qq / Ctrl-C", "quit"),
        ],
    ),
];

fn render_help_modal(frame: &mut Frame, app: &App) {
    let pal = app.palette();
    let area = centered_rect(64, 80, frame.area());
    frame.render_widget(Clear, area);
    let mut lines: Vec<Line> = Vec::new();
    for (si, (title, entries)) in HELP_SECTIONS.iter().enumerate() {
        // Blank separator between sections (not before the first).
        if si > 0 {
            lines.push(Line::from(""));
        }
        lines.push(Line::from(Span::styled(
            format!(" {}", title),
            Style::default()
                .fg(pal.hunk)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
        )));
        for (key, desc) in entries.iter() {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("  {:12}", key),
                    Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
                ),
                Span::styled(desc.to_string(), Style::default().fg(pal.accent_dim)),
            ]));
        }
    }
    let para = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(pal.accent))
            .title(" Keybindings (? or Esc to close) "),
    );
    frame.render_widget(para, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{App, DiffLine, FileChange, Status};
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;
    use std::path::PathBuf;

    fn dl(kind: LineKind, text: &str) -> DiffLine {
        DiffLine {
            kind,
            text: text.into(),
            old_lineno: None,
            new_lineno: None,
        }
    }

    #[test]
    fn split_diff_renders_both_sides_without_panic() {
        let backend = TestBackend::new(100, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.split_diff = true;
        app.set_diff(vec![
            dl(LineKind::Hunk, "@@ -1,2 +1,2 @@"),
            dl(LineKind::Del, "old_left_token"),
            dl(LineKind::Add, "new_right_token"),
            dl(LineKind::Context, "shared_ctx"),
        ]);
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("old_left"), "old side token must render");
        assert!(dump.contains("new_right"), "new side token must render");
        assert!(dump.contains(""), "column separator must render");
    }

    #[test]
    fn split_context_comment_renders_one_box() {
        let backend = TestBackend::new(100, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.split_diff = true;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Context,
            text: "ctx".into(),
            old_lineno: Some(1),
            new_lineno: Some(1),
        }]);
        // Comment on the context line (new_lineno 1).
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "uniq_box_text".to_string(),
            "ctx".to_string(),
            vec![],
            vec![],
            0,
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The comment box top border "╭─ comment" must appear exactly once.
        let box_tops = dump.matches("╭─").count();
        assert_eq!(box_tops, 1, "context-line comment must render a single box");
    }

    #[test]
    fn pair_rows_context_maps_to_both_sides() {
        let diff = vec![dl(LineKind::Context, "same")];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].left, Some(0));
        assert_eq!(rows[0].right, Some(0));
        assert_eq!(rows[0].header, None);
    }

    #[test]
    fn pair_rows_hunk_is_header() {
        let diff = vec![dl(LineKind::Hunk, "@@ -1 +1 @@")];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].header, Some(0));
        assert_eq!(rows[0].left, None);
        assert_eq!(rows[0].right, None);
    }

    #[test]
    fn pair_rows_equal_del_add_run_zips() {
        // del0 del1 add2 add3 -> two rows: (0,2) (1,3)
        let diff = vec![
            dl(LineKind::Del, "old0"),
            dl(LineKind::Del, "old1"),
            dl(LineKind::Add, "new0"),
            dl(LineKind::Add, "new1"),
        ];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 2);
        assert_eq!((rows[0].left, rows[0].right), (Some(0), Some(2)));
        assert_eq!((rows[1].left, rows[1].right), (Some(1), Some(3)));
    }

    #[test]
    fn pair_rows_unequal_run_pads_blank() {
        // 2 dels, 1 add -> rows: (0,2) (1,None)
        let diff = vec![
            dl(LineKind::Del, "old0"),
            dl(LineKind::Del, "old1"),
            dl(LineKind::Add, "new0"),
        ];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 2);
        assert_eq!((rows[0].left, rows[0].right), (Some(0), Some(2)));
        assert_eq!((rows[1].left, rows[1].right), (Some(1), None));
    }

    #[test]
    fn pair_rows_add_only_run_has_blank_left() {
        let diff = vec![dl(LineKind::Add, "new0"), dl(LineKind::Add, "new1")];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 2);
        assert_eq!((rows[0].left, rows[0].right), (None, Some(0)));
        assert_eq!((rows[1].left, rows[1].right), (None, Some(1)));
    }

    #[test]
    fn pair_rows_del_only_run_has_blank_right() {
        let diff = vec![dl(LineKind::Del, "old0")];
        let rows = pair_diff_rows(&diff);
        assert_eq!(rows.len(), 1);
        assert_eq!((rows[0].left, rows[0].right), (Some(0), None));
    }

    #[test]
    fn wrap_text_wraps_long_lines_on_word_boundaries() {
        let lines = wrap_text("the quick brown fox", 9);
        // "the quick" (9), "brown fox" (9)
        assert_eq!(
            lines,
            vec!["the quick".to_string(), "brown fox".to_string()]
        );
        // No visual line exceeds the width.
        assert!(lines.iter().all(|l| l.chars().count() <= 9));
    }

    #[test]
    fn wrap_text_hard_splits_overlong_word() {
        let lines = wrap_text("abcdefghij", 4);
        assert_eq!(lines, vec!["abcd", "efgh", "ij"]);
    }

    #[test]
    fn wrap_text_preserves_blank_lines_and_short_lines() {
        let lines = wrap_text("hi\n\nbye", 10);
        assert_eq!(
            lines,
            vec!["hi".to_string(), String::new(), "bye".to_string()]
        );
    }

    #[test]
    fn wrap_text_clamps_zero_width_to_one() {
        let lines = wrap_text("ab", 0);
        assert_eq!(lines, vec!["a", "b"]);
    }

    fn comment_with_response(text: &str, response: &str) -> crate::comments::Comment {
        crate::comments::Comment {
            file: PathBuf::from("a.rs"),
            line: 1,
            hunk: String::new(),
            text: text.into(),
            line_text: String::new(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 0,
            stale: false,
            status: CommentStatus::Open,
            response: Some(response.into()),
            updated: 0,
        }
    }

    /// Render a comment box into plain strings (joining each line's spans).
    fn render_box(c: &crate::comments::Comment, wrap_w: usize) -> Vec<String> {
        let pal = Palette::for_theme(crate::theme::Theme::Dark);
        let mut out = Vec::new();
        let mut rows = 0usize;
        push_comment_box(&mut out, &mut rows, usize::MAX, c, wrap_w, &pal);
        out.iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect()
    }

    #[test]
    fn response_lines_never_overflow_inner_width() {
        // inner_w = wrap_w + BODY_PREFIX_W (body prefix is 6 cols).
        let wrap_w = 30usize;
        let inner_w = wrap_w + BODY_PREFIX_W;
        let resp = "this is a fairly long agent response that must wrap across \
                    several visual lines without spilling past the pane border";
        let c = comment_with_response("short comment", resp);
        for line in render_box(&c, wrap_w) {
            assert!(
                line.chars().count() <= inner_w,
                "rendered line {:?} ({} cols) exceeds inner_w {}",
                line,
                line.chars().count(),
                inner_w
            );
        }
    }

    #[test]
    fn comment_box_height_matches_rendered_line_count() {
        let wrap_w = 24usize;
        let resp = "multi line response text long enough to wrap onto several \
                    lines so the height calc and the renderer must agree exactly";
        let body = "comment body that itself wraps onto two or more lines here";
        let c = comment_with_response(body, resp);
        let rendered = render_box(&c, wrap_w);
        assert_eq!(
            rendered.len(),
            comment_box_height(&c, wrap_w),
            "height calc must equal rendered line count or scrolling drifts"
        );
    }

    fn app_with_diff() -> App {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "let x = 1;".into(),
                old_lineno: None,
                new_lineno: Some(1),
            },
        ]);
        app
    }

    #[test]
    fn status_row_shows_search_input() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        app.focus = Pane::Diff;
        app.search_input = Some("foo".into());
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("/foo"),
            "status row should show the /-prefixed query while typing"
        );
    }

    #[test]
    fn render_with_active_search_is_stable() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        app.focus = Pane::Diff;
        app.search = Some(crate::app::SearchState {
            query: "let".into(),
            matches: vec![1],
            cur: 0,
        });
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!dump.is_empty());
        assert!(dump.contains("let x = 1;"));
    }

    #[test]
    fn diff_title_shows_history_revision() {
        use crate::app::{CommentScope, FileHistory};
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        app.selected = 1;
        app.focus = Pane::Diff;
        app.history = Some(FileHistory {
            file: std::path::PathBuf::from("a.rs"),
            commits: vec![crate::git::CommitInfo {
                id: "deadbeefcafebabe".into(),
                short: "deadbeef".into(),
                summary: "old change".into(),
                author: "t".into(),
                time: "2024-01-01".into(),
            }],
            idx: 1,
            baseline_scope: CommentScope::Worktree,
        });
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("deadbeef"), "title should show short sha");
        assert!(dump.contains("1/1"), "title should show revision position");
        assert!(dump.contains("old change"), "title should show summary");
    }

    #[test]
    fn render_does_not_panic_and_shows_file() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let app = app_with_diff();
        terminal.draw(|f| render(f, &app)).unwrap();
        let buf = terminal.backend().buffer().clone();
        let dump: String = buf.content().iter().map(|c| c.symbol()).collect();
        assert!(dump.contains("a.rs"));
        assert!(dump.contains(""));
    }

    #[test]
    fn diff_scroll_start_center_places_cursor_mid_viewport() {
        let rh = |_| 1usize;
        // page 10, cursor 15 -> ~4 lines above -> start 11
        assert_eq!(diff_scroll_start_center(15, 10, &rh), 11);
        // early cursor: clamped to top
        assert_eq!(diff_scroll_start_center(2, 10, &rh), 0);
    }

    #[test]
    fn diff_scroll_start_follow_places_cursor_at_bottom() {
        let rh = |_| 1usize;
        // page 10, cursor 15 -> start 6 (lines 6..=15 fill the page)
        assert_eq!(diff_scroll_start_follow(15, 10, &rh), 6);
    }

    #[test]
    fn history_mode_scrolls_cursor_toward_center() {
        use crate::app::{CommentScope, FileHistory};
        use ratatui::layout::Rect;
        let backend = TestBackend::new(80, 12);
        let mut terminal = Terminal::new(backend).unwrap();
        let diff_area = Rect::new(0, 0, 80, 8); // page = 6 diff lines
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        let mut diff_lines = vec![DiffLine {
            kind: LineKind::Hunk,
            text: "@@".into(),
            old_lineno: None,
            new_lineno: None,
        }];
        for i in 0..20u32 {
            diff_lines.push(DiffLine {
                kind: LineKind::Context,
                text: format!("LINE_{i}"),
                old_lineno: Some(i + 1),
                new_lineno: Some(i + 1),
            });
        }
        app.set_diff(diff_lines);
        // Index 19 = LINE_18 (index 0 is the hunk header).
        app.diff_cursor = 19;

        // Default (follow): LINE_13 visible; centered history mode hides it.
        terminal.draw(|f| render_diff(f, &app, diff_area)).unwrap();
        let follow_dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            follow_dump.contains("LINE_13"),
            "follow scroll should include LINE_13 above cursor"
        );

        app.history = Some(FileHistory {
            file: PathBuf::from("a.rs"),
            commits: vec![crate::git::CommitInfo {
                id: "abc".into(),
                short: "abc".into(),
                summary: "s".into(),
                author: "t".into(),
                time: "2024".into(),
            }],
            idx: 1,
            baseline_scope: CommentScope::Worktree,
        });

        terminal.draw(|f| render_diff(f, &app, diff_area)).unwrap();
        let center_dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            !center_dump.contains("LINE_13"),
            "centered history scroll should hide LINE_13"
        );
        assert!(
            center_dump.contains("LINE_16"),
            "centered history scroll should show lines nearer the cursor"
        );
        assert!(
            center_dump.contains("LINE_18"),
            "centered history scroll must show the cursor line"
        );
    }

    #[test]
    fn scroll_offset_hides_earlier_lines() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        // With the cursor near the end, the viewport scrolls so earlier lines are not rendered.
        app.set_diff({
            let mut lines = vec![crate::app::DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            }];
            // Add 18 context lines after hunk so page=18 and cursor=18 scrolls past the hunk.
            for i in 1..=18u32 {
                lines.push(crate::app::DiffLine {
                    kind: LineKind::Add,
                    text: "let x = 1;".into(),
                    old_lineno: None,
                    new_lineno: Some(i),
                });
            }
            lines
        });
        // With page=18, cursor=18 -> scroll = 18+1-18 = 1, so hunk at index 0 is hidden.
        app.diff_cursor = 18;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!dump.contains("@@ -1 +1 @@"));
        assert!(dump.contains("let x = 1;"));
    }

    #[test]
    fn empty_diff_shows_placeholder() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("No changes"));
    }

    #[test]
    fn hscroll_offsets_diff_text() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![DiffLine {
            kind: LineKind::Context,
            text: "ABCDEFGHIJ".into(),
            old_lineno: Some(1),
            new_lineno: Some(1),
        }]);
        // no scroll: "ABCDEF..." visible
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump0: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump0.contains("ABCDEFGHIJ"));
        // scroll right 4: leading "ABCD" gone, "EFGHIJ" remains
        app.diff_hscroll = 4;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump1: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump1.contains("EFGHIJ"));
        assert!(!dump1.contains("ABCDEFGHIJ"));
    }

    #[test]
    fn diff_shows_line_numbers() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "ctx".into(),
                old_lineno: Some(7),
                new_lineno: Some(7),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "added".into(),
                old_lineno: None,
                new_lineno: Some(8),
            },
            DiffLine {
                kind: LineKind::Del,
                text: "removed".into(),
                old_lineno: Some(5),
                new_lineno: None,
            },
        ]);
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains('7'), "context line number 7 missing");
        assert!(dump.contains('8'), "add line number 8 missing");
        assert!(dump.contains('5'), "del line number 5 missing");
        assert!(dump.contains("ctx"), "context text missing");
        assert!(dump.contains("added"), "add text missing");
        assert!(dump.contains("removed"), "del text missing");
    }

    #[test]
    fn tree_view_shows_dir_and_basenames() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![
            FileChange {
                path: PathBuf::from("src/main.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("top.rs"),
                status: Status::Modified,
            },
        ];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("src"),
            "directory name 'src' missing from tree view"
        );
        assert!(
            dump.contains("main.rs"),
            "file basename 'main.rs' missing from tree view"
        );
        assert!(
            dump.contains("top.rs"),
            "file basename 'top.rs' missing from tree view"
        );
        assert!(
            !dump.contains("src/main.rs"),
            "full path 'src/main.rs' should not appear; tree view shows basenames"
        );
    }

    #[test]
    fn reviewed_file_shows_tick() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // select a.rs row (row 1) and review it
        app.selected = 1;
        app.toggle_reviewed(); // review a.rs
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains(""));
    }

    #[test]
    fn both_sections_headers_render_when_both_non_empty() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let unstaged = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let staged = vec![FileChange {
            path: PathBuf::from("b.rs"),
            status: Status::Added,
        }];
        let app = App::new(unstaged, staged, PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("Unstaged"), "Unstaged header missing");
        assert!(dump.contains("Staged"), "Staged header missing");
        assert!(dump.contains("a.rs"), "a.rs missing");
        assert!(dump.contains("b.rs"), "b.rs missing");
    }

    #[test]
    fn files_title_has_no_mode_label() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The block title shows the tab bar with Changes and Commits tabs.
        // In Changes mode, Changes tab is active (in brackets).
        assert!(dump.contains("Changes"), "Changes tab missing from title");
        assert!(dump.contains("Commits"), "Commits tab missing from title");
        assert!(
            !dump.contains("STAGED"),
            "[STAGED] mode label should be gone"
        );
        assert!(
            !dump.contains("UNSTAGED"),
            "[UNSTAGED] mode label should be gone"
        );
    }

    #[test]
    fn hidden_file_pane_shows_only_diff() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("zzz.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_files = false;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!dump.contains("zzz.rs")); // file pane hidden
        assert!(dump.contains("No changes") || dump.contains("Diff")); // diff pane present
    }

    #[test]
    fn modified_file_shows_m_status_letter() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains('M'),
            "Modified file should show 'M' status letter"
        );
        assert!(dump.contains("a.rs"), "filename should still appear");
    }

    #[test]
    fn input_modal_shows_buffer_and_title() {
        use crate::app::InputState;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        app.focus = Pane::Diff;
        app.input = Some(InputState {
            buffer: "hello world".to_string(),
            target_file: PathBuf::from("a.rs"),
            target_line: 1,
            target_hunk: "@@ -1 +1 @@".to_string(),
            anchor_line_text: String::new(),
            anchor_before: vec![],
            anchor_after: vec![],
        });
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("hello world"),
            "modal buffer text must appear"
        );
        assert!(
            dump.contains("Comment"),
            "modal title must contain 'Comment'"
        );
    }

    #[test]
    fn commented_line_shows_comment_text_inline() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs row
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(5),
        }]);
        // attach a comment for a.rs line 5
        app.comments.set(
            PathBuf::from("a.rs"),
            5,
            "@@ -3,4 @@".to_string(),
            "review note here".to_string(),
            "let x = 1;".to_string(),
            vec![],
            vec![],
            0,
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("review note here"),
            "inline comment text must appear below commented line"
        );
    }

    /// FIX 2: comment on a line near the bottom of a small viewport must not be clipped.
    /// Build a diff of 30 context lines + one Add line with a comment. Set the cursor
    /// on the Add line. Use an 80x10 backend (page = 8 visible rows). With the old
    /// scroll formula (diff-index space), the comment would be pushed off screen.
    /// With rendered-height scroll the comment must appear in the buffer.
    #[test]
    fn comment_not_clipped_when_cursor_near_bottom() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 10);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs
        app.focus = Pane::Diff;

        // 30 context lines, then one Add line at new_lineno 31
        let mut diff_lines = Vec::new();
        for i in 1u32..=30 {
            diff_lines.push(DiffLine {
                kind: LineKind::Context,
                text: format!("ctx {}", i),
                old_lineno: Some(i),
                new_lineno: Some(i),
            });
        }
        diff_lines.push(DiffLine {
            kind: LineKind::Add,
            text: "added_line".into(),
            old_lineno: None,
            new_lineno: Some(31),
        });
        app.set_diff(diff_lines);

        // cursor on the Add line (index 30)
        app.diff_cursor = 30;

        // attach a comment to that Add line
        app.comments.set(
            PathBuf::from("a.rs"),
            31,
            "".to_string(),
            "clipping_test_comment".to_string(),
            "added_line".to_string(),
            vec![],
            vec![],
            0,
        );

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("clipping_test_comment"),
            "comment on cursor line must not be clipped even near the viewport bottom"
        );
    }

    /// FIX 1: saving a comment with leading/trailing whitespace must store only the
    /// trimmed text. Verify by setting a padded comment and checking that the rendered
    /// inline comment shows the trimmed text (no surrounding spaces).
    #[test]
    fn trimmed_comment_stored_without_whitespace_padding() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "fn main() {}".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        // Simulate what main.rs does after Fix 1: store the trimmed text.
        let raw = "   trimmed_note   ";
        let trimmed = raw.trim().to_string();
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "".to_string(),
            trimmed,
            "fn main() {}".to_string(),
            vec![],
            vec![],
            0,
        );

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("trimmed_note"),
            "trimmed comment text must appear"
        );
        // The raw padded string (with surrounding spaces) must not be stored/rendered.
        assert!(
            !dump.contains("   trimmed_note   "),
            "padded comment text must not appear"
        );
    }

    #[test]
    fn added_file_shows_a_deleted_shows_d() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![
            FileChange {
                path: PathBuf::from("new.rs"),
                status: Status::Added,
            },
            FileChange {
                path: PathBuf::from("old.rs"),
                status: Status::Deleted,
            },
        ];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains('A'),
            "Added file should show 'A' status letter"
        );
        assert!(
            dump.contains('D'),
            "Deleted file should show 'D' status letter"
        );
    }

    #[test]
    fn resolved_comment_shows_status_and_response() {
        use crate::app::LineKind;
        use crate::comments::CommentStatus;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "fn foo() {}".into(),
            old_lineno: None,
            new_lineno: Some(3),
        }]);
        app.comments.set(
            PathBuf::from("a.rs"),
            3,
            "@@".to_string(),
            "please fix this".to_string(),
            "fn foo() {}".to_string(),
            vec![],
            vec![],
            0,
        );
        app.comments.items[0].status = CommentStatus::Resolved;
        app.comments.items[0].response = Some("Fixed it".to_string());

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("resolved"),
            "resolved status must appear in comment box"
        );
        assert!(
            dump.contains("Fixed it"),
            "agent response must appear in comment box"
        );
    }

    #[test]
    fn stale_comment_shows_outdated_prefix() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let y = 2;".into(),
            old_lineno: None,
            new_lineno: Some(7),
        }]);
        // Insert a stale comment directly
        app.comments.set(
            PathBuf::from("a.rs"),
            7,
            "@@".to_string(),
            "stale note".to_string(),
            "let y = 2;".to_string(),
            vec![],
            vec![],
            0,
        );
        // Mark it stale manually (simulating relocation failure)
        app.comments.items[0].stale = true;

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("outdated"),
            "stale comment must show '(outdated)' prefix"
        );
        assert!(
            dump.contains("stale note"),
            "stale comment text must still appear"
        );
    }

    #[test]
    fn comment_pane_shows_status_header_and_item() {
        let backend = TestBackend::new(160, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Enable comment pane
        app.show_comments = true;
        // Add an Open comment
        app.comments.set(
            PathBuf::from("a.rs"),
            5,
            "@@ -3,4 @@".to_string(),
            "look at this".to_string(),
            "fn foo()".to_string(),
            vec![],
            vec![],
            0,
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The comment pane title must appear
        assert!(dump.contains("Comments"), "comment pane title must appear");
        // The Open status header must appear
        assert!(
            dump.contains("Open") || dump.contains("open"),
            "Open status header must appear"
        );
        // The file basename must appear
        assert!(
            dump.contains("a.rs"),
            "file basename must appear in comment list"
        );
    }

    #[test]
    fn help_hint_renders_in_diff_pane_border() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("? help"),
            "diff pane border must show the '? help' hint"
        );
    }

    #[test]
    fn comment_pane_hidden_by_default() {
        let backend = TestBackend::new(120, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // show_comments is false by default
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "hidden comment".to_string(),
            "fn x()".to_string(),
            vec![],
            vec![],
            0,
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // Comment pane title must NOT appear when show_comments is false
        assert!(
            !dump.contains("hidden comment"),
            "comment text must not appear when pane hidden"
        );
    }

    #[test]
    fn help_overlay_shows_keybindings_title() {
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_help = true;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("Keybindings"),
            "help overlay must show 'Keybindings' title"
        );
    }

    #[test]
    fn help_overlay_shows_theme_toggle_key() {
        let backend = TestBackend::new(80, 50);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_help = true;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("theme"),
            "help overlay must mention theme toggle"
        );
        // Grouped help: category headers must render.
        assert!(
            dump.contains("Navigation"),
            "help overlay must show the Navigation section header"
        );
        assert!(
            dump.contains("History"),
            "help overlay must show the History & search section header"
        );
    }

    #[test]
    fn empty_response_does_not_break_layout() {
        // A comment with an empty-string response must render without a phantom line
        // (regression: rendered-height overcounted, clipping the box bottom).
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs row (row 0=Unstaged header, row 1=File a.rs)
        app.focus = Pane::Diff;
        // place a comment with empty response on a line in the diff
        app.comments.items.push(crate::comments::Comment {
            file: PathBuf::from("a.rs"),
            line: 1,
            hunk: String::new(),
            text: "please fix".into(),
            line_text: "let x = 1;".into(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 1,
            stale: false,
            status: crate::comments::CommentStatus::Open,
            response: Some(String::new()),
            updated: 0,
        });
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // the comment text renders; no panic; "response:" label NOT shown for empty response
        assert!(dump.contains("please fix"));
        assert!(!dump.contains("response:"));
    }

    #[test]
    fn light_theme_renders_without_panic() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        app.theme = crate::theme::Theme::Light;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("a.rs"), "file must appear in light theme");
    }
}