hewdiff 0.5.0

High-performance review-first terminal diff viewer with PR-style comments
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
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
//! TUI application state and render loop.

use crate::comments::model::{CommentStore, LineRange};
use crate::diff::model::{Changeset, LineKind, Side};
use crate::ui::highlight_cache::HighlightCache;
use crate::ui::render_rows::{
    build_rows, build_split_rows, char_width, str_width, take_width, CommentKind, CommentLine,
    ComposerAnchor, ComposerKind, ComposerLine, ComposerSpec, Row, RowKind, SideCell, SplitRow,
    SplitRowKind,
};
use crate::ui::sidebar::{
    base_of, build_sidebar_rows, dir_of, file_comment_state, file_status, SbRow,
};
use crate::ui::theme::theme;
use anyhow::Result;
use crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use ratatui::prelude::*;
use ratatui::widgets::{
    Block, BorderType, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
};
use std::cell::RefCell;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tui_textarea::TextArea;

/// Diff layout: unified (stacked) or split (old | new, like `git delta`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum View {
    Unified,
    Split,
}

/// Which pane keyboard navigation acts on.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Focus {
    Sidebar,
    Diff,
}

const SIDEBAR_WIDTH: u16 = 38;
const MIN_SIDEBAR: u16 = 14;
const MIN_DIFF: u16 = 20;
/// The column separator drawn between the two halves of the split view. Shared
/// by `render_split` and `sync_comment_wrap` so the comment-wrap math can't
/// desync from the rendered layout if the literal ever changes.
const SPLIT_DIVIDER: &str = "";

/// Per-file (additions, deletions) counts for the sidebar.
fn file_stats(changeset: &Changeset) -> Vec<(usize, usize)> {
    changeset
        .files
        .iter()
        .map(|f| {
            let mut adds = 0;
            let mut dels = 0;
            for h in &f.hunks {
                for l in &h.lines {
                    match l.kind {
                        LineKind::Addition => adds += 1,
                        LineKind::Deletion => dels += 1,
                        LineKind::Context => {}
                    }
                }
            }
            (adds, dels)
        })
        .collect()
}

/// Minimal standard base64 (no deps) for OSC 52 clipboard writes.
fn base64(data: &[u8]) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = *chunk.get(1).unwrap_or(&0) as u32;
        let b2 = *chunk.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(T[(n >> 18 & 63) as usize] as char);
        out.push(T[(n >> 12 & 63) as usize] as char);
        out.push(if chunk.len() > 1 {
            T[(n >> 6 & 63) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            T[(n & 63) as usize] as char
        } else {
            '='
        });
    }
    out
}

/// Is `(col, row)` inside `rect`?
fn hit(rect: Rect, col: u16, row: u16) -> bool {
    col >= rect.x && col < rect.x + rect.width && row >= rect.y && row < rect.y + rect.height
}

/// Map a click/drag at terminal `row` on a vertical scrollbar track to a top
/// line index, placing the thumb's top under the cursor. Mirrors ratatui's
/// thumb geometry so the thumb actually follows the pointer.
fn sb_thumb_pos(track_y: u16, track_h: usize, total: usize, viewport: usize, row: u16) -> usize {
    let max_top = total.saturating_sub(viewport);
    if max_top == 0 || track_h == 0 {
        return 0;
    }
    // Thumb length matches the render model below (content_length = max_top + 1,
    // viewport_content_length = viewport): thumb = viewport * track / total.
    let thumb = ((viewport as f32) * (track_h as f32) / (total as f32))
        .round()
        .max(1.0) as usize;
    let span = track_h.saturating_sub(thumb).max(1);
    let off = (row.saturating_sub(track_y) as usize).min(span);
    ((off as f32 / span as f32) * max_top as f32).round() as usize
}

/// Right-pad `s` with spaces so its display width is exactly `w` (no-op when it
/// already meets/exceeds `w`). Use after `elide_left`/`take_width` so a wide
/// glyph can't push the column past `w`.
fn pad_width(s: &str, w: usize) -> String {
    let sw = str_width(s);
    if sw >= w {
        s.to_string()
    } else {
        format!("{s}{}", " ".repeat(w - sw))
    }
}

/// Truncate `s` from the left (keeping the tail) to fit `w` display columns,
/// prefixing an ellipsis when it doesn't fit.
fn elide_left(s: &str, w: usize) -> String {
    if str_width(s) <= w {
        return s.to_string();
    }
    if w <= 1 {
        return "".repeat(w);
    }
    // Keep the widest tail that fits in `w - 1` cells (room for the ellipsis).
    let budget = w - 1;
    let mut tail: std::collections::VecDeque<char> = std::collections::VecDeque::new();
    let mut used = 0usize;
    for c in s.chars().rev() {
        let cw = char_width(c);
        if used + cw > budget {
            break;
        }
        tail.push_front(c);
        used += cw;
    }
    let tail: String = tail.into_iter().collect();
    format!("{tail}")
}

/// A view-independent handle to the selected row, stable across row rebuilds
/// and unified/split switches (raw indices are not).
enum SelKey {
    /// A diff line, keyed by its comment anchor `(file, side, line)`.
    Line(usize, Side, u32),
    /// A comment message, keyed by its stable id.
    Comment(String),
}

/// What an open composer will write on submit.
enum ComposeTarget {
    /// A brand-new thread anchored to a diff line range (`start == end` for a
    /// single line; a wider span comes from visual line-select mode).
    NewThread {
        file_idx: usize,
        side: Side,
        start: u32,
        end: u32,
    },
    /// A reply appended to an existing thread.
    Reply { thread_id: String },
}

/// In-progress comment text and where it lands. The text + cursor live in a
/// [`TextArea`], used purely as an edit model (readline/emacs keybindings,
/// multi-line cursor, undo) — the box is drawn inline in the diff row stream,
/// not via tui-textarea's own widget.
struct Composer {
    target: ComposeTarget,
    textarea: TextArea<'static>,
}

/// Zero-width marker spliced in at the composer's cursor position. It is a
/// non-control format char, so it survives `sanitize_line`; being zero-width,
/// it never consumes a cell during wrapping (so moving the cursor can't reflow
/// the text) and it is never emitted to the terminal — the renderer finds it,
/// drops it, and draws the cursor as a *reversed* overlay on the cell under it.
const COMPOSER_CARET: char = '\u{2060}';

/// The composer body as a single string with the caret glyph spliced in at the
/// cursor position, ready for the row builder to wrap. A `TextArea` always has
/// at least one line, so the cursor row is always valid.
///
/// Built in one pass over `ta.lines()` (pushing line slices, not cloning each
/// line into a `Vec<String>`): this runs on every row rebuild — i.e. per
/// keystroke — so the per-line clone + join is worth avoiding.
fn body_with_caret(ta: &TextArea<'static>) -> String {
    let (row, col) = ta.cursor();
    let lines = ta.lines();
    let cap =
        lines.iter().map(|l| l.len()).sum::<usize>() + lines.len() + COMPOSER_CARET.len_utf8();
    let mut out = String::with_capacity(cap);
    for (i, line) in lines.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        if i == row {
            // `col` is a char index; translate to a byte offset to splice.
            let byte = line
                .char_indices()
                .nth(col)
                .map(|(b, _)| b)
                .unwrap_or(line.len());
            out.push_str(&line[..byte]);
            out.push(COMPOSER_CARET);
            out.push_str(&line[byte..]);
        } else {
            out.push_str(line);
        }
    }
    out
}

/// A clickable on-screen button's effect. Recorded with the button's screen
/// `Rect` during render (see `App::button_hits`) and dispatched on left-click.
/// Thread/comment ids are captured so a click acts on *that* box regardless of
/// where the keyboard cursor currently sits.
#[derive(Clone, Debug)]
enum ButtonAction {
    /// Start a new comment on the current diff-line selection (same as `i`).
    AddComment,
    /// Submit the open composer (same as Ctrl+S).
    Submit,
    /// Cancel the open composer (same as Esc).
    Cancel,
    /// Reply to the given thread.
    Reply(String),
    /// Toggle resolved on the given thread.
    ToggleResolve(String),
    /// Delete a session-added comment (thread_id, comment_id).
    Delete(String, String),
}

/// Diff/review TUI state. Comments are loaded from a sidecar (immutable),
/// displayed and navigated inline, and mutated in place
/// (compose/reply/resolve/delete); on exit the final store is diffed against
/// the base into an action log.
pub struct App {
    changeset: Arc<Changeset>,
    rows: Vec<Row>,
    comments: CommentStore,
    /// Comment ids present at load (from the input sidecar). These are
    /// immutable: `D` deletes a single comment, and only ones added in-session,
    /// so an input comment is never removed and the action log never emits a
    /// delete (an in-session add+delete cancels out of the diff).
    base_comment_ids: HashSet<String>,
    split_rows: Vec<SplitRow>,
    view: View,
    selected: usize, // index into the active row list
    scroll: usize,   // top row of viewport
    height: usize,   // last known viewport height
    status: String,
    needs_clear: bool,
    show_sidebar: bool,
    sidebar_width: u16,
    sidebar_scroll: usize, // top file row of the sidebar (independent of selection)
    sidebar_sel: usize,    // cursor row in the sidebar (a Dir or File row)
    collapsed: HashSet<String>, // directory paths collapsed in the sidebar tree
    comment_wrap: usize,   // width used to wrap inline comment bodies
    resizing: bool,        // dragging the sidebar/diff divider
    focus: Focus,
    current_file: usize,          // the diff pane shows only this file
    sidebar_rows: Vec<SbRow>,     // file list grouped by directory
    file_to_sbrow: Vec<usize>,    // file_idx -> index into sidebar_rows
    sel_anchor: Option<usize>,    // drag-selection anchor (cursor = `selected`)
    pending_copy: Option<String>, // text to push to the clipboard next frame
    file_stats: Vec<(usize, usize)>,
    diff_area: Rect,        // last-drawn diff pane rect (for mouse hit-testing)
    sidebar_area: Rect,     // last-drawn sidebar rect (zero-sized when hidden)
    diff_sb: Rect,          // diff scrollbar track (zero-sized when none)
    sidebar_sb: Rect,       // sidebar scrollbar track (zero-sized when none)
    sb_drag: Option<Focus>, // which scrollbar is being dragged
    /// Clickable button regions recorded during the last render (the inline
    /// composer's submit/cancel and a thread box's reply/resolve/delete), so a
    /// left-click can be mapped to its action. Rebuilt every frame; uses
    /// interior mutability because the render path is `&self`.
    button_hits: RefCell<Vec<(Rect, ButtonAction)>>,
    /// Syntax-highlight cache + background warm worker (see [`HighlightCache`]).
    hl: HighlightCache,
    /// Cached `[start, end)` row span of `current_file` (see `file_range`).
    file_span: (usize, usize),
    /// `[start, end)` row span of every file in the *active* row list, indexed
    /// by file_idx. Rebuilt in one O(rows) pass whenever the row list or view
    /// changes, so a file switch is an O(1) lookup instead of a full scan.
    file_spans: Vec<(usize, usize)>,
    composer: Option<Composer>,
    /// Visual line-select mode: movement keeps `sel_anchor` so the user can
    /// grow a multi-line selection (then `i` anchors a comment to the range).
    visual: bool,
    quit: bool,
}

impl App {
    /// Consume the app and return the final in-memory review store, so the
    /// caller can diff it against the immutable base to produce the action log.
    pub fn into_comments(self) -> CommentStore {
        self.comments
    }

    /// Construct with a pre-loaded comment store (e.g. from a sidecar JSON).
    pub fn with_comments(changeset: Changeset, comments: CommentStore) -> Self {
        // Comment threads always render expanded inline.
        let rows = build_rows(&changeset, &comments, 0, None);
        let split_rows = build_split_rows(&changeset, &comments, 0, None);
        // Snapshot every loaded comment id: these came from the input sidecar
        // and are protected from deletion (only in-session comments can be
        // removed).
        let base_comment_ids: HashSet<String> = comments
            .threads
            .iter()
            .flat_map(|t| t.comments.iter().map(|c| c.id.clone()))
            .collect();
        let stats = file_stats(&changeset);
        let collapsed = HashSet::new();
        let (sidebar_rows, file_to_sbrow) = build_sidebar_rows(&changeset, &collapsed);
        let changeset = Arc::new(changeset);
        let hl = HighlightCache::new(changeset.clone());
        let mut app = App {
            changeset,
            rows,
            split_rows,
            view: View::Split,
            comments,
            base_comment_ids,
            selected: 0,
            scroll: 0,
            height: 1,
            status: String::new(),
            needs_clear: false,
            show_sidebar: true,
            sidebar_width: SIDEBAR_WIDTH,
            sidebar_scroll: 0,
            sidebar_sel: file_to_sbrow
                .iter()
                .copied()
                .find(|&r| r != usize::MAX)
                .unwrap_or(0),
            collapsed,
            comment_wrap: 0,
            resizing: false,
            focus: Focus::Sidebar,
            current_file: 0,
            sidebar_rows,
            file_to_sbrow,
            sel_anchor: None,
            pending_copy: None,
            file_stats: stats,
            diff_area: Rect::default(),
            sidebar_area: Rect::default(),
            diff_sb: Rect::default(),
            sidebar_sb: Rect::default(),
            sb_drag: None,
            button_hits: RefCell::new(Vec::new()),
            hl,
            file_span: (0, 0),
            file_spans: Vec::new(),
            composer: None,
            visual: false,
            quit: false,
        };
        app.rebuild_file_spans();
        app.recompute_file_span();
        app.selected = app.first_selectable().unwrap_or(0);
        app
    }

    /// Highlighted spans for `text`, truncated/padded to exactly `width` chars,
    /// with an optional background applied to every run (and the padding).
    fn styled_fit(
        &self,
        file_idx: usize,
        text: &str,
        width: usize,
        bg: Option<Color>,
    ) -> Vec<Span<'static>> {
        let hl = self.hl.runs(file_idx, text);
        let mut out = Vec::new();
        let mut used = 0usize;
        for (c, s) in hl.iter() {
            if used >= width {
                break;
            }
            let (take, tw) = take_width(s, width - used);
            if take.is_empty() {
                continue;
            }
            used += tw;
            let mut st = Style::default().fg(*c);
            if let Some(b) = bg {
                st = st.bg(b);
            }
            out.push(Span::styled(take, st));
        }
        if used < width {
            let mut st = Style::default();
            if let Some(b) = bg {
                st = st.bg(b);
            }
            out.push(Span::styled(" ".repeat(width - used), st));
        }
        out
    }

    fn first_selectable(&self) -> Option<usize> {
        let (s, e) = self.file_range();
        (s..e).find(|&i| self.is_stop_at(i))
    }

    fn last_selectable(&self) -> Option<usize> {
        let (s, e) = self.file_range();
        (s..e).rev().find(|&i| self.is_stop_at(i))
    }

    pub fn run(&mut self, terminal: &mut Terminal<impl Backend>) -> Result<()> {
        while !self.quit {
            if self.needs_clear {
                terminal.clear()?;
                self.needs_clear = false;
            }
            terminal.draw(|f| self.draw(f))?;
            // Block for the first event, then drain every event already queued
            // before redrawing. A burst of mouse-drag events thus collapses
            // into a single frame instead of one render per event, which is
            // what made divider drags lag.
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    self.on_key(key.code, key.modifiers);
                }
                Event::Mouse(me) => self.on_mouse(me),
                Event::Paste(text) => self.on_paste(text),
                _ => {}
            }
            while event::poll(Duration::from_millis(0))? {
                match event::read()? {
                    Event::Key(key) if key.kind == KeyEventKind::Press => {
                        self.on_key(key.code, key.modifiers);
                    }
                    Event::Mouse(me) => self.on_mouse(me),
                    Event::Paste(text) => self.on_paste(text),
                    _ => {}
                }
            }
            if let Some(text) = self.pending_copy.take() {
                // OSC 52: write the selection to the terminal clipboard.
                // Target stderr, where the TUI renders; stdout is the JSON
                // result channel and may be redirected to a file.
                use std::io::Write;
                let seq = format!("\x1b]52;c;{}\x07", base64(text.as_bytes()));
                let mut out = std::io::stderr();
                let _ = out.write_all(seq.as_bytes());
                let _ = out.flush();
            }
        }
        Ok(())
    }

    /// Column of the draggable sidebar/diff divider, if the sidebar is shown.
    fn divider_col(&self) -> Option<u16> {
        // The diff panel's left border (just past the sidebar) is the divider.
        (self.sidebar_area.width > 0).then(|| self.sidebar_area.x + self.sidebar_area.width)
    }

    /// Resize the sidebar so its divider sits at column `col`.
    fn resize_to(&mut self, col: u16) {
        let total = self.sidebar_area.width + self.diff_area.width;
        let max = total.saturating_sub(MIN_DIFF).max(MIN_SIDEBAR);
        self.sidebar_width = col
            .saturating_sub(self.sidebar_area.x)
            .clamp(MIN_SIDEBAR, max);
    }

    /// Mouse: wheel scrolls the pane under the pointer; left-click selects;
    /// dragging the divider resizes the sidebar.
    /// The button whose recorded screen rect contains `(col, row)`, if any.
    fn button_at(&self, col: u16, row: u16) -> Option<ButtonAction> {
        self.button_hits
            .borrow()
            .iter()
            .find(|(r, _)| hit(*r, col, row))
            .map(|(_, a)| a.clone())
    }

    /// Run a clicked button's action.
    fn dispatch_button(&mut self, action: ButtonAction) {
        match action {
            ButtonAction::AddComment => self.open_new_thread(),
            ButtonAction::Submit => self.submit_compose(),
            ButtonAction::Cancel => self.cancel_compose(),
            ButtonAction::Reply(tid) => self.open_reply_to(tid),
            ButtonAction::ToggleResolve(tid) => self.toggle_resolved_thread(tid),
            ButtonAction::Delete(tid, cid) => self.delete_comment(tid, cid),
        }
    }

    fn on_mouse(&mut self, me: MouseEvent) {
        // Clickable buttons win over everything else (and work while the
        // composer is open, since its submit/cancel live in the box).
        if let MouseEventKind::Down(MouseButton::Left) = me.kind {
            if let Some(action) = self.button_at(me.column, me.row) {
                self.dispatch_button(action);
                return;
            }
        }
        // The composer modal swallows all other mouse input.
        if self.composer.is_some() {
            return;
        }
        let (col, row) = (me.column, me.row);
        let on_divider = self.divider_col() == Some(col);
        let over_sidebar = self.sidebar_area.width > 0 && hit(self.sidebar_area, col, row);
        match me.kind {
            MouseEventKind::Up(_) => {
                self.resizing = false;
                self.sb_drag = None;
            }
            // Scrollbar thumb drag (start + continue).
            MouseEventKind::Down(MouseButton::Left) if hit(self.diff_sb, col, row) => {
                self.sb_drag = Some(Focus::Diff);
                self.drag_diff_sb(row);
            }
            MouseEventKind::Down(MouseButton::Left) if hit(self.sidebar_sb, col, row) => {
                self.sb_drag = Some(Focus::Sidebar);
                self.drag_sidebar_sb(row);
            }
            // The pane border (rightmost column) is the resize divider.
            MouseEventKind::Down(MouseButton::Left) if on_divider => self.resizing = true,
            MouseEventKind::Drag(MouseButton::Left) if self.sb_drag == Some(Focus::Diff) => {
                self.drag_diff_sb(row)
            }
            MouseEventKind::Drag(MouseButton::Left) if self.sb_drag == Some(Focus::Sidebar) => {
                self.drag_sidebar_sb(row)
            }
            MouseEventKind::Drag(MouseButton::Left) if self.resizing => self.resize_to(col),
            // Wheel scrolls the pane under the pointer. Over the sidebar it
            // moves the list only — selection/focus are left untouched.
            MouseEventKind::ScrollDown => {
                if over_sidebar {
                    self.scroll_sidebar(3);
                } else {
                    self.focus = Focus::Diff;
                    self.scroll_view(3);
                }
            }
            MouseEventKind::ScrollUp => {
                if over_sidebar {
                    self.scroll_sidebar(-3);
                } else {
                    self.focus = Focus::Diff;
                    self.scroll_view(-3);
                }
            }
            MouseEventKind::Down(MouseButton::Left) => {
                if over_sidebar {
                    self.click_sidebar(row);
                } else if hit(self.diff_area, col, row) {
                    self.click_diff(row, true);
                }
            }
            // Drag in the diff extends the line selection.
            MouseEventKind::Drag(MouseButton::Left) if hit(self.diff_area, col, row) => {
                self.click_diff(row, false);
            }
            _ => {}
        }
    }

    /// Inclusive `[lo, hi]` row span of the current selection: the cursor line
    /// alone, or the cursor-to-anchor range when a drag/visual selection is
    /// active. The single source of truth for selection extent.
    fn selection_bounds(&self) -> (usize, usize) {
        let anchor = self.sel_anchor.unwrap_or(self.selected);
        (anchor.min(self.selected), anchor.max(self.selected))
    }

    /// Whether row `idx` falls within the current selection. When the cursor is
    /// on a comment, the whole message (its contiguous rows) is the selection;
    /// otherwise it's the diff-line cursor/drag range.
    fn in_selection(&self, idx: usize) -> bool {
        if let Some((lo, hi)) = self.comment_unit_span(self.selected) {
            return idx >= lo && idx <= hi;
        }
        let (lo, hi) = self.selection_bounds();
        idx >= lo && idx <= hi
    }

    /// The code text of row `idx` (sign stripped / new side), if it's a line.
    fn line_text(&self, idx: usize) -> Option<String> {
        match self.view {
            View::Unified => match self.rows.get(idx)?.kind {
                RowKind::Line { .. } => {
                    let t = &self.rows[idx].text;
                    Some(t.get(1..).unwrap_or("").to_string())
                }
                _ => None,
            },
            View::Split => match &self.split_rows.get(idx)?.kind {
                SplitRowKind::Pair { left, right } => {
                    right.as_ref().or(left.as_ref()).map(|c| c.text.clone())
                }
                _ => None,
            },
        }
    }

    /// Copy the selection to the system clipboard (via OSC 52 next frame): the
    /// focused comment's body when a comment is selected, else the diff lines.
    fn copy_selection(&mut self) {
        if let Some((thread_id, comment_id)) = self.focused_comment() {
            if let Some(body) = self
                .comments
                .threads
                .iter()
                .find(|t| t.id == thread_id)
                .and_then(|t| {
                    t.comments
                        .iter()
                        .find(|c| c.id == comment_id)
                        .map(|c| c.body.clone())
                })
            {
                self.status = "copied comment".into();
                self.pending_copy = Some(body);
            }
            return;
        }
        let (lo, hi) = self.selection_bounds();
        let lines: Vec<String> = (lo..=hi).filter_map(|i| self.line_text(i)).collect();
        if lines.is_empty() {
            return;
        }
        self.status = format!("copied {} line(s)", lines.len());
        self.pending_copy = Some(lines.join("\n"));
    }

    /// Map a scrollbar drag at terminal `row` to a scroll position.
    fn drag_diff_sb(&mut self, row: u16) {
        let (start, end) = self.file_range();
        let total = end - start;
        let pos = sb_thumb_pos(
            self.diff_sb.y,
            self.diff_sb.height as usize,
            total,
            self.height,
            row,
        );
        self.scroll = start + pos;
    }

    fn drag_sidebar_sb(&mut self, row: u16) {
        let h = self.sidebar_sb.height as usize;
        self.sidebar_scroll = sb_thumb_pos(self.sidebar_sb.y, h, self.sidebar_rows.len(), h, row);
    }

    /// Scroll the file list independently of the selection.
    fn scroll_sidebar(&mut self, delta: isize) {
        let h = self.sidebar_area.height as usize;
        let max = self.sidebar_rows.len().saturating_sub(h);
        self.sidebar_scroll =
            (self.sidebar_scroll as isize + delta).clamp(0, max as isize) as usize;
    }

    /// Scroll the list so the sidebar cursor row is visible.
    fn reveal_sidebar(&mut self) {
        let h = self.sidebar_area.height as usize;
        if h == 0 {
            return;
        }
        let r = self
            .sidebar_sel
            .min(self.sidebar_rows.len().saturating_sub(1));
        // Include the row just above (dir header / parent file) when present.
        let target = r.saturating_sub(1);
        if target < self.sidebar_scroll {
            self.sidebar_scroll = target;
        } else if r >= self.sidebar_scroll + h {
            self.sidebar_scroll = r + 1 - h;
        }
    }

    /// Rebuild the sidebar tree from the current collapse set.
    fn rebuild_sidebar(&mut self) {
        let (sr, map) = build_sidebar_rows(&self.changeset, &self.collapsed);
        self.sidebar_rows = sr;
        self.file_to_sbrow = map;
        // The row count shrank/grew; keep the scroll within bounds so clicks and
        // rendering agree.
        let h = self.sidebar_area.height as usize;
        let max = self.sidebar_rows.len().saturating_sub(h);
        self.sidebar_scroll = self.sidebar_scroll.min(max);
    }

    /// Expand every ancestor directory of `fi` so its row is visible.
    fn reveal_file_in_tree(&mut self, fi: usize) {
        let Some(f) = self.changeset.files.get(fi) else {
            return;
        };
        let dir = dir_of(f.display_path());
        if dir.is_empty() {
            return;
        }
        let segs: Vec<&str> = dir.split('/').collect();
        let mut changed = false;
        for d in 0..segs.len() {
            if self.collapsed.remove(&segs[..=d].join("/")) {
                changed = true;
            }
        }
        if changed {
            self.rebuild_sidebar();
        }
    }

    /// Open or close directory `path`, keeping the cursor on its row.
    fn set_dir_collapsed(&mut self, path: String, collapsed: bool) {
        let changed = if collapsed {
            self.collapsed.insert(path.clone())
        } else {
            self.collapsed.remove(&path)
        };
        if !changed {
            return;
        }
        self.rebuild_sidebar();
        if let Some(r) = self
            .sidebar_rows
            .iter()
            .position(|row| matches!(row, SbRow::Dir { path: p, .. } if *p == path))
        {
            self.sidebar_sel = r;
        }
        self.sidebar_sel = self
            .sidebar_sel
            .min(self.sidebar_rows.len().saturating_sub(1));
        self.reveal_sidebar();
    }

    /// Toggle the directory under the cursor (no-op on file rows).
    fn toggle_dir(&mut self, path: String) {
        let collapsed = self.collapsed.contains(&path);
        self.set_dir_collapsed(path, !collapsed);
    }

    /// Collapse (`collapse = true`) or expand the directory under the cursor.
    /// Collapsing while on a file row closes its containing folder and
    /// moves the cursor onto that folder.
    fn fold_dir(&mut self, collapse: bool) {
        match self.sidebar_rows.get(self.sidebar_sel) {
            Some(SbRow::Dir { path, .. }) => {
                let path = path.clone();
                // ← on an already-closed folder closes its container instead.
                if collapse && self.collapsed.contains(&path) {
                    let parent = dir_of(&path);
                    if !parent.is_empty() {
                        self.set_dir_collapsed(parent.to_string(), true);
                    }
                } else {
                    self.set_dir_collapsed(path, collapse);
                }
            }
            Some(SbRow::File { idx, .. }) if collapse => {
                let fi = *idx;
                if let Some(parent) = self.parent_dir_of_file(fi) {
                    self.set_dir_collapsed(parent, true);
                }
            }
            _ => {}
        }
    }

    /// The immediate containing directory of file `fi`, if it lives in one.
    fn parent_dir_of_file(&self, fi: usize) -> Option<String> {
        let f = self.changeset.files.get(fi)?;
        let dir = dir_of(f.display_path());
        (!dir.is_empty()).then(|| dir.to_string())
    }

    /// Toggle the directory under the cursor open/closed.
    fn fold_dir_toggle(&mut self) {
        if let Some(SbRow::Dir { path, .. }) = self.sidebar_rows.get(self.sidebar_sel) {
            let path = path.clone();
            self.toggle_dir(path);
        }
    }

    /// Move the sidebar cursor to the next/prev row and act on it. Every tree
    /// row (dir, file) is a valid landing spot, so this is a simple clamped step.
    fn move_sidebar(&mut self, dir: isize) {
        let n = self.sidebar_rows.len();
        let next = self.sidebar_sel as isize + dir;
        if next < 0 || next as usize >= n {
            return;
        }
        self.sidebar_sel = next as usize;
        self.activate_sidebar();
    }

    /// Jump the sidebar cursor to the first/last row.
    fn sidebar_edge(&mut self, last: bool) {
        let n = self.sidebar_rows.len();
        if n == 0 {
            return;
        }
        self.sidebar_sel = if last { n - 1 } else { 0 };
        self.activate_sidebar();
    }

    /// Apply the row under the sidebar cursor: switch to the file it names.
    fn activate_sidebar(&mut self) {
        // Directory rows are just a cursor resting spot during navigation;
        // they toggle only on explicit activation.
        if let Some(SbRow::File { idx, .. }) = self.sidebar_rows.get(self.sidebar_sel) {
            let fi = *idx;
            if fi != self.current_file {
                self.set_current_file(fi);
            }
            self.reveal_sidebar();
        }
    }

    fn click_sidebar(&mut self, row: u16) {
        let off = row.saturating_sub(self.sidebar_area.y) as usize;
        // Mirror render's clamp so clicks map to the row actually drawn.
        let h = self.sidebar_area.height as usize;
        let max = self.sidebar_rows.len().saturating_sub(h);
        let scroll = self.sidebar_scroll.min(max);
        let idx = scroll + off;
        match self.sidebar_rows.get(idx) {
            Some(SbRow::Dir { path, .. }) => {
                let path = path.clone();
                self.focus = Focus::Sidebar;
                self.sidebar_sel = idx;
                self.toggle_dir(path);
            }
            Some(SbRow::File { idx: fi, .. }) => {
                let fi = *fi;
                self.focus = Focus::Sidebar;
                self.set_current_file(fi);
            }
            None => {}
        }
    }

    /// Rebuild the diff row lists from the changeset + inline comment threads,
    /// keeping the cursor on the same (file, side, line) anchor.
    fn rebuild_rows(&mut self) {
        let key = self.sel_key();
        let cur_file = self.current_file;
        let composer = self.composer_spec();
        self.rows = build_rows(
            &self.changeset,
            &self.comments,
            self.comment_wrap,
            composer.as_ref(),
        );
        self.split_rows = build_split_rows(
            &self.changeset,
            &self.comments,
            self.comment_wrap,
            composer.as_ref(),
        );
        // Rows changed; recompute every file's span, then the current one,
        // before first_selectable/ensure_visible read it.
        self.rebuild_file_spans();
        self.recompute_file_span();
        let target = key.as_ref().and_then(|k| self.find_sel_key(k));
        self.selected = target
            .or_else(|| self.first_selectable())
            .unwrap_or(0)
            .min(self.active_len().saturating_sub(1));
        self.current_file = self.row_file_idx(self.selected).unwrap_or(cur_file);
        self.recompute_file_span();
        self.ensure_visible();
    }

    /// A stable handle to the current selection that survives a row rebuild or
    /// a view switch: the focused comment's message id, else the diff-line
    /// anchor `(file, side, line)`.
    fn sel_key(&self) -> Option<SelKey> {
        if let Some((_, cid)) = self.focused_comment() {
            return Some(SelKey::Comment(cid));
        }
        self.anchor_at(self.selected)
            .map(|(f, s, l)| SelKey::Line(f, s, l))
    }

    /// Re-find the row matching `key` in the (freshly rebuilt) active list.
    fn find_sel_key(&self, key: &SelKey) -> Option<usize> {
        (0..self.active_len()).find(|&i| match key {
            SelKey::Line(f, s, l) => {
                self.is_selectable_at(i) && self.anchor_at(i) == Some((*f, *s, *l))
            }
            SelKey::Comment(cid) => {
                self.is_stop_at(i)
                    && self.comment_unit_at(i).map(|(_, c)| c).as_deref() == Some(cid.as_str())
            }
        })
    }

    /// Translate the live composer into a row-stream injection spec (where the
    /// box renders inline + its title), or `None` when no composer is open.
    fn composer_spec(&self) -> Option<ComposerSpec> {
        let c = self.composer.as_ref()?;
        let (anchor, title) = match &c.target {
            ComposeTarget::NewThread {
                file_idx,
                side,
                start: _,
                end,
            } => {
                // The box renders right under the selected line(s), so the
                // file/range is obvious from context — keep the title bare.
                (
                    ComposerAnchor::NewThread {
                        file_idx: *file_idx,
                        side: *side,
                        // Anchor the composer after the *last* line of the
                        // range (GitHub-style), matching where the resulting
                        // thread box renders (see `last_anchor_lines`).
                        line: *end,
                    },
                    " new comment ".into(),
                )
            }
            ComposeTarget::Reply { thread_id } => (
                ComposerAnchor::Reply {
                    thread_id: thread_id.clone(),
                },
                " reply ".into(),
            ),
        };
        Some(ComposerSpec {
            anchor,
            title,
            body: body_with_caret(&c.textarea),
        })
    }

    /// Whether the active row at `i` is a line of the inline composer box.
    fn is_composer_at(&self, i: usize) -> bool {
        match self.view {
            View::Unified => matches!(
                self.rows.get(i).map(|r| &r.kind),
                Some(RowKind::Composer(_))
            ),
            View::Split => matches!(
                self.split_rows.get(i).map(|r| &r.kind),
                Some(SplitRowKind::Composer { .. })
            ),
        }
    }

    /// Whether the active row at `i` is the composer body row that carries the
    /// caret glyph. With cursor movement the caret can sit on any wrapped body
    /// line (not just the last), so scrolling keys off the glyph itself.
    fn is_composer_caret_at(&self, i: usize) -> bool {
        let body = match self.view {
            View::Unified => match self.rows.get(i).map(|r| &r.kind) {
                Some(RowKind::Composer(ComposerLine {
                    kind: ComposerKind::Body(s),
                })) => s,
                _ => return false,
            },
            View::Split => match self.split_rows.get(i).map(|r| &r.kind) {
                Some(SplitRowKind::Composer {
                    line:
                        ComposerLine {
                            kind: ComposerKind::Body(s),
                        },
                    ..
                }) => s,
                _ => return false,
            },
        };
        body.contains(COMPOSER_CARET)
    }

    /// Scroll so the (contiguous) inline composer box is in view, anchored to
    /// the body row carrying the caret. The cursor can be on any line now, so
    /// when the box is taller than the viewport we keep the caret row on screen
    /// rather than pinning the top or the bottom.
    fn ensure_composer_visible(&mut self) {
        let (s, e) = self.file_range();
        let Some(first) = (s..e).find(|&i| self.is_composer_at(i)) else {
            return;
        };
        let last = (first..e)
            .take_while(|&i| self.is_composer_at(i))
            .last()
            .unwrap_or(first);
        // Anchor scroll to the row carrying the caret glyph (the cursor line),
        // wherever it is in the box — falling back to the last row if the glyph
        // somehow isn't found, so we never leave the box fully off-screen.
        let caret = (first..=last)
            .find(|&i| self.is_composer_caret_at(i))
            .unwrap_or(last);
        let height = self.height.max(1);
        // Caret below the fold: scroll down so it's the last visible row.
        if caret >= self.scroll + height {
            self.scroll = (caret + 1).saturating_sub(height).max(s);
        }
        // Caret above the viewport (cursor moved up in a tall box): scroll up to
        // it.
        if caret < self.scroll {
            self.scroll = caret.max(s);
        }
        // When the whole box fits, prefer showing its top.
        let fits = last - first < height;
        if first < self.scroll && fits {
            self.scroll = first.max(s);
        }
    }

    /// Open the composer for a new thread anchored to the current selection —
    /// the cursor line, or a multi-line range from visual mode (`v`) or a mouse
    /// drag (see [`Self::selection_range`]).
    fn open_new_thread(&mut self) {
        let Some((file_idx, side, start, end)) = self.selection_range() else {
            self.status = "put the cursor on a diff line first".into();
            return;
        };
        // A drag could be in flight when the composer opens via the keyboard;
        // clear it so the swallowed mouse-up can't leave us stuck mid-drag.
        self.resizing = false;
        self.sb_drag = None;
        self.composer = Some(Composer {
            target: ComposeTarget::NewThread {
                file_idx,
                side,
                start,
                end,
            },
            textarea: TextArea::default(),
        });
        self.status = "new comment — enter for newline, ctrl+s to submit, esc to cancel".into();
        self.rebuild_rows();
        self.ensure_composer_visible();
    }

    /// Open the composer to reply to the focused thread (the comment the cursor
    /// is on, or the thread anchored to the focused diff line).
    fn open_reply(&mut self) {
        let Some(id) = self.focused_thread_id() else {
            self.status = "no comment thread here".into();
            return;
        };
        self.open_reply_to(id);
    }

    /// Open the composer to reply to a specific thread (used by the reply
    /// button, which acts on the clicked box regardless of cursor position).
    fn open_reply_to(&mut self, thread_id: String) {
        self.resizing = false;
        self.sb_drag = None;
        self.composer = Some(Composer {
            target: ComposeTarget::Reply { thread_id },
            textarea: TextArea::default(),
        });
        self.status = "reply — enter for newline, ctrl+s to submit, esc to cancel".into();
        self.rebuild_rows();
        self.ensure_composer_visible();
    }

    /// Cancel the open composer (button equivalent of Esc).
    fn cancel_compose(&mut self) {
        self.composer = None;
        self.visual = false;
        self.sel_anchor = None;
        self.status = "cancelled".into();
        self.rebuild_rows();
    }

    /// Insert pasted text in one shot (bracketed paste). Only meaningful while
    /// the composer is open; elsewhere a paste is ignored rather than being
    /// replayed as commands. A single rebuild keeps a multi-paragraph paste from
    /// triggering one full row rebuild per character.
    fn on_paste(&mut self, text: String) {
        let Some(c) = self.composer.as_mut() else {
            return;
        };
        // Normalize newlines; `insert_str` splits on `\n` into the buffer at the
        // cursor (which then sits after the inserted text).
        c.textarea
            .insert_str(text.replace("\r\n", "\n").replace('\r', "\n"));
        self.rebuild_rows();
        self.ensure_composer_visible();
    }

    /// Keystrokes while the composer modal is open. hew's own chords (submit /
    /// cancel) are handled here; everything else is forwarded to the `TextArea`
    /// model, which provides readline/emacs editing (Ctrl+A/E/B/F/K/U/W,
    /// Alt+B/F, arrows, ↑/↓ line moves, Ctrl+D delete-forward, undo, …).
    fn on_key_compose(&mut self, code: KeyCode, mods: KeyModifiers) {
        let ctrl = mods.contains(KeyModifiers::CONTROL);
        match code {
            // Esc or Ctrl-C cancels without saving. (Ctrl+D is left to the
            // editor as delete-forward, per readline.)
            KeyCode::Esc => {
                self.composer = None;
                self.visual = false;
                self.sel_anchor = None;
                self.status = "cancelled".into();
            }
            KeyCode::Char('c') if ctrl => {
                self.composer = None;
                self.visual = false;
                self.sel_anchor = None;
                self.status = "cancelled".into();
            }
            // Ctrl+S is the primary submit: it's a C0 control byte, so it
            // survives tmux/SSH without any keyboard-protocol negotiation
            // (raw mode clears IXON, so there's no XOFF freeze). Ctrl+Enter is
            // kept as a GitHub-style alias for terminals that forward the kitty
            // keyboard-enhancement protocol (DISAMBIGUATE_ESCAPE_CODES, enabled
            // in `run`); under tmux that protocol is usually swallowed, which is
            // why a protocol-free fallback exists at all. A bare Enter inserts a
            // newline (handled by the editor). Shift+Enter is intentionally not
            // used: the protocol reports ctrl+key but not plain shift+key, so it
            // would be indistinguishable from a bare Enter.
            KeyCode::Char('s') if ctrl => self.submit_compose(),
            KeyCode::Enter if ctrl => self.submit_compose(),
            // Line start / end. tui-textarea binds these to Ctrl+A / Ctrl+E,
            // but its match arms require a lowercase `Char('a')` with no Alt;
            // some terminals (kitty keyboard protocol) report the chord with
            // the Shift bit set or as uppercase, which slips through and does
            // nothing. Drive the move ourselves so the binding is deterministic
            // regardless of how the terminal encodes it.
            KeyCode::Char('a') | KeyCode::Char('A') if ctrl => {
                if let Some(c) = self.composer.as_mut() {
                    c.textarea.move_cursor(tui_textarea::CursorMove::Head);
                }
            }
            KeyCode::Char('e') | KeyCode::Char('E') if ctrl => {
                if let Some(c) = self.composer.as_mut() {
                    c.textarea.move_cursor(tui_textarea::CursorMove::End);
                }
            }
            // Everything else: hand the key to the edit model. We always rebuild
            // afterward (below) rather than keying off `input()`'s return value:
            // it reports whether the *text* changed, so cursor-only moves (←/→,
            // Ctrl+A/E, ↑/↓, …) return false even though the caret moved and the
            // row stream needs to redraw it.
            _ => {
                let Some(c) = self.composer.as_mut() else {
                    return;
                };
                c.textarea.input(KeyEvent::new(code, mods));
            }
        }
        // The composer is part of the row stream now, so any state change
        // (typed text, cancel) must rebuild rows to reflect it. `submit_compose`
        // already rebuilds; a redundant rebuild here is cheap and harmless.
        self.rebuild_rows();
        if self.composer.is_some() {
            self.ensure_composer_visible();
        }
    }

    /// Commit the composer's text as a new thread or a reply.
    fn submit_compose(&mut self) {
        let Some(c) = self.composer.take() else {
            return;
        };
        let body = c.textarea.lines().join("\n").trim().to_string();
        if body.is_empty() {
            self.status = "empty comment discarded".into();
            return;
        }
        match c.target {
            ComposeTarget::NewThread {
                file_idx,
                side,
                start,
                end,
            } => {
                let Some(file) = self.changeset.files.get(file_idx) else {
                    // Defensive: the anchor's file index should always be valid
                    // (the changeset is fixed for the session).
                    self.status = "comment discarded — unknown file".into();
                    return;
                };
                let path = PathBuf::from(file.display_path());
                self.comments.add_thread(
                    path,
                    side,
                    LineRange { start, end },
                    Some("you".into()),
                    body,
                );
                // Leaving the composer also leaves visual mode.
                self.visual = false;
                self.sel_anchor = None;
                self.status = "added comment".into();
            }
            ComposeTarget::Reply { thread_id } => {
                if self.comments.reply(&thread_id, Some("you".into()), body) {
                    self.status = "added reply".into();
                } else {
                    self.status = "thread no longer exists".into();
                }
            }
        }
        self.rebuild_rows();
    }

    /// The id of the first comment thread anchored to the selected line, if any.
    fn current_thread_id(&self) -> Option<String> {
        let (fi, side, line) = self.anchor_at(self.selected)?;
        let file = self.changeset.files.get(fi)?;
        let path = Path::new(file.display_path());
        self.comments
            .threads
            .iter()
            .find(|t| t.file.as_path() == path && t.side == side && t.range.contains(line))
            .map(|t| t.id.clone())
    }

    /// Toggle the resolved state of the focused thread.
    fn resolve_current_thread(&mut self) {
        let Some(id) = self.focused_thread_id() else {
            self.status = "no comment thread here".into();
            return;
        };
        self.toggle_resolved_thread(id);
    }

    /// Toggle resolved on a specific thread (used by the resolve button).
    fn toggle_resolved_thread(&mut self, id: String) {
        match self.comments.toggle_resolved(&id) {
            Some(true) => self.status = "resolved thread".into(),
            Some(false) => self.status = "unresolved thread".into(),
            None => return,
        }
        self.rebuild_rows();
    }

    /// Delete the focused *comment* — but only if it was added in this session.
    /// The unit of deletion is a single comment (e.g. a reply you wrote), never
    /// a whole thread; removing a thread's last comment drops the thread.
    /// Comments loaded from the input sidecar are immutable, so `D` on one is a
    /// no-op — which is what keeps the action log free of delete actions.
    fn delete_current_comment(&mut self) {
        let Some((thread_id, comment_id)) = self.focused_comment() else {
            self.status = "put the cursor on a comment to delete".into();
            return;
        };
        self.delete_comment(thread_id, comment_id);
    }

    /// Delete a specific session-added comment (used by the delete button).
    fn delete_comment(&mut self, thread_id: String, comment_id: String) {
        if self.base_comment_ids.contains(&comment_id) {
            self.status = "can't delete a comment from the input".into();
            return;
        }
        if self.comments.remove_comment(&thread_id, &comment_id) {
            self.status = "deleted comment".into();
            self.rebuild_rows();
        }
    }

    /// Place the cursor at the clicked diff row. `anchor` starts a new
    /// selection there; otherwise the existing anchor is kept (drag extend).
    fn click_diff(&mut self, row: u16, anchor: bool) {
        self.focus = Focus::Diff;
        let (start, end) = self.file_range();
        let top = self.scroll.max(start);
        let idx = (top + row.saturating_sub(self.diff_area.y) as usize)
            .clamp(start, end.saturating_sub(1).max(start));
        if let Some(i) = self.stop_for(idx) {
            self.selected = i;
            // A drag-range only makes sense between diff lines; landing on a
            // comment selects that one message and drops any range anchor.
            if self.is_selectable_at(i) {
                if anchor {
                    self.sel_anchor = Some(i);
                }
            } else {
                self.sel_anchor = None;
            }
            self.ensure_visible();
        }
    }

    // ---- active-list abstraction (unified vs split) ----

    fn active_len(&self) -> usize {
        match self.view {
            View::Unified => self.rows.len(),
            View::Split => self.split_rows.len(),
        }
    }

    fn is_selectable_at(&self, i: usize) -> bool {
        match self.view {
            View::Unified => self.rows.get(i).is_some_and(|r| r.is_selectable()),
            View::Split => self.split_rows.get(i).is_some_and(|r| r.is_selectable()),
        }
    }

    /// The comment-thread line at row `i`, in whichever view is active.
    fn comment_at(&self, i: usize) -> Option<&CommentLine> {
        match self.view {
            View::Unified => match &self.rows.get(i)?.kind {
                RowKind::Comment(cl) => Some(cl),
                _ => None,
            },
            View::Split => match &self.split_rows.get(i)?.kind {
                SplitRowKind::Comment { line, .. } => Some(line),
                _ => None,
            },
        }
    }

    /// `(thread_id, comment_id)` of the message that row `i` belongs to, if it's
    /// a content line of a comment (author/body/gap). Chrome rows return `None`.
    fn comment_unit_at(&self, i: usize) -> Option<(String, String)> {
        let cl = self.comment_at(i)?;
        Some((cl.thread_id.clone(), cl.comment_id.clone()?))
    }

    /// A "stop" is a place the cursor can land: a diff line, or the *first* row
    /// of a comment message (so a multi-line message is a single stop).
    fn is_stop_at(&self, i: usize) -> bool {
        if self.is_selectable_at(i) {
            return true;
        }
        match self.comment_unit_at(i) {
            // First row of a message: the row above belongs to a different
            // message (or is chrome / a diff line).
            Some((_, cid)) => i == 0 || self.comment_unit_at(i - 1).map(|(_, c)| c) != Some(cid),
            None => false,
        }
    }

    /// Inclusive `[lo, hi]` rows of the comment message covering row `i`, if `i`
    /// is a comment content line. Used to highlight/scroll the whole message.
    fn comment_unit_span(&self, i: usize) -> Option<(usize, usize)> {
        let (_, cid) = self.comment_unit_at(i)?;
        let same =
            |j: usize| self.comment_unit_at(j).map(|(_, c)| c).as_deref() == Some(cid.as_str());
        let mut lo = i;
        while lo > 0 && same(lo - 1) {
            lo -= 1;
        }
        let mut hi = i;
        let len = self.active_len();
        while hi + 1 < len && same(hi + 1) {
            hi += 1;
        }
        Some((lo, hi))
    }

    /// First stop at/beyond `from` scanning in `dir`, within the file.
    fn nearest_stop(&self, from: usize, dir: isize) -> Option<usize> {
        let (start, end) = self.file_range();
        let mut i = from as isize;
        while i >= start as isize && (i as usize) < end {
            if self.is_stop_at(i as usize) {
                return Some(i as usize);
            }
            i += dir;
        }
        None
    }

    /// Map a clicked/landed row to the stop it should select: itself if it's a
    /// stop, the message head if it's inside a message, else the nearest stop.
    fn stop_for(&self, idx: usize) -> Option<usize> {
        if self.is_stop_at(idx) {
            return Some(idx);
        }
        if self.comment_unit_at(idx).is_some() {
            return self.comment_unit_span(idx).map(|(lo, _)| lo);
        }
        self.nearest_stop(idx, 1)
            .or_else(|| self.nearest_stop(idx, -1))
    }

    /// `(thread_id, comment_id)` the cursor is currently on, if it's a comment.
    fn focused_comment(&self) -> Option<(String, String)> {
        self.comment_unit_at(self.selected)
    }

    /// The thread the cursor acts on: the focused comment's thread, else the
    /// thread anchored to the focused diff line.
    fn focused_thread_id(&self) -> Option<String> {
        if let Some(cl) = self.comment_at(self.selected) {
            return Some(cl.thread_id.clone());
        }
        self.current_thread_id()
    }

    /// The file index a row belongs to (header rows included).
    fn row_file_idx(&self, i: usize) -> Option<usize> {
        match self.view {
            View::Unified => self.rows.get(i).map(|r| r.file_idx),
            View::Split => self.split_rows.get(i).map(|r| r.file_idx),
        }
    }

    /// `[start, end)` row range of the current file in the active list. Files
    /// are contiguous, so this is a single slice. Cached (see `file_span`) and
    /// only recomputed when the file, view, or row lists change — it's read on
    /// every keystroke and several times per frame, so the O(rows) scan must
    /// not run on the hot path.
    fn file_range(&self) -> (usize, usize) {
        self.file_span
    }

    /// Recompute the cached current-file row span. Call after any change to
    /// `current_file`, `view`, or the active row list, and before code that
    /// reads `file_range` (navigation, scrolling, rendering).
    fn recompute_file_span(&mut self) {
        let len = self.active_len();
        self.file_span = self
            .file_spans
            .get(self.current_file)
            .copied()
            .unwrap_or((len, len));
    }

    /// Recompute the `[start, end)` row span of *every* file in the active row
    /// list in a single pass. Files emit contiguous row blocks (build order),
    /// so one sweep fills them all; call this whenever the active row list or
    /// view changes. Keeps per-file-switch span lookup O(1).
    fn rebuild_file_spans(&mut self) {
        let n = self.changeset.files.len();
        let len = self.active_len();
        let mut spans = vec![(len, len); n];
        for i in 0..len {
            if let Some(fi) = self.row_file_idx(i) {
                if let Some(span) = spans.get_mut(fi) {
                    if span.0 == len {
                        span.0 = i;
                    }
                    span.1 = i + 1;
                }
            }
        }
        self.file_spans = spans;
    }

    /// Switch the diff pane to the next/prev file.
    fn jump_file(&mut self, dir: isize) {
        let n = self.changeset.files.len();
        if n == 0 {
            return;
        }
        let target = (self.current_file as isize + dir).clamp(0, n as isize - 1) as usize;
        if target == self.current_file {
            return;
        }
        self.set_current_file(target);
    }

    /// Point the diff pane at `file`, resetting the cursor to its top.
    fn set_current_file(&mut self, file: usize) {
        self.sel_anchor = None;
        self.current_file = file.min(self.changeset.files.len().saturating_sub(1));
        self.recompute_file_span();
        // A file in a collapsed directory has no visible row; open its ancestors.
        self.reveal_file_in_tree(self.current_file);
        self.sidebar_sel = self
            .file_to_sbrow
            .get(self.current_file)
            .copied()
            .filter(|&r| r != usize::MAX)
            .unwrap_or(0);
        self.reveal_sidebar();
        let (start, _) = self.file_range();
        self.scroll = start;
        self.selected = self.first_selectable().unwrap_or(start);
        self.ensure_visible();
    }

    /// `(file_idx, side, line)` anchor for the row at `i`, if it carries one.
    fn anchor_at(&self, i: usize) -> Option<(usize, Side, u32)> {
        match self.view {
            View::Unified => {
                let r = self.rows.get(i)?;
                let (s, l) = r.anchor()?;
                Some((r.file_idx, s, l))
            }
            View::Split => {
                let r = self.split_rows.get(i)?;
                let (s, l) = r.anchor()?;
                Some((r.file_idx, s, l))
            }
        }
    }

    /// Toggle between unified and split, keeping the cursor on the same line
    /// (and preserving any multi-line visual selection across the switch).
    fn toggle_view(&mut self) {
        let key = self.sel_key();
        // Remember the selection anchor by its line identity so a multi-line
        // visual/drag selection survives the layout switch instead of
        // collapsing to the cursor line. The anchor is always a diff line.
        let anchor_key = self
            .sel_anchor
            .and_then(|a| self.anchor_at(a))
            .map(|(f, s, l)| SelKey::Line(f, s, l));
        self.view = match self.view {
            View::Unified => View::Split,
            View::Split => View::Unified,
        };
        // The active list switched (unified/split spans differ); recompute all
        // file spans, then the current one, before first_selectable reads it.
        self.rebuild_file_spans();
        self.recompute_file_span();
        // Re-find the same line / comment message in the other layout.
        let target = key.as_ref().and_then(|k| self.find_sel_key(k));
        self.selected = target
            .or_else(|| self.first_selectable())
            .unwrap_or(0)
            .min(self.active_len().saturating_sub(1));
        // Remap the anchor into the new layout. If it can't be found (e.g. the
        // anchored line has no counterpart in this view), drop the selection
        // rather than leave a stale row index dangling.
        self.sel_anchor = anchor_key.as_ref().and_then(|k| self.find_sel_key(k));
        if self.sel_anchor.is_none() {
            self.visual = false;
        }
        // Stay on the same file across the layout switch.
        self.current_file = self
            .row_file_idx(self.selected)
            .unwrap_or(self.current_file);
        self.recompute_file_span();
        // Recenter so the cursor is roughly mid-viewport (clamped to the file).
        self.scroll = self.selected.saturating_sub(self.height / 2);
        self.ensure_visible();
        self.status = match self.view {
            View::Unified => "unified view".into(),
            View::Split => "split view".into(),
        };
    }

    /// Is the file sidebar an actual pane the user can focus?
    fn sidebar_available(&self) -> bool {
        self.show_sidebar && !self.changeset.files.is_empty()
    }

    /// Focus clamped to reality (never Sidebar when there's no sidebar).
    fn effective_focus(&self) -> Focus {
        if self.sidebar_available() {
            self.focus
        } else {
            Focus::Diff
        }
    }

    /// Selection background for the diff pane (dim when it isn't focused).
    fn diff_cursor_bg(&self) -> Color {
        if self.effective_focus() == Focus::Diff {
            theme().cursor_bg
        } else {
            theme().unfocus_bg
        }
    }

    fn on_key(&mut self, code: KeyCode, mods: KeyModifiers) {
        // While composing, the modal owns every keystroke.
        if self.composer.is_some() {
            return self.on_key_compose(code, mods);
        }
        let ctrl = mods.contains(KeyModifiers::CONTROL);
        // Global keys, independent of the focused pane.
        match code {
            // Quit only on q / Ctrl-C (never Esc; Ctrl-D is half-page down).
            KeyCode::Char('q') => return self.quit = true,
            KeyCode::Char('c') if ctrl => return self.quit = true,
            KeyCode::Tab | KeyCode::Char('s') => return self.toggle_view(),
            KeyCode::Char('b') if ctrl => {
                self.show_sidebar = !self.show_sidebar;
                if !self.show_sidebar {
                    self.focus = Focus::Diff;
                }
                return;
            }
            KeyCode::Char('l') if ctrl => return self.needs_clear = true,
            _ => {}
        }
        match self.effective_focus() {
            Focus::Sidebar => self.on_key_sidebar(code),
            Focus::Diff => self.on_key_diff(code, ctrl, mods.contains(KeyModifiers::SHIFT)),
        }
    }

    /// Navigation when the file sidebar (left pane) is focused.
    fn on_key_sidebar(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('j') | KeyCode::Down => self.move_sidebar(1),
            KeyCode::Char('k') | KeyCode::Up => self.move_sidebar(-1),
            KeyCode::Char('g') | KeyCode::Home => self.sidebar_edge(false),
            KeyCode::Char('G') | KeyCode::End => self.sidebar_edge(true),
            // Left/Right (or h/l): toggle the folder open state on a dir row.
            KeyCode::Left | KeyCode::Char('h') => self.fold_dir(true),
            KeyCode::Right | KeyCode::Char('l') => self.fold_dir(false),
            KeyCode::Char(' ') | KeyCode::Char('o') => self.fold_dir_toggle(),
            // Enter: move focus to the right (diff) pane.
            KeyCode::Enter => self.focus = Focus::Diff,
            _ => {}
        }
    }

    /// Navigation when the diff pane is focused.
    fn on_key_diff(&mut self, code: KeyCode, ctrl: bool, shift: bool) {
        let page = self.height.max(1);
        let half = (self.height / 2).max(1);
        // Shift+Up/Down extends a line selection (an alternative to `v` visual
        // mode). Modified arrow keys ride the standard CSI cursor encoding, so
        // they survive tmux/SSH without the kitty protocol — unlike Shift+Enter.
        if shift {
            match code {
                KeyCode::Down => return self.extend_selection(1),
                KeyCode::Up => return self.extend_selection(-1),
                _ => {}
            }
        }
        match code {
            KeyCode::Char('j') | KeyCode::Down => self.move_by(1, 1),
            KeyCode::Char('k') | KeyCode::Up => self.move_by(-1, 1),

            // Half-page down / up: Ctrl-D / Ctrl-U.
            KeyCode::Char('d') if ctrl => self.move_by(1, half),
            KeyCode::Char('u') if ctrl => self.move_by(-1, half),

            // Full page: Space / Ctrl-F / PageDown forward, b / PageUp back.
            KeyCode::Char(' ') | KeyCode::Char('f') | KeyCode::PageDown => self.move_by(1, page),
            KeyCode::Char('b') | KeyCode::PageUp => self.move_by(-1, page),

            // One-line viewport scroll, cursor stays in view: Ctrl-E / Ctrl-Y (less/vim).
            KeyCode::Char('e') if ctrl => self.scroll_view(1),
            KeyCode::Char('y') if ctrl => self.scroll_view(-1),

            // Top / bottom.
            KeyCode::Char('g') | KeyCode::Home => {
                if !self.visual {
                    self.sel_anchor = None;
                }
                self.selected = self.first_selectable().unwrap_or(0);
                self.ensure_visible();
            }
            KeyCode::Char('G') | KeyCode::End => {
                if !self.visual {
                    self.sel_anchor = None;
                }
                self.selected = self.last_selectable().unwrap_or(0);
                self.ensure_visible();
            }

            // Jump between comment threads.
            KeyCode::Char('n') => self.jump_comment(1),
            KeyCode::Char('N') => self.jump_comment(-1),

            // Visual line-select: anchor a comment to a multi-line range.
            KeyCode::Char('v') => self.toggle_visual(),

            // Compose a new thread (i) or reply to the thread here (r).
            KeyCode::Char('i') => self.open_new_thread(),
            KeyCode::Char('r') => self.open_reply(),

            // Resolve/unresolve (R) the thread on this line, or delete (D) the
            // focused comment.
            KeyCode::Char('R') => self.resolve_current_thread(),
            KeyCode::Char('D') => self.delete_current_comment(),

            // Jump between files.
            KeyCode::Char(']') => self.jump_file(1),
            KeyCode::Char('[') => self.jump_file(-1),

            // Copy the selected line(s).
            KeyCode::Char('y') => self.copy_selection(),
            // Esc: drop any drag selection and hand focus back to the sidebar
            // (never quits).
            KeyCode::Esc => {
                self.sel_anchor = None;
                if self.visual {
                    // First Esc just leaves visual mode (keeps focus here).
                    self.visual = false;
                    self.status = "visual off".into();
                } else if self.sidebar_available() {
                    self.focus = Focus::Sidebar;
                }
            }
            _ => {}
        }
    }

    /// Enter/leave visual line-select mode. Entering anchors the selection at
    /// the cursor; leaving drops it.
    fn toggle_visual(&mut self) {
        if self.visual {
            self.visual = false;
            self.sel_anchor = None;
            self.status = "visual off".into();
        } else {
            self.visual = true;
            self.sel_anchor = Some(self.selected);
            self.status = "visual — j/k to extend, i to comment, esc to cancel".into();
        }
    }

    /// Extend the line selection by one row (Shift+Up/Down). Moves only across
    /// selectable *diff lines* (skipping comment rows): a line selection must
    /// stay anchored on diff lines, or `selection_range()` — which reads
    /// `anchor_at(selected)` — would return `None` and `i` (new thread) would
    /// have nothing to anchor to. A no-op when there is no diff line in that
    /// direction.
    ///
    /// Unlike `v`, this does NOT enter persistent visual mode: terminals can't
    /// report Shift key-release, so the heuristic is that the *next* unmodified
    /// movement (plain `j`/`k`) collapses the range (via `move_selection`'s
    /// `!visual` branch). Consecutive Shift+arrows keep growing it because the
    /// anchor survives between presses.
    fn extend_selection(&mut self, dir: isize) {
        let (start, end) = self.file_range();
        let mut i = self.selected as isize + dir;
        let target = loop {
            if i < start as isize || i as usize >= end {
                return;
            }
            if self.is_selectable_at(i as usize) {
                break i as usize;
            }
            i += dir;
        };
        // Anchor the range at the current line on the first Shift+arrow; keep it
        // on subsequent ones (so the span grows). A prior plain move will have
        // cleared it, starting a fresh range here.
        if self.sel_anchor.is_none() {
            self.sel_anchor = Some(self.selected);
        }
        self.selected = target;
        self.ensure_visible();
        self.status = "shift+↑/↓ to extend · i to comment · move to clear".into();
    }

    /// The (file, side, line-range) covered by the current selection, matching
    /// the cursor line's file+side. Falls back to the single cursor line when
    /// there's no active selection. Lines on a different side/file than the
    /// cursor are ignored (a comment anchors to one side).
    fn selection_range(&self) -> Option<(usize, Side, u32, u32)> {
        let (fi, side, cur) = self.anchor_at(self.selected)?;
        let (lo, hi) = self.selection_bounds();
        let (mut start, mut end) = (cur, cur);
        for i in lo..=hi {
            if let Some((f, s, l)) = self.anchor_at(i) {
                if f == fi && s == side {
                    start = start.min(l);
                    end = end.max(l);
                }
            }
        }
        Some((fi, side, start, end))
    }

    fn move_selection(&mut self, delta: isize) {
        if !self.visual {
            self.sel_anchor = None;
        }
        let (start, end) = self.file_range();
        let mut i = self.selected as isize;
        loop {
            i += delta;
            if i < start as isize || i as usize >= end {
                return;
            }
            if self.is_stop_at(i as usize) {
                self.selected = i as usize;
                self.ensure_visible();
                return;
            }
        }
    }

    /// Move the selection `count` selectable rows in `dir` (+1 down / -1 up).
    fn move_by(&mut self, dir: isize, count: usize) {
        for _ in 0..count {
            let before = self.selected;
            self.move_selection(dir);
            if self.selected == before {
                break; // hit top/bottom
            }
        }
    }

    /// Scroll the viewport by `delta` rows, dragging the selection back into
    /// view if it would fall outside (less/vim Ctrl-E / Ctrl-Y behavior).
    fn scroll_view(&mut self, delta: isize) {
        let (start, end) = self.file_range();
        // Use an effective viewport height of at least 1 so scroll math stays
        // valid even when the bordered diff panel's inner height is 0.
        let height = self.height.max(1);
        // Cap at the last full screen so the wheel can't scroll past the final
        // line into empty space (which would drag the selection along with it).
        // Mirrors the scrollbar's `total - height` maximum.
        let max_top = end.saturating_sub(height).max(start) as isize;
        self.scroll = (self.scroll as isize + delta).clamp(start as isize, max_top) as usize;
        // Scrolling the pane is independent of the selected line: the cursor
        // stays put (and simply scrolls out of view) until the user moves it.
    }

    fn ensure_visible(&mut self) {
        let (start, end) = self.file_range();
        let height = self.height.max(1);
        // For a focused comment, keep the whole message in view (biased to its
        // top when taller than the viewport); otherwise just the cursor row.
        let (top_row, bot_row) = self
            .comment_unit_span(self.selected)
            .unwrap_or((self.selected, self.selected));
        if bot_row >= self.scroll + height {
            self.scroll = bot_row + 1 - height;
        }
        if top_row < self.scroll {
            self.scroll = top_row;
        }
        // Never scroll outside the current file's slice, and never past the
        // last full screen of content.
        self.scroll = self
            .scroll
            .clamp(start, end.saturating_sub(height).max(start));
    }

    fn jump_comment(&mut self, dir: isize) {
        self.sel_anchor = None;
        // Collect the *head* row of each thread in the current file. Navigation
        // (`n`/`N`) deliberately stops once per thread, at its first line
        // (`range.start`) — unlike the act-on-thread operations (reply/resolve/
        // delete), which match anywhere in the range via `range.contains`.
        let (start, end) = self.file_range();
        let mut targets: Vec<usize> = Vec::new();
        for i in start..end {
            if let Some((file_idx, side, line)) = self.anchor_at(i) {
                if let Some(file) = self.changeset.files.get(file_idx) {
                    let path = PathBuf::from(file.display_path());
                    if self
                        .comments
                        .threads
                        .iter()
                        .any(|t| t.file == path && t.side == side && t.range.start == line)
                    {
                        targets.push(i);
                    }
                }
            }
        }
        if targets.is_empty() {
            self.status = "no comments".into();
            return;
        }
        let next = if dir > 0 {
            targets
                .iter()
                .find(|&&i| i > self.selected)
                .copied()
                .or_else(|| targets.first().copied())
        } else {
            targets
                .iter()
                .rev()
                .find(|&&i| i < self.selected)
                .copied()
                .or_else(|| targets.last().copied())
        };
        if let Some(i) = next {
            self.selected = i;
            self.ensure_visible();
        }
    }

    /// Re-wrap inline comment bodies to the current diff width, rebuilding the
    /// row lists when it changes. This is the sole row-affecting side effect of
    /// drawing: the diff width is only known during layout, yet the wrapped
    /// rows must be rebuilt before the frame reads them (and before any
    /// selection mapping). While the sidebar/diff divider is being dragged the
    /// wrap is frozen — the next draw after release picks up the final width and
    /// rebuilds exactly once instead of on every drag event.
    fn sync_comment_wrap(&mut self, diff_inner_width: u16) {
        let inner = diff_inner_width as usize;
        let cw = match self.view {
            // Unified: the box spans the full inner width. Reserve a 2-col
            // margin + 2 borders + 3-col body indent + 1 scrollbar column = 8.
            View::Unified => inner.saturating_sub(8),
            // Split: the box lives inside one half-column, so wrapping to the
            // full width would clip every line on the right. Mirror
            // `render_split`'s `side_w = (area - SPLIT_DIVIDER.len()) / 2` for
            // the worst case (a scrollbar present trims the area by 1), then
            // reserve the box chrome (2-col margin + 2 borders + 3-col indent
            // = 7).
            View::Split => {
                let side = inner.saturating_sub(1 + SPLIT_DIVIDER.len()) / 2;
                side.saturating_sub(7)
            }
        };
        if cw != self.comment_wrap && !self.resizing {
            self.comment_wrap = cw;
            // Re-wrap when there are inline boxes to re-wrap: comment threads
            // or an open composer (which renders inline too).
            if !self.comments.threads.is_empty() || self.composer.is_some() {
                self.rebuild_rows();
            }
        }
    }

    fn draw(&mut self, f: &mut Frame) {
        // Pre-highlight the file in view off the render path so scrolling stays
        // smooth. Catches every path that changes the visible file (nav, jumps,
        // scroll across file boundaries).
        self.hl.warm(self.current_file);
        let area = f.area();
        // Paint the themed background across the whole frame first; widgets draw
        // on top, and any gaps (padding, short lines) keep the theme bg instead
        // of the terminal default.
        f.render_widget(
            Block::default().style(Style::default().bg(theme().bg)),
            area,
        );
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(1)])
            .split(area);

        // Body: optional file sidebar on the left, diff on the right.
        let body = chunks[0];
        let sidebar = self.show_sidebar && !self.changeset.files.is_empty() && body.width >= 60;
        let (diff_outer, sidebar_area) = if sidebar {
            let cols = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Length(self.sidebar_width), Constraint::Min(1)])
                .split(body);
            (cols[1], cols[0])
        } else {
            (body, Rect::default())
        };
        // The diff is a floating panel sitting *on top of* the sidebar: a
        // rounded border frames it and brightens when it holds focus, so Esc
        // (which drops diff focus back to the sidebar) reads as dismissing the
        // panel. Its left border doubles as the resize divider.
        let diff_focused = self.effective_focus() == Focus::Diff;
        let diff_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .style(Style::default().bg(theme().bg))
            .border_style(Style::default().fg(if diff_focused {
                theme().border_focus
            } else {
                theme().border_unfocus
            }));
        let diff_inner = diff_block.inner(diff_outer);
        // Layout is only known here, so the one row-affecting side effect of
        // drawing (re-wrapping inline comments to the diff width) is isolated
        // in this helper and must run before any code reads the row lists.
        self.sync_comment_wrap(diff_inner.width);
        if sidebar {
            self.render_sidebar(f, sidebar_area);
        }
        self.sidebar_area = sidebar_area;
        self.sidebar_sb =
            if sidebar_area.width > 0 && self.sidebar_rows.len() > sidebar_area.height as usize {
                Rect {
                    x: sidebar_area.x + sidebar_area.width.saturating_sub(1),
                    y: sidebar_area.y,
                    width: 1,
                    height: sidebar_area.height,
                }
            } else {
                Rect::default()
            };
        f.render_widget(diff_block, diff_outer);
        self.height = diff_inner.height as usize;
        // Reserve the rightmost inner column for a scrollbar when it overflows.
        let (fr_start, fr_end) = self.file_range();
        let overflow = fr_end - fr_start > self.height;
        let content = if overflow {
            Rect {
                width: diff_inner.width.saturating_sub(1),
                ..diff_inner
            }
        } else {
            diff_inner
        };
        self.diff_area = content;
        self.diff_sb = if overflow {
            Rect {
                x: diff_inner.x + diff_inner.width.saturating_sub(1),
                y: diff_inner.y,
                width: 1,
                height: diff_inner.height,
            }
        } else {
            Rect::default()
        };
        self.render_diff(f, content);
        if overflow {
            self.render_diff_scrollbar(f, diff_inner);
        }

        // Footer: transient status on the left, a context key-hint legend on
        // the right (so shortcuts like Tab are discoverable). Comment actions
        // live on buttons now, so they're omitted from the legend.
        let fw = chunks[1].width as usize;
        let legend = self.footer_legend();
        let sl = str_width(&self.status);
        let ll = str_width(&legend);
        let footer = if sl + ll + 2 <= fw {
            Line::from(vec![
                Span::styled(self.status.clone(), Style::default().fg(theme().muted)),
                Span::raw(" ".repeat(fw - sl - ll)),
                Span::styled(legend, Style::default().fg(theme().faint)),
            ])
        } else if sl > 0 {
            // Not enough room for both: the transient status wins.
            Line::from(Span::styled(
                self.status.clone(),
                Style::default().fg(theme().muted),
            ))
        } else {
            Line::from(Span::styled(legend, Style::default().fg(theme().faint)))
        };
        f.render_widget(
            Paragraph::new(footer).style(Style::default().bg(theme().bg)),
            chunks[1],
        );
    }

    /// Context-aware key-hint legend shown on the right of the footer.
    fn footer_legend(&self) -> String {
        if self.composer.is_some() {
            return "ctrl+s submit · esc cancel".into();
        }
        match self.effective_focus() {
            Focus::Sidebar => "j/k move · enter open · h/l fold · tab view · q quit".into(),
            Focus::Diff => {
                "j/k move · v select · n/N comments · [/] files · tab view · y copy · esc back · q quit"
                    .into()
            }
        }
    }

    fn render_diff(&self, f: &mut Frame, area: Rect) {
        // Button hit regions are recreated each frame as the boxes render.
        self.button_hits.borrow_mut().clear();
        match self.view {
            View::Unified => self.render_unified(f, area),
            View::Split => self.render_split(f, area),
        }
    }

    /// Left-hand collapsible file tree: directories and files (with a one-letter
    /// change status and a comment-state dot), indented by depth.
    fn render_sidebar(&self, f: &mut Frame, area: Rect) {
        let focused = self.effective_focus() == Focus::Sidebar;
        // No border on the sidebar: the floating diff panel's rounded left
        // border is the visual divider between the two panes.
        let inner = area;

        let h = inner.height as usize;
        let n = self.sidebar_rows.len();
        // The scrollbar sits just left of the right border; reserve a content
        // column for it when the list overflows.
        let need_sb = n > h;
        let w = (inner.width as usize).saturating_sub(if need_sb { 1 } else { 0 });
        let max = n.saturating_sub(h);
        let scroll = self.sidebar_scroll.min(max);

        let mut lines: Vec<Line> = Vec::new();
        for idx in scroll..n.min(scroll + h) {
            let is_cursor = focused && idx == self.sidebar_sel;
            match &self.sidebar_rows[idx] {
                SbRow::Dir { name, depth, path } => {
                    let indent = "  ".repeat(depth + 1);
                    let arrow = if self.collapsed.contains(path) {
                        ""
                    } else {
                        ""
                    };
                    let avail = w.saturating_sub(indent.chars().count() + 2);
                    let label = pad_width(&elide_left(name, avail), avail);
                    let bg = if is_cursor {
                        Some(theme().cursor_bg)
                    } else {
                        None
                    };
                    let wbg = |st: Style| match bg {
                        Some(b) => st.bg(b),
                        None => st,
                    };
                    lines.push(Line::from(vec![
                        Span::styled(indent, wbg(Style::default())),
                        Span::styled(arrow, wbg(Style::default().fg(theme().muted))),
                        Span::styled(label, wbg(Style::default().fg(theme().muted))),
                    ]));
                }
                SbRow::File { idx: fi, depth } => {
                    let fi = *fi;
                    let is_cur = fi == self.current_file;
                    let (status, status_color) = self
                        .changeset
                        .files
                        .get(fi)
                        .map(file_status)
                        .unwrap_or(('M', theme().warn));
                    let indent = "  ".repeat(depth + 1);
                    let path = self
                        .changeset
                        .files
                        .get(fi)
                        .map(|f| f.display_path())
                        .unwrap_or_default();
                    // A comment dot just left of the filename: yellow = open,
                    // hollow gray = all resolved, blank = none.
                    let (dot, dot_color) = match file_comment_state(&self.comments, path) {
                        Some(true) => ("", theme().warn),
                        Some(false) => ("", theme().muted),
                        None => ("  ", theme().none),
                    };
                    let (adds, dels) = self.file_stats.get(fi).copied().unwrap_or((0, 0));
                    let counts = format!(" +{adds} -{dels}");
                    let avail = w
                        .saturating_sub(indent.chars().count() + 4)
                        .saturating_sub(counts.chars().count());
                    let base = base_of(path);
                    let name = pad_width(&elide_left(base, avail), avail);
                    let bg = if is_cursor {
                        Some(theme().cursor_bg)
                    } else if is_cur {
                        Some(theme().unfocus_bg)
                    } else {
                        None
                    };
                    let wbg = |st: Style| match bg {
                        Some(b) => st.bg(b),
                        None => st,
                    };
                    let name_style = if is_cur {
                        Style::default()
                            .fg(theme().text_strong)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(theme().text)
                    };
                    lines.push(Line::from(vec![
                        Span::styled(indent, wbg(Style::default())),
                        Span::styled(format!("{status} "), wbg(Style::default().fg(status_color))),
                        Span::styled(dot, wbg(Style::default().fg(dot_color))),
                        Span::styled(name, wbg(name_style)),
                        Span::styled(format!(" +{adds}"), wbg(Style::default().fg(theme().added))),
                        Span::styled(
                            format!(" -{dels}"),
                            wbg(Style::default().fg(theme().removed)),
                        ),
                    ]));
                }
            }
        }
        f.render_widget(
            Paragraph::new(lines).style(Style::default().bg(theme().bg)),
            inner,
        );
        if need_sb {
            let mut sb = ScrollbarState::new(max + 1)
                .position(scroll)
                .viewport_content_length(h);
            // Render inside `inner` so the thumb lands one column left of the
            // pane border (which stays a clean, continuous resize divider). The
            // track is blank so it doesn't double up against the border.
            f.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(None)
                    .end_symbol(None)
                    .track_symbol(Some(" "))
                    .thumb_symbol("")
                    .thumb_style(Style::default().fg(theme().scrollbar_thumb)),
                inner,
                &mut sb,
            );
        }
    }

    /// A vertical scrollbar on the right edge of `area` for the diff pane.
    fn render_diff_scrollbar(&self, f: &mut Frame, area: Rect) {
        let (start, end) = self.file_range();
        let total = end - start;
        if total <= self.height {
            return;
        }
        let max_top = total - self.height;
        let pos = self.scroll.saturating_sub(start).min(max_top);
        let mut sb = ScrollbarState::new(max_top + 1)
            .position(pos)
            .viewport_content_length(self.height);
        f.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .track_symbol(Some(" "))
                .thumb_symbol("")
                .thumb_style(Style::default().fg(theme().scrollbar_thumb)),
            area,
            &mut sb,
        );
    }

    fn render_unified(&self, f: &mut Frame, area: Rect) {
        let width = area.width as usize;
        let (start, file_end) = self.file_range();
        let top = self.scroll.max(start);
        let end = (top + self.height).min(file_end);
        let mut lines: Vec<Line> = Vec::new();
        for idx in top..end {
            let row = &self.rows[idx];
            let selected = self.in_selection(idx);
            let y = area.y + (idx - top) as u16;
            let line = match &row.kind {
                RowKind::Comment(cl) if matches!(cl.kind, CommentKind::Actions) => {
                    let border = if cl.resolved {
                        theme().muted
                    } else {
                        theme().border_unfocus
                    };
                    let btns = self.comment_buttons(cl);
                    self.action_row_line(&btns, border, area.x, y, width, 0, width)
                }
                RowKind::Composer(c) if matches!(c.kind, ComposerKind::Hint) => {
                    let btns = self.composer_buttons();
                    self.action_row_line(&btns, theme().accent, area.x, y, width, 0, width)
                }
                RowKind::Line { .. } if self.show_add_button(idx) => {
                    let base = self.row_to_line(row, selected, width).spans;
                    self.append_right_button(
                        base,
                        width,
                        "comment(i)",
                        theme().accent,
                        ButtonAction::AddComment,
                        area.x,
                        y,
                    )
                }
                _ => self.row_to_line(row, selected, width),
            };
            lines.push(line);
        }
        f.render_widget(
            Paragraph::new(lines).style(Style::default().bg(theme().bg)),
            area,
        );
    }

    /// Whether the floating `comment(i)` button should appear on row `idx`: the
    /// diff pane is focused, no composer is open, and `idx` is the *last* row of
    /// the current selection. A new thread (and its composer) renders after the
    /// last line of its range, so the button sits there too — right where the
    /// comment box will open — not on a different end of a range selection.
    fn show_add_button(&self, idx: usize) -> bool {
        self.composer.is_none()
            && self.effective_focus() == Focus::Diff
            && idx == self.selection_bounds().1
    }

    fn render_split(&self, f: &mut Frame, area: Rect) {
        let total = area.width as usize;
        let divider = SPLIT_DIVIDER;
        let side_w = total.saturating_sub(divider.len()) / 2;
        let (start, file_end) = self.file_range();
        let top = self.scroll.max(start);
        let end = (top + self.height).min(file_end);
        let dw = divider.chars().count();
        let mut lines: Vec<Line> = Vec::new();
        for idx in top..end {
            let row = &self.split_rows[idx];
            let selected = self.in_selection(idx);
            let y = area.y + (idx - top) as u16;
            let line = match &row.kind {
                SplitRowKind::Comment { side, line: cl }
                    if matches!(cl.kind, CommentKind::Actions) =>
                {
                    let border = if cl.resolved {
                        theme().muted
                    } else {
                        theme().border_unfocus
                    };
                    let btns = self.comment_buttons(cl);
                    let left = if matches!(side, Side::Old) {
                        0
                    } else {
                        side_w + dw
                    };
                    self.action_row_line(&btns, border, area.x, y, total, left, side_w)
                }
                SplitRowKind::Composer { side, line: cl }
                    if matches!(cl.kind, ComposerKind::Hint) =>
                {
                    let btns = self.composer_buttons();
                    let left = if matches!(side, Side::Old) {
                        0
                    } else {
                        side_w + dw
                    };
                    self.action_row_line(&btns, theme().accent, area.x, y, total, left, side_w)
                }
                SplitRowKind::Pair { .. } if self.show_add_button(idx) => {
                    let base = self.split_row_to_line(row, selected, side_w, divider).spans;
                    self.append_right_button(
                        base,
                        total,
                        "comment(i)",
                        theme().accent,
                        ButtonAction::AddComment,
                        area.x,
                        y,
                    )
                }
                _ => self.split_row_to_line(row, selected, side_w, divider),
            };
            lines.push(line);
        }
        f.render_widget(
            Paragraph::new(lines).style(Style::default().bg(theme().bg)),
            area,
        );
    }

    fn split_row_to_line(
        &self,
        row: &SplitRow,
        selected: bool,
        side_w: usize,
        divider: &str,
    ) -> Line<'static> {
        match &row.kind {
            SplitRowKind::FileHeader => Line::from(Span::styled(
                format!("{}", row.text),
                Style::default()
                    .fg(theme().text_strong)
                    .bg(theme().file_header_bg)
                    .add_modifier(Modifier::BOLD),
            )),
            SplitRowKind::HunkHeader => Line::from(Span::styled(
                row.text.clone(),
                Style::default()
                    .fg(theme().faint)
                    .add_modifier(Modifier::ITALIC),
            )),
            SplitRowKind::Pair { left, right } => {
                let mut spans = self.side_spans(left.as_ref(), row.file_idx, side_w, selected);
                spans.push(Span::styled(
                    divider.to_string(),
                    Style::default().fg(theme().subtle),
                ));
                spans.extend(self.side_spans(right.as_ref(), row.file_idx, side_w, selected));
                Line::from(spans)
            }
            SplitRowKind::Comment { side, line: cl } => {
                // Render the thread under the column it is anchored to: old
                // (deletion) comments on the left, new (addition) comments on
                // the right. The opposite column is left blank.
                let body = self.comment_line_to_line(cl, selected, side_w).spans;
                match side {
                    Side::Old => {
                        let mut spans = body;
                        // Pad out to the divider + right column so the row
                        // fills its width.
                        spans.push(Span::styled(
                            " ".repeat(divider.chars().count() + side_w),
                            Style::default(),
                        ));
                        Line::from(spans)
                    }
                    Side::New => {
                        let pad = side_w + divider.chars().count();
                        let mut spans = vec![Span::styled(" ".repeat(pad), Style::default())];
                        spans.extend(body);
                        Line::from(spans)
                    }
                }
            }
            SplitRowKind::Composer { side, line: cl } => {
                // Same side-aware placement as comment rows: render under the
                // anchored column, blank the other.
                let body = self.composer_line_to_line(cl, side_w).spans;
                match side {
                    Side::Old => {
                        let mut spans = body;
                        spans.push(Span::styled(
                            " ".repeat(divider.chars().count() + side_w),
                            Style::default(),
                        ));
                        Line::from(spans)
                    }
                    Side::New => {
                        let pad = side_w + divider.chars().count();
                        let mut spans = vec![Span::styled(" ".repeat(pad), Style::default())];
                        spans.extend(body);
                        Line::from(spans)
                    }
                }
            }
        }
    }

    /// Render one side (old/new) of a split pair into spans of width `width`.
    fn side_spans(
        &self,
        cell: Option<&SideCell>,
        file_idx: usize,
        width: usize,
        selected: bool,
    ) -> Vec<Span<'static>> {
        const PREFIX: usize = 5; // line number(4) + space(1)
        match cell {
            None => vec![Span::styled(
                " ".repeat(width),
                Style::default().bg(theme().comment_bg),
            )],
            Some(c) => {
                let num = c
                    .line
                    .map(|n| format!("{n:>4}"))
                    .unwrap_or_else(|| "    ".into());
                let bg = if selected {
                    Some(self.diff_cursor_bg())
                } else {
                    match c.kind {
                        LineKind::Addition => Some(theme().add_bg),
                        LineKind::Deletion => Some(theme().del_bg),
                        LineKind::Context => None,
                    }
                };
                let mut spans = vec![Span::styled(
                    format!("{num} "),
                    Style::default().fg(theme().muted),
                )];
                spans.extend(self.styled_fit(file_idx, &c.text, width.saturating_sub(PREFIX), bg));
                spans
            }
        }
    }

    fn row_to_line(&self, row: &Row, selected: bool, width: usize) -> Line<'static> {
        match &row.kind {
            RowKind::FileHeader => {
                let st = Style::default()
                    .fg(theme().text_strong)
                    .bg(theme().file_header_bg)
                    .add_modifier(Modifier::BOLD);
                let text = format!("{}", row.text);
                let pad = width.saturating_sub(str_width(&text));
                Line::from(vec![
                    Span::styled(text, st),
                    Span::styled(" ".repeat(pad), st),
                ])
            }
            RowKind::HunkHeader => Line::from(Span::styled(
                row.text.clone(),
                Style::default()
                    .fg(theme().faint)
                    .add_modifier(Modifier::ITALIC),
            )),
            RowKind::Line {
                kind,
                old_line,
                new_line,
            } => {
                let num = format!(
                    "{:>5} {:>5} ",
                    old_line.map(|n| n.to_string()).unwrap_or_default(),
                    new_line.map(|n| n.to_string()).unwrap_or_default(),
                );
                let (sign, code) = row.text.split_at(1);
                let bg = if selected {
                    Some(self.diff_cursor_bg())
                } else {
                    match kind {
                        LineKind::Addition => Some(theme().add_bg),
                        LineKind::Deletion => Some(theme().del_bg),
                        LineKind::Context => None,
                    }
                };
                let sign_color = match kind {
                    LineKind::Addition => theme().added,
                    LineKind::Deletion => theme().removed,
                    LineKind::Context => theme().muted,
                };
                let with_bg = |st: Style| match bg {
                    Some(b) => st.bg(b),
                    None => st,
                };
                let mut used = str_width(&num) + 1;
                let mut spans = vec![
                    Span::styled(num, with_bg(Style::default().fg(theme().muted))),
                    Span::styled(sign.to_string(), with_bg(Style::default().fg(sign_color))),
                ];
                // Highlighted code, with the diff background tint behind it.
                let hl = self.hl.runs(row.file_idx, code);
                for (c, s) in hl.iter() {
                    used += str_width(s);
                    spans.push(Span::styled(s.clone(), with_bg(Style::default().fg(*c))));
                }
                // Fill the rest so the tint / selection spans the whole line.
                if bg.is_some() && used < width {
                    spans.push(Span::styled(
                        " ".repeat(width - used),
                        with_bg(Style::default()),
                    ));
                }
                Line::from(spans)
            }
            RowKind::Comment(cl) => self.comment_line_to_line(cl, selected, width),
            RowKind::Composer(cl) => self.composer_line_to_line(cl, width),
        }
    }

    /// Buttons for a thread box's action row: reply, resolve/unresolve, and
    /// (only when the focused comment is a session-added one in this thread)
    /// delete. `(label-with-hotkey, action, label text color)` — the chip's
    /// background is a uniform subtle surface; this color is its foreground.
    fn comment_buttons(&self, cl: &CommentLine) -> Vec<(String, ButtonAction, Color)> {
        let tid = cl.thread_id.clone();
        let mut v = vec![(
            "reply(r)".to_string(),
            ButtonAction::Reply(tid.clone()),
            theme().accent,
        )];
        if cl.resolved {
            v.push((
                "unresolve(R)".to_string(),
                ButtonAction::ToggleResolve(tid.clone()),
                theme().warn,
            ));
        } else {
            v.push((
                "resolve(R)".to_string(),
                ButtonAction::ToggleResolve(tid.clone()),
                theme().added,
            ));
        }
        if let Some((ftid, fcid)) = self.focused_comment() {
            if ftid == tid && !self.base_comment_ids.contains(&fcid) {
                v.push((
                    "delete(D)".to_string(),
                    ButtonAction::Delete(tid, fcid),
                    theme().removed,
                ));
            }
        }
        v
    }

    /// Buttons for the open composer's action row: submit and cancel.
    fn composer_buttons(&self) -> Vec<(String, ButtonAction, Color)> {
        vec![
            (
                "submit(ctrl+s)".to_string(),
                ButtonAction::Submit,
                theme().accent,
            ),
            (
                "cancel(esc)".to_string(),
                ButtonAction::Cancel,
                theme().muted,
            ),
        ]
    }

    /// Build one full-width action-button row inside a box. The box (margin +
    /// `│ … │` + button chips) is `box_w` cells wide and starts `left_pad`
    /// cells into the row (for split-view side placement); the rest is padded
    /// to `width`. Each chip is a subtle raised surface with the action's color
    /// as its label text, and its on-screen rect is recorded (at `x0` + offset,
    /// row `y`) for click hit-testing.
    #[allow(clippy::too_many_arguments)]
    fn action_row_line(
        &self,
        btns: &[(String, ButtonAction, Color)],
        border: Color,
        x0: u16,
        y: u16,
        width: usize,
        left_pad: usize,
        box_w: usize,
    ) -> Line<'static> {
        const MARGIN: usize = 2;
        let bstyle = Style::default().fg(border);
        if box_w <= MARGIN + 2 {
            return Line::from(Span::raw(" ".repeat(width)));
        }
        let inner_w = box_w - MARGIN - 2;
        let mut spans: Vec<Span<'static>> = Vec::new();
        if left_pad > 0 {
            spans.push(Span::raw(" ".repeat(left_pad)));
        }
        spans.push(Span::raw(" ".repeat(MARGIN)));
        spans.push(Span::styled("".to_string(), bstyle));
        // Inner content: ` label ` chips packed left-to-right. Each chip is a
        // subtle raised surface with the action's color as the *text* (a soft,
        // toolbar-like button rather than a loud solid fill); the chip padding
        // and distinct text colors keep them readable as separate buttons even
        // packed tight, which matters in split view's narrow side column. Each
        // chip's screen rect is recorded for click hit-testing.
        let mut col = 0usize;
        let base_x = x0 + (left_pad + MARGIN + 1) as u16;
        let mut inner: Vec<Span<'static>> = Vec::new();
        for (i, (label, action, color)) in btns.iter().enumerate() {
            let chip = format!(" {label} ");
            let w = str_width(&chip);
            // A one-cell (box-background) gap before each chip after the first,
            // so the raised surfaces read as separate buttons. The gap is part
            // of the fit test, so it never dangles and drops the next chip.
            let gap = usize::from(i > 0);
            if col + gap + w > inner_w {
                break;
            }
            if gap > 0 {
                inner.push(Span::raw(" "));
                col += 1;
            }
            self.button_hits.borrow_mut().push((
                Rect {
                    x: base_x + col as u16,
                    y,
                    width: w as u16,
                    height: 1,
                },
                action.clone(),
            ));
            inner.push(Span::styled(
                chip,
                Style::default()
                    .bg(theme().subtle)
                    .fg(*color)
                    .add_modifier(Modifier::BOLD),
            ));
            col += w;
        }
        if col < inner_w {
            inner.push(Span::raw(" ".repeat(inner_w - col)));
        }
        spans.extend(inner);
        spans.push(Span::styled("".to_string(), bstyle));
        let used = left_pad + box_w;
        if used < width {
            spans.push(Span::raw(" ".repeat(width - used)));
        }
        Line::from(spans)
    }

    /// Overlay a right-aligned button chip on an already-built diff line: clip
    /// the line's content to leave room, then append ` label `. Used to float a
    /// `comment(i)` button at the end of the focused diff line (GitHub-style).
    /// Records the chip's screen rect (at `x0` + offset, row `y`) for clicks.
    #[allow(clippy::too_many_arguments)]
    fn append_right_button(
        &self,
        spans: Vec<Span<'static>>,
        width: usize,
        label: &str,
        color: Color,
        action: ButtonAction,
        x0: u16,
        y: u16,
    ) -> Line<'static> {
        let chip = format!(" {label} ");
        let cw = str_width(&chip);
        if width <= cw {
            return Line::from(spans);
        }
        let keep = width - cw;
        // Clip the existing spans to `keep` display cells (preserving styles,
        // so the line's selection tint carries up to the button).
        let mut out: Vec<Span<'static>> = Vec::new();
        let mut acc = 0usize;
        for s in spans {
            if acc >= keep {
                break;
            }
            let sw = str_width(&s.content);
            if acc + sw <= keep {
                acc += sw;
                out.push(s);
            } else {
                let (t, tw) = take_width(&s.content, keep - acc);
                out.push(Span::styled(t, s.style));
                acc += tw;
                break;
            }
        }
        if acc < keep {
            out.push(Span::raw(" ".repeat(keep - acc)));
        }
        self.button_hits.borrow_mut().push((
            Rect {
                x: x0 + keep as u16,
                y,
                width: cw as u16,
                height: 1,
            },
            action,
        ));
        out.push(Span::styled(
            chip,
            Style::default()
                .bg(theme().subtle)
                .fg(color)
                .add_modifier(Modifier::BOLD),
        ));
        Line::from(out)
    }

    /// Render one inline comment line as part of a rounded box spanning `width`
    /// (2-column left margin + `╭─╮`/`│ │`/`╰─╯` frame). `focused` is set for
    /// the rows of the message the cursor is on.
    fn comment_line_to_line(&self, cl: &CommentLine, focused: bool, width: usize) -> Line<'static> {
        const MARGIN: usize = 2;
        // Border brightness signals focus: the focused message keeps the bright
        // (theme) border so the cursor is visible even on a resolved thread
        // (whose box is otherwise dimmed). Only an *unfocused* resolved thread
        // reads as fully settled. Without the focus check first, landing on a
        // resolved comment gave no visual feedback at all.
        let border_col = if focused {
            theme().border_focus
        } else if cl.resolved {
            theme().muted
        } else {
            theme().border_unfocus
        };
        let bstyle = Style::default().fg(border_col);
        // Box occupies cols [MARGIN, width); inner_w is the span between borders.
        let inner_w = width.saturating_sub(MARGIN + 2);
        if width <= MARGIN + 2 {
            return Line::from(Span::raw(" ".repeat(width)));
        }
        let margin = Span::raw(" ".repeat(MARGIN));
        match &cl.kind {
            CommentKind::Top => Line::from(vec![
                margin,
                Span::styled(format!("{}", "".repeat(inner_w)), bstyle),
            ]),
            CommentKind::Bottom => Line::from(vec![
                margin,
                Span::styled(format!("{}", "".repeat(inner_w)), bstyle),
            ]),
            // The action row is normally drawn by `action_row_line` straight
            // from the render loop (it needs the screen position to record
            // click rects); this is a blank-box fallback if it's ever reached.
            CommentKind::Actions => Line::from(vec![
                margin,
                Span::styled("".to_string(), bstyle),
                Span::raw(" ".repeat(inner_w)),
                Span::styled("".to_string(), bstyle),
            ]),
            CommentKind::Author { name, date } => {
                // Name on the left, date flush right (1-col gutter before the
                // border). Spans below total exactly `inner_w`.
                let left = format!(" @{name}");
                let llen = str_width(&left);
                let dlen = str_width(date);
                let name_col = if cl.resolved {
                    theme().muted
                } else {
                    theme().warn
                };
                let name_style = Style::default().fg(name_col).add_modifier(Modifier::BOLD);
                let inner = if llen + dlen + 2 <= inner_w {
                    vec![
                        Span::styled(left, name_style),
                        Span::raw(" ".repeat(inner_w - llen - dlen - 1)),
                        Span::styled(date.clone(), Style::default().fg(theme().muted)),
                        Span::raw(" "),
                    ]
                } else {
                    let (l, lw) = take_width(&left, inner_w);
                    let pad = inner_w - lw;
                    vec![Span::styled(l, name_style), Span::raw(" ".repeat(pad))]
                };
                let mut spans = vec![margin, Span::styled("".to_string(), bstyle)];
                spans.extend(inner);
                spans.push(Span::styled("".to_string(), bstyle));
                Line::from(spans)
            }
            _ => {
                let (content, color, bold) = match &cl.kind {
                    CommentKind::Head { replies } => (
                        format!(
                            "{} · {} message{}",
                            if cl.resolved { "resolved" } else { "open" },
                            replies,
                            if *replies == 1 { "" } else { "s" }
                        ),
                        if cl.resolved {
                            theme().muted
                        } else {
                            theme().accent
                        },
                        true,
                    ),
                    CommentKind::Body(b) => (
                        format!(" {b}"),
                        if cl.resolved {
                            theme().muted
                        } else {
                            theme().text
                        },
                        false,
                    ),
                    _ => (String::new(), theme().text, false), // Gap
                };
                let mut cstyle = Style::default().fg(color);
                if bold {
                    cstyle = cstyle.add_modifier(Modifier::BOLD);
                }
                let clen = str_width(&content);
                let content = if clen > inner_w {
                    take_width(&content, inner_w).0
                } else {
                    format!("{content}{}", " ".repeat(inner_w - clen))
                };
                Line::from(vec![
                    margin,
                    Span::styled("".to_string(), bstyle),
                    Span::styled(content, cstyle),
                    Span::styled("".to_string(), bstyle),
                ])
            }
        }
    }

    /// Render one inline composer line as part of a rounded accent box spanning
    /// `width` (2-col left margin + framed title / live body / key hint).
    fn composer_line_to_line(&self, cl: &ComposerLine, width: usize) -> Line<'static> {
        const MARGIN: usize = 2;
        let bstyle = Style::default().fg(theme().accent);
        let inner_w = width.saturating_sub(MARGIN + 2);
        if width <= MARGIN + 2 {
            return Line::from(Span::raw(" ".repeat(width)));
        }
        let margin = Span::raw(" ".repeat(MARGIN));
        // Pad/truncate `s` to exactly `inner_w` display cells.
        let fit = |s: &str| -> String {
            let w = str_width(s);
            if w > inner_w {
                take_width(s, inner_w).0
            } else {
                format!("{s}{}", " ".repeat(inner_w - w))
            }
        };
        match &cl.kind {
            ComposerKind::Top { title } => {
                let t = take_width(title, inner_w).0;
                let dashes = inner_w.saturating_sub(str_width(&t));
                Line::from(vec![
                    margin,
                    Span::styled("".to_string(), bstyle),
                    Span::styled(
                        t,
                        Style::default()
                            .fg(theme().accent)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled("".repeat(dashes), bstyle),
                    Span::styled("".to_string(), bstyle),
                ])
            }
            ComposerKind::Bottom => Line::from(vec![
                margin,
                Span::styled(format!("{}", "".repeat(inner_w)), bstyle),
            ]),
            ComposerKind::Body(b) => {
                let text_style = Style::default().fg(theme().text);
                let mut spans = vec![margin, Span::styled("".to_string(), bstyle)];
                // The caret is an *overlay*, not a character: render the cell at
                // the cursor with a reversed (block) style instead of splicing a
                // glyph in, so the surrounding text never shifts.
                if let Some(idx) = b.find(COMPOSER_CARET) {
                    let pre = &b[..idx];
                    let after = &b[idx + COMPOSER_CARET.len_utf8()..];
                    // The character sitting under the cursor (or a space at EOL).
                    let mut chars = after.chars();
                    let under = chars.next();
                    let tail: String = chars.collect();
                    let mut cursor_cell =
                        under.map(|c| c.to_string()).unwrap_or_else(|| " ".into());
                    // Lay out exactly `inner_w` cells, honoring the same
                    // pad/truncate contract as `fit`: reserve the cursor cell
                    // first (so the caret is never the thing that gets clipped),
                    // then fit the lead text and tail around it. A wide cursor
                    // glyph wider than the whole box degrades to a space.
                    if str_width(&cursor_cell) > inner_w {
                        cursor_cell = " ".into();
                    }
                    let cursor_w = str_width(&cursor_cell);
                    let (lead, lead_w) = take_width(&format!(" {pre}"), inner_w - cursor_w);
                    let (tail, tail_w) = take_width(&tail, inner_w - lead_w - cursor_w);
                    let pad = inner_w - lead_w - cursor_w - tail_w;
                    spans.push(Span::styled(lead, text_style));
                    spans.push(Span::styled(
                        cursor_cell,
                        text_style.add_modifier(Modifier::REVERSED),
                    ));
                    spans.push(Span::styled(
                        format!("{tail}{}", " ".repeat(pad)),
                        text_style,
                    ));
                } else {
                    spans.push(Span::styled(fit(&format!(" {b}")), text_style));
                }
                spans.push(Span::styled("".to_string(), bstyle));
                Line::from(spans)
            }
            ComposerKind::Hint => Line::from(vec![
                margin,
                Span::styled("".to_string(), bstyle),
                Span::styled(
                    fit(" ctrl+s: submit · enter: newline · esc: cancel"),
                    Style::default().fg(theme().muted),
                ),
                Span::styled("".to_string(), bstyle),
            ]),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::parse::parse_report;

    // Four additions framed by two context lines, so the new side carries
    // lines 1..=6 and there are six selectable rows in a known order.
    const DIFF: &str = "\
--- a/f.rs
+++ b/f.rs
@@ -1,2 +1,6 @@
 a
+b
+c
+d
+e
 f
";

    // Two files, to exercise per-file navigation.
    const TWO_FILES: &str = "\
--- a/one.rs
+++ b/one.rs
@@ -1 +1,2 @@
 x
+y
--- a/two.rs
+++ b/two.rs
@@ -1 +1,2 @@
 p
+q
";

    fn app_with(diff: &str) -> App {
        let cs = parse_report(diff).0;
        let mut app = App::with_comments(cs, CommentStore::default());
        app.height = 4; // deterministic viewport for scroll math
        app
    }

    #[test]
    fn precomputed_file_spans_match_a_full_scan() {
        // The O(1) per-file-switch span lookup must agree with a brute-force
        // scan of the active row list, in both layouts.
        let mut app = app_with(TWO_FILES);
        for toggled in [false, true] {
            if toggled {
                app.toggle_view();
            }
            let len = app.active_len();
            for fi in 0..app.changeset.files.len() {
                app.current_file = fi;
                app.recompute_file_span();
                let (mut s, mut e) = (len, len);
                for i in 0..len {
                    if app.row_file_idx(i) == Some(fi) {
                        if s == len {
                            s = i;
                        }
                        e = i + 1;
                    }
                }
                assert_eq!(
                    app.file_span,
                    (s, e),
                    "file {fi} span mismatch (toggled={toggled})"
                );
            }
        }
    }

    /// Move the cursor onto the row anchored at `(current_file, side, line)`.
    fn goto(app: &mut App, side: Side, line: u32) {
        let (s, e) = app.file_range();
        for i in s..e {
            if app.anchor_at(i) == Some((app.current_file, side, line)) {
                app.selected = i;
                return;
            }
        }
        panic!("no selectable row for {side:?} line {line}");
    }

    #[test]
    fn navigation_clamps_within_the_file() {
        let mut app = app_with(DIFF);
        let first = app.first_selectable().unwrap();
        let last = app.last_selectable().unwrap();
        app.selected = first;

        // Up past the top is a no-op.
        app.move_by(-1, 5);
        assert_eq!(app.selected, first);

        // Down past the bottom clamps to the last selectable row.
        app.move_by(1, 100);
        assert_eq!(app.selected, last);
    }

    #[test]
    fn ensure_visible_keeps_cursor_in_viewport() {
        let mut app = app_with(DIFF);
        let (start, end) = app.file_range();
        app.selected = app.last_selectable().unwrap();
        app.ensure_visible();
        let h = app.height;
        assert!(app.scroll <= app.selected, "cursor above viewport");
        assert!(app.selected < app.scroll + h, "cursor below viewport");
        // Scroll never leaves the file's row slice.
        assert!(app.scroll >= start && app.scroll < end);
    }

    #[test]
    fn visual_selection_spans_a_multi_line_range() {
        let mut app = app_with(DIFF);
        goto(&mut app, Side::New, 2);
        app.toggle_visual();
        assert!(app.visual && app.sel_anchor.is_some());
        goto(&mut app, Side::New, 5);

        // The selection covers new-side lines 2..=5 on a single side.
        let (fi, side, lo, hi) = app.selection_range().unwrap();
        assert_eq!((fi, side, lo, hi), (app.current_file, Side::New, 2, 5));

        // Leaving visual drops the anchor.
        app.toggle_visual();
        assert!(!app.visual && app.sel_anchor.is_none());
    }

    #[test]
    fn shift_arrows_extend_a_line_selection() {
        // Shift+Down/Up builds a multi-line selection without entering `v`
        // visual mode, anchoring at the starting line. `visual` stays false so
        // a later unmodified move collapses the range.
        let mut app = app_with(DIFF);
        goto(&mut app, Side::New, 2);
        assert!(!app.visual && app.sel_anchor.is_none());

        app.on_key_diff(KeyCode::Down, false, true);
        app.on_key_diff(KeyCode::Down, false, true);
        assert!(!app.visual && app.sel_anchor.is_some());
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 4)
        );

        // Shrinking back up narrows the range.
        app.on_key_diff(KeyCode::Up, false, true);
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 3)
        );
    }

    #[test]
    fn unmodified_move_collapses_a_shift_selection() {
        // Regression: Shift+arrow used to flip on persistent visual mode, so the
        // multi-select stayed active after releasing Shift (terminals can't
        // report Shift key-up). A plain j/k must collapse the range back to a
        // single line.
        let mut app = app_with(DIFF);
        goto(&mut app, Side::New, 2);
        app.on_key_diff(KeyCode::Down, false, true);
        app.on_key_diff(KeyCode::Down, false, true);
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 4),
            "shift extended the range"
        );

        // A plain (no-shift) Down collapses to the single cursor line.
        app.on_key_diff(KeyCode::Down, false, false);
        assert!(app.sel_anchor.is_none(), "plain move must drop the anchor");
        let (_, side, lo, hi) = app.selection_range().unwrap();
        assert_eq!(
            (side, lo, hi),
            (Side::New, 5, 5),
            "range collapsed to one line"
        );

        // A fresh Shift+arrow starts a brand-new range from here.
        app.on_key_diff(KeyCode::Down, false, true);
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 5, 6)
        );
    }

    #[test]
    fn shift_arrows_skip_comment_rows_and_keep_a_valid_line_range() {
        // Regression: extend_selection used to step to the next *stop*, which
        // includes comment/collapsed rows — landing the cursor off a diff line
        // so selection_range() went None. It must skip over an inline thread's
        // rows and keep selecting diff lines.
        let (mut app, _tid, _reply) = app_with_thread(3);
        goto(&mut app, Side::New, 2);

        // Walk down across the line-3 thread's inline rows; every step must stay
        // on a diff line with a valid line range.
        for _ in 0..3 {
            app.on_key_diff(KeyCode::Down, false, true);
            assert!(
                app.is_selectable_at(app.selected),
                "cursor landed on a non-diff row"
            );
            assert!(
                app.selection_range().is_some(),
                "selection range went None mid-extend"
            );
        }
        // The range spans diff lines (start stays at the anchor, end advanced).
        let (_, side, lo, hi) = app.selection_range().unwrap();
        assert_eq!((side, lo), (Side::New, 2));
        assert!(hi > lo, "selection should have grown past the anchor line");
    }

    #[test]
    fn toggling_view_preserves_a_multi_line_selection() {
        // Regression: switching unified<->split used to collapse a visual
        // selection down to the cursor line. The whole range must survive.
        let mut app = app_with(DIFF);
        goto(&mut app, Side::New, 2);
        app.toggle_visual();
        goto(&mut app, Side::New, 5);
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 5)
        );

        app.toggle_view(); // -> split
        assert!(app.visual && app.sel_anchor.is_some());
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 5),
            "selection collapsed after toggling to split"
        );

        app.toggle_view(); // -> back to unified
        assert_eq!(
            app.selection_range().unwrap(),
            (app.current_file, Side::New, 2, 5),
            "selection collapsed after toggling back to unified"
        );
    }

    #[test]
    fn selection_range_is_single_line_without_an_anchor() {
        let mut app = app_with(DIFF);
        goto(&mut app, Side::New, 3);
        let (_, side, lo, hi) = app.selection_range().unwrap();
        assert_eq!((side, lo, hi), (Side::New, 3, 3));
    }

    #[test]
    fn jumping_files_moves_the_cursor_into_the_new_file() {
        let mut app = app_with(TWO_FILES);
        assert_eq!(app.current_file, 0);
        app.jump_file(1);
        assert_eq!(app.current_file, 1);
        // The cursor lands on a selectable row belonging to file 1.
        assert!(app.is_selectable_at(app.selected));
        assert_eq!(app.row_file_idx(app.selected), Some(1));
        // ...and back.
        app.jump_file(-1);
        assert_eq!(app.current_file, 0);
        assert_eq!(app.row_file_idx(app.selected), Some(0));
    }

    /// Build an app with one new-side thread (two messages) anchored to `line`,
    /// rendered inline.
    fn app_with_thread(line: u32) -> (App, String, String) {
        let cs = parse_report(DIFF).0;
        let mut store = CommentStore::default();
        let tid = store.add_thread(
            "f.rs".into(),
            Side::New,
            LineRange {
                start: line,
                end: line,
            },
            Some("a".into()),
            "root message".into(),
        );
        store.reply(&tid, Some("b".into()), "a reply".into());
        let reply_id = store.threads[0].comments[1].id.clone();
        let mut app = App::with_comments(cs, store);
        app.height = 40; // tall enough to hold the whole thread
        (app, tid, reply_id)
    }

    /// First active row that is a content line of comment `comment_id`.
    fn comment_head(app: &App, comment_id: &str) -> usize {
        (0..app.active_len())
            .find(|&i| {
                app.is_stop_at(i)
                    && app.comment_unit_at(i).map(|(_, c)| c).as_deref() == Some(comment_id)
            })
            .expect("comment head row")
    }

    #[test]
    fn delete_targets_session_comments_only() {
        // Both the root and the reply here come from the input sidecar.
        let (mut app, tid, base_reply_id) = app_with_thread(3);

        // Cursor on an input comment: `D` is a no-op.
        app.selected = comment_head(&app, &base_reply_id);
        app.delete_current_comment();
        assert_eq!(app.status, "can't delete a comment from the input");
        assert_eq!(
            app.comments.threads[0].comments.len(),
            2,
            "an input comment must survive D"
        );

        // Add a reply this session (to the same base thread), then delete it.
        app.selected = comment_head(&app, &base_reply_id);
        app.open_reply();
        app.on_key_compose(KeyCode::Char('y'), KeyModifiers::NONE);
        app.submit_compose();
        assert_eq!(app.comments.threads[0].comments.len(), 3);
        let new_reply_id = app.comments.threads[0].comments[2].id.clone();

        app.selected = comment_head(&app, &new_reply_id);
        app.delete_current_comment();
        assert_eq!(app.status, "deleted comment");
        assert_eq!(
            app.comments.threads[0].comments.len(),
            2,
            "only the session reply is removed"
        );
        assert!(
            app.comments.threads.iter().any(|t| t.id == tid),
            "the thread (and its input comments) survives"
        );
    }

    #[test]
    fn deleting_a_session_thread_last_comment_drops_the_thread() {
        // A wholly in-session thread: deleting its only comment removes it.
        let (mut app, _tid, _reply) = app_with_thread(3);
        goto(&mut app, Side::New, 1);
        app.open_new_thread();
        app.on_key_compose(KeyCode::Char('x'), KeyModifiers::NONE);
        app.submit_compose();
        let new_tid = app
            .comments
            .threads
            .iter()
            .find(|t| t.range.contains(1) && t.side == Side::New)
            .expect("new thread")
            .id
            .clone();
        let cid = app
            .comments
            .threads
            .iter()
            .find(|t| t.id == new_tid)
            .unwrap()
            .comments[0]
            .id
            .clone();
        app.selected = comment_head(&app, &cid);
        app.delete_current_comment();
        assert!(
            !app.comments.threads.iter().any(|t| t.id == new_tid),
            "emptying a thread drops it"
        );
    }

    #[test]
    fn comments_are_navigable_stops() {
        let (mut app, _tid, reply_id) = app_with_thread(3);
        // Land on the diff line the thread anchors to, then walk down: we must
        // eventually stop on each comment message (a stop that is not a line).
        goto(&mut app, Side::New, 3);
        let mut comment_stops = 0;
        for _ in 0..40 {
            app.move_by(1, 1);
            if app.comment_unit_at(app.selected).is_some() {
                comment_stops += 1;
            }
        }
        assert!(
            comment_stops >= 2,
            "navigation should stop on each comment message (got {comment_stops})"
        );
        // And the reply message is reachable as its own stop.
        let head = comment_head(&app, &reply_id);
        assert!(app.is_stop_at(head));
    }

    #[test]
    fn paste_inserts_into_composer_and_is_ignored_otherwise() {
        // Outside the composer a paste is a no-op (not replayed as commands).
        let mut app = app_with(DIFF);
        app.on_paste("qqq deletes nothing".into());
        assert!(!app.quit);
        assert!(app.composer.is_none());

        // Inside the composer the whole multi-line paste lands in one shot,
        // with CRLF/CR normalized to `\n`.
        open_composer(&mut app);
        app.on_paste("first line\r\nsecond line\rthird".into());
        assert_eq!(
            app.composer.as_ref().unwrap().textarea.lines().join("\n"),
            "first line\nsecond line\nthird"
        );
        assert!(app.composer.is_some(), "paste must not submit");
    }

    #[test]
    fn resolved_thread_comment_shows_focus_border() {
        // Regression: a resolved thread's box was always drawn with the muted
        // border, even when the cursor was on it — so an individual comment in a
        // resolved thread gave no visual "selected" feedback. Focus must win.
        let (mut app, tid, reply_id) = app_with_thread(3);
        app.comments.toggle_resolved(&tid);
        app.rebuild_rows();
        assert!(app.comments.threads[0].resolved);

        // The reply's individual comment is still a reachable stop...
        let head = comment_head(&app, &reply_id);
        assert!(app.is_stop_at(head));

        // ...and when focused, its box border is the focus color, not muted.
        let cl = app.comment_at(head).unwrap().clone();
        let focused = app.comment_line_to_line(&cl, true, 40);
        let unfocused = app.comment_line_to_line(&cl, false, 40);
        let border_fg = |line: &ratatui::text::Line| {
            // The box border span (`╭`/`│`/`╰`) carries the border color.
            line.spans
                .iter()
                .find(|s| s.content.chars().any(|c| "╭╮╰╯│".contains(c)))
                .and_then(|s| s.style.fg)
        };
        assert_eq!(border_fg(&focused), Some(theme().border_focus));
        assert_eq!(border_fg(&unfocused), Some(theme().muted));
    }

    #[test]
    fn split_view_wraps_comment_body_into_the_half_column() {
        // Regression: comment bodies were wrapped to the full diff width but
        // rendered into a half-width column in split view, so every line got
        // clipped on the right. `sync_comment_wrap` must wrap to the split
        // column width.
        let cs = parse_report(DIFF).0;
        let mut store = CommentStore::default();
        store.add_thread(
            "f.rs".into(),
            Side::New,
            LineRange { start: 2, end: 2 },
            Some("you".into()),
            "The labor market has shifted into a higher gear, powering through \
             an energy shock and immigration restrictions to pull more people."
                .into(),
        );
        let mut app = App::with_comments(cs, store);
        app.view = View::Split;

        // Mirror render_split's column math for a known inner width.
        let inner: u16 = 90;
        app.sync_comment_wrap(inner);
        // Worst case (scrollbar present) side column, as render computes it.
        let side_w = (inner as usize).saturating_sub(1 + SPLIT_DIVIDER.len()) / 2;
        let inner_w = side_w - 2; // borders
        let indent = 3; // columns reserved for the body indent in comment_wrap

        // Every wrapped body fragment must fit the rendered half-column with its
        // indent — i.e. it is never clipped by `take_width`.
        let mut body_rows = 0;
        for i in 0..app.split_rows.len() {
            if let SplitRowKind::Comment { line, .. } = &app.split_rows[i].kind {
                if let CommentKind::Body(b) = &line.kind {
                    body_rows += 1;
                    assert!(
                        str_width(b) + indent <= inner_w,
                        "body fragment {:?} ({}+{}) exceeds split inner width {}",
                        b,
                        str_width(b),
                        indent,
                        inner_w
                    );
                }
            }
        }
        assert!(body_rows >= 2, "long body should wrap to several rows");
    }

    #[test]
    fn focusing_a_comment_selects_the_whole_message_and_its_thread() {
        let (mut app, tid, reply_id) = app_with_thread(3);
        let head = comment_head(&app, &reply_id);
        app.selected = head;

        // The focused-thread action target is the comment's thread.
        assert_eq!(app.focused_thread_id(), Some(tid.clone()));
        assert_eq!(app.focused_comment(), Some((tid, reply_id)));

        // Every row of the message (and only those) is in the selection.
        let (lo, hi) = app.comment_unit_span(head).unwrap();
        assert!(hi >= lo);
        for i in lo..=hi {
            assert!(
                app.in_selection(i),
                "row {i} of the message should highlight"
            );
        }
        assert!(!app.in_selection(lo.saturating_sub(1)) || lo == 0);
        assert!(!app.in_selection(hi + 1));
    }

    #[test]
    fn comment_selection_survives_view_toggle() {
        let (mut app, tid, reply_id) = app_with_thread(3);
        app.selected = comment_head(&app, &reply_id);
        app.toggle_view(); // unified <-> split
        assert_eq!(
            app.focused_comment(),
            Some((tid, reply_id)),
            "the same comment should stay focused across a view switch"
        );
    }

    /// Open a new-thread composer anchored on a known diff line.
    fn open_composer(app: &mut App) {
        goto(app, Side::New, 3);
        app.open_new_thread();
        assert!(app.composer.is_some(), "composer should be open");
    }

    /// The current composer text (no caret), for assertions.
    fn composer_text(app: &App) -> String {
        app.composer.as_ref().unwrap().textarea.lines().join("\n")
    }

    #[test]
    fn composer_supports_readline_cursor_editing() {
        let mut app = app_with(DIFF);
        open_composer(&mut app);
        // Type "ac", move left (←), insert "b" between them — cursor editing.
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('c'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Left, KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('b'), KeyModifiers::NONE);
        assert_eq!(composer_text(&app), "abc");

        // Ctrl+A jumps to line start; typed text lands there.
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::CONTROL);
        app.on_key_compose(KeyCode::Char('X'), KeyModifiers::NONE);
        assert_eq!(composer_text(&app), "Xabc");

        // Ctrl+E jumps to line end.
        app.on_key_compose(KeyCode::Char('e'), KeyModifiers::CONTROL);
        app.on_key_compose(KeyCode::Char('Z'), KeyModifiers::NONE);
        assert_eq!(composer_text(&app), "XabcZ");
    }

    #[test]
    fn cursor_move_rebuilds_the_rendered_composer() {
        // Regression: a cursor-only key (←) doesn't change the text, so
        // TextArea::input returns false. The row stream must still be rebuilt,
        // or the drawn caret would stay put while the real cursor moved.
        let mut app = app_with(DIFF);
        app.toggle_view(); // Split -> Unified, so the caret rides a `Row`
        open_composer(&mut app);
        // Tests never draw, so `comment_wrap` would be 0 and wrap each glyph
        // onto its own line; give the body a real width so it stays one line.
        app.comment_wrap = 40;
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('b'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Left, KeyModifiers::NONE);
        let body = app
            .rows
            .iter()
            .find_map(|r| match &r.kind {
                RowKind::Composer(ComposerLine {
                    kind: ComposerKind::Body(s),
                }) if s.contains(COMPOSER_CARET) => Some(s.clone()),
                _ => None,
            })
            .expect("a composer body row carrying the caret");
        assert_eq!(
            body,
            format!("a{COMPOSER_CARET}b"),
            "the caret marker must follow the cursor"
        );
    }

    #[test]
    fn composer_caret_renders_at_the_cursor() {
        let mut app = app_with(DIFF);
        open_composer(&mut app);
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('b'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::CONTROL); // to start
        let spec = app.composer_spec().expect("composer spec");
        assert_eq!(
            spec.body,
            format!("{COMPOSER_CARET}ab"),
            "caret renders at the cursor, not the end"
        );
    }

    #[test]
    fn composer_body_overlay_fills_exactly_the_inner_width() {
        // Regression: the caret-overlay path must honor the same width contract
        // as `fit` — a body longer than the box is truncated, never overflowed.
        let app = app_with(DIFF);
        let width = 12; // inner_w = width - margin(2) - borders(2) = 8
        let cl = ComposerLine {
            kind: ComposerKind::Body(format!("{COMPOSER_CARET}abcdefghijklmnopqrstuvwxyz")),
        };
        let line = app.composer_line_to_line(&cl, width);
        let total: usize = line.spans.iter().map(|s| str_width(&s.content)).sum();
        assert_eq!(
            total, width,
            "composer body line must fill exactly the row width, even when truncated"
        );
    }

    #[test]
    fn ctrl_d_deletes_forward_and_does_not_cancel() {
        // Ctrl+D is readline delete-forward now, not a cancel chord.
        let mut app = app_with(DIFF);
        open_composer(&mut app);
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('b'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::CONTROL); // to start
        app.on_key_compose(KeyCode::Char('d'), KeyModifiers::CONTROL); // delete 'a'
        assert!(app.composer.is_some(), "Ctrl+D must not cancel");
        assert_eq!(composer_text(&app), "b");
    }

    #[test]
    fn composer_keeps_caret_visible_when_taller_than_viewport() {
        // Regression: typing a long comment scrolled the box's *top* into view
        // and pushed the caret (its bottom body line) off-screen below. The
        // viewport must follow the caret instead.
        let mut app = app_with(DIFF);
        app.height = 6; // viewport far shorter than the box
        app.toggle_view(); // default Split -> Unified (refreshes file span)
        assert!(matches!(app.view, View::Unified));
        open_composer(&mut app);
        for _ in 0..200 {
            app.on_key_compose(KeyCode::Enter, KeyModifiers::NONE);
        }
        app.on_key_compose(KeyCode::Char('x'), KeyModifiers::NONE);
        app.ensure_composer_visible();

        let (s, e) = app.file_range();
        // The caret rides the last composer Body row.
        let caret = (s..e)
            .rev()
            .find(|&i| {
                matches!(
                    app.rows.get(i).map(|r| &r.kind),
                    Some(RowKind::Composer(ComposerLine {
                        kind: ComposerKind::Body(_)
                    }))
                )
            })
            .expect("composer body row");
        assert!(
            caret >= app.scroll && caret < app.scroll + app.height,
            "caret row {caret} must stay within view [{}, {})",
            app.scroll,
            app.scroll + app.height
        );
    }

    #[test]
    fn composer_caret_visible_on_a_tiny_viewport() {
        // The caret sits on the last Body row, with Hint+Bottom chrome below it.
        // Anchoring to the box's bottom border (height < 3) would leave the
        // caret off-screen, so the scroll must follow the body row instead.
        let mut app = app_with(DIFF);
        app.height = 2;
        app.toggle_view(); // default Split -> Unified
        open_composer(&mut app);
        for _ in 0..50 {
            app.on_key_compose(KeyCode::Enter, KeyModifiers::NONE);
        }
        app.on_key_compose(KeyCode::Char('x'), KeyModifiers::NONE);
        app.ensure_composer_visible();

        let (s, e) = app.file_range();
        let caret = (s..e)
            .find(|&i| app.is_composer_caret_at(i))
            .expect("composer caret row");
        assert!(
            caret >= app.scroll && caret < app.scroll + app.height,
            "caret row {caret} must stay within view [{}, {}) on a tiny viewport",
            app.scroll,
            app.scroll + app.height
        );
    }

    #[test]
    fn ensure_composer_visible_follows_caret_upward() {
        // Regression: scrolling anchored to the *last* body row, so with the
        // cursor moved up in a box taller than the viewport, a bottom-anchored
        // scroll left the caret off-screen above. The pass must pull the
        // viewport up to the caret row.
        let mut app = app_with(DIFF);
        app.height = 4;
        app.toggle_view(); // Split -> Unified
        open_composer(&mut app);
        app.comment_wrap = 40;
        for _ in 0..40 {
            app.on_key_compose(KeyCode::Enter, KeyModifiers::NONE);
        }
        app.on_key_compose(KeyCode::Char('x'), KeyModifiers::NONE);
        // Cursor to the top of the buffer, then force the viewport to the
        // bottom (as if we'd just been typing at the end) and re-run the pass.
        for _ in 0..45 {
            app.on_key_compose(KeyCode::Up, KeyModifiers::NONE);
        }
        let (_, e) = app.file_range();
        app.scroll = e.saturating_sub(app.height); // bottom-anchored
        app.ensure_composer_visible();

        let (s, e) = app.file_range();
        let caret = (s..e)
            .find(|&i| app.is_composer_caret_at(i))
            .expect("composer caret row");
        assert!(
            caret >= app.scroll && caret < app.scroll + app.height,
            "caret row {caret} must stay within view [{}, {}) when the cursor is up",
            app.scroll,
            app.scroll + app.height
        );
    }

    #[test]
    fn bare_enter_inserts_a_newline_in_the_composer() {
        let mut app = app_with(DIFF);
        open_composer(&mut app);
        app.on_key_compose(KeyCode::Char('a'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Enter, KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('b'), KeyModifiers::NONE);
        // A bare Enter must NOT submit — the composer stays open with a newline.
        assert!(app.composer.is_some(), "bare Enter should not submit");
        assert_eq!(
            app.composer.as_ref().unwrap().textarea.lines().join("\n"),
            "a\nb"
        );
    }

    #[test]
    fn ctrl_enter_submits_the_composer() {
        let (mut app, _tid, _reply) = app_with_thread(3);
        let before = app.comments.threads.len();
        goto(&mut app, Side::New, 1);
        app.open_new_thread();
        app.on_key_compose(KeyCode::Char('h'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('i'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Enter, KeyModifiers::CONTROL);
        // Ctrl+Enter submits: composer closes and a new thread is recorded.
        assert!(app.composer.is_none(), "Ctrl+Enter should submit");
        assert_eq!(app.comments.threads.len(), before + 1);
    }

    #[test]
    fn ctrl_s_submits_the_composer() {
        // The protocol-free primary submit: a C0 control byte that survives
        // tmux/SSH even when the kitty keyboard protocol (and thus Ctrl+Enter)
        // is not forwarded.
        let (mut app, _tid, _reply) = app_with_thread(3);
        let before = app.comments.threads.len();
        goto(&mut app, Side::New, 1);
        app.open_new_thread();
        app.on_key_compose(KeyCode::Char('h'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('i'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Char('s'), KeyModifiers::CONTROL);
        assert!(app.composer.is_none(), "Ctrl+S should submit");
        assert_eq!(app.comments.threads.len(), before + 1);
    }

    #[test]
    fn shift_enter_does_not_submit_the_composer() {
        // Regression: Shift+Enter is indistinguishable from a bare Enter under
        // the DISAMBIGUATE_ESCAPE_CODES protocol, so it must behave like one
        // (insert a newline) rather than submit.
        let mut app = app_with(DIFF);
        open_composer(&mut app);
        app.on_key_compose(KeyCode::Char('x'), KeyModifiers::NONE);
        app.on_key_compose(KeyCode::Enter, KeyModifiers::SHIFT);
        assert!(app.composer.is_some(), "Shift+Enter must not submit");
        assert_eq!(
            app.composer.as_ref().unwrap().textarea.lines().join("\n"),
            "x\n"
        );
    }

    // Render into a TestBackend and return the app (button hit rects are
    // recorded during the draw).
    fn render(app: &mut App, w: u16, h: u16) {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| app.draw(f)).unwrap();
    }

    fn click(app: &mut App, r: Rect) {
        app.on_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: r.x,
            row: r.y,
            modifiers: KeyModifiers::NONE,
        });
    }

    #[test]
    fn comment_box_records_reply_and_resolve_buttons() {
        let (mut app, tid, _rid) = app_with_thread(2);
        render(&mut app, 160, 40);
        let hits = app.button_hits.borrow();
        assert!(
            hits.iter()
                .any(|(_, a)| matches!(a, ButtonAction::Reply(t) if *t == tid)),
            "reply button should be recorded"
        );
        assert!(
            hits.iter()
                .any(|(_, a)| matches!(a, ButtonAction::ToggleResolve(t) if *t == tid)),
            "resolve button should be recorded"
        );
    }

    #[test]
    fn clicking_the_reply_button_opens_the_composer() {
        let (mut app, tid, _rid) = app_with_thread(2);
        render(&mut app, 160, 40);
        let rect = app
            .button_hits
            .borrow()
            .iter()
            .find(|(_, a)| matches!(a, ButtonAction::Reply(t) if *t == tid))
            .map(|(r, _)| *r)
            .expect("reply button recorded");
        click(&mut app, rect);
        assert!(app.composer.is_some(), "clicking reply opens the composer");
    }

    #[test]
    fn clicking_the_resolve_button_toggles_the_thread() {
        let (mut app, _tid, _rid) = app_with_thread(2);
        render(&mut app, 160, 40);
        let before = app.comments.threads[0].resolved;
        let rect = app
            .button_hits
            .borrow()
            .iter()
            .find(|(_, a)| matches!(a, ButtonAction::ToggleResolve(_)))
            .map(|(r, _)| *r)
            .expect("resolve button recorded");
        click(&mut app, rect);
        assert_ne!(
            before, app.comments.threads[0].resolved,
            "clicking resolve toggles the thread"
        );
    }

    #[test]
    fn range_comment_box_renders_after_the_last_line() {
        // A New-side range 2..=4 should inject its box right after the row for
        // line 4 (GitHub-style: below the last line), not after line 2.
        let cs = parse_report(DIFF).0;
        let mut store = CommentStore::default();
        store.add_thread(
            "f.rs".into(),
            Side::New,
            LineRange { start: 2, end: 4 },
            Some("a".into()),
            "msg".into(),
        );
        let app = App::with_comments(cs, store);
        let line4 = app
            .rows
            .iter()
            .position(|r| {
                matches!(
                    &r.kind,
                    RowKind::Line {
                        new_line: Some(4),
                        ..
                    }
                )
            })
            .unwrap();
        let top = app
            .rows
            .iter()
            .position(
                |r| matches!(&r.kind, RowKind::Comment(cl) if matches!(cl.kind, CommentKind::Top)),
            )
            .unwrap();
        assert_eq!(
            top,
            line4 + 1,
            "box should immediately follow the last range line"
        );
    }

    #[test]
    fn cursor_diff_line_shows_a_clickable_add_comment_button() {
        let mut app = app_with(DIFF);
        app.focus = Focus::Diff;
        goto(&mut app, Side::New, 2);
        render(&mut app, 120, 40);
        let rect = app
            .button_hits
            .borrow()
            .iter()
            .find(|(_, a)| matches!(a, ButtonAction::AddComment))
            .map(|(r, _)| *r)
            .expect("add-comment button recorded on the cursor line");
        click(&mut app, rect);
        assert!(
            app.composer.is_some(),
            "clicking comment(i) opens a new-thread composer"
        );
    }

    #[test]
    fn composer_records_submit_and_cancel_buttons() {
        let (mut app, _tid, _rid) = app_with_thread(2);
        app.focus = Focus::Diff;
        app.jump_comment(1);
        app.open_reply();
        render(&mut app, 160, 40);
        let hits = app.button_hits.borrow();
        assert!(hits.iter().any(|(_, a)| matches!(a, ButtonAction::Submit)));
        assert!(hits.iter().any(|(_, a)| matches!(a, ButtonAction::Cancel)));
    }
}