hjkl 0.35.0

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
//! Per-frame render functions.
//!
//! [`frame`] is the top-level entry point called from the event loop.
//! It splits the terminal area into a buffer pane + status line row and
//! delegates to [`buffer_pane`] and [`status_line`].

use hjkl_buffer::Viewport;
use hjkl_buffer_tui::{BufferView, DiagOverlay, Gutter, GutterNumbers};
use hjkl_engine::{Host, Query};
use hjkl_statusline::{
    Bar, Color as SlColor, Segment as SlSegment, StatusTheme, Style as SlStyle, StyleExt,
    dirty_segment, filename_segment, loading_segment, mode_segment, pending_segment,
    search_count_segment, truncate_filename,
};
use hjkl_vim::VimEditorExt;
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph},
};

use crate::app::{App, DiagSeverity, DiskState, STATUS_LINE_HEIGHT, TOP_BAR_HEIGHT, window};
use hjkl_holler_tui::{HollerLayout, render_active};
use hjkl_prompt_tui::{PromptTheme, build_prompt_line};
use hjkl_tabs::TabBar;
use hjkl_tabs_tui::{TabBarTheme, build_line as build_tab_line};

// ── Explorer color constants ──────────────────────────────────────────────────

/// Git-status BACKGROUND colors for explorer filenames. The status is shown as
/// the name's background so the filetype/dir foreground color stays distinct
/// from the git state. The name text itself is repainted [`GIT_TEXT`] for
/// contrast against these mid-tone backgrounds.
const GIT_MODIFIED: Color = Color::Rgb(0xd7, 0x87, 0x5f);
const GIT_STAGED: Color = Color::Rgb(0x87, 0xaf, 0x5f);
const GIT_DELETED: Color = Color::Rgb(0xd7, 0x5f, 0x5f);
const GIT_UNTRACKED: Color = Color::Rgb(0x5f, 0xaf, 0xaf);

/// High-contrast text color painted over a git-status background so the
/// filename stays readable on any of the mid-tone status backgrounds.
const GIT_TEXT: Color = Color::Rgb(0x1c, 0x1c, 0x1c);

/// Convert an `Option<(u8,u8,u8)>` RGB triple to a ratatui `Color::Rgb`.
fn rgb(o: Option<(u8, u8, u8)>) -> Option<Color> {
    o.map(|(r, g, b)| Color::Rgb(r, g, b))
}

/// Convert a `ratatui::style::Color::Rgb` to `hjkl_statusline::Color`.
/// Named/indexed colors fall back to white.
fn ratatui_rgb_to_sl(c: Color) -> SlColor {
    match c {
        Color::Rgb(r, g, b) => SlColor::rgb(r, g, b),
        _ => SlColor::rgb(0xff, 0xff, 0xff),
    }
}

/// Convert a `ratatui::style::Color::Rgb` to `hjkl_theme::Color`.
/// Named/indexed colors fall back to white.
fn to_hjkl_color(c: Color) -> hjkl_theme::Color {
    match c {
        Color::Rgb(r, g, b) => hjkl_theme::Color::rgb(r, g, b),
        _ => hjkl_theme::Color::rgb(0xff, 0xff, 0xff),
    }
}

/// Build a `StatusTheme` from the app's `UiTheme`.
///
/// `StatusTheme` is `#[non_exhaustive]`; construct via `Default` + field mutation
/// so new colour slots added upstream don't break this site.
fn app_status_theme(app: &App) -> StatusTheme {
    let ui = &app.theme.ui;
    let mut t = StatusTheme::default();
    t.bg = ratatui_rgb_to_sl(ui.surface_bg);
    t.fg = ratatui_rgb_to_sl(ui.text);
    t.fill_bg = ratatui_rgb_to_sl(ui.panel_bg);
    t.mode_normal_bg = ratatui_rgb_to_sl(ui.mode_normal_bg);
    t.mode_normal_fg = ratatui_rgb_to_sl(ui.on_accent);
    t.mode_insert_bg = ratatui_rgb_to_sl(ui.mode_insert_bg);
    t.mode_insert_fg = ratatui_rgb_to_sl(ui.on_accent);
    t.mode_visual_bg = ratatui_rgb_to_sl(ui.mode_visual_bg);
    t.mode_visual_fg = ratatui_rgb_to_sl(ui.on_accent);
    t.dirty_fg = ratatui_rgb_to_sl(ui.status_dirty_marker);
    t.readonly_fg = ratatui_rgb_to_sl(ui.text);
    t.new_file_fg = ratatui_rgb_to_sl(ui.text);
    t.recording_bg = ratatui_rgb_to_sl(ui.recording_bg);
    t.recording_fg = ratatui_rgb_to_sl(ui.recording_fg);
    t
}

/// Build the normal-mode status bar as an agnostic `Bar`.
///
/// Populates left/right segments from app state. The caller converts
/// to ratatui via `hjkl_statusline_tui::to_line`.
pub(crate) fn build_normal_status_bar(app: &App, width: u16) -> Line<'static> {
    let theme = app_status_theme(app);
    let ui = &app.theme.ui;
    let mode = app.mode_label();

    let mut bar = Bar {
        fill_style: SlStyle::default_style()
            .bg(ratatui_rgb_to_sl(ui.panel_bg))
            .fg(ratatui_rgb_to_sl(ui.text)),
        ..Default::default()
    };

    // ── Left side ────────────────────────────────────────────────────────────
    // Note: recording @r is handled in build_status_line as a full-line
    // takeover (vim bottom-line behaviour). It never reaches this path.
    bar.left.push(mode_segment(mode, &theme));

    {
        let pc = app.active_editor().pending_count();
        let po = app.active_editor().pending_op();
        let po_str = po.map(|s| s.to_string());
        if let Some(seg) = pending_segment(pc.map(|n| n as u64), po_str.as_deref(), &theme) {
            bar.left.push(seg);
        }
    }

    // Filename with tags.
    let ro_tag = if app.active_editor().is_readonly() {
        " [RO]"
    } else {
        ""
    };
    let new_tag = if app.active().is_new_file {
        " [New File]"
    } else {
        ""
    };
    let disk_tag = match app.active().disk_state {
        DiskState::DeletedOnDisk => " [deleted]",
        DiskState::ChangedOnDisk => " [changed on disk]",
        DiskState::Synced => "",
    };
    let untracked_tag = if app.active().is_untracked && !app.active().is_new_file {
        " [Untracked]"
    } else {
        ""
    };
    let raw_filename: String = app
        .active()
        .filename
        .as_ref()
        .and_then(|p| p.to_str())
        .unwrap_or("[No Name]")
        .to_owned();
    let suffix = format!("{ro_tag}{new_tag}{disk_tag}{untracked_tag}");

    // Reserve space for all right-side blocks + filename padding + suffix
    // to determine how many chars the filename itself can occupy.
    // We use char counts to stay consistent with Bar::layout.
    let (row, col) = app.active_editor().cursor();
    let line_count = app.active_editor().buffer().line_count() as usize;

    let pos_content = format!(" {}:{} ", row + 1, col + 1);
    let pct_content = {
        let pct = ((row + 1) * 100).checked_div(line_count).unwrap_or(0);
        format!(" {pct}% ")
    };

    // Build loading label (used both for reservation + actual segment).
    let loading_label: String = if !app.lsp_pending.is_empty() {
        let label = app
            .lsp_pending
            .values()
            .next()
            .map(|p| match p {
                crate::app::LspPendingRequest::GotoDefinition { .. } => "definition",
                crate::app::LspPendingRequest::GotoDeclaration { .. } => "declaration",
                crate::app::LspPendingRequest::GotoTypeDefinition { .. } => "type definition",
                crate::app::LspPendingRequest::GotoImplementation { .. } => "implementation",
                crate::app::LspPendingRequest::GotoReferences { .. } => "references",
                crate::app::LspPendingRequest::Hover { .. } => "hover",
                crate::app::LspPendingRequest::Completion { .. } => "completion",
                crate::app::LspPendingRequest::CodeAction { .. } => "code action",
                crate::app::LspPendingRequest::Rename { .. } => "rename",
                _ => "request",
            })
            .unwrap_or("request");
        format!("{} LSP:{label}", hjkl_editor_tui::spinner::frame())
    } else {
        let names = app.directory.in_flight_names();
        match names.len() {
            0 => String::new(),
            1 => format!("{} grammar:{}", hjkl_editor_tui::spinner::frame(), names[0]),
            n => format!(
                "{} grammar:{} +{}",
                hjkl_editor_tui::spinner::frame(),
                names[0],
                n - 1
            ),
        }
    };

    // Build diag count content.
    let diag_count_content: String = {
        let diags = &app.active().lsp_diags;
        if diags.is_empty() {
            String::new()
        } else {
            let e = diags
                .iter()
                .filter(|d| d.severity == DiagSeverity::Error)
                .count();
            let w2 = diags
                .iter()
                .filter(|d| d.severity == DiagSeverity::Warning)
                .count();
            let i = diags
                .iter()
                .filter(|d| d.severity == DiagSeverity::Info)
                .count();
            let h = diags
                .iter()
                .filter(|d| d.severity == DiagSeverity::Hint)
                .count();
            let mut parts = Vec::new();
            if e > 0 {
                parts.push(format!("E:{e}"));
            }
            if w2 > 0 {
                parts.push(format!("W:{w2}"));
            }
            if i > 0 {
                parts.push(format!("I:{i}"));
            }
            if h > 0 {
                parts.push(format!("H:{h}"));
            }
            if parts.is_empty() {
                String::new()
            } else {
                format!(" {} ", parts.join(" "))
            }
        }
    };

    // Search count content.
    let search_count_content: String = search_count(app)
        .map(|(idx, total)| format!(" [{idx}/{total}] "))
        .unwrap_or_default();

    // Dirty marker content.
    let dirty_content = if app.active().dirty { "" } else { "" };

    // Compute available chars for filename:
    // total = left_fixed + " " + name + suffix + " " + dirty + search + diag + loading + pos + pct
    // Note: rec_chars omitted — recording is a full-line takeover handled in
    // build_status_line and never reaches this function.
    let w = width as usize;
    let mode_chars = mode.chars().count() + 2; // " MODE "
    let pending_chars = {
        let pc = app.active_editor().pending_count();
        let po = app.active_editor().pending_op();
        match (pc, po) {
            (Some(n), Some(op)) => format!(" {n}{op} ").chars().count(),
            (Some(n), None) => format!(" {n} ").chars().count(),
            (None, Some(op)) => format!(" {op} ").chars().count(),
            (None, None) => 0,
        }
    };
    let right_chars = pos_content.chars().count() + pct_content.chars().count();
    let loading_chars = if loading_label.is_empty() {
        0
    } else {
        loading_label.chars().count() + 2 // " ... "
    };
    let reserved = mode_chars
        + pending_chars
        + 2 // " name "
        + suffix.chars().count()
        + dirty_content.chars().count()
        + search_count_content.chars().count()
        + diag_count_content.chars().count()
        + loading_chars
        + right_chars;
    let avail_for_name = w.saturating_sub(reserved);
    let filename = truncate_filename(&raw_filename, avail_for_name);

    bar.left.push(filename_segment(&filename, &suffix, &theme));

    // ── Left-side extras (dirty, search, diag, loading) go as left segments ─
    if let Some(seg) = dirty_segment(app.active().dirty, &theme) {
        bar.left.push(seg);
    }

    if !search_count_content.is_empty() {
        bar.left.push(search_count_segment(
            0, // dummy — we use raw content via loading_segment
            0, &theme,
        ));
        // Replace last segment with the actual pre-formatted content.
        if let Some(SlSegment::Text { content, .. }) = bar.left.last_mut() {
            *content = search_count_content.clone().into();
        }
    }

    if !diag_count_content.is_empty() {
        // Color by highest severity — routed through StatusTheme so the host
        // controls the palette (adapts to terminal-named colors vs RGB).
        let diags = &app.active().lsp_diags;
        let diag_fg = if diags.iter().any(|d| d.severity == DiagSeverity::Error) {
            theme.diag_error_fg
        } else if diags.iter().any(|d| d.severity == DiagSeverity::Warning) {
            theme.diag_warning_fg
        } else if diags.iter().any(|d| d.severity == DiagSeverity::Info) {
            theme.diag_info_fg
        } else {
            theme.diag_hint_fg
        };
        bar.left.push(SlSegment::Text {
            content: diag_count_content.clone().into(),
            style: SlStyle::default_style()
                .bg(ratatui_rgb_to_sl(ui.surface_bg))
                .fg(diag_fg),
        });
    }

    if !loading_label.is_empty() {
        bar.left.push(loading_segment(&loading_label, "", &theme));
        // Fix content: loading_segment adds " frame label " but we want " frame+label "
        if let Some(SlSegment::Text { content, .. }) = bar.left.last_mut() {
            *content = format!(" {loading_label} ").into();
        }
    }

    // ── Right side ───────────────────────────────────────────────────────────
    bar.right.push(SlSegment::Text {
        content: pos_content.into(),
        style: SlStyle::default_style()
            .bg(ratatui_rgb_to_sl(ui.surface_bg))
            .fg(ratatui_rgb_to_sl(ui.text)),
    });
    bar.right.push(SlSegment::Text {
        content: pct_content.into(),
        style: SlStyle::default_style()
            .bg(ratatui_rgb_to_sl(ui.mode_normal_bg))
            .fg(ratatui_rgb_to_sl(ui.on_accent))
            .bold(),
    });

    hjkl_statusline_tui::to_line(&bar, width)
}

/// Build the style for a diagnostic severity used in overlays and the status line.
/// Style for the diagnostic span overlay on the offending code. Only the
/// *underline* is colored (by severity) — the text keeps its syntax-highlight
/// foreground, so the line is not recolored, just underlined. Applied via
/// `Style::patch`, so leaving `fg` unset preserves the cell's existing color.
fn diag_severity_style(sev: DiagSeverity) -> Style {
    Style::default()
        .underline_color(diag_severity_fg(sev))
        .add_modifier(Modifier::UNDERLINED)
}

/// Severity color: red = error, orange = warning, green = information,
/// cyan = hint. Used for the colored underline on the offending span and for
/// the inline end-of-line ghost-text hint, so both read the same palette.
fn diag_severity_fg(sev: DiagSeverity) -> Color {
    match sev {
        DiagSeverity::Error => Color::Red,
        DiagSeverity::Warning => Color::Rgb(255, 165, 0), // orange
        DiagSeverity::Info => Color::Green,
        DiagSeverity::Hint => Color::Cyan,
    }
}

/// Sort rank for severity — lower is more severe. Used to pick the single
/// diagnostic to surface as the cursor-line inline hint.
fn diag_severity_rank(sev: DiagSeverity) -> u8 {
    match sev {
        DiagSeverity::Error => 0,
        DiagSeverity::Warning => 1,
        DiagSeverity::Info => 2,
        DiagSeverity::Hint => 3,
    }
}

/// Char-safe truncation with an ellipsis. Byte-indexing `&str` panics when the
/// cut lands inside a multi-byte char (CJK / emoji); counting chars avoids it.
fn truncate_chars(s: &str, max: usize) -> String {
    if s.chars().count() > max {
        format!("{}\u{2026}", s.chars().take(max).collect::<String>())
    } else {
        s.to_string()
    }
}

/// `true` when `row` falls inside the visible viewport `[vp_top, vp_bot)`.
///
/// Shared by [`build_diag_overlays`] and the eol-hint builder in
/// `render_window` so both skip diagnostics outside the current viewport
/// instead of touching every entry of the uncapped `slot.lsp_diags` list
/// every frame (audit D2 — allocation churn proportional to total diagnostic
/// count, independent of what's on screen).
fn row_in_viewport(row: usize, vp_top: usize, vp_bot: usize) -> bool {
    row >= vp_top && row < vp_bot
}

/// Build `DiagOverlay` items for the active buffer slot, filtered to the
/// visible viewport `[vp_top, vp_bot)`. Called once per frame per visible
/// window in `render_window`.
fn build_diag_overlays(
    slot: &crate::app::BufferSlot,
    _ui: &crate::theme::UiTheme,
    vp_top: usize,
    vp_bot: usize,
) -> Vec<DiagOverlay> {
    slot.lsp_diags
        .iter()
        .filter(|d| row_in_viewport(d.start_row, vp_top, vp_bot))
        .map(|d| DiagOverlay {
            row: d.start_row,
            col_start: d.start_col,
            col_end: if d.end_row == d.start_row && d.end_col > d.start_col {
                d.end_col
            } else {
                d.start_col + 1
            },
            style: diag_severity_style(d.severity),
        })
        .collect()
}

/// Widest line-number gutter across all open (non-explorer) buffers, so the
/// number column can be sized to the biggest file and the text column stays put
/// when switching buffers. Buffers with line numbers off contribute 0.
pub(crate) fn max_lnum_width(app: &App) -> u16 {
    app.slots()
        .iter()
        .filter(|s| !s.is_explorer)
        .map(|s| s.lnum_width())
        .max()
        .unwrap_or(0)
}

/// Stable `(sign_column_width, fold_column_width)` reserved for ALL non-explorer
/// buffers — sized to the max each would need across every open buffer. This
/// keeps the text column from shifting when a diagnostic/git sign (or a fold)
/// appears in one buffer but not another (or scrolls in/out of view): once any
/// buffer needs a sign/fold column, it's reserved everywhere.
///
/// The sign decision uses whether a buffer has ANY signs (not just ones in the
/// current viewport), so scrolling within a buffer doesn't jiggle either.
pub(crate) fn stable_gutter_extra(app: &App) -> (u16, u16) {
    use hjkl_engine::types::SignColumnMode;
    let mut sign_w = 0u16;
    let mut fold_w = 0u16;
    for slot in app.slots().iter().filter(|s| !s.is_explorer) {
        let st = slot.settings();
        let has_any_signs = !slot.diag_signs.is_empty()
            || !slot.diag_signs_lsp.is_empty()
            || !slot.git_signs.is_empty();
        let sw = match st.signcolumn {
            SignColumnMode::Yes => 1,
            SignColumnMode::No => 0,
            SignColumnMode::Auto => {
                if has_any_signs {
                    1
                } else {
                    0
                }
            }
        };
        sign_w = sign_w.max(sw);
        let has_folds = !slot.buffer().folds().is_empty();
        let fw = (st.foldcolumn.min(12) as u16).max(if has_folds { 1 } else { 0 });
        fold_w = fold_w.max(fw);
    }
    // Window-level folds: the shared buffer only holds the focused window's
    // set, so an unfocused window with folds wouldn't be seen by the loop
    // above. Reserve the fold column if ANY window's snapshot has folds.
    if fold_w == 0 && app.window_folds.values().any(|f| !f.is_empty()) {
        fold_w = 1;
    }
    (sign_w, fold_w)
}

/// Total rendered gutter width (sign + number + fold cells) for `slot_idx`,
/// matching exactly what `render_window` draws: the number column is sized to
/// the cross-buffer max, and the sign/fold columns are the stable reserved
/// widths. The explorer pane is gutterless (0). This is the single source of
/// truth shared with the mouse hit-test so clicks map to the right column even
/// when the gutter is widened beyond the buffer's own line-count width.
pub(crate) fn rendered_gutter_width(app: &App, win_id: window::WindowId) -> u16 {
    let Some(Some(win)) = app.windows.get(win_id) else {
        return 0;
    };
    let slot_idx = win.slot;
    let Some(slot) = app.slots().get(slot_idx) else {
        return 0;
    };
    if slot.is_explorer {
        return 0;
    }
    let (sign_w, fold_w) = stable_gutter_extra(app);
    // lnum_width depends on per-window `number`/`relativenumber` (#151 Phase D) —
    // read this window's editor so the mouse gutter matches render_window's.
    let own_lnum = app
        .window_editors
        .get(&win_id)
        .map(|e| e.lnum_width())
        .unwrap_or_else(|| slot.lnum_width());
    let num_gw = if own_lnum > 0 { max_lnum_width(app) } else { 0 };
    sign_w + num_gw + fold_w
}

/// Parse a comma-separated colorcolumn string into a sorted `Vec<u16>` of
/// 1-based column indices. Non-numeric or zero entries are silently ignored.
fn parse_colorcolumn(cc: &str) -> Vec<u16> {
    if cc.is_empty() {
        return Vec::new();
    }
    let mut cols: Vec<u16> = cc
        .split(',')
        .filter_map(|s| s.trim().parse::<u16>().ok())
        .filter(|&n| n > 0)
        .collect();
    cols.sort_unstable();
    cols.dedup();
    cols
}

/// Bg painted across the cursor row in both the editor pane and the
/// picker preview pane. Subtle blue-grey — visible enough to track the
/// cursor at a glance without competing with the syntax foreground.
fn cursor_line_bg(theme: &crate::theme::UiTheme) -> Style {
    Style::default().bg(theme.cursor_line_bg)
}

/// Base background painted behind the editor text area + gutter (#303).
///
/// Returns `Style::default()` (no fill — the terminal's own background shows
/// through, vim's transparent behaviour) when `app.theme_transparent` is set;
/// otherwise a `bg`-only style using the theme's editor background. Threaded
/// into [`hjkl_buffer_tui::BufferView::background`], which layers it under
/// syntax / cursorline / selection styling.
pub(crate) fn buffer_background_style(app: &App) -> Style {
    if app.theme_transparent {
        Style::default()
    } else {
        Style::default().bg(app.theme.ui.background)
    }
}

/// Split a `Rect` into two parts according to `dir` and `ratio`.
fn split_rect(area: Rect, dir: window::SplitDir, ratio: f32) -> (Rect, Rect) {
    match dir.axis() {
        window::Axis::Row => {
            let a_h = ((area.height as f32) * ratio).round() as u16;
            let a_h = a_h.clamp(1, area.height.saturating_sub(1).max(1));
            let b_h = area.height.saturating_sub(a_h);
            let rect_a = Rect {
                x: area.x,
                y: area.y,
                width: area.width,
                height: a_h,
            };
            let rect_b = Rect {
                x: area.x,
                y: area.y + a_h,
                width: area.width,
                height: b_h,
            };
            (rect_a, rect_b)
        }
        window::Axis::Col => {
            let a_w = ((area.width as f32) * ratio).round() as u16;
            let a_w = a_w.clamp(1, area.width.saturating_sub(1).max(1));
            let b_w = area.width.saturating_sub(a_w);
            let rect_a = Rect {
                x: area.x,
                y: area.y,
                width: a_w,
                height: area.height,
            };
            let rect_b = Rect {
                x: area.x + a_w,
                y: area.y,
                width: b_w,
                height: area.height,
            };
            (rect_a, rect_b)
        }
    }
}

/// Draw a 1-cell-wide separator between sibling panes.
///
/// For `SplitDir::Vertical` (side-by-side panes) the separator is a column
/// of `│` characters. For `SplitDir::Horizontal` (stacked panes) it is a
/// row of `─` characters. The separator uses `theme.border` so it matches
/// the popup / picker border color without requiring a new theme field.
fn draw_separator(
    frame: &mut Frame,
    sep_rect: Rect,
    dir: window::SplitDir,
    border_color: ratatui::style::Color,
) {
    use ratatui::buffer::Cell;
    let style = Style::default().fg(border_color);
    let (glyph, glyph_width) = match dir.axis() {
        window::Axis::Col => ("", 1u16),
        window::Axis::Row => ("", 1u16),
    };
    let buf = frame.buffer_mut();
    match dir.axis() {
        window::Axis::Col => {
            // sep_rect is a single column; iterate rows.
            for row in sep_rect.y..sep_rect.y + sep_rect.height {
                if let Some(cell) = buf.cell_mut((sep_rect.x, row)) {
                    *cell = Cell::default();
                    cell.set_symbol(glyph);
                    cell.set_style(style);
                }
            }
        }
        window::Axis::Row => {
            // sep_rect is a single row; iterate columns.
            let mut col = sep_rect.x;
            while col < sep_rect.x + sep_rect.width {
                if let Some(cell) = buf.cell_mut((col, sep_rect.y)) {
                    *cell = Cell::default();
                    cell.set_symbol(glyph);
                    cell.set_style(style);
                    col += glyph_width;
                } else {
                    break;
                }
            }
        }
    }
}

/// Walk the layout tree and render each leaf window into its allocated rect.
/// Takes `&mut LayoutTree` so that Split nodes can record their `last_rect`
/// for use by resize commands in later phases.
fn render_layout(frame: &mut Frame, app: &mut App, area: Rect, layout: &mut window::LayoutTree) {
    match layout {
        window::LayoutTree::Leaf(id) => render_window(frame, app, area, *id),
        window::LayoutTree::Split {
            dir,
            ratio,
            a,
            b,
            last_rect,
        } => {
            // Record the FULL rect (pre-separator) so that resize commands
            // can convert line/column deltas to ratio updates correctly.
            *last_rect = Some(window::rect_to_layout(area));

            let (rect_a, rect_b) = split_rect(area, *dir, *ratio);

            // Carve a 1-cell separator between the two child rects and
            // shrink the right/bottom child by 1 cell so children never
            // overlap the separator. Skip when the rect is too small.
            let border_color = app.theme.ui.border;
            let (rect_a, sep_rect, rect_b) = match dir.axis() {
                window::Axis::Col => {
                    // Side-by-side: separator is the rightmost column of rect_a.
                    // Shrink rect_a by 1 on the right; sep is that freed column;
                    // rect_b stays (it already starts right after rect_a).
                    if rect_a.width < 2 || rect_b.width == 0 {
                        // Too narrow — no separator, pass through as-is.
                        (rect_a, None, rect_b)
                    } else {
                        let a_shrunk = Rect {
                            width: rect_a.width.saturating_sub(1),
                            ..rect_a
                        };
                        let sep = Rect {
                            x: rect_a.x + rect_a.width.saturating_sub(1),
                            y: rect_a.y,
                            width: 1,
                            height: rect_a.height,
                        };
                        (a_shrunk, Some(sep), rect_b)
                    }
                }
                window::Axis::Row => {
                    // Stacked: separator is the bottom row of rect_a.
                    if rect_a.height < 2 || rect_b.height == 0 {
                        (rect_a, None, rect_b)
                    } else {
                        let a_shrunk = Rect {
                            height: rect_a.height.saturating_sub(1),
                            ..rect_a
                        };
                        let sep = Rect {
                            x: rect_a.x,
                            y: rect_a.y + rect_a.height.saturating_sub(1),
                            width: rect_a.width,
                            height: 1,
                        };
                        (a_shrunk, Some(sep), rect_b)
                    }
                }
            };

            render_layout(frame, app, rect_a, a);
            render_layout(frame, app, rect_b, b);

            // Draw separator on top of both children after they render so
            // that no window content bleeds into the separator cell.
            if let Some(sep) = sep_rect {
                draw_separator(frame, sep, *dir, border_color);
            }
        }
        // `LayoutTree` is `#[non_exhaustive]`; unknown variant → skip rendering.
        _ => {}
    }
}

/// Render a single window occupying `area`.
fn render_window(frame: &mut Frame, app: &mut App, area: Rect, win_id: window::WindowId) {
    // Record the rendered rect for Phase 2+ direction navigation.
    if let Some(win) = app.windows[win_id].as_mut() {
        win.last_rect = Some(window::rect_to_layout(area));
    }

    // Extract window metadata (then drop the borrow so we can access slots).
    let (slot_idx, is_focused) = {
        let win = match app.windows[win_id].as_ref() {
            Some(w) => w,
            None => return, // closed window — skip
        };
        (win.slot, win_id == app.focused_window())
    };

    // 1-col left/right padding for the file list so it isn't flush against
    // the pane edges.
    let mut area = area;
    if app.slots()[slot_idx].is_explorer && area.width >= 2 {
        area.x += 1;
        area.width -= 2;
    }

    // Per-window state (#151 Phase D): settings, cursor, viewport, blame-view
    // come from THIS window's editor. Buffer + syntax spans + per-buffer
    // metadata (blame data, diag/git signs) stay on the slot editor (shared).
    let win_settings = app
        .window_editors
        .get(&win_id)
        .map(|e| e.settings().clone())
        .unwrap_or_else(|| app.slots()[slot_idx].settings().clone());
    let s = &win_settings;
    // `is_blame` has no slot-level counterpart (#151 Stage 2b — it's
    // transient per-window UI state, never meant to persist beyond a
    // window's life); default it off in the (should-not-happen) fallback.
    let (w_cursor_row, w_is_blame) = app
        .window_editors
        .get(&win_id)
        .map(|e| (e.buffer().cursor().row, e.is_blame()))
        .unwrap_or_else(|| (app.slots()[slot_idx].buffer().cursor().row, false));
    let (nu, rnu) = (s.number, s.relativenumber);
    let (cul, cuc) = (s.cursorline, s.cursorcolumn);
    let colorcolumn = s.colorcolumn.clone();
    let list_active = s.list;
    let listchars_owned = s.listchars.clone();
    let indent_guides_enabled = s.indent_guides;
    let indent_guide_char = s.indent_guide_char;
    let indent_guide_shiftwidth = s.shiftwidth;
    let indent_guide_tabstop = s.tabstop;

    // Stable sign + fold columns: reserve the max width each would need across
    // ALL open buffers, so a diagnostic/git sign (or fold) appearing in one
    // buffer doesn't shift the text column when switching buffers or scrolling.
    // The explorer pane is gutterless.
    let is_explorer_slot = app.slots()[slot_idx].is_explorer;
    let (sign_w, fold_w) = if is_explorer_slot {
        (0, 0)
    } else {
        stable_gutter_extra(app)
    };
    // Stable line-number gutter: when this buffer shows numbers, size the column
    // to the widest needed across ALL open buffers (the biggest file's line
    // count) so switching buffers doesn't shift the text column horizontally.
    let own_lnum = app
        .window_editors
        .get(&win_id)
        .map(|e| e.lnum_width())
        .unwrap_or_else(|| app.slots()[slot_idx].lnum_width());
    let num_gw_for_text = if own_lnum > 0 { max_lnum_width(app) } else { 0 };
    // Extra padding added to the number column beyond the buffer's own width —
    // folded into the cursor's gutter offset below so the caret stays aligned.
    let lnum_pad = num_gw_for_text.saturating_sub(own_lnum);
    let gw = sign_w + num_gw_for_text + fold_w;
    let text_width = area.width.saturating_sub(gw);

    // For the focused window: publish viewport dims into the engine so
    // scrolloff math and cursor-screen-pos work correctly.
    if is_focused {
        let tabstop = s.tabstop as u16;
        if let Some(e) = app.window_editors.get_mut(&win_id) {
            let vp = e.host_mut().viewport_mut();
            vp.width = text_width;
            vp.height = area.height;
            vp.text_width = text_width;
            vp.tab_width = tabstop;
            e.set_viewport_height(area.height);
        }
    }

    // Relative/hybrid line numbers count from THIS window's cursor row. The
    // focused window's editor cursor is authoritative and matches its saved
    // `cursor_row`; an unfocused window must use its own saved row so its
    // relative numbers don't count from the active window's cursor.
    let cursor_row = w_cursor_row;
    let numbers = match (nu, rnu) {
        (false, false) => GutterNumbers::None,
        (true, false) => GutterNumbers::Absolute,
        (false, true) => GutterNumbers::Relative { cursor_row },
        (true, true) => GutterNumbers::Hybrid { cursor_row },
    };
    // Number-column width only (sign/fold widths are tracked separately).
    // Uses the stable cross-buffer max computed above.
    let num_gw = num_gw_for_text;
    let gutter = if num_gw > 0 || sign_w > 0 || fold_w > 0 {
        Some(Gutter {
            width: num_gw,
            style: Style::default().fg(app.theme.ui.gutter),
            line_offset: 0,
            numbers,
            sign_column_width: sign_w,
            fold_column_width: fold_w,
        })
    } else {
        None
    };

    // Viewport for this window: focused uses editor's live viewport (with
    // auto-scroll applied); non-focused builds one from the window's own
    // stored scroll position so it doesn't chase the focused editor.
    // This window's viewport comes from its own editor (#151 Phase D): focused
    // windows get live auto-scrolled scroll; non-focused windows keep the scroll
    // they were left at (their editor isn't dispatched while unfocused).
    let mut viewport_owned = app
        .window_editors
        .get(&win_id)
        .map(|e| *e.host().viewport())
        .unwrap_or_default();
    viewport_owned.width = text_width;
    viewport_owned.height = area.height;
    viewport_owned.text_width = text_width;

    // Smooth-scroll (#195): interpolate the RENDER top so the text
    // `BufferView` paints below and the overlays that key off `vp_top`
    // (signs, matchparen, hop, diff bands, the explorer devicon pass) all
    // agree on which doc rows are on screen during an active anim.
    //
    // Before this fix, `vp_top` was computed (as below) and used ONLY by
    // the overlays — `viewport_owned.top_row` (what `BufferView` actually
    // draws from, `viewport_ref` below) stayed at the FINAL target the
    // whole time. So the feature was visually inert (text never moved
    // during the anim) AND the overlays were misaligned relative to that
    // static text by up to `|target - start|` rows while a scroll was
    // mid-flight. Writing the animated top back into `viewport_owned`
    // before `viewport_ref` is taken fixes both at once.
    //
    // `target_top_row` (the real, un-animated top) is kept for the cursor
    // block further down: `Editor::cursor_screen_pos` reads the ENGINE's
    // own live viewport (a separate object from this function's local
    // `viewport_owned` snapshot, so it's untouched by the write below) and
    // has no "compute from an arbitrary top" variant — it always resolves
    // the cursor's screen row from the target top. Left alone, the cursor
    // would now be the thing that disagrees with the animated text (the
    // exact bug this fix is closing, just moved from overlays to the
    // cursor); the cursor block re-derives the screen row from `vp_top`
    // using the same fold/wrap-aware row counting the engine uses
    // (`View::screen_rows_between`) to keep it in step.
    let target_top_row = viewport_owned.top_row;
    let vp_top = app.scroll_anim_render_top(win_id).unwrap_or(target_top_row);
    viewport_owned.top_row = vp_top;
    let viewport_ref: &Viewport = &viewport_owned;

    let in_prompt = app.command_field.is_some()
        || app.filter_field.is_some()
        || app.search_field.is_some()
        || app.picker.is_some()
        || app.explorer_git_discard_confirm.is_some();

    // Merge diagnostic + LSP diag + git signs, filtered to the visible viewport.
    let vp_bot = vp_top + area.height as usize;
    let mut visible_signs: Vec<hjkl_buffer_tui::Sign> = app.slots()[slot_idx]
        .diag_signs
        .iter()
        .copied()
        .filter(|s| s.row >= vp_top && s.row < vp_bot)
        .chain(
            app.slots()[slot_idx]
                .diag_signs_lsp
                .iter()
                .copied()
                .filter(|s| s.row >= vp_top && s.row < vp_bot),
        )
        .chain(
            app.slots()[slot_idx]
                .git_signs
                .iter()
                .copied()
                .filter(|s| s.row >= vp_top && s.row < vp_bot),
        )
        .collect();
    visible_signs.sort_by_key(|s| s.row);

    // Visual selection belongs to the focused window only. The selection is
    // editor state shared by every window on the same slot, so an unfocused
    // split would otherwise paint the active window's selection too.
    let selection = if is_focused {
        app.window_editors
            .get(&win_id)
            .and_then(|e| e.buffer_selection())
    } else {
        None
    };
    // styled_spans / style_table live on the window editor, not the slot
    // (#151 Stage 2b — see `App::install_syntax_spans_for_slot`): a buffer
    // open in N splits gets N independent installs, and a span's `style` id
    // only resolves correctly against the SAME editor's style table that
    // assigned it. `syntax_glue::recompute_and_install` installs into every
    // window showing a slot, so a live window editor always has spans by the
    // time it's focused enough to render with signs/gutter; the fallback
    // here (no window editor yet) is the same "should not happen" case as
    // elsewhere and just renders unstyled.
    let buffer_spans: &[Vec<hjkl_buffer::Span>] = app
        .window_editors
        .get(&win_id)
        .map(|e| e.buffer_spans())
        .unwrap_or(&[]);
    let search_pattern_owned = app
        .window_editors
        .get(&win_id)
        .and_then(|e| e.search_state().pattern.clone());
    let search_pattern = search_pattern_owned.as_ref();

    let search_bg = if search_pattern.is_some() {
        app.theme.ui.search_match_style()
    } else {
        Style::default()
    };

    let style_table = app
        .window_editors
        .get(&win_id)
        .map(|e| e.style_table().to_owned())
        .unwrap_or_default();
    let resolver = move |id: u32| {
        hjkl_engine_tui::style_to_ratatui(style_table.get(id as usize).copied().unwrap_or_default())
    };

    // For non-focused windows, don't show cursor highlight or cursor position.
    let show_cursor = is_focused && !in_prompt;

    // Resolve cursorline / cursorcolumn styles for this window. The cursor line
    // stays visible on UNFOCUSED windows too (e.g. the explorer's selection when
    // focus is in the editor), painted with a fainter bg and without the cursor.
    let cursor_line_style = if cul {
        if show_cursor {
            cursor_line_bg(&app.theme.ui)
        } else {
            Style::default().bg(app.theme.ui.cursor_line_inactive_bg)
        }
    } else {
        Style::default()
    };
    let cursor_column_style = if show_cursor && cuc {
        Style::default().bg(app.theme.ui.cursor_column_bg)
    } else {
        Style::default()
    };

    // Colorcolumn indices (1-based) — rendered under syntax.
    let cc_cols = parse_colorcolumn(&colorcolumn);
    let cc_style = Style::default().bg(app.theme.ui.colorcolumn_bg);

    // Compute indent guide active column from the cursor row's leading whitespace.
    // The active column is the deepest guide column at the cursor's indent level:
    //   active_col = floor((leading_vcols - 1) / sw) * sw
    // Returns None when sw == 0 or the cursor row has no leading whitespace.
    // Only the focused window highlights its active indent column — it keys off
    // the shared editor cursor, so an unfocused window would otherwise track the
    // active window's cursor instead of staying put.
    let indent_guide_active_col: Option<usize> =
        if is_focused && indent_guides_enabled && indent_guide_shiftwidth > 0 {
            let cursor_row = w_cursor_row;
            let rope = app.slots()[slot_idx].buffer().rope();
            let cursor_line = hjkl_buffer::rope_line_str(&rope, cursor_row);
            let tab_width = indent_guide_tabstop.max(1);
            let mut leading_vcols: usize = 0;
            for ch in cursor_line.chars() {
                match ch {
                    ' ' => leading_vcols += 1,
                    '\t' => {
                        leading_vcols += tab_width - (leading_vcols % tab_width);
                    }
                    _ => break,
                }
            }
            if leading_vcols >= indent_guide_shiftwidth {
                // paint_row paints guides at sw, 2*sw, ... while
                // `guide_col < leading_vcols`. Deepest painted is
                // ((L - 1) / sw) * sw.
                let level = (leading_vcols - 1) / indent_guide_shiftwidth;
                Some(level * indent_guide_shiftwidth)
            } else {
                None
            }
        } else {
            None
        };

    let diag_overlays = build_diag_overlays(&app.slots()[slot_idx], &app.theme.ui, vp_top, vp_bot);

    // Inline end-of-line ghost text, rendered comment-style (`// …` in
    // Rust/JS, `# …` in Python, …) so it reads like a trailing comment, with
    // per-hint colors. Two sources:
    //   1. LSP diagnostics — `// message` in the severity color. Mode is
    //      `:set diagnostics_inline=off|current|all` (default `all`): `all`
    //      annotates every diagnostic line, `current` only the cursor line.
    //      One hint per line (most-severe diagnostic wins).
    //   2. Inline git blame — `// author · summary` dimmed on the cursor line,
    //      idle-gated so it doesn't flicker while moving (#202 P5). Shown only
    //      when the cursor line has no diagnostic hint.
    use hjkl_engine::types::DiagInlineMode;
    const BLAME_IDLE_DELAY: std::time::Duration = std::time::Duration::from_millis(400);
    use hjkl_buffer_tui::render::EolHint;
    let comment_lead = app.active_comment_lead();
    let eol_hints: Vec<EolHint> = {
        let slot = &app.slots()[slot_idx];
        let cursor_row = w_cursor_row;
        let diag_mode = s.diagnostics_inline;

        let mut hints: Vec<EolHint> = Vec::new();

        // 1. Diagnostics — pick the most-severe diagnostic per (start) line.
        if is_focused && diag_mode != DiagInlineMode::Off {
            let mut by_row: std::collections::HashMap<usize, (DiagSeverity, &str)> =
                std::collections::HashMap::new();
            for d in &slot.lsp_diags {
                // Skip diagnostics outside the visible viewport (audit D2):
                // only a diagnostic whose start row is on screen can produce
                // a visible EOL hint. Safe for `Current` mode too — the
                // focused cursor row is always inside `[vp_top, vp_bot)`.
                if !row_in_viewport(d.start_row, vp_top, vp_bot) {
                    continue;
                }
                if diag_mode == DiagInlineMode::Current && d.start_row != cursor_row {
                    continue;
                }
                let msg = d.message.lines().next().unwrap_or("");
                by_row
                    .entry(d.start_row)
                    .and_modify(|cur| {
                        if diag_severity_rank(d.severity) < diag_severity_rank(cur.0) {
                            *cur = (d.severity, msg);
                        }
                    })
                    .or_insert((d.severity, msg));
            }
            for (row, (severity, msg)) in by_row {
                hints.push(EolHint {
                    row,
                    text: format!("{comment_lead} {}", truncate_chars(msg, 80)),
                    style: Style::default()
                        .fg(diag_severity_fg(severity))
                        .add_modifier(Modifier::ITALIC),
                });
            }
        }

        // 2. Inline blame on the cursor line, unless a diagnostic already
        //    annotates it (errors take precedence over blame).
        let blame_show = s.blame_inline
            && !w_is_blame
            && is_focused
            && app.blame_cursor_moved_at.elapsed() >= BLAME_IDLE_DELAY
            && !hints.iter().any(|h| h.row == cursor_row);
        if blame_show && let Some(Some(info)) = slot.blame.get(cursor_row) {
            let body = if info.is_uncommitted {
                "You \u{00b7} Not Committed Yet".to_string()
            } else {
                format!(
                    "{} \u{00b7} {}",
                    info.author,
                    truncate_chars(&info.summary, 50)
                )
            };
            hints.push(EolHint {
                row: cursor_row,
                text: format!("{comment_lead} {body}"),
                style: Style::default().fg(app.theme.ui.non_text),
            });
        }

        hints
    };

    // Boxed-blame layout: when the blame view is on (Wrap::None), build a
    // render plan that frames each commit run in a box (titled top border,
    // `│` sides, bottom border). The engine's cursor/scroll stays authoritative
    // — this only changes how the viewport is painted.
    let box_mode = w_is_blame && matches!(viewport_owned.wrap, hjkl_buffer::Wrap::None);
    let blame_box_plan: Vec<hjkl_buffer_tui::render::BlameRow> = if box_mode {
        let s = &app.slots()[slot_idx];
        let vp_top = viewport_owned.top_row;
        let line_count = s.buffer().line_count() as usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let buf = s.buffer();
        crate::app::git_hunks::build_blame_box_plan(
            &s.blame,
            line_count,
            |r| buf.is_row_hidden(r),
            vp_top,
            area.height as usize,
            now,
        )
    } else {
        Vec::new()
    };

    // ── Explorer conceals: hide the <US><id> tail on each non-root line ─────
    //
    // When this slot is the explorer and debug_mode is off, build one Conceal
    // per buffer line that contains a Unit Separator (U+001F). The conceal
    // covers [byte of US .. end of line] with an empty replacement so the tail
    // is invisible. The buffer text itself is unchanged; only the rendered cells
    // differ. In debug_mode the raw ids are shown for diagnostics.
    let explorer_conceals: Vec<hjkl_buffer_tui::Conceal> = if is_explorer_slot && !app.debug_mode {
        use crate::app::explorer_reconcile::ID_SEP;
        let buf_text = app.slots()[slot_idx].buffer().as_string();
        buf_text
            .lines()
            .enumerate()
            .filter_map(|(row, line)| {
                let us_byte = line.find(ID_SEP)?;
                Some(hjkl_buffer_tui::Conceal {
                    row,
                    start_byte: us_byte,
                    end_byte: line.len(),
                    replacement: String::new(),
                })
            })
            .collect()
    } else {
        Vec::new()
    };

    // Diff-mode filler plan (#250): blank rows that keep the two diff windows
    // aligned. Built once and reused by the renderer, the cursor placement, and
    // the diff-band overlay so all three agree on screen rows.
    let diff_filler_plan = app.diff_filler_plan(win_id);

    let view = BufferView {
        buffer: app.slots()[slot_idx].buffer(),
        viewport: viewport_ref,
        selection,
        resolver: &resolver,
        cursor_line_bg: cursor_line_style,
        // Cursorline row = THIS window's own editor cursor (`w_cursor_row`), the
        // same single source of truth (#151) that relative line numbers, indent
        // guides, and EOL hints above already key off. It resolves correctly for
        // both cases: the focused window's authoritative cursor is its window
        // editor, and each unfocused split keeps its own saved cursor — so the
        // ghost line stays put when a sibling window on the same buffer moves.
        //
        // Passing it explicitly (rather than `None` → the renderer's slot-buffer
        // fallback) matters because `BufferView.buffer` is the SHARED slot
        // editor's buffer, whose cursor is a distinct object from the focused
        // window editor's cursor; the two can diverge, and the fallback would
        // then paint the cursorline on the wrong row.
        cursor_line_row: Some(w_cursor_row),
        // The explorer is a tree, not code — don't tint folded directory rows.
        fold_line_bg: if is_explorer_slot {
            Style::default()
        } else {
            Style::default().bg(app.theme.ui.fold_line_bg)
        },
        // Unfocused windows render their OWN fold snapshot (window-level folds);
        // the shared buffer holds only the focused window's set. Focused window:
        // `None` reads the live `buffer.folds()`.
        folds_override: if is_focused {
            None
        } else {
            app.window_folds.get(&win_id).map(Vec::as_slice)
        },
        cursor_column_bg: cursor_column_style,
        selection_bg: Style::default().bg(Color::Blue),
        cursor_style: Style::default(),
        gutter,
        search_bg,
        signs: &visible_signs,
        conceals: &explorer_conceals,
        spans: buffer_spans,
        search_pattern,
        non_text_style: Style::default().fg(app.theme.ui.non_text),
        show_eob: app.slots()[slot_idx].features.end_of_buffer,
        diag_overlays: &diag_overlays,
        colorcolumn_cols: &cc_cols,
        colorcolumn_style: cc_style,
        listchars: if list_active {
            Some(&listchars_owned)
        } else {
            None
        },
        indent_guides_enabled,
        indent_guide_char,
        indent_guide_shiftwidth,
        indent_guide_fg: app.theme.ui.indent_guide_fg,
        indent_guide_active_fg: app.theme.ui.indent_guide_active_fg,
        indent_guide_active_col,
        // Inline EOL ghost text (cursor line): diagnostics + git blame.
        eol_hints: &eol_hints,
        blame_plan: if box_mode {
            Some(&blame_box_plan)
        } else {
            None
        },
        diff_filler: diff_filler_plan.as_ref(),
        // Terminal-background painting (#303): fill the text area + gutter with
        // the theme's editor background so the terminal's own bg doesn't show
        // through. `transparent = true` in config clears it (no fill), restoring
        // vim's see-through behaviour.
        background: buffer_background_style(app),
    };
    frame.render_widget(view, area);

    // ── Explorer devicon + git-status color overlay ───────────────────────
    //
    // Post-render cell walk applied only to the window matching the explorer
    // pane's win_id so multiple windows on the same buffer are not
    // double-painted.
    //
    // The buffer now contains only indentation spaces + bare names (no glyphs).
    // This pass does two things in one loop:
    //   1. PAINT GLYPHS — write the tree-guide, connector, and icon characters
    //      into the leading blank cells that `render_text` left empty.
    //   2. PAINT COLORS — repaint the icon cell with a devicon/dir RGB fg and
    //      every name cell with the git-status color (or devicon fg for clean).
    //
    // Column layout (depth-0 root / depth ≥ 1):
    //   depth 0 : col 0 = icon, col 1 = space, col 2.. = name
    //   depth ≥ 1:
    //     col i*2        (i in 0..branches.len()) = '│' or space  (guide)
    //     col i*2+1                                = space
    //     col (depth-1)*2   = '└' or '├'          (connector)
    //     col (depth-1)*2+1 = '╴'
    //     col depth*2       = icon
    //     col depth*2+1     = space
    //     col depth*2+2..   = name
    // `:debug` mode renders the explorer as its RAW buffer text (no glyph /
    // guide / git-color overlay) so the actual on-disk buffer contents are
    // visible for debugging.
    if is_explorer_slot
        && !app.debug_mode
        && let Some(ref pane) = app.explorer
        && pane.win_id == win_id
    {
        let buf = frame.buffer_mut();
        let screen_top = area.y;
        let screen_height = area.height as usize;
        // Explorer is gutterless: text starts at area.x (sign_w=fold_w=num_gw=0).
        let text_x = area.x;

        // The viewport top row for this window (same variable as the BufferView uses).
        let vp_top_ex = vp_top;

        // Dim color used for tree guides and connectors.
        let guide_fg = app.theme.ui.indent_guide_fg;

        // Build the fold list + live buffer text once. The fold list MUST match
        // what `BufferView` rendered with: a FOCUSED window draws from the live
        // `buffer.folds()`, an UNFOCUSED one from its `window_folds` snapshot
        // (window-level folds). Reading the wrong source here desyncs the glyph
        // overlay from the drawn rows and garbles the tree.
        let (explorer_folds, buf_text): (Vec<hjkl_buffer::Fold>, String) =
            if let Some(slot_idx) = app.slots().iter().position(|s| s.is_explorer) {
                let b = app.slots()[slot_idx].buffer();
                let folds = if is_focused {
                    b.folds()
                } else {
                    app.window_folds
                        .get(&win_id)
                        .cloned()
                        .unwrap_or_else(|| b.folds())
                };
                (folds, b.as_string())
            } else {
                (Vec::new(), String::new())
            };

        // Layout (icons, guides, depth) is derived from the LIVE buffer text —
        // NOT the last-reconciled `pane.tree.nodes` — so glyphs stay aligned
        // while the buffer is being edited (a mid-edit `o`/`O` shifts rows
        // before the Normal-mode reconcile rebuilds the tree). `None` slots are
        // blank lines (e.g. a fresh open-line awaiting a name).
        let overlay_nodes =
            crate::app::explorer::overlay_nodes_from_buffer(&buf_text, &pane.tree.root);

        // Git status follows the PATH, not the row: resolve each row's color
        // from the reconciled tree's status map (which carries rollup + the
        // dirty-buffer overlay). New / renamed paths absent from the map render
        // clean until the next reconcile.
        let git_map: std::collections::HashMap<&std::path::Path, hjkl_app::git::ExplorerGit> = pane
            .tree
            .nodes
            .iter()
            .filter_map(|n| n.git.map(|g| (n.path.as_path(), g)))
            .collect();

        // Walk doc rows starting at vp_top, skipping hidden rows, collecting
        // up to `screen_height` visible rows — mirroring BufferView's render
        // loop (crates/hjkl-buffer-tui/src/render.rs) which skips
        // rows where any fold f.hides(row).
        let total_nodes = overlay_nodes.len();
        let mut doc_row = vp_top_ex;
        let mut screen_row_idx: usize = 0;

        while doc_row < total_nodes && screen_row_idx < screen_height {
            // Skip rows hidden by a closed fold.
            if explorer_folds.iter().any(|f| f.hides(doc_row)) {
                doc_row += 1;
                continue;
            }

            let buf_row = doc_row;
            let screen_row = screen_top + screen_row_idx as u16;
            if screen_row >= screen_top + area.height {
                break;
            }
            screen_row_idx += 1;
            doc_row += 1;

            let Some(node) = overlay_nodes.get(buf_row).and_then(|o| o.as_ref()) else {
                continue;
            };
            // Git status by path (overlay parse leaves `node.git` = None).
            let node_git = git_map.get(node.path.as_path()).copied();

            let right = area.x + area.width;

            // ── Glyph painting ────────────────────────────────────────────

            // Drive the dir open/closed icon from the tree's `expanded` set. The
            // lazy explorer has no buffer folds — a collapsed dir's children are
            // simply absent — so the icon reads expansion state directly.
            let is_expanded = app
                .explorer
                .as_ref()
                .map(|ep| ep.tree.is_expanded(node.path.as_path()))
                .unwrap_or(false);

            // Icon character for this node.
            let icon_ch = if node.is_dir {
                hjkl_icons::dir_icon_for_path(&node.path, is_expanded, app.icon_mode)
            } else {
                hjkl_icons::file_icon_for_path(&node.path, app.icon_mode)
            };

            if node.depth == 0 {
                // Root: icon at col 0, space at col 1.
                let icon_abs = text_x;
                if icon_abs < right
                    && let Some(cell) = buf.cell_mut((icon_abs, screen_row))
                {
                    cell.set_symbol(&icon_ch.to_string());
                }
                // col 1 is already space from the buffer — nothing to write.
            } else {
                // Guide columns: for each ancestor level.
                for (i, &has_sibling) in node.branches.iter().enumerate() {
                    let col = text_x + (i as u16) * 2;
                    if col < right
                        && let Some(cell) = buf.cell_mut((col, screen_row))
                    {
                        let sym = if has_sibling { "" } else { " " };
                        cell.set_symbol(sym);
                        cell.set_fg(guide_fg);
                    }
                    // col+1 stays space — leave it.
                }

                // Connector: at col (depth-1)*2 and (depth-1)*2+1.
                let connector_col = text_x + (node.branches.len() as u16) * 2;
                if connector_col < right
                    && let Some(cell) = buf.cell_mut((connector_col, screen_row))
                {
                    let sym = if node.is_last { "" } else { "" };
                    cell.set_symbol(sym);
                    cell.set_fg(guide_fg);
                }
                let connector_col2 = connector_col + 1;
                if connector_col2 < right
                    && let Some(cell) = buf.cell_mut((connector_col2, screen_row))
                {
                    cell.set_symbol("");
                    cell.set_fg(guide_fg);
                }

                // Icon: at col depth*2 (= name_col - 2).
                let icon_abs = text_x + node.depth as u16 * 2;
                if icon_abs < right
                    && let Some(cell) = buf.cell_mut((icon_abs, screen_row))
                {
                    cell.set_symbol(&icon_ch.to_string());
                }
                // col depth*2+1 is the space between icon and name — leave it.
            }

            // ── Color painting ────────────────────────────────────────────

            // Compute icon and name screen-column offsets.
            // Layout (same as what render_text used to emit):
            //   depth-0 (root): icon(1) + space(1) + name(...)
            //   depth>0: branches*(2) + connector(2) + icon(1) + space(1) + name(...)
            let (icon_col, name_col) = if node.depth == 0 {
                (text_x, text_x + 2)
            } else {
                let guide_cols = node.branches.len() as u16 * 2;
                let icon_off = guide_cols + 2; // +2 for the connector (e.g. `├╴`)
                (text_x + icon_off, text_x + icon_off + 2)
            };

            // Icon color: devicon per-filetype or folder blue. Falls back to the
            // theme text color so the icon ALWAYS gets a definite fg — otherwise
            // a colorless devicon (e.g. a generic file) would inherit whatever
            // the cursorline painted underneath, making the icon change color
            // depending on which row the cursor sits on.
            let icon_color = if node.is_dir {
                let name = node.path.file_name().and_then(|n| n.to_str());
                rgb(hjkl_icons::dir_color(name))
            } else {
                rgb(hjkl_icons::file_color_for_path(&node.path))
            }
            .unwrap_or(app.theme.ui.text);

            // Git status → name BACKGROUND (so the filetype/dir foreground stays
            // distinct). Clean nodes keep their devicon/dir foreground and the
            // normal background.
            let git_bg = match node_git {
                Some(hjkl_app::git::ExplorerGit::Modified) => Some(GIT_MODIFIED),
                Some(hjkl_app::git::ExplorerGit::Staged) => Some(GIT_STAGED),
                Some(hjkl_app::git::ExplorerGit::Deleted) => Some(GIT_DELETED),
                Some(hjkl_app::git::ExplorerGit::Untracked) => Some(GIT_UNTRACKED),
                None => None,
            };
            // Foreground for the name when clean: devicon (files) / folder (dirs),
            // falling back to the theme text color.
            let clean_name_fg = if node.is_dir {
                rgb(hjkl_icons::dir_color(
                    node.path.file_name().and_then(|n| n.to_str()),
                ))
            } else {
                rgb(hjkl_icons::file_color_for_path(&node.path))
            }
            .unwrap_or(app.theme.ui.text);

            // Repaint the icon cell foreground (icon keeps its filetype/dir color
            // regardless of git state — the icon column never gets a git bg).
            // Always set a definite fg so the icon never inherits the
            // cursorline's foreground on the cursor row.
            if icon_col < right
                && let Some(cell) = buf.cell_mut((icon_col, screen_row))
            {
                cell.set_fg(icon_color);
            }

            // Name span width = the ACTUAL displayed name on this row: the live
            // line text after the indent, up to the concealed `<US><id>` tail.
            // Deriving it from the buffer (not `path.file_name()`) keeps the
            // git-bg / clean-color highlight tight AND correct mid-edit when the
            // typed name contains a `/` (e.g. `somedir/test.txt`) — there
            // `file_name()` would be `test.txt` and only cover part of the name,
            // leaving the rest mis-colored. The trailing `/` on a dir name is
            // part of the line text, so it's counted naturally.
            let indent_chars = name_col.saturating_sub(text_x) as usize;
            let name_len = buf_text
                .lines()
                .nth(buf_row)
                .map(|line| {
                    line.chars()
                        .skip(indent_chars)
                        .take_while(|&c| c != '\u{1F}')
                        .count() as u16
                })
                .unwrap_or(0);
            let name_end = name_col.saturating_add(name_len).min(right);

            // Repaint name cells.
            for col in name_col..name_end {
                if let Some(cell) = buf.cell_mut((col, screen_row)) {
                    match git_bg {
                        Some(bg) => {
                            cell.set_bg(bg);
                            cell.set_fg(GIT_TEXT);
                        }
                        None => {
                            cell.set_fg(clean_name_fg);
                        }
                    }
                }
            }
        }
    }

    // ── Auto-indent flash overlay ─────────────────────────────────────────
    //
    // Approach: post-render ratatui buffer walk. After `BufferView` has painted
    // all cells, we overwrite the bg of every cell on flash rows that are
    // currently visible. Instant on, instant off — no fade (per UX spec).
    // The overlay is painted only on the focused window to avoid a visually
    // confusing multi-pane flash.
    //
    // We call `indent_flash_active` on the shared App state here rather than
    // passing a pre-computed value so the expiry check happens at render time
    // (the same instant the user sees the frame).
    if is_focused && let Some((flash_top, flash_bot)) = app.indent_flash_active() {
        let flash_bg = app.theme.ui.indent_flash_bg;
        let flash_style = Style::default().bg(flash_bg);
        let buf = frame.buffer_mut();
        let screen_top = area.y;
        let screen_height = area.height;
        // Constrain to the TEXT area only — the flash overlay must not bleed
        // into the gutter. The buffer renderer paints text starting at
        // `area.x + sign_w + num_gw` (dedicated sign column + number column).
        // Without this, the gutter and text area share the same flash bg
        // and the cursor visually appears to sit "in the gutter".
        let text_x = area.x + sign_w + num_gw + fold_w;
        let text_right = area.x + area.width;
        // Clamp flash range to visible rows.
        let vis_start = flash_top.max(vp_top);
        let vis_end = flash_bot.min(vp_top + screen_height as usize - 1);
        for buf_row in vis_start..=vis_end {
            let screen_row = screen_top + (buf_row - vp_top) as u16;
            if screen_row >= screen_top + screen_height {
                break;
            }
            for col in text_x..text_right {
                let cell = buf.cell_mut((col, screen_row));
                if let Some(c) = cell {
                    c.set_style(c.style().patch(flash_style));
                }
            }
        }
    }

    // ── Diff-mode overlay (#208 Phase 2) ──────────────────────────────────
    // Post-render pass: tint changed/added lines (DiffChange/DiffAdd) and the
    // changed character ranges within them (DiffText), for both windows of an
    // active diff pair. Colors are hardcoded (vim-like dark palette) pending a
    // theme promotion. Filler-line alignment is a separate concern.
    if app.is_diff_window(win_id) {
        let classes = app.diff_line_classes(win_id);
        if !classes.is_empty() {
            // Vim-like dark diff palette (bg only; syntax fg is preserved).
            let add_bg = Color::Rgb(32, 51, 32); // DiffAdd
            let change_bg = Color::Rgb(32, 42, 60); // DiffChange
            let text_bg = Color::Rgb(48, 78, 110); // DiffText (stronger)
            let text_x = area.x + sign_w + num_gw + fold_w;
            let text_right = area.x + area.width;
            let screen_top = area.y;
            let screen_height = area.height as usize;
            let buf = frame.buffer_mut();
            for (&line, class) in &classes {
                if line < vp_top {
                    continue;
                }
                // Account for filler rows inserted above this line so the band
                // lands on the same screen row the renderer painted it.
                let off = match diff_filler_plan.as_ref() {
                    Some(p) => p.screen_offset(vp_top, line),
                    None => line - vp_top,
                };
                if off >= screen_height {
                    continue;
                }
                let screen_row = screen_top + off as u16;
                let band_bg = match class.band {
                    crate::app::diff_mode::DiffBand::Add => add_bg,
                    crate::app::diff_mode::DiffBand::Change => change_bg,
                };
                for col in text_x..text_right {
                    if let Some(c) = buf.cell_mut((col, screen_row)) {
                        c.set_style(c.style().patch(Style::default().bg(band_bg)));
                    }
                }
                // Char-level DiffText over the changed byte ranges.
                if !class.text_ranges.is_empty() {
                    let rope = hjkl_engine::Query::rope(app.slots()[slot_idx].buffer());
                    let lt = hjkl_buffer::rope_line_str(&rope, line);
                    let lt = lt.trim_end_matches('\n');
                    let len = lt.len();
                    for r in &class.text_ranges {
                        let start = r.start.min(len);
                        let end = r.end.min(len);
                        let cs = lt[..start].chars().count();
                        let ce = lt[..end].chars().count();
                        for ci in cs..ce {
                            let scol = text_x + ci as u16;
                            if scol >= text_right {
                                break;
                            }
                            if let Some(c) = buf.cell_mut((scol, screen_row)) {
                                c.set_style(c.style().patch(Style::default().bg(text_bg)));
                            }
                        }
                    }
                }
            }
        }
    }

    // ── Confirm-substitute active-match highlight ─────────────────────────
    // Paint inverse-video (search highlight) over the cell range of the
    // match currently being prompted. Only for the focused window so
    // inactive splits don't flash confusingly.
    if is_focused
        && let Some(cs) = app.confirming_substitute.as_ref()
        && cs.idx < cs.matches.len()
    {
        let m = &cs.matches[cs.idx];
        let match_row = m.row as usize;
        // Only paint when the row is visible in this window.
        let vp_bot = vp_top + area.height as usize;
        if match_row >= vp_top && match_row < vp_bot {
            let screen_row = area.y + (match_row - vp_top) as u16;
            // Convert byte offsets to char columns for rendering.
            let rope = hjkl_engine::Query::rope(app.slots()[slot_idx].buffer());
            let line = hjkl_buffer::rope_line_str(&rope, match_row);
            let line_no_nl = line.trim_end_matches('\n');
            let char_start = line_no_nl[..m.byte_start as usize].chars().count();
            let char_end = line_no_nl[..m.byte_end as usize].chars().count();
            let text_x = area.x + sign_w + num_gw + fold_w;
            let highlight_style = app
                .theme
                .ui
                .search_match_style()
                .add_modifier(Modifier::REVERSED);
            let buf = frame.buffer_mut();
            for ch_idx in char_start..char_end {
                let screen_col = text_x + ch_idx as u16;
                if screen_col >= area.x + area.width {
                    break;
                }
                if let Some(cell) = buf.cell_mut((screen_col, screen_row)) {
                    cell.set_style(cell.style().patch(highlight_style));
                }
            }
        }
    }

    // Map a doc `(row, col)` to a terminal cell for post-render overlays,
    // box-aware: the boxed-blame layout shifts the screen row (virtual border
    // rows) and the column (+1 box frame). `None` when the row isn't visible.
    let base_text_x = area.x + sign_w + num_gw + fold_w;
    let vp_bot_overlay = vp_top + area.height as usize;
    let map_doc_to_screen = |pair_row: usize, pair_col: usize| -> Option<(u16, u16)> {
        if box_mode {
            let idx = blame_box_plan.iter().position(
                |r| matches!(r, hjkl_buffer_tui::render::BlameRow::Buffer(d) if *d == pair_row),
            )?;
            Some((
                base_text_x + hjkl_buffer_tui::render::BLAME_BOX_FRAME_LEFT + pair_col as u16,
                area.y + idx as u16,
            ))
        } else if pair_row >= vp_top && pair_row < vp_bot_overlay {
            Some((
                base_text_x + pair_col as u16,
                area.y + (pair_row - vp_top) as u16,
            ))
        } else {
            None
        }
    };

    // ── matchparen bracket highlight (focused window only) ─────────────────
    if is_focused && let Some(pairs) = app.matchparen_cells() {
        let match_paren_style = Style::default()
            .bg(app.theme.ui.match_paren_bg)
            .add_modifier(Modifier::BOLD | Modifier::REVERSED);
        let right = area.x + area.width;
        let buf = frame.buffer_mut();
        for (pair_row, pair_col) in pairs {
            if let Some((screen_col, screen_row)) = map_doc_to_screen(pair_row, pair_col)
                && screen_col < right
                && let Some(cell) = buf.cell_mut((screen_col, screen_row))
            {
                cell.set_style(cell.style().patch(match_paren_style));
            }
        }
    }

    // ── matchparen tag highlight ──────────────────────────────────────────
    if is_focused && let Some(tag_cells) = app.matchparen_tag_cells() {
        let match_paren_style = Style::default()
            .bg(app.theme.ui.match_paren_bg)
            .add_modifier(Modifier::BOLD | Modifier::REVERSED);
        let right = area.x + area.width;
        let buf = frame.buffer_mut();
        for (pair_row, pair_col) in tag_cells {
            if let Some((screen_col, screen_row)) = map_doc_to_screen(pair_row, pair_col)
                && screen_col < right
                && let Some(cell) = buf.cell_mut((screen_col, screen_row))
            {
                cell.set_style(cell.style().patch(match_paren_style));
            }
        }
    }

    // ── Hop / easymotion label overlay (#197) ────────────────────────────
    // Paint each hop target's label string starting at the target's screen cell.
    // Only rendered for the window that owns the active hop state.
    if let Some(hop) = app.hop.as_ref()
        && hop.win_id == win_id
    {
        let label_style = Style::default()
            .fg(app.theme.ui.hop_label_fg)
            .bg(app.theme.ui.hop_label_bg)
            .add_modifier(Modifier::BOLD);
        let right = area.x + area.width;
        let bottom = area.y + area.height;
        // Clone the snapshot so we can call frame.buffer_mut() below.
        let targets: Vec<(usize, usize, String)> = hop
            .targets
            .iter()
            .map(|t| (t.row, t.col, t.label.clone()))
            .collect();
        let buf = frame.buffer_mut();
        for (doc_row, doc_col, label) in &targets {
            if let Some((screen_col, screen_row)) = map_doc_to_screen(*doc_row, *doc_col)
                && screen_col < right
                && screen_row < bottom
            {
                // Paint each char of the label into consecutive cells.
                for (i, ch) in label.chars().enumerate() {
                    let x = screen_col + i as u16;
                    if x >= right {
                        break;
                    }
                    if let Some(cell) = buf.cell_mut((x, screen_row)) {
                        cell.set_char(ch);
                        cell.set_style(label_style);
                    }
                }
            }
        }
    }

    // Emit the terminal cursor only for the focused window.
    // extra_gutter_width = sign_w + fold_w + lnum_pad. The engine computes the
    // cursor x from the buffer's OWN line-number width; `lnum_pad` accounts for
    // the extra cells when the number column is widened to the cross-buffer max.
    // Cursor rendering. The BLOCK (normal/visual) and UNDERLINE shapes are drawn
    // as a SOFTWARE cursor — a styled cell — because the terminal's hardware
    // cursor trails/flickers during scroll redraws (ratatui flushes the cell
    // diff BEFORE repositioning it), and held-`j`/`k` scrolling happens in those
    // modes. Both keep the underlying character visible (reversed / underlined).
    //
    // The BAR (insert) shape can't be a software cursor: a thin bar AND the
    // character can't share one cell, so painting `▏` would erase the char under
    // the cursor. Insert mode uses the real HARDWARE bar instead (positioned via
    // `set_cursor_position`), which renders between cells and leaves the char
    // intact. Insert mode has no held-scroll, so the hardware cursor doesn't
    // trail there. The command/search prompt likewise keeps the hardware cursor.
    if show_cursor
        && let Some((cx, cy)) = app.active_editor_mut().cursor_screen_pos(
            area.x,
            area.y,
            area.width,
            area.height,
            sign_w + fold_w + lnum_pad,
        )
    {
        // Boxed-blame: the cursor's screen row comes from the plan (borders
        // shift content down); the column shifts right by the box frame.
        // `None` when the cursor row scrolled past the plan's last row.
        let pos = if box_mode {
            let cur = w_cursor_row;
            blame_box_plan
                .iter()
                .position(
                    |r| matches!(r, hjkl_buffer_tui::render::BlameRow::Buffer(d) if *d == cur),
                )
                .map(|idx| {
                    (
                        cx + hjkl_buffer_tui::render::BLAME_BOX_FRAME_LEFT,
                        area.y + idx as u16,
                    )
                })
        } else if let Some(p) = diff_filler_plan.as_ref() {
            // Diff filler rows above the cursor shift it down by that many rows.
            let cur = w_cursor_row;
            if cur >= vp_top {
                let off = p.screen_offset(vp_top, cur);
                if (off as u16) < area.height {
                    Some((cx, area.y + off as u16))
                } else {
                    None
                }
            } else {
                Some((cx, cy))
            }
        } else {
            // Plain case (no box mode, no diff filler): `cy` came from
            // `cursor_screen_pos`, which resolves the cursor's screen row
            // from the ENGINE's own (target-top) viewport — see the
            // `target_top_row` comment above. Re-derive it from `vp_top`
            // instead, using the same fold/wrap-aware row counting the
            // engine itself uses, so the cursor tracks the animated text
            // rather than the target it's about to reach. A no-op once the
            // anim settles (`vp_top == target_top_row`, shift = 0).
            let shift: i64 = match vp_top.cmp(&target_top_row) {
                std::cmp::Ordering::Equal => 0,
                std::cmp::Ordering::Less => app.slots()[slot_idx].buffer().screen_rows_between(
                    viewport_ref,
                    vp_top,
                    target_top_row - 1,
                ) as i64,
                std::cmp::Ordering::Greater => {
                    -(app.slots()[slot_idx].buffer().screen_rows_between(
                        viewport_ref,
                        target_top_row,
                        vp_top - 1,
                    ) as i64)
                }
            };
            let adj_cy = cy as i64 + shift;
            if adj_cy >= area.y as i64 && adj_cy < (area.y as i64 + area.height as i64) {
                Some((cx, adj_cy as u16))
            } else {
                // Shifted row falls off the animated viewport mid-scroll —
                // skip drawing the cursor this frame rather than clamp it
                // to a misleading edge position.
                None
            }
        };
        if let Some((cx, cy)) = pos {
            let shape = app.active_editor().host().cursor_shape();
            match shape {
                hjkl_engine::CursorShape::Bar => {
                    // Hardware bar — keeps the char under the cursor visible.
                    frame.set_cursor_position((cx, cy));
                }
                hjkl_engine::CursorShape::Block => {
                    if let Some(cell) = frame.buffer_mut().cell_mut((cx, cy)) {
                        cell.set_style(Style::default().add_modifier(Modifier::REVERSED));
                    }
                }
                hjkl_engine::CursorShape::Underline => {
                    if let Some(cell) = frame.buffer_mut().cell_mut((cx, cy)) {
                        cell.set_style(Style::default().add_modifier(Modifier::UNDERLINED));
                    }
                }
            }
        }
    }
}

/// Render the completion popup, floating below the cursor position.
///
/// Only called when `app.completion.is_some()`.
fn completion_popup(frame: &mut Frame, app: &App, buf_area: Rect) {
    let completion = match app.completion.as_ref() {
        Some(p) => p,
        None => return,
    };

    // Convert buffer coordinates to screen coordinates. Anchor relative to the
    // FOCUSED window's rect (not `buf_area`) so the popup lands correctly when
    // the window is offset — e.g. the editor sits right of the explorer sidebar.
    let fw = app.focused_window();
    let win_rect = app.windows[fw].as_ref().and_then(|w| w.last_rect);
    let (base_x, base_y) = win_rect
        .map(|r| (r.x, r.y))
        .unwrap_or((buf_area.x, buf_area.y));
    // Per-window viewport lives on the window's own editor (#151 Phase D) —
    // per-window editors own scroll, but the SLOT bridge editor's viewport
    // stays pinned at its creation top_row. Reading the slot viewport here
    // (as this used to) anchored the popup using a stale top_row once the
    // window had scrolled independently of the slot (mouse.rs's
    // `hit_test_window` reads the window editor first for the same reason).
    let focused_editor = app.window_editor(fw);
    let vp = focused_editor.host().viewport();
    let vp_top = vp.top_row;
    // Stable cross-buffer gutter width (matches render_window) so the popup
    // anchors under the cursor even when the number/sign/fold columns are
    // widened to the open-buffer max.
    let own_lnum = focused_editor.lnum_width();
    let eff_lnum = if own_lnum > 0 { max_lnum_width(app) } else { 0 };
    let (sign_w, fold_w) = stable_gutter_extra(app);
    let gw = eff_lnum + sign_w + fold_w;

    // Cursor cell in absolute screen coordinates (0-based row relative to viewport top).
    let cursor_row = completion.anchor_row.saturating_sub(vp_top) as u16;
    let cursor_col = completion.anchor_col as u16 + gw;
    let anchor = Rect {
        x: base_x + cursor_col,
        y: base_y + cursor_row,
        width: 1,
        height: 1,
    };

    let ui = &app.theme.ui;
    let theme = hjkl_completion_tui::CompletionTheme::new(
        to_hjkl_color(ui.border_active),
        to_hjkl_color(ui.picker_selection_bg),
        to_hjkl_color(ui.text),
        to_hjkl_color(ui.text_dim),
    );
    hjkl_completion_tui::popup(frame, completion, &theme, anchor, buf_area);
}

pub fn frame(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    // Record the real terminal rect for `App::screen_rect` (fix: screen_rect
    // used to be derived from the focused window's viewport, which the
    // renderer sets to the pane's dims — wrong with any split open). This is
    // the one place that unconditionally sees the full frame every draw.
    app.last_frame_rect = Some(area);

    // Special-pane slots (explorer, bottom qf/loclist dock) don't count as
    // additional user buffers for the top-bar visibility decision —
    // otherwise opening the explorer or `:copen` alone would show the bar.
    let real_slots = (0..app.slots().len())
        .filter(|&idx| !app.slot_is_special(idx))
        .count();
    let show_top_bar = app.tabs.len() > 1 || real_slots > 1;
    let (buf_area, status_area, top_bar_area) = {
        // Build constraint list dynamically based on what rows are visible.
        let mut constraints = Vec::new();
        if show_top_bar {
            constraints.push(Constraint::Length(TOP_BAR_HEIGHT));
        }
        constraints.push(Constraint::Min(1));
        constraints.push(Constraint::Length(STATUS_LINE_HEIGHT));

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints)
            .split(area);

        let mut idx = 0usize;
        let tb_area = if show_top_bar {
            let a = Some(chunks[idx]);
            idx += 1;
            a
        } else {
            None
        };
        let buf = chunks[idx];
        idx += 1;
        let stat = chunks[idx];
        (buf, stat, tb_area)
    };

    // Splash screen path — skip all buffer rendering while active.
    if let Some(ref screen) = app.start_screen {
        if let Some(tb) = top_bar_area {
            top_bar(frame, app, tb);
        }
        crate::start_screen::render(frame, buf_area, screen, &app.theme);
        status_line(frame, app, status_area);
        return;
    }

    // Spans are kept current by the event loop's end-of-drain flush
    // (`pending_recompute` → `recompute_and_install`). App::new seeds
    // `pending_recompute = true` so the first frame's flush handles the
    // initial parse. Calling recompute here every frame meant TWO sync
    // tree-sitter parses per draw — visible as ~half of per-keystroke
    // CPU on huge files.

    if let Some(tb) = top_bar_area {
        top_bar(frame, app, tb);
    }

    // Left dock (#63 Phase A): carved off the frame BEFORE the tree gets the
    // remainder, exactly once per frame, so it holds a config-driven width
    // across resizes without needing a split ratio at all (the old
    // `pin_explorer_width` re-pinned a ratio every frame; the dock doesn't
    // have one to re-pin — its rect is computed directly here). Uses
    // `render_window` directly, same as any tree leaf — the dock's `WindowId`
    // has a normal `windows[..]` / `window_editors[..]` entry, it's just
    // never referenced by a `LayoutTree` leaf.
    let dock_win = app.left_dock.as_ref().map(|d| d.win_id);
    let main_area = if let Some(dock_win) = dock_win {
        let total_w = buf_area.width;
        let dock_w =
            crate::app::dock::clamp_dock_width(app.config.explorer.width, total_w).min(total_w);
        // Mirrors the Col-axis separator carving in `render_layout` /
        // `headless_split_rect` exactly, so `mouse::hit_test_border`'s dock
        // border cell lines up with what's actually drawn.
        let (dock_rect, sep_rect, rest) = if dock_w >= 2 && buf_area.width > dock_w {
            let content = Rect {
                x: buf_area.x,
                y: buf_area.y,
                width: dock_w - 1,
                height: buf_area.height,
            };
            let sep = Rect {
                x: buf_area.x + dock_w - 1,
                y: buf_area.y,
                width: 1,
                height: buf_area.height,
            };
            let rest = Rect {
                x: buf_area.x + dock_w,
                y: buf_area.y,
                width: buf_area.width - dock_w,
                height: buf_area.height,
            };
            (content, Some(sep), rest)
        } else {
            let w = dock_w.min(buf_area.width);
            let content = Rect {
                x: buf_area.x,
                y: buf_area.y,
                width: w,
                height: buf_area.height,
            };
            let rest = Rect {
                x: buf_area.x + w,
                y: buf_area.y,
                width: buf_area.width - w,
                height: buf_area.height,
            };
            (content, None, rest)
        };
        render_window(frame, app, dock_rect, dock_win);
        if let Some(sep) = sep_rect {
            draw_separator(frame, sep, window::SplitDir::Vertical, app.theme.ui.border);
        }
        rest
    } else {
        buf_area
    };

    // Bottom dock (#63 Phase B: quickfix/location-list, real window/buffer —
    // replaces the old `quickfix_popup_overlay`). Carved from the REMAINDER
    // after the left dock, so it spans only the main area's width — per the
    // approved design, `<C-w>j` from the explorer must not reach it (the
    // bottom dock sits below the tree, to the right of the left dock, not
    // below the left dock too). Same `render_window` / separator approach as
    // the left dock, just along the row axis instead of the column axis.
    let bottom_dock_win = app.bottom_dock.as_ref().map(|d| d.win_id);
    let main_area = if let Some(dock_win) = bottom_dock_win {
        let total_h = main_area.height;
        let dock_h =
            crate::app::dock::clamp_dock_height(app.config.panel.height, total_h).min(total_h);
        let (dock_rect, sep_rect, rest) = if dock_h >= 2 && main_area.height > dock_h {
            let sep = Rect {
                x: main_area.x,
                y: main_area.y + main_area.height - dock_h,
                width: main_area.width,
                height: 1,
            };
            let content = Rect {
                x: main_area.x,
                y: sep.y + 1,
                width: main_area.width,
                height: dock_h - 1,
            };
            let rest = Rect {
                x: main_area.x,
                y: main_area.y,
                width: main_area.width,
                height: main_area.height - dock_h,
            };
            (content, Some(sep), rest)
        } else {
            let h = dock_h.min(main_area.height);
            let content = Rect {
                x: main_area.x,
                y: main_area.y + main_area.height - h,
                width: main_area.width,
                height: h,
            };
            let rest = Rect {
                x: main_area.x,
                y: main_area.y,
                width: main_area.width,
                height: main_area.height - h,
            };
            (content, None, rest)
        };
        render_window(frame, app, dock_rect, dock_win);
        if let Some(sep) = sep_rect {
            draw_separator(
                frame,
                sep,
                window::SplitDir::Horizontal,
                app.theme.ui.border,
            );
        }
        rest
    } else {
        main_area
    };

    // Walk the window tree and render each pane. Use take_layout /
    // restore_layout so we can pass `&mut LayoutTree` to render_layout
    // (which writes last_rect on Split nodes) while also holding
    // `&mut App` for render_window.
    let mut layout = app.take_layout();
    render_layout(frame, app, main_area, &mut layout);
    app.restore_layout(layout);

    status_line(frame, app, status_area);

    // Picker overlay sits on top of the buffer pane. Renders last so
    // its `Clear` widget masks the editor content beneath it.
    if app.picker.is_some() {
        picker_overlay(frame, app, buf_area);
    }

    // Completion popup: command-bar popup anchored above the status line;
    // LSP/buffer popup anchored at the buffer cursor.
    if app.completion.is_some() {
        if app.command_field.is_some() {
            command_completion_popup(frame, app, status_area, buf_area);
        } else {
            completion_popup(frame, app, buf_area);
        }
    }

    // Which-key popup: shown after a prefix key idles past the configured delay.
    if app.which_key_active {
        which_key_popup(frame, app, buf_area);
    }

    // Quickfix / location-list is now a real bottom-dock window/buffer
    // (#63 Phase B), carved and rendered via `render_window` above alongside
    // the left dock — no overlay draw needed here anymore.

    // Info popup (`:reg`, `:marks`, `:jumps`, `:changes`) renders on top of
    // the picker overlay so it always shows.
    if app.info_popup.is_some() {
        info_popup_overlay(frame, app, buf_area);
    }

    // Context menu (right-click, Phase 2 Round A) — floats above everything.
    if let Some(ref menu) = app.context_menu {
        crate::menu::render(frame, menu, area, &crate::menu::MenuTheme::default());
    }

    // Hover popup (Phase 5 mouse support) — renders above all other content.
    if let Some(ref popup) = app.hover_popup {
        let hover_theme = hjkl_hover_tui::HoverTheme::new(
            app.theme.ui.border_active,
            app.theme.ui.panel_bg,
            hjkl_markdown_tui::MdTheme::default(),
        );
        hjkl_hover_tui::render(frame, popup, &hover_theme, frame.area());
    }

    // Toast notifications — float top-right, newest on top.
    let holler_layout = HollerLayout::default();
    render_active(
        frame,
        area,
        &app.bus,
        &holler_layout,
        std::time::SystemTime::now(),
    );
}

/// Render the unified top bar into a single row.
///
/// Left side: buffer-line entries (one per slot), only when `app.slots().len() > 1`.
/// Format: ` name ` or ` name+ ` (dirty), separated by `│`.
///
/// Right side: tab entries (one per layout tab), only when `app.tabs.len() > 1`.
/// Rendered via [`hjkl_tabs_tui::build_line`] so tab-bar behaviour (active
/// highlight, dirty marker `●`, overflow `<`/`>`) is owned by `hjkl-tabs-tui`.
///
/// If both sides overflow the row width, the left (buffer) side is truncated
/// from the right with `…`. If buffers still don't fit even after truncation,
/// they are dropped entirely.
///
/// Show the row whenever EITHER side has content. When neither does, this
/// function is not called (see `render::frame`).
fn top_bar(frame: &mut Frame, app: &App, area: Rect) {
    let ui = &app.theme.ui;
    let active_style = Style::default()
        .fg(ui.on_accent)
        .bg(ui.mode_normal_bg)
        .add_modifier(Modifier::BOLD);
    let inactive_style = Style::default().fg(ui.text_dim).bg(ui.surface_bg);
    let sep_style = Style::default().fg(ui.border);

    let show_tabs = app.tabs.len() > 1;
    // Count only real (non-special-pane) slots for the buffer-line visibility check.
    let real_slot_count = (0..app.slots().len())
        .filter(|&idx| !app.slot_is_special(idx))
        .count();
    let show_buffers = real_slot_count > 1;
    let total_width = area.width as usize;

    // ── Right side: build a hjkl_tabs::TabBar from the layout tabs ──────────
    //
    // Each `hjkl_layout::Tab` (a window-split tree tab) maps to one
    // `hjkl_tabs::Tab<usize>` where the id is the positional index.
    // The title is `"{n}: {filename}"` matching the pre-migration format.
    // Dirty = any leaf window in the layout has a dirty slot.
    let mut tab_bar: TabBar<usize> = TabBar::new();
    if show_tabs {
        // `:set tabline_icons` (default on) — Nerd-Font filetype icon per tab.
        let tabline_icons = app.active_editor().settings().tabline_icons;
        for (i, layout_tab) in app.tabs.iter().enumerate() {
            let slot_idx = app.windows[layout_tab.focused_window]
                .as_ref()
                .map(|w| w.slot)
                .unwrap_or(0);
            let slot = &app.slots()[slot_idx];
            let base_name = slot
                .filename
                .as_ref()
                .and_then(|p| p.file_name())
                .and_then(|n| n.to_str())
                .unwrap_or("[No Name]");
            let title = format!("{}: {} {}", i + 1, base_name, crate::app::TAB_CLOSE_GLYPH);
            tab_bar.open(i, title);
            let tab_dirty = layout_tab.layout.leaves().iter().any(|&wid| {
                app.windows[wid]
                    .as_ref()
                    .map(|w| app.slots()[w.slot].dirty)
                    .unwrap_or(false)
            });
            if let Some(t) = tab_bar.tabs.last_mut() {
                t.dirty = tab_dirty;
                // Per-filetype icon as a separate colored span (#260). Generic
                // glyph when the buffer is unnamed / extension unknown; devicon
                // color via `file_color_for_path` (None → inherits tab fg).
                // Gated on the `tabline_icons` toggle.
                if tabline_icons {
                    let glyph = match slot.filename.as_deref() {
                        Some(p) => hjkl_icons::file_icon_for_path(p, app.icon_mode),
                        None => hjkl_icons::file_icon(None, app.icon_mode),
                    };
                    t.icon = Some(glyph.to_string());
                    t.icon_color = slot
                        .filename
                        .as_deref()
                        .and_then(hjkl_icons::file_color_for_path);
                }
            }
        }
        tab_bar.focus(&app.active_tab);
    }

    // Build the tab line via hjkl-tabs-tui so active/dirty/overflow logic
    // is owned by that crate.
    let tab_theme = TabBarTheme::new(
        ui.on_accent,
        ui.mode_normal_bg,
        ui.text_dim,
        ui.surface_bg,
        ui.border,
        ui.border,
    );
    let tab_line = if show_tabs {
        build_tab_line(area.width, &tab_bar, &tab_theme)
    } else {
        hjkl_tabs_tui::build_line(0, &tab_bar, &tab_theme)
    };
    let tabs_total_len: usize = tab_line
        .spans
        .iter()
        .map(|s| s.content.chars().count())
        .sum();

    // ── Left side: compute how much width buffers can use ────────────────────
    // Tabs are right-aligned and never truncated; buffers get the remainder.
    let buf_budget = if show_buffers {
        total_width.saturating_sub(tabs_total_len)
    } else {
        0
    };

    // Build buffer spans within the budget.
    let mut buf_spans: Vec<Span<'static>> = Vec::new();
    let mut buf_used = 0usize;

    if show_buffers && buf_budget > 0 {
        let mut first = true;
        for (i, slot) in app.slots().iter().enumerate() {
            // Skip special-pane scratch buffers (explorer, bottom qf/loclist
            // dock) — real windows, but not user-visible named buffers, so
            // they must not appear in the buffer line.
            if app.slot_is_special(i) {
                continue;
            }
            let base_name = slot
                .filename
                .as_ref()
                .and_then(|p| p.file_name())
                .and_then(|n| n.to_str())
                .unwrap_or("[No Name]");
            let label = if slot.dirty {
                format!(" {}+ {} ", base_name, crate::app::TAB_CLOSE_GLYPH)
            } else {
                format!(" {} {} ", base_name, crate::app::TAB_CLOSE_GLYPH)
            };
            let sep_len = if first { 0 } else { 1 };
            let entry_width = sep_len + label.chars().count();

            if buf_used + entry_width > buf_budget {
                // Truncate with ellipsis if space remains.
                if buf_used < buf_budget {
                    buf_spans.push(Span::styled("".to_string(), sep_style));
                }
                break;
            }

            if !first {
                buf_spans.push(Span::styled("".to_string(), sep_style));
            }
            let style = if i == app.active_index() {
                active_style
            } else {
                inactive_style
            };
            buf_spans.push(Span::styled(label, style));
            buf_used += entry_width;
            first = false;
        }
    }

    // ── Assemble the full line ────────────────────────────────────────────────
    // Layout: [buf_spans ... padding ... tab_spans]
    // Padding fills the gap so tabs land flush-right.

    let mut all_spans: Vec<Span<'static>> = buf_spans;

    if show_tabs {
        // Pad between left and right sides.
        let used_left = buf_used;
        let pad_width = total_width.saturating_sub(used_left + tabs_total_len);
        if pad_width > 0 {
            all_spans.push(Span::raw(" ".repeat(pad_width)));
        }

        // Emit tab spans from hjkl-tabs-tui.
        all_spans.extend(tab_line.spans);
    }

    let paragraph = Paragraph::new(Line::from(all_spans));
    frame.render_widget(paragraph, area);
}

/// Build a [`PromptTheme`] from the app's [`crate::theme::UiTheme`].
///
/// Maps the form color slots to the corresponding `PromptTheme` fields so that
/// wildmenu and prompt-bar rendering respect the user's configured palette.
fn prompt_theme(ui: &crate::theme::UiTheme) -> PromptTheme {
    PromptTheme::new(
        ui.form_insert_bg,
        ui.form_normal_bg,
        ui.text,
        ui.form_tag_insert_fg,
        ui.form_tag_normal_fg,
        ui.panel_bg,
        ui.text,
        ui.picker_selection_bg,
    )
}

/// Render the completion popup anchored above the command-line row.
/// Called when both `app.command_field` and `app.completion` are `Some`.
/// The anchor rect is placed at `status_area.y` so the popup flips above it.
fn command_completion_popup(frame: &mut Frame, app: &App, status_area: Rect, viewport: Rect) {
    let completion = match app.completion.as_ref() {
        Some(p) => p,
        None => return,
    };
    // Anchor at the cursor column in the status line. The cursor column is
    // 1 (for the `:` prefix) + field cursor col.
    let cursor_col: u16 = if let Some(ref field) = app.command_field {
        let (_, col) = field.cursor();
        1u16 + col as u16
    } else {
        1
    };
    let anchor = Rect {
        x: status_area.x + cursor_col.min(status_area.width.saturating_sub(1)),
        y: status_area.y,
        width: 1,
        height: 1,
    };
    let ui = &app.theme.ui;
    let theme = hjkl_completion_tui::CompletionTheme::new(
        to_hjkl_color(ui.border_active),
        to_hjkl_color(ui.picker_selection_bg),
        to_hjkl_color(ui.text),
        to_hjkl_color(ui.text_dim),
    );
    // Use full frame area as viewport so popup can extend into buf_area above.
    hjkl_completion_tui::popup(frame, completion, &theme, anchor, viewport);
}

/// Render the one-row status line.
///
/// When the user is typing a `:` command or a `/`/`?` search, the status
/// area shows the prompt instead of the normal mode/file/cursor info, and
/// the terminal cursor is moved to the insertion point.
fn status_line(frame: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let (status, cursor_col) = build_status_line(app, area.width);
    let paragraph = Paragraph::new(status);
    frame.render_widget(paragraph, area);

    // Move the terminal cursor to the insertion point in the prompt row.
    if let Some(col) = cursor_col {
        frame.set_cursor_position((area.x + col, area.y));
    }
}

/// Count search matches in the buffer and return `(current_idx, total)`.
/// `current_idx` is 1-based (the match the cursor is on or just passed).
/// Returns `None` when no pattern is active or there are no matches.
/// Caps at 10 000 matches to avoid stalling on huge files.
///
/// Result is memoised on `App::search_count_cache` keyed by
/// `(buffer_id, dirty_gen, cursor, pattern_text)` — the status line
/// re-runs this every render, but the scan only re-runs when one of
/// those changes. On a cache miss the scan walks
/// `View::content_joined` (cached `Arc<String>`) once with regex's
/// SIMD-fast `find_iter`, translating each match position back to its
/// row via the cumulative newline count instead of cloning per-line
/// `Vec<String>`s.
pub(crate) fn search_count(app: &App) -> Option<(usize, usize)> {
    const MATCH_CAP: usize = 10_000;
    let st = app.active_editor().search_state();
    let pat = st.pattern.as_ref()?;
    let pattern_str = pat.as_str();

    let buf = app.active_editor().buffer();
    let buffer_id = app.active().buffer_id;
    let dirty_gen = buf.dirty_gen();
    let cursor = app.active_editor().cursor();

    // Cache hit — return immediately.
    if let Some(cached) = app.search_count_cache.borrow().as_ref()
        && cached.buffer_id == buffer_id
        && cached.dirty_gen == dirty_gen
        && cached.cursor == cursor
        && cached.pattern == pattern_str
    {
        return cached.result;
    }

    let (cursor_row, cursor_col) = cursor;

    // `cursor_col` is a char index; regex match offsets are bytes.
    // Convert cursor's column to a byte offset within its own line.
    let cursor_byte_in_row = {
        let rope = buf.rope();
        if cursor_row < rope.len_lines() {
            let line = hjkl_buffer::rope_line_str(&rope, cursor_row);
            line.char_indices()
                .nth(cursor_col)
                .map(|(b, _)| b)
                .unwrap_or(line.len())
        } else {
            0
        }
    };

    // Single shared `Arc<String>` of the whole document — cached against
    // `dirty_gen`, so calling content_joined here costs an `Arc::clone`.
    let content = buf.content_joined();

    // O(log N) rope lookup beats the prior linear newline scan that ran
    // up to ~3 MB per keystroke on huge files when search was active.
    let cursor_global_byte = {
        let rope = buf.rope();
        let row = cursor_row.min(rope.len_lines());
        rope.line_to_byte(row) + cursor_byte_in_row
    };

    let mut total = 0usize;
    let mut current_idx = 0usize;
    for m in pat.find_iter(&content) {
        total += 1;
        if m.start() <= cursor_global_byte {
            current_idx = total;
        }
        if total >= MATCH_CAP {
            break;
        }
    }
    let result = if total == 0 {
        None
    } else {
        Some((current_idx, total))
    };

    *app.search_count_cache.borrow_mut() = Some(crate::app::SearchCountCache {
        buffer_id,
        dirty_gen,
        cursor,
        pattern: pattern_str.to_string(),
        result,
    });

    result
}

/// Build the status line text as a ratatui [`Line`].
///
/// Returns `(line, Some(cursor_col))` when a prompt is active so the
/// caller can position the terminal cursor at the insertion point.
///
/// Priority (highest first):
/// 1. Command input (user typing `:cmd`) — shows `:{typed_text}`.
/// 2. Engine search prompt (`/` or `?`) — shows `/{typed_text}`.
/// 3. Status message (ex-command result) — shown until next keypress.
/// 4. Normal mode/filename/cursor line.
fn build_status_line(app: &App, width: u16) -> (Line<'static>, Option<u16>) {
    // ── Command prompt (`:`) ─────────────────────────────────────────────────
    if let Some(ref field) = app.command_field {
        let text = field.text();
        let display: String = text.lines().next().unwrap_or("").to_string();
        let content = format!(":{display}");
        let (_, ccol) = field.cursor();
        let cursor_col = 1u16 + ccol as u16;
        let theme = prompt_theme(&app.theme.ui);
        return (
            build_prompt_line(&content, field.coarse_mode(), &theme, width),
            Some(cursor_col),
        );
    }

    // ── Filter prompt (`!`) ───────────────────────────────────────────────────
    if let Some(ref field) = app.filter_field {
        let text = field.text();
        let display: String = text.lines().next().unwrap_or("").to_string();
        let content = format!("!{display}");
        let (_, ccol) = field.cursor();
        let cursor_col = 1u16 + ccol as u16;
        let theme = prompt_theme(&app.theme.ui);
        return (
            build_prompt_line(&content, field.coarse_mode(), &theme, width),
            Some(cursor_col),
        );
    }

    // ── Host search prompt (`/` or `?`) ──────────────────────────────────────
    if let Some(ref field) = app.search_field {
        let prefix = match app.search_dir {
            crate::app::SearchDir::Forward => '/',
            crate::app::SearchDir::Backward => '?',
        };
        let text = field.text();
        let display: String = text.lines().next().unwrap_or("").to_string();
        let content = format!("{prefix}{display}");
        let (_, ccol) = field.cursor();
        let cursor_col = 1u16 + ccol as u16;
        let theme = prompt_theme(&app.theme.ui);
        return (
            build_prompt_line(&content, field.coarse_mode(), &theme, width),
            Some(cursor_col),
        );
    }

    // ── Crash-recovery prompt (issue #185) ─────────────────────────────────
    // While pending_recovery is Some, show the recovery prompt in the status
    // line (mirrors the confirm-substitute pattern).
    if let Some(pr) = app.pending_recovery.as_ref() {
        let content = format!(
            "E325: swap file found (written {} ago). Recover? [y/N/q]",
            pr.written_ago
        );
        let padded = format!("{content:<width$}", width = width as usize);
        return (
            Line::from(vec![Span::styled(
                padded,
                Style::default()
                    .bg(app.theme.ui.search_bg)
                    .fg(app.theme.ui.search_fg)
                    .add_modifier(Modifier::BOLD),
            )]),
            None,
        );
    }

    // ── Dirty-buffer disk-change prompt (issue #241) ────────────────────────
    // While pending_disk_change is Some, offer keep / reload / diff in place of
    // the normal status bar (mirrors the recovery-prompt pattern).
    if let Some(pdc) = app.pending_disk_change.as_ref() {
        let name = pdc
            .path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| pdc.path.to_string_lossy().into_owned());
        let content =
            format!("W12: \"{name}\" changed on disk since editing — [k]eep / [r]eload / [d]iff");
        let padded = format!("{content:<width$}", width = width as usize);
        return (
            Line::from(vec![Span::styled(
                padded,
                Style::default()
                    .bg(app.theme.ui.search_bg)
                    .fg(app.theme.ui.search_fg)
                    .add_modifier(Modifier::BOLD),
            )]),
            None,
        );
    }

    // ── Explorer git-discard confirm ────────────────────────────────────────
    if let Some(ref path) = app.explorer_git_discard_confirm {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.to_string_lossy().into_owned());
        let content = format!("Discard changes to {name}? (y/n)");
        let padded = format!("{content:<width$}", width = width as usize);
        return (
            Line::from(vec![Span::styled(
                padded,
                Style::default()
                    .bg(app.theme.ui.search_bg)
                    .fg(app.theme.ui.search_fg)
                    .add_modifier(Modifier::BOLD),
            )]),
            None,
        );
    }

    // ── Interactive substitute confirm (:s/pat/rep/c) ──────────────────────
    // While confirming_substitute is Some, show the per-match prompt instead
    // of the normal status bar.
    if let Some(cs) = app.confirming_substitute.as_ref() {
        let rep = if cs.idx < cs.matches.len() {
            cs.matches[cs.idx].replacement.as_str()
        } else {
            ""
        };
        let content = format!("replace with \"{rep}\"? (y/n/a/q/l)");
        let padded = format!("{content:<width$}", width = width as usize);
        return (
            Line::from(vec![Span::styled(
                padded,
                Style::default()
                    .bg(app.theme.ui.search_bg)
                    .fg(app.theme.ui.search_fg)
                    .add_modifier(Modifier::BOLD),
            )]),
            None,
        );
    }

    // ── Macro recording indicator ───────────────────────────────────────────
    // Vim shows "recording @r" while `q{reg}` is active. Render it as a
    // status-message-equivalent so it visually pre-empts the lualine row,
    // matching vim's bottom-line takeover.
    if let Some(reg) = app.active_editor().recording_register() {
        let content = format!(" recording @{reg}");
        let padded = format!("{content:<width$}", width = width as usize);
        return (
            Line::from(vec![Span::styled(
                padded,
                Style::default()
                    .bg(app.theme.ui.surface_bg)
                    .fg(app.theme.ui.text)
                    .add_modifier(Modifier::BOLD),
            )]),
            None,
        );
    }

    // ── Normal status line — delegated to hjkl-statusline ───────────────────
    // Palette + segments built in `build_normal_status_bar`; ratatui
    // conversion via `hjkl_statusline_tui::to_line`.
    (build_normal_status_bar(app, width), None)
}

/// Format the status line as a plain string (unit-test helper).
///
/// `readonly` and `is_new_file` mirror the app state flags.
/// Filename is truncated with `…` when necessary.
#[cfg(test)]
pub fn format_status_line(
    mode: &str,
    filename: &str,
    dirty: bool,
    row: usize,
    col: usize,
    total_lines: usize,
    width: u16,
) -> String {
    format_status_line_full(
        mode,
        filename,
        dirty,
        false,
        false,
        row,
        col,
        total_lines,
        width,
    )
}

/// Full status line formatter with readonly + new-file flags.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub fn format_status_line_full(
    mode: &str,
    filename: &str,
    dirty: bool,
    readonly: bool,
    is_new_file: bool,
    row: usize,
    col: usize,
    total_lines: usize,
    width: u16,
) -> String {
    let dirty_marker = if dirty { "*" } else { " " };
    let ro_tag = if readonly { " [RO]" } else { "" };
    let new_tag = if is_new_file { " [New File]" } else { "" };
    let pct = ((row + 1) * 100).checked_div(total_lines).unwrap_or(0);
    let pos = format!("{}:{}", row + 1, col + 1);
    let pct_str = format!("{pct}%");
    let right = format!("{pos}  {pct_str} ");
    let left_prefix = format!(" {mode}  {dirty_marker} ");
    let suffix = format!("{ro_tag}{new_tag}");
    let w = width as usize;
    let reserved = left_prefix.len() + suffix.len() + right.len();
    let avail_for_name = w.saturating_sub(reserved);
    let truncated: String = if filename.chars().count() <= avail_for_name {
        filename.to_string()
    } else if avail_for_name <= 1 {
        String::new()
    } else {
        let keep = avail_for_name.saturating_sub(1);
        // Walk from the end to find the byte start of the last `keep` chars,
        // avoiding a panic when `filename` contains multibyte characters.
        let start_byte = filename
            .char_indices()
            .rev()
            .nth(keep.saturating_sub(1))
            .map(|(byte_idx, _)| byte_idx)
            .unwrap_or(0);
        format!("\u{2026}{}", &filename[start_byte..])
    };
    let left = format!("{left_prefix}{truncated}{suffix}");
    let used = left.len() + right.len();
    let pad_count = w.saturating_sub(used);
    let spacer = " ".repeat(pad_count);
    format!("{left}{spacer}{right}")
}

/// Format the write-success status message. Used in tests.
#[cfg(test)]
pub fn format_write_message(path: &str, lines: usize, bytes: usize) -> String {
    format!("\"{}\" {}L, {}B written", path, lines, bytes)
}

/// Render the status-line content for `app` at the given `width` and return
/// the concatenated plaintext string. Used in unit tests to assert which
/// branch (full-line banner vs normal bar) fires.
#[cfg(test)]
pub(crate) fn status_line_text(app: &App, width: u16) -> String {
    let (line, _cursor_col) = build_status_line(app, width);
    line.spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<Vec<_>>()
        .join("")
}

/// Centered popup containing the picker's query input + scrollable
/// result list. Drawn on top of the buffer pane via `Clear` so the
/// editor content beneath is masked.
fn picker_overlay(frame: &mut Frame, app: &mut App, buf_area: Rect) {
    let area = centered_rect(80, 70, buf_area);
    frame.render_widget(Clear, area);

    let p = match app.picker.as_mut() {
        Some(p) => p,
        None => return,
    };

    // Tick debounce for Spawn sources.
    p.tick(std::time::Instant::now());

    p.refresh();
    p.refresh_preview();

    const PREVIEW_MIN_WIDTH: u16 = 80;
    let with_preview = p.has_preview() && area.width >= PREVIEW_MIN_WIDTH;

    let (left_area, preview_area) = if with_preview {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(area);
        (cols[0], Some(cols[1]))
    } else {
        (area, None)
    };

    render_picker_input_and_list(frame, p, &app.theme.ui, left_area);
    // p (mut borrow on app.picker) ends here; below re-borrows app immutably
    // both as the picker handle and as the `PreviewHighlighter` impl.

    if let Some(right) = preview_area {
        let ui = &app.theme.ui;
        let theme = hjkl_picker_tui::PreviewTheme {
            border: Style::default().fg(ui.border),
            gutter: Style::default().fg(ui.gutter),
            non_text: Style::default().fg(ui.non_text),
            cursor_line: cursor_line_bg(ui),
        };
        // Re-borrow the picker immutably (the earlier `as_mut` borrow ended
        // above). Use `if let` rather than `expect` so a cleared picker skips
        // the preview instead of panicking the render path.
        if let Some(picker) = app.picker.as_ref() {
            hjkl_picker_tui::preview_pane(frame, picker, app, &theme, right);
        }
    }
}

/// Shared input + list rendering for the non-generic `Picker`.
fn render_picker_input_and_list(
    frame: &mut Frame,
    picker: &mut crate::picker::Picker,
    theme: &crate::theme::UiTheme,
    left_area: Rect,
) {
    let layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(1)])
        .split(left_area);
    let input_area = layout[0];
    let list_area = layout[1];

    let total = picker.total();
    let matched = picker.matched();
    let scan_tag = if picker.scan_done() {
        "".to_string()
    } else {
        format!(" {} scanning", hjkl_editor_tui::spinner::frame())
    };
    let kind = picker.title();
    let title = format!(" picker — {kind}{matched}/{total}{scan_tag} ");

    let query_text = picker.query.text();
    let display: String = query_text.lines().next().unwrap_or("").to_string();
    let input_block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::default().fg(theme.border_active));
    let input_inner = input_block.inner(input_area);
    frame.render_widget(input_block, input_area);
    let input_para = Paragraph::new(format!("/ {display}"));
    frame.render_widget(input_para, input_inner);

    let (_, ccol) = picker.query.cursor();
    let cx = input_inner.x + 2 + ccol as u16;
    let cy = input_inner.y;
    if cx < input_inner.x + input_inner.width && cy < input_inner.y + input_inner.height {
        frame.set_cursor_position((cx, cy));
    }

    let entries = picker.visible_entries();
    let row_styles = picker.visible_entry_styles();
    // Match-position highlight inside picker rows — uses the same orange
    // as search match highlighting.
    let match_style = Style::default()
        .fg(theme.search_bg)
        .add_modifier(Modifier::BOLD);
    let items: Vec<ListItem> = entries
        .iter()
        .enumerate()
        .map(|(row_idx, (label, matches))| {
            let styles = row_styles.get(row_idx).map(Vec::as_slice).unwrap_or(&[]);
            if matches.is_empty() && styles.is_empty() {
                return ListItem::new(label.clone());
            }
            let spans: Vec<Span> = label
                .chars()
                .enumerate()
                .map(|(ci, ch)| {
                    let s = ch.to_string();
                    let base_engine = styles
                        .iter()
                        .find(|(r, _)| r.contains(&ci))
                        .map(|(_, st)| *st)
                        .unwrap_or_default();
                    let base = hjkl_engine_tui::style_to_ratatui(base_engine);
                    if matches.contains(&ci) {
                        Span::styled(s, base.patch(match_style))
                    } else if base != Style::default() {
                        Span::styled(s, base)
                    } else {
                        Span::raw(s)
                    }
                })
                .collect();
            ListItem::new(Line::from(spans))
        })
        .collect();
    // Keep labels for length check below.
    let label_count = entries.len();
    let list_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.border));
    let list = List::new(items).block(list_block).highlight_style(
        Style::default()
            .bg(theme.picker_selection_bg)
            .add_modifier(Modifier::BOLD),
    );
    let mut state = ListState::default();
    if label_count > 0 {
        state.select(Some(picker.selected.min(label_count.saturating_sub(1))));
    }
    frame.render_stateful_widget(list, list_area, &mut state);
}

/// Centered popup for multi-line `:reg` / `:marks` / `:jumps` / `:changes`
/// output and the K-key LSP hover info path. Delegates to
/// `hjkl_info_popup_tui::render` (thin shim, ≤10 LOC).
fn info_popup_overlay(frame: &mut Frame, app: &App, buf_area: Rect) {
    let popup = match app.info_popup.as_ref() {
        Some(p) => p,
        None => return,
    };
    let theme = hjkl_info_popup_tui::InfoPopupTheme::new(app.theme.ui.border_active);
    hjkl_info_popup_tui::render(frame, popup, &theme, buf_area);
}

/// Render the which-key popup anchored at the bottom of `buf_area`.
///
/// Only called when `app.which_key_active` is `true` and a prefix is pending.
fn which_key_popup(frame: &mut Frame, app: &App, buf_area: Rect) {
    if !app.which_key_active {
        return;
    }
    let pending = app.active_which_key_prefix();
    if pending.is_empty() && !app.which_key_sticky {
        return;
    }

    let leader = app.config.editor.leader;
    // The popup is Normal-mode only by design: `entries_for` is called with a
    // hardcoded `Mode::Normal` regardless of the current vim mode.
    // Non-Normal modes (Visual, Insert, etc.) suppress the popup implicitly
    // because `active_which_key_prefix` reads the Normal pending buffer of the
    // context keymap, which is always empty when the mode is not Normal.
    // When the explorer sidebar is focused, `ctx_keymap()` returns
    // `explorer_keymap` so the popup lists explorer-specific bindings.
    let entries =
        hjkl_which_key::entries_for(app.ctx_keymap(), hjkl_vim::Mode::Normal, &pending, leader);
    if entries.is_empty() {
        return;
    }

    let ui = &app.theme.ui;
    let popup_layout = hjkl_which_key::layout(&entries, buf_area.width);

    let header_label = if pending.is_empty() {
        "root".to_string()
    } else {
        hjkl_keymap::Chord(pending.clone()).to_notation(leader)
    };

    let theme = hjkl_which_key_tui::PopupTheme::new(
        ratatui_rgb_to_sl(ui.border_active),
        ratatui_rgb_to_sl(ui.text_dim),
    );

    hjkl_which_key_tui::render(frame, &popup_layout, &header_label, &theme, buf_area);
}

/// Compute a centered Rect of `pct_x`% × `pct_y`% of `area`.
fn centered_rect(pct_x: u16, pct_y: u16, area: Rect) -> Rect {
    let width = area.width.saturating_mul(pct_x) / 100;
    let height = area.height.saturating_mul(pct_y) / 100;
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    Rect {
        x,
        y,
        width,
        height,
    }
}

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

    #[test]
    fn status_line_normal_mode_no_name() {
        let s = format_status_line("NORMAL", "[No Name]", false, 0, 0, 1, 60);
        assert!(s.contains("NORMAL"));
        assert!(s.contains("[No Name]"));
        assert!(s.contains("1:1"));
        assert!(s.contains("100%"));
    }

    #[test]
    fn status_line_dirty_marker() {
        let clean = format_status_line("NORMAL", "foo.txt", false, 0, 0, 1, 60);
        let dirty = format_status_line("NORMAL", "foo.txt", true, 0, 0, 1, 60);
        assert!(clean.contains(" [No Name]") || clean.contains(" foo.txt"));
        // dirty marker is `*` in dirty, ` ` in clean
        let dirty_idx = dirty.find('*');
        assert!(dirty_idx.is_some(), "dirty status should contain '*'");
        let clean_contains_star = clean.contains('*');
        assert!(!clean_contains_star, "clean status should not contain '*'");
    }

    #[test]
    fn status_line_percentage() {
        let s = format_status_line("NORMAL", "f.txt", false, 4, 0, 10, 60);
        // row 4 of 10 = 50%
        assert!(s.contains("50%"));
    }

    #[test]
    fn status_line_fits_width() {
        let width: u16 = 40;
        let s = format_status_line("INSERT", "myfile.rs", true, 0, 0, 100, width);
        assert_eq!(s.len(), width as usize);
    }

    #[test]
    fn write_message_format() {
        let msg = format_write_message("/tmp/foo.txt", 10, 128);
        assert_eq!(msg, "\"/tmp/foo.txt\" 10L, 128B written");
    }

    #[test]
    fn status_line_readonly_tag() {
        let s = format_status_line_full("NORMAL", "foo.txt", false, true, false, 0, 0, 1, 80);
        assert!(s.contains("[RO]"), "readonly tag must appear");
    }

    #[test]
    fn status_line_new_file_tag() {
        let s = format_status_line_full("NORMAL", "newfile.txt", false, false, true, 0, 0, 1, 80);
        assert!(s.contains("[New File]"), "new-file tag must appear");
    }

    #[test]
    fn status_line_truncates_long_filename() {
        // Very narrow terminal — filename must be truncated.
        let long = "some/very/long/path/to/a/deeply/nested/file.rs";
        let s = format_status_line_full("NORMAL", long, false, false, false, 0, 0, 1, 30);
        // Truncated filename starts with `…`
        assert!(
            s.contains('\u{2026}'),
            "truncated filename must start with …"
        );
    }

    /// Truncating a filename that contains multibyte chars must not panic.
    ///
    /// Before the fix, `format_status_line_full` computed
    /// `start = filename.len().saturating_sub(keep)` and sliced `&filename[start..]`.
    /// `keep` is a display-width value, not a byte count; on a filename like
    /// "éàü.rs" (each accent = 2 UTF-8 bytes), `filename.len() - keep` can land
    /// inside a multibyte char, causing a panic "byte index N is not a char boundary".
    #[test]
    fn status_line_truncates_multibyte_filename_no_panic() {
        // 6 accented chars (2 bytes each) + ".rs" = 15 bytes, 9 chars.
        // Force truncation with a narrow width so keep < byte_len.
        let name = "éàüöïâ.rs";
        // width=30 will likely force truncation; the exact geometry doesn't
        // matter — we just need it to not panic and produce valid UTF-8.
        let s = format_status_line_full("NORMAL", name, false, false, false, 0, 0, 1, 30);
        // Result must be valid UTF-8 (String guarantees this on success).
        // Also verify the ellipsis is present when the name was truncated.
        let _ = s; // no panic = success
    }

    #[test]
    fn status_line_arg_parsing_plus_n() {
        // Smoke test: +5 → goto_line=Some(5). Tested via parse logic in main.
        // Here we verify the status-line can handle being on line 5.
        let s = format_status_line("NORMAL", "file.txt", false, 4, 0, 10, 60);
        // row 4 (0-based) → 5 in display
        assert!(s.contains("5:1"));
    }

    #[test]
    fn top_bar_height_is_one() {
        assert_eq!(crate::app::TOP_BAR_HEIGHT, 1);
    }

    /// #303: `transparent = false` (the default) paints the editor text area +
    /// gutter with the theme's editor background; `transparent = true` clears
    /// the fill so the terminal's own background shows through.
    #[test]
    fn buffer_background_honours_transparent_flag() {
        use crate::app::App;
        use ratatui::style::{Color, Style};

        // Opaque (default): the base background carries the theme's editor bg.
        let mut cfg = hjkl_app::config::Config::default();
        cfg.theme.transparent = false;
        let app = App::new(None, false, None, None)
            .unwrap()
            .with_config(cfg.clone());
        assert!(!app.theme_transparent);
        assert_eq!(
            buffer_background_style(&app),
            Style::default().bg(app.theme.ui.background),
            "opaque config must fill with the theme background"
        );
        // Sanity: a bg is actually set (not Reset).
        assert!(matches!(
            buffer_background_style(&app).bg,
            Some(Color::Rgb(_, _, _))
        ));

        // Transparent: no fill — BufferView.background is the empty default.
        cfg.theme.transparent = true;
        let app_t = App::new(None, false, None, None).unwrap().with_config(cfg);
        assert!(app_t.theme_transparent);
        assert_eq!(
            buffer_background_style(&app_t),
            Style::default(),
            "transparent config must leave the background unpainted (terminal shows through)"
        );
        assert_eq!(buffer_background_style(&app_t).bg, None);
    }

    /// A file's name in the explorer must be colored uniformly — every cell of
    /// the name (including the LAST one) gets the filetype color, not a stray
    /// default-white cell at the end.
    #[test]
    fn explorer_file_name_coloring_is_uniform() {
        use crate::app::App;
        use crate::keymap_actions::AppAction;
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("a").join("b").join("c")).unwrap();
        std::fs::write(
            tmp.path().join("a").join("b").join("c").join("widget.rs"),
            b"x",
        )
        .unwrap();
        let _cwd = crate::test_cwd::CwdGuard::enter(tmp.path());

        // Open the DEEP file so there's no splash and its ancestors are expanded
        // (the white-last-char artifact only shows on nested rows).
        let mut app = App::new(Some("a/b/c/widget.rs".into()), false, None, None).unwrap();
        app.dispatch_action(AppAction::ToggleExplorer, 1);

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        // Draw twice: the first frame settles window rects/viewports.
        terminal.draw(|f| frame(f, &mut app)).unwrap();
        terminal.draw(|f| frame(f, &mut app)).unwrap();
        let buf = terminal.backend().buffer().clone();
        let text_color = app.theme.ui.text;

        // Locate the contiguous run of cells spelling "widget.rs".
        let name: Vec<char> = "widget.rs".chars().collect();
        let n = name.len() as u16;
        let cell_sym = |x: u16, y: u16| -> String {
            buf.cell((x, y))
                .map(|c| c.symbol().to_string())
                .unwrap_or_default()
        };
        let mut found: Option<(u16, u16)> = None;
        'scan: for y in 0..24u16 {
            for x in 0..(80 - n) {
                if (0..n).all(|i| cell_sym(x + i, y) == name[i as usize].to_string()) {
                    found = Some((x, y));
                    break 'scan;
                }
            }
        }
        let (sx, sy) = found.expect("widget.rs must be rendered in the explorer");
        let _ = text_color;

        // The icon (two cells before the name) carries the filetype color; the
        // whole name must share that exact color — no `Reset`/white cells.
        let icon_fg = buf.cell((sx - 2, sy)).unwrap().fg;
        assert_ne!(icon_fg, Color::Reset, "icon should be filetype-colored");
        let fgs: Vec<Color> = (0..n).map(|i| buf.cell((sx + i, sy)).unwrap().fg).collect();
        assert!(
            fgs.iter().all(|&f| f == icon_fg),
            "every cell of the name must share the filetype color (no uncolored/white \
             cells); icon_fg={icon_fg:?} name fgs={fgs:?}"
        );
    }

    /// `:diffsplit` paints DiffChange line bands and DiffText char highlights
    /// (#208 Phase 2). One line differs; its changed characters get the stronger
    /// DiffText bg and the rest of the line gets the DiffChange band bg.
    #[test]
    fn diffsplit_paints_change_band_and_difftext() {
        use crate::app::App;
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.txt");
        let b = tmp.path().join("b.txt");
        std::fs::write(&a, "alpha\nbeta\ngamma\n").unwrap();
        std::fs::write(&b, "alpha\nBETA\ngamma\n").unwrap();

        let mut app = App::new(Some(a.clone()), false, None, None).unwrap();
        app.dispatch_ex(&format!("diffsplit {}", b.display()));

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        // Draw twice so window rects/viewports settle before the overlay pass.
        terminal.draw(|f| frame(f, &mut app)).unwrap();
        terminal.draw(|f| frame(f, &mut app)).unwrap();
        let buf = terminal.backend().buffer().clone();

        let change_bg = Color::Rgb(32, 42, 60);
        let text_bg = Color::Rgb(48, 78, 110);

        let mut has_change = false;
        let mut has_text = false;
        for y in 0..24u16 {
            for x in 0..80u16 {
                if let Some(c) = buf.cell((x, y)) {
                    if c.bg == change_bg {
                        has_change = true;
                    }
                    if c.bg == text_bg {
                        has_text = true;
                    }
                }
            }
        }
        assert!(has_change, "a DiffChange band must be painted");
        assert!(has_text, "a DiffText char highlight must be painted");
    }

    /// Filler rows (#250) keep both diff windows aligned: a line only present in
    /// one buffer pushes a blank `DiffDelete`-tinted filler into the other, so a
    /// shared line below the insertion lands on the SAME screen row in both
    /// windows.
    #[test]
    fn diffsplit_filler_aligns_shared_line() {
        use crate::app::App;
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.txt");
        let b = tmp.path().join("b.txt");
        // `ins` exists only in b → a gets a filler row before the later lines.
        // The shared marker `zebra` sits well below the transient top-right
        // toast so the alignment check isn't occluded by it.
        std::fs::write(&a, "l0\nl1\nl2\nl3\nl4\nl5\nzebra\n").unwrap();
        std::fs::write(&b, "l0\nl1\nins\nl2\nl3\nl4\nl5\nzebra\n").unwrap();

        let mut app = App::new(Some(a.clone()), false, None, None).unwrap();
        app.dispatch_ex(&format!("diffsplit {}", b.display()));

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

        let cell_sym = |x: u16, y: u16| -> String {
            buf.cell((x, y))
                .map(|c| c.symbol().to_string())
                .unwrap_or_default()
        };
        // Find both occurrences of the shared marker (one per window).
        let needle: Vec<char> = "zebra".chars().collect();
        let n = needle.len() as u16;
        let mut gamma_rows = Vec::new();
        for y in 0..24u16 {
            for x in 0..(80 - n) {
                if (0..n).all(|i| cell_sym(x + i, y) == needle[i as usize].to_string()) {
                    gamma_rows.push(y);
                }
            }
        }
        assert_eq!(
            gamma_rows.len(),
            2,
            "gamma must render once per diff window; got {gamma_rows:?}"
        );
        assert_eq!(
            gamma_rows[0], gamma_rows[1],
            "filler must align `gamma` on the same screen row in both windows"
        );

        // A DiffDelete filler row must be painted (muted dark red).
        let filler_bg = Color::Rgb(60, 32, 32);
        let has_filler = (0..24u16)
            .any(|y| (0..80u16).any(|x| buf.cell((x, y)).map(|c| c.bg) == Some(filler_bg)));
        assert!(has_filler, "a DiffDelete filler row must be painted");
    }

    // ── Audit D2: diagnostics clipped to the visible viewport ──────────────

    /// `row_in_viewport` is the shared predicate `build_diag_overlays` and the
    /// eol-hint builder use to skip off-screen diagnostics. `vp_top` is
    /// inclusive, `vp_bot` is exclusive — matches the `top_row..top_row+height`
    /// convention used everywhere else in this file (e.g. `visible_signs`).
    #[test]
    fn row_in_viewport_bounds() {
        assert!(!row_in_viewport(4, 5, 10), "row before vp_top is out");
        assert!(row_in_viewport(5, 5, 10), "vp_top is inclusive");
        assert!(row_in_viewport(9, 5, 10), "last visible row is inclusive");
        assert!(!row_in_viewport(10, 5, 10), "vp_bot is exclusive");
        assert!(!row_in_viewport(500, 5, 10), "far off-screen row is out");
    }

    /// `build_diag_overlays` must only emit an overlay for a diagnostic whose
    /// `start_row` is inside `[vp_top, vp_bot)`. Before the fix it mapped
    /// every entry in `slot.lsp_diags` unconditionally — this is the direct
    /// regression guard for that allocation-churn bug (audit D2): a
    /// diagnostic thousands of lines off-screen must neither appear in the
    /// output nor be touched by the `.map()` at all.
    #[test]
    fn build_diag_overlays_clips_to_viewport() {
        use crate::app::{App, LspDiag};

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("diag_clip.txt");
        let content: String = (0..500).map(|i| format!("line {i}\n")).collect();
        std::fs::write(&path, &content).unwrap();

        let mut app = App::new(Some(path), false, None, None).unwrap();
        let mk = |row: usize, msg: &str| LspDiag {
            start_row: row,
            start_col: 0,
            end_row: row,
            end_col: 3,
            severity: DiagSeverity::Error,
            message: msg.to_string(),
            source: None,
            code: None,
        };
        app.slots_mut()[0].lsp_diags = vec![
            mk(0, "top edge, in range"),
            mk(5, "middle, in range"),
            mk(49, "bottom edge, in range (vp_bot exclusive at 50)"),
            mk(50, "just past vp_bot, out"),
            mk(400, "far off-screen, out"),
        ];

        let overlays = build_diag_overlays(&app.slots()[0], &app.theme.ui, 0, 50);
        let mut rows: Vec<usize> = overlays.iter().map(|o| o.row).collect();
        rows.sort_unstable();
        assert_eq!(
            rows,
            vec![0, 5, 49],
            "only diagnostics with start_row in [0, 50) may produce an overlay"
        );

        // Scrolling the viewport down must reveal the previously off-screen
        // diagnostic and hide the ones that scrolled out — proves the clip is
        // a real viewport window, not a fixed cutoff.
        let overlays2 = build_diag_overlays(&app.slots()[0], &app.theme.ui, 400, 450);
        let rows2: Vec<usize> = overlays2.iter().map(|o| o.row).collect();
        assert_eq!(rows2, vec![400]);
    }

    /// End-to-end regression guard: a diagnostic on a visible row must still
    /// render its EOL ghost-text hint exactly as before the viewport clip —
    /// the clip must be invisible for on-screen rows. `diagnostics_inline`
    /// defaults to `all`, so no config is needed to enable the hint.
    #[test]
    fn visible_diagnostic_eol_hint_still_renders() {
        use crate::app::{App, LspDiag};
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("diag_eol.rs");
        // Plenty of trailing lines so a diagnostic near the end is off-screen
        // while the cursor (row 0) stays on-screen.
        let content: String = std::iter::once("let x = 1;\n".to_string())
            .chain((0..500).map(|i| format!("// filler {i}\n")))
            .collect();
        std::fs::write(&path, &content).unwrap();

        let mut app = App::new(Some(path), false, None, None).unwrap();
        app.slots_mut()[0].lsp_diags = vec![
            LspDiag {
                start_row: 0,
                start_col: 0,
                end_row: 0,
                end_col: 1,
                severity: DiagSeverity::Error,
                message: "visible unused variable".to_string(),
                source: None,
                code: None,
            },
            LspDiag {
                start_row: 450,
                start_col: 0,
                end_row: 450,
                end_col: 1,
                severity: DiagSeverity::Error,
                message: "offscreen diagnostic".to_string(),
                source: None,
                code: None,
            },
        ];

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

        let mut rendered = String::new();
        for y in 0..24u16 {
            for x in 0..80u16 {
                if let Some(c) = buf.cell((x, y)) {
                    rendered.push_str(c.symbol());
                }
            }
        }
        assert!(
            rendered.contains("visible unused variable"),
            "the cursor-row diagnostic's EOL hint must still render: {rendered:?}"
        );
        assert!(
            !rendered.contains("offscreen diagnostic"),
            "the far off-screen diagnostic must never reach the screen buffer"
        );
    }

    // ── Fix 2: screen_rect derived from the focused window's viewport ──────

    /// `App::screen_rect()` must return the real terminal size even with a
    /// split open. Before the fix it derived from the FOCUSED window's
    /// viewport — but this render loop sets each window's viewport to its
    /// PANE dims (`render_window`, `vp.height = area.height` above), so
    /// with a horizontal split the old `screen_rect()` returned the
    /// focused pane's height, not the terminal's. That broke the
    /// status-line hit-test (mouse.rs) and context-menu clamping/hover
    /// (event_loop.rs): right-clicking the real bottom row resolved to a
    /// mid-screen zone instead of `Zone::StatusLine`.
    #[test]
    fn screen_rect_is_real_terminal_rect_with_split() {
        use crate::app::App;
        use crate::app::mouse::{Zone, hit_test_zone};
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("split_screen_rect.txt");
        std::fs::write(&path, "l0\nl1\nl2\nl3\nl4\n").unwrap();

        let mut app = App::new(Some(path), false, None, None).unwrap();
        // Horizontal split: the focused window's pane is roughly half the
        // terminal height, so a bug in `screen_rect()` shows up as a wrong
        // height rather than accidentally matching by coincidence.
        app.dispatch_ex("sp");

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        // Draw twice: the first frame settles window rects/viewports (same
        // pattern as the other TestBackend tests in this file).
        terminal.draw(|f| frame(f, &mut app)).unwrap();
        terminal.draw(|f| frame(f, &mut app)).unwrap();

        let screen = app.screen_rect();
        assert_eq!(
            (screen.width, screen.height),
            (80, 24),
            "screen_rect() must report the real 80x24 terminal, not the \
             focused pane's shrunken dims"
        );

        // The real bottom row (23, 0-based on a 24-row terminal) must
        // hit-test as the status line. With the pre-fix `screen_rect()`
        // undercounting the height, this row is ABOVE the (wrongly
        // computed) status row, so it fell through to whatever window pane
        // occupies row 23 instead.
        let zone = hit_test_zone(&app, 10, 23);
        assert_eq!(
            zone,
            Zone::StatusLine,
            "row 23 (the real bottom row) must hit-test as the status line; got {zone:?}"
        );
    }

    // ── Fix 5: completion popup anchored to the stale slot-editor viewport ──

    /// `completion_popup` used to read `app.slots()[slot_idx].editor.host().viewport()`
    /// — the SLOT bridge editor's viewport, which stays pinned at its
    /// creation `top_row` (#151: per-window editors own scroll, not the
    /// slot bridge). Scroll a window deep, open a completion popup anchored
    /// near the new (scrolled) cursor row, and check the popup actually
    /// renders near that row instead of computing a huge/garbage row from
    /// the stale `top_row=0` and vanishing off the 24-row screen entirely.
    #[test]
    fn completion_popup_anchors_to_scrolled_window_not_stale_slot_viewport() {
        use crate::app::App;
        use crate::completion::{Completion, CompletionItem};
        use ratatui::{Terminal, backend::TestBackend};

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("completion_scroll.txt");
        let content: String = (0..100).map(|i| format!("line{i}\n")).collect();
        std::fs::write(&path, &content).unwrap();

        let mut app = App::new(Some(path), false, None, None).unwrap();

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        // First frame settles window rects/viewports/text_width.
        terminal.draw(|f| frame(f, &mut app)).unwrap();

        // Scroll the WINDOW's own editor deep (mirrors real scroll: #151
        // per-window editors own top_row) while leaving the SLOT bridge
        // editor's viewport at its creation value (top_row=0) — exactly the
        // divergence the bug depends on.
        let fw = app.focused_window();
        if let Some(e) = app.window_editors.get_mut(&fw) {
            e.host_mut().viewport_mut().top_row = 50;
        }

        // Anchor the popup near the NEW (scrolled) cursor row: doc row 55,
        // i.e. screen row 5 relative to the real top_row=50. Pre-fix (stale
        // top_row=0), this computes screen row 55 — off the 24-row screen,
        // and the popup's own overflow-clamp math still can't pull a
        // `y=55`-anchored popup back into a 24-row buffer, so it renders
        // nowhere on screen at all.
        app.completion = Some(Completion::new(
            55,
            0,
            vec![CompletionItem::new("uniqueitemlabel")],
        ));

        terminal.draw(|f| frame(f, &mut app)).unwrap();
        let buf = terminal.backend().buffer().clone();

        let mut found_row: Option<u16> = None;
        'scan: for y in 0..24u16 {
            for x in 0..80u16 {
                if let Some(c) = buf.cell((x, y))
                    && c.symbol() == "u"
                {
                    let mut s = String::new();
                    for i in 0..15u16 {
                        if let Some(cc) = buf.cell((x + i, y)) {
                            s.push_str(cc.symbol());
                        }
                    }
                    if s.starts_with("uniqueitemlabe") {
                        found_row = Some(y);
                        break 'scan;
                    }
                }
            }
        }

        let row = found_row.expect(
            "completion item must render somewhere on the 24-row screen — \
             pre-fix it anchored off-screen using the stale slot viewport",
        );
        assert!(
            row <= 10,
            "completion popup must anchor NEAR the scrolled cursor row \
             (doc row 55, window top_row 50 → screen row ~5); got row {row}, \
             too far down to be anchored correctly"
        );
    }

    // ── Fix 6: smooth-scroll interpolated top never reached the renderer ───

    /// `render_window` computed the animated render top (`vp_top`, via
    /// `scroll_anim_render_top`) but only ever used it for overlays (signs,
    /// matchparen, hop, diff bands) — `viewport_owned.top_row`, the
    /// viewport `BufferView` actually paints text from, stayed at the
    /// FINAL target the whole time. So the feature was visually inert: the
    /// TEXT never moved during a scroll anim, only the (invisible without
    /// text moving too) overlay math.
    ///
    /// With an active mid-flight anim from top 0 toward target 100, the
    /// rendered text's top row must show the line at the ANIMATED top
    /// (strictly between 0 and 100), not `line100` (the target).
    #[test]
    fn scroll_anim_render_top_reaches_the_text_renderer() {
        use crate::app::{App, ScrollAnim};
        use ratatui::{Terminal, backend::TestBackend};
        use std::time::{Duration, Instant};

        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("scroll_anim.txt");
        let content: String = (0..200).map(|i| format!("line{i}\n")).collect();
        std::fs::write(&path, &content).unwrap();

        let mut app = App::new(Some(path), false, None, None).unwrap();

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        // First frame settles window rects/viewports/text_width.
        terminal.draw(|f| frame(f, &mut app)).unwrap();

        // Force the REAL (target) viewport top to 100, then arm a
        // long-duration (10s) mid-flight anim from 0 toward it, 5s in
        // (p=0.5). The long duration means the few microseconds between
        // reading `expected_top` below and the render call can't shift the
        // eased fraction enough to change the rounded row.
        let fw = app.focused_window();
        if let Some(e) = app.window_editors.get_mut(&fw) {
            e.host_mut().viewport_mut().top_row = 100;
        }
        app.scroll_anim = Some(ScrollAnim {
            win_id: fw,
            start_top: 0,
            target_top: 100,
            started_at: Instant::now() - Duration::from_secs(5),
            duration: Duration::from_secs(10),
        });

        let expected_top = app
            .scroll_anim_render_top(fw)
            .expect("mid-flight anim must return Some");
        assert!(
            expected_top > 0 && expected_top < 100,
            "test setup sanity: expected_top must be strictly between the \
             anim's start (0) and target (100); got {expected_top}"
        );

        terminal.draw(|f| frame(f, &mut app)).unwrap();
        let buf = terminal.backend().buffer().clone();

        let mut rows: Vec<String> = Vec::with_capacity(24);
        for y in 0..24u16 {
            let mut row = String::new();
            for x in 0..80u16 {
                if let Some(c) = buf.cell((x, y)) {
                    row.push_str(c.symbol());
                }
            }
            rows.push(row);
        }
        let rendered = rows.join("\n");

        let needle = format!("line{expected_top}");
        assert!(
            rendered.contains(&needle),
            "rendered text must show {needle:?} (the line at the ANIMATED \
             top) somewhere on screen — pre-fix, text always drew from the \
             target top (\"line100\") regardless of the animation. \
             rendered:\n{rendered}"
        );
        assert!(
            !rows[0].trim_start().starts_with("line100"),
            "the top screen row must show the animated line, not the \
             target's — got top row {:?}",
            rows[0]
        );
    }
}