fresh-editor 0.4.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
//! Settings UI renderer
//!
//! Renders the settings modal with category navigation and setting controls.

use rust_i18n::t;

use crate::primitives::display_width::str_width;

use super::entry_dialog::EntryDialogState;
use super::items::SettingControl;
use super::layout::{SettingsHit, SettingsLayout};
use super::search::{DeepMatch, SearchResult};
use super::state::SettingsState;
use crate::view::controls::{
    render_dropdown_aligned, render_dual_list_partial, render_number_input_aligned,
    render_text_input_aligned, render_toggle_aligned, DropdownColors, DualListColors, MapColors,
    NumberInputColors, TextInputColors, TextListColors, ToggleColors,
};
use crate::view::theme::Theme;
use crate::view::ui::scrollbar::{render_scrollbar, ScrollbarColors, ScrollbarState};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use ratatui::Frame;

/// Build spans for a text line with selection highlighting
///
/// Returns a vector of spans where selected portions are highlighted.
#[allow(clippy::too_many_arguments)]
fn build_selection_spans(
    display_text: &str,
    display_len: usize,
    line_idx: usize,
    start_row: usize,
    start_col: usize,
    end_row: usize,
    end_col: usize,
    text_color: Color,
    selection_bg: Color,
) -> Vec<Span<'static>> {
    let chars: Vec<char> = display_text.chars().collect();
    let char_count = chars.len();

    // Determine selection range for this line
    let (sel_start, sel_end) = if line_idx < start_row || line_idx > end_row {
        // Line not in selection
        (char_count, char_count)
    } else if line_idx == start_row && line_idx == end_row {
        // Selection within single line
        let start = byte_to_char_idx(display_text, start_col).min(char_count);
        let end = byte_to_char_idx(display_text, end_col).min(char_count);
        (start, end)
    } else if line_idx == start_row {
        // Selection starts on this line
        let start = byte_to_char_idx(display_text, start_col).min(char_count);
        (start, char_count)
    } else if line_idx == end_row {
        // Selection ends on this line
        let end = byte_to_char_idx(display_text, end_col).min(char_count);
        (0, end)
    } else {
        // Entire line is selected
        (0, char_count)
    };

    let mut spans = Vec::new();
    let normal_style = Style::default().fg(text_color);
    let selected_style = Style::default().fg(text_color).bg(selection_bg);

    if sel_start >= sel_end || sel_start >= char_count {
        // No selection on this line
        let padded = format!("{:width$}", display_text, width = display_len);
        spans.push(Span::styled(padded, normal_style));
    } else {
        // Before selection
        if sel_start > 0 {
            let before: String = chars[..sel_start].iter().collect();
            spans.push(Span::styled(before, normal_style));
        }

        // Selection
        let selected: String = chars[sel_start..sel_end].iter().collect();
        spans.push(Span::styled(selected, selected_style));

        // After selection
        if sel_end < char_count {
            let after: String = chars[sel_end..].iter().collect();
            spans.push(Span::styled(after, normal_style));
        }

        // Pad to display_len
        let current_len = char_count;
        if current_len < display_len {
            let padding = " ".repeat(display_len - current_len);
            spans.push(Span::styled(padding, normal_style));
        }
    }

    spans
}

/// Convert byte offset to char index in a string
fn byte_to_char_idx(s: &str, byte_offset: usize) -> usize {
    s.char_indices()
        .take_while(|(i, _)| *i < byte_offset)
        .count()
}

/// Truncate `s` to at most `max_chars` characters, appending `"..."` if it
/// was actually shortened. Counts characters (not bytes) so non-ASCII
/// inputs (CJK descriptions, emoji, etc.) don't byte-slice through a
/// multi-byte UTF-8 sequence and panic — same class as #1718.
fn truncate_chars_with_ellipsis(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        s.to_string()
    } else {
        let kept: String = s.chars().take(max_chars.saturating_sub(3)).collect();
        format!("{}...", kept)
    }
}

/// Render the settings modal
pub fn render_settings(
    frame: &mut Frame,
    area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
) -> SettingsLayout {
    // Minimum size guard — prevent panics from zero-sized layout arithmetic
    if area.width < 40 || area.height < 10 {
        let msg = "[Terminal too small for settings]";
        let x = area.x + area.width.saturating_sub(msg.len() as u16) / 2;
        let y = area.y + area.height / 2;
        if area.width > 0 && area.height > 0 {
            frame.render_widget(
                Paragraph::new(msg).style(Style::default().fg(theme.diagnostic_warning_fg)),
                Rect::new(x, y, msg.len() as u16, 1),
            );
        }
        return SettingsLayout::new(Rect::ZERO);
    }

    // Calculate modal size (90% of screen width, 90% height to fill most of available space)
    let modal_width = (area.width * 90 / 100).min(160);
    let modal_height = area.height * 90 / 100;
    // Offsets must be ABSOLUTE — `area.x` / `area.y` are nonzero when
    // `area` is the chrome region right of the dock (or a bottom-anchored
    // split). Centring with bare `area.width / 2` placed the modal at the
    // FRAME origin, where the dock then over-drew its left edge — hiding
    // the title bar and clipping the rounded top-left corner.
    let modal_x = area.x + (area.width.saturating_sub(modal_width)) / 2;
    let modal_y = area.y + (area.height.saturating_sub(modal_height)) / 2;

    let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height);

    // Clear the modal area and draw border
    frame.render_widget(Clear, modal_area);

    let title = if state.has_changes() {
        format!(" Settings [{}] • (modified) ", state.target_layer_name())
    } else {
        format!(" Settings [{}] ", state.target_layer_name())
    };

    let block = Block::default()
        .title(title.as_str())
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.popup_border_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, modal_area);

    // Inner area after border
    let inner_area = Rect::new(
        modal_area.x + 1,
        modal_area.y + 1,
        modal_area.width.saturating_sub(2),
        modal_area.height.saturating_sub(2),
    );

    // Determine layout mode: vertical (narrow) vs horizontal (wide)
    // Narrow mode when inner width < 60 columns
    let narrow_mode = inner_area.width < 60;

    // Always render search bar at the top (1 line height to avoid layout
    // jump), with a 1-row blank gap below it so the bar reads as a header
    // rather than running into the panels.
    let search_area = Rect::new(inner_area.x, inner_area.y, inner_area.width, 1);
    let search_header_height = 1u16;
    let search_gap = 1u16;
    if state.search_active {
        render_search_header(frame, search_area, state, theme);
    } else {
        render_search_hint(frame, search_area, theme);
    }

    // Footer height: 2 lines for horizontal (separator + buttons), 7 for vertical
    let footer_height = if narrow_mode { 7 } else { 2 };
    let chrome_height = search_header_height + search_gap + footer_height;
    let content_area = Rect::new(
        inner_area.x,
        inner_area.y + search_header_height + search_gap,
        inner_area.width,
        inner_area.height.saturating_sub(chrome_height),
    );

    // Create layout tracker
    let mut layout = SettingsLayout::new(modal_area);

    if narrow_mode {
        // Vertical layout: categories on top, items below
        render_vertical_layout(frame, content_area, modal_area, state, theme, &mut layout);
    } else {
        // Horizontal layout: categories left, items right
        render_horizontal_layout(frame, content_area, modal_area, state, theme, &mut layout);
    }

    // Determine the topmost dialog layer and apply dimming to layers below
    let has_confirm = state.showing_confirm_dialog;
    let has_reset = state.showing_reset_dialog;
    let has_entry = state.showing_entry_dialog();
    let has_help = state.showing_help;

    // Render confirmation dialog if showing
    if has_confirm {
        if !has_entry && !has_help {
            crate::view::dimming::apply_dimming(frame, modal_area);
        }
        render_confirm_dialog(frame, modal_area, state, theme);
    }

    // Render reset confirmation dialog if showing
    if has_reset {
        if !has_confirm && !has_entry && !has_help {
            crate::view::dimming::apply_dimming(frame, modal_area);
        }
        render_reset_dialog(frame, modal_area, state, theme);
    }

    // Render entry dialog stack — dim between each level
    if has_entry {
        let stack_depth = state.entry_dialog_stack.len();
        for dialog_idx in 0..stack_depth {
            if !has_help || dialog_idx < stack_depth - 1 {
                crate::view::dimming::apply_dimming(frame, modal_area);
            }
            render_entry_dialog_at(frame, modal_area, state, theme, dialog_idx);
        }
    }

    // Render entry-dialog discard-confirm prompt if showing, on top of
    // the entry dialog stack. Dim first so the user can see the prompt
    // is asking about the dialog underneath.
    if state.showing_entry_discard_confirm {
        crate::view::dimming::apply_dimming(frame, modal_area);
        render_entry_discard_confirm(frame, modal_area, state, theme);
    }

    // Render entry-dialog delete-confirm prompt on top of everything
    // else. Same chrome as the discard prompt but worded for
    // destructive action.
    if state.showing_entry_delete_confirm {
        crate::view::dimming::apply_dimming(frame, modal_area);
        render_entry_delete_confirm(frame, modal_area, state, theme);
    }

    // Render help overlay if showing
    if has_help {
        crate::view::dimming::apply_dimming(frame, modal_area);
        render_help_overlay(frame, modal_area, theme);
    }

    layout
}

/// Render horizontal layout (wide mode): categories left, items right
fn render_horizontal_layout(
    frame: &mut Frame,
    content_area: Rect,
    modal_area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    // Layout: [left panel (categories)] | [right panel (settings)]
    // 24 cols for categories, 1 col for the divider, the rest for settings.
    let chunks = Layout::horizontal([
        Constraint::Length(24),
        Constraint::Length(1),
        Constraint::Min(40),
    ])
    .split(content_area);

    let categories_area = chunks[0];
    let divider_area = chunks[1];
    let settings_area = chunks[2];

    // Render category list (left panel)
    render_categories(frame, categories_area, state, theme, layout);

    // Single straight vertical line dividing categories from settings.
    let divider_style = Style::default().fg(theme.split_separator_fg);
    for y in 0..divider_area.height {
        frame.render_widget(
            Paragraph::new("").style(divider_style),
            Rect::new(divider_area.x, divider_area.y + y, 1, 1),
        );
    }

    // 1-col gutter on each side of the settings panel for breathing room.
    let horizontal_padding = 1u16;
    let settings_inner = Rect::new(
        settings_area.x + horizontal_padding,
        settings_area.y,
        settings_area.width.saturating_sub(horizontal_padding * 2),
        settings_area.height,
    );

    if state.search_active && !state.search_results.is_empty() {
        render_search_results(frame, settings_inner, state, theme, layout);
    } else {
        render_settings_panel(frame, settings_inner, state, theme, layout);
    }

    // Render footer with buttons (horizontal layout)
    render_footer(frame, modal_area, state, theme, layout, false);
}

/// Render vertical layout (narrow mode): categories on top, items below
fn render_vertical_layout(
    frame: &mut Frame,
    content_area: Rect,
    modal_area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    // Calculate footer height for vertical buttons (5 buttons + separators)
    let footer_height = 7;

    // Layout: [categories (3 lines)] / [separator] / [settings] / [footer]
    let main_height = content_area.height.saturating_sub(footer_height);
    let category_height = 3u16.min(main_height);
    let settings_height = main_height.saturating_sub(category_height + 1); // +1 for separator

    // Categories area (horizontal strip at top)
    let categories_area = Rect::new(
        content_area.x,
        content_area.y,
        content_area.width,
        category_height,
    );

    // Separator line
    let sep_y = content_area.y + category_height;

    // Settings area
    let settings_area = Rect::new(
        content_area.x,
        sep_y + 1,
        content_area.width,
        settings_height,
    );

    // Render horizontal category strip
    render_categories_horizontal(frame, categories_area, state, theme, layout);

    // Render horizontal separator
    if sep_y < content_area.y + content_area.height {
        let sep_line: String = "".repeat(content_area.width as usize);
        frame.render_widget(
            Paragraph::new(sep_line).style(Style::default().fg(theme.split_separator_fg)),
            Rect::new(content_area.x, sep_y, content_area.width, 1),
        );
    }

    // Render settings panel
    if state.search_active && !state.search_results.is_empty() {
        render_search_results(frame, settings_area, state, theme, layout);
    } else {
        render_settings_panel(frame, settings_area, state, theme, layout);
    }

    // Render footer with buttons (vertical layout)
    render_footer(frame, modal_area, state, theme, layout, true);
}

/// Render categories as a horizontal strip (for narrow mode)
fn render_categories_horizontal(
    frame: &mut Frame,
    area: Rect,
    state: &SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    use super::state::FocusPanel;

    if area.height == 0 || area.width == 0 {
        return;
    }

    let is_focused = state.focus_panel() == FocusPanel::Categories;

    // Build category labels with indicators
    let mut spans = Vec::new();
    let mut total_width = 0u16;

    for (i, page) in state.pages.iter().enumerate() {
        let is_selected = i == state.selected_category;
        let has_modified = page.items.iter().any(|item| item.modified);

        let indicator = if has_modified { "" } else { "  " };
        let name = &page.name;

        let style = if is_selected && is_focused {
            Style::default()
                .fg(theme.menu_highlight_fg)
                .bg(theme.menu_highlight_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_selected {
            Style::default()
                .fg(theme.menu_highlight_fg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.popup_text_fg)
        };

        let indicator_style = if has_modified {
            Style::default().fg(theme.menu_highlight_fg)
        } else {
            style
        };

        // Add separator between categories
        if i > 0 {
            spans.push(Span::styled(
                "",
                Style::default().fg(theme.split_separator_fg),
            ));
            total_width += 3;
        }

        spans.push(Span::styled(indicator, indicator_style));
        spans.push(Span::styled(name.as_str(), style));
        total_width += (indicator.len() + name.len()) as u16;

        // Track category rect for click handling (approximate)
        let cat_x = area.x + total_width.saturating_sub((indicator.len() + name.len()) as u16);
        let cat_width = (indicator.len() + name.len()) as u16;
        layout
            .categories
            .push((i, Rect::new(cat_x, area.y, cat_width, 1)));
    }

    // Render the category line
    let line = Line::from(spans);
    frame.render_widget(Paragraph::new(line), area);

    // Show navigation hint on line 2 if space
    if area.height >= 2 {
        let hint = "←→: Switch category";
        let hint_style = Style::default().fg(theme.line_number_fg);
        frame.render_widget(
            Paragraph::new(hint).style(hint_style),
            Rect::new(area.x, area.y + 1, area.width, 1),
        );
    }
}

/// Get an icon for a settings category name (Nerd Font icons)
fn category_icon(name: &str) -> &'static str {
    match name.to_lowercase().as_str() {
        "general" => "\u{f013} ",       //
        "editor" => "\u{f044} ",        //
        "clipboard" => "\u{f328} ",     //
        "file browser" => "\u{f07b} ",  //
        "file explorer" => "\u{f07c} ", //
        "packages" => "\u{f487} ",      //
        "plugins" => "\u{f1e6} ",       //
        "terminal" => "\u{f120} ",      //
        "warnings" => "\u{f071} ",      //
        "keybindings" => "\u{f11c} ",   //
        _ => "\u{f111} ",               //  (dot circle as fallback)
    }
}

/// Render the category tree (categories + expanded sections) in the left panel.
///
/// Rows are flattened by [`SettingsState::visible_tree`] and rendered through
/// [`ScrollablePanel`], which handles partial-row clipping and the scrollbar.
/// Per-row Rects are recorded on `layout` for hit-testing.
fn render_categories(
    frame: &mut Frame,
    area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    use super::state::{FocusPanel, TreeRow};

    layout.categories_panel_area = Some(area);

    let rows = state.visible_tree();
    state.categories_scroll.set_viewport(area.height);
    state
        .categories_scroll
        .update_content_height(&rows, area.width);

    let focus_panel = state.focus_panel();
    let selected_category = state.selected_category;
    // Where the keyboard cursor lives in the tree. `None` = on the
    // category row; `Some(s_idx)` = on the s-th section row inside the
    // currently-selected category. This is the single source of truth
    // for the `>` indicator and the row-bg highlight.
    let tree_cursor = state.tree_cursor_section;

    // Snapshot the data each row needs so we don't hold a borrow on `state`
    // through the render callback.
    struct RowData {
        chevron: &'static str,
        is_expandable: bool,
        is_selected: bool,
        has_changes: bool,
        indent_cols: u16,
        is_category: bool,
        cat_idx: Option<usize>,
        section_idx: Option<usize>,
        label: String,
        icon: Option<&'static str>,
    }
    let row_data: Vec<RowData> = rows
        .iter()
        .map(|row| match *row {
            TreeRow::Category {
                idx,
                expandable,
                expanded,
            } => {
                let page = &state.pages[idx];
                RowData {
                    chevron: if expandable {
                        if expanded {
                            ""
                        } else {
                            ""
                        }
                    } else {
                        " "
                    },
                    is_expandable: expandable,
                    // Category row is "selected" iff the keyboard cursor
                    // is sitting on it (no section is the cursor target).
                    is_selected: idx == selected_category && tree_cursor.is_none(),
                    has_changes: page.items.iter().any(|i| i.modified),
                    indent_cols: 0,
                    is_category: true,
                    cat_idx: Some(idx),
                    section_idx: None,
                    label: page.name.clone(),
                    icon: Some(category_icon(&page.name)),
                }
            }
            TreeRow::Section {
                cat_idx,
                section_idx,
            } => {
                let section = &state.pages[cat_idx].sections[section_idx];
                // Section row is "selected" iff the explicit tree cursor
                // points at it. The cursor follows the user's keyboard
                // navigation AND syncs to body scroll (handled by the
                // sync-on-scroll path), so this single check covers
                // both keyboard and wheel-driven highlight updates.
                let is_current = cat_idx == selected_category && tree_cursor == Some(section_idx);
                RowData {
                    chevron: " ",
                    is_expandable: false,
                    is_selected: is_current,
                    has_changes: false,
                    indent_cols: 4,
                    is_category: false,
                    cat_idx: Some(cat_idx),
                    section_idx: Some(section_idx),
                    label: section.name.clone(),
                    icon: None,
                }
            }
        })
        .collect();

    // Render through ScrollablePanel so we get scrollbar + clipping.
    let panel_layout = state.categories_scroll.render(
        frame,
        area,
        &rows,
        |frame, info, row| {
            // Find this row's snapshot. `rows` and `row_data` are 1:1 by index.
            let idx = info.index;
            let data = &row_data[idx];
            let row_area = info.area;

            // Only the cursor row paints a bg — no separate hover-bg
            // path. Hover bg in addition to the cursor bg produced two
            // visually-highlighted rows simultaneously (with two
            // *different* colors, since hover and selection use
            // different theme keys), which violates the single-cursor
            // invariant. The OS mouse cursor itself is the user's
            // "where am I" indicator; we don't need an in-app one.
            let row_bg = if data.is_selected {
                if focus_panel == FocusPanel::Categories {
                    Some(theme.menu_highlight_bg)
                } else {
                    Some(theme.selection_bg)
                }
            } else {
                None
            };
            if let Some(bg) = row_bg {
                frame.render_widget(
                    Paragraph::new(" ".repeat(row_area.width as usize))
                        .style(Style::default().bg(bg)),
                    row_area,
                );
            }

            let fg = if data.is_selected {
                if focus_panel == FocusPanel::Categories {
                    theme.menu_highlight_fg
                } else {
                    theme.menu_fg
                }
            } else {
                theme.popup_text_fg
            };
            let bg = row_bg.unwrap_or(theme.popup_bg);
            let style = Style::default().fg(fg).bg(bg);

            let mut spans: Vec<Span> = Vec::with_capacity(8);
            // Selection indicator (">" when this row is the focused one in
            // the categories panel) lives in col 0 before any indentation.
            // The category-selection-indicator-visible test asserts on this.
            let selected_marker = if data.is_selected && focus_panel == FocusPanel::Categories {
                ">"
            } else {
                " "
            };
            spans.push(Span::styled(selected_marker.to_string(), style));
            if data.indent_cols > 0 {
                spans.push(Span::styled(" ".repeat(data.indent_cols as usize), style));
            }
            // Chevron occupies one column; followed by a space for breathing room.
            spans.push(Span::styled(format!("{} ", data.chevron), style));
            if data.has_changes {
                spans.push(Span::styled(
                    "",
                    Style::default().fg(theme.menu_highlight_fg).bg(bg),
                ));
            } else {
                spans.push(Span::styled("  ", style));
            }
            if let Some(icon) = data.icon {
                spans.push(Span::styled(
                    icon.to_string(),
                    Style::default().fg(theme.popup_border_fg).bg(bg),
                ));
            } else {
                spans.push(Span::styled(" ", style));
            }
            spans.push(Span::styled(data.label.clone(), style));

            frame.render_widget(Paragraph::new(Line::from(spans)), row_area);

            // Hand back the row identity so we can register hit-test areas
            // after rendering.
            (
                row_area,
                data.is_category,
                data.is_expandable,
                data.cat_idx,
                data.section_idx,
                data.indent_cols,
                *row,
            )
        },
        theme,
    );

    // Translate per-row Rects into hit-test entries.
    for layout_info in panel_layout.item_layouts.iter() {
        let (row_area, is_category, is_expandable, cat_idx, section_idx, indent_cols, _row) =
            layout_info.layout;
        if is_category {
            if let Some(idx) = cat_idx {
                layout.add_category(idx, row_area);
                if is_expandable {
                    // Chevron sits one column after the selection-indicator
                    // marker plus any indent for nested rows.
                    let chevron_x = row_area.x.saturating_add(1 + indent_cols);
                    let chevron_area = Rect::new(chevron_x, row_area.y, 1, 1);
                    layout.add_category_disclosure(idx, chevron_area);
                }
            }
        } else if let (Some(c), Some(s)) = (cat_idx, section_idx) {
            layout.add_section(c, s, row_area);
        }
    }
    if let Some(scrollbar) = panel_layout.scrollbar_area {
        layout.categories_scrollbar_area = Some(scrollbar);
    }
}

/// Context for rendering a setting item (extracted to avoid borrow issues)
struct RenderContext {
    selected_item: usize,
    settings_focused: bool,
    hover_hit: Option<SettingsHit>,
}

/// Render the settings panel for the current category
fn render_settings_panel(
    frame: &mut Frame,
    area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    let page = match state.current_page() {
        Some(p) => p,
        None => return,
    };

    // Page description suppressed: it duplicated the category name visible
    // in the sidebar and pushed the actual settings down without adding
    // information. The category names + section headers carry enough
    // context.
    let mut y = area.y;
    let header_start_y = y;

    // "Clear" button for nullable categories (e.g., Option<LanguageConfig>)
    if page.nullable && state.current_category_has_values() {
        let btn_text = format!("[{}]", t!("settings.btn_clear_category"));
        let btn_len = btn_text.len() as u16;
        let is_hovered = matches!(state.hover_hit, Some(SettingsHit::ClearCategoryButton));
        let btn_style = if is_hovered {
            Style::default()
                .fg(theme.menu_hover_fg)
                .bg(theme.menu_hover_bg)
        } else {
            Style::default().fg(theme.line_number_fg)
        };
        let btn_area = Rect::new(area.x, y, btn_len, 1);
        frame.render_widget(Paragraph::new(btn_text).style(btn_style), btn_area);
        layout.clear_category_button = Some(btn_area);
        y += 1;
    } else {
        layout.clear_category_button = None;
    }

    y += 1; // Blank line

    let header_height = (y - header_start_y) as usize;
    let items_start_y = y;

    // Calculate available height for items
    let available_height = area.height.saturating_sub(header_height as u16);

    // The body panel width is the full width of the area allocated to items.
    // Items size themselves against this width directly via the ScrollItem
    // trait — there's no longer a cached per-item layout_width to keep in
    // sync.
    state.layout_width = area.width;

    // Update scroll panel with current viewport and content
    let page = state.pages.get(state.selected_category).unwrap();
    state.scroll_panel.set_viewport(available_height);
    state
        .scroll_panel
        .update_content_height(&page.items, area.width);

    // Extract state needed for rendering (to avoid borrow issues with scroll_panel)
    use super::state::FocusPanel;
    let render_ctx = RenderContext {
        selected_item: state.selected_item,
        settings_focused: state.focus_panel() == FocusPanel::Settings,
        hover_hit: state.hover_hit,
    };

    // Area for items (below header)
    let items_area = Rect::new(area.x, items_start_y, area.width, available_height.max(1));

    // Get items reference for rendering
    let page = state.pages.get(state.selected_category).unwrap();

    // Calculate max label width for column alignment (only for single-row controls)
    let max_label_width = page
        .items
        .iter()
        .filter_map(|item| {
            // Only consider single-row controls for alignment
            match &item.control {
                SettingControl::Toggle(s) => Some(s.label.len() as u16),
                SettingControl::Number(s) => Some(s.label.len() as u16),
                SettingControl::Dropdown(s) => Some(s.label.len() as u16),
                SettingControl::Text(s) => Some(s.label.len() as u16),
                // Multi-row controls have their labels on separate lines
                _ => None,
            }
        })
        .max();

    // Use ScrollablePanel to render items with automatic scroll handling
    let panel_layout = state.scroll_panel.render(
        frame,
        items_area,
        &page.items,
        |frame, info, item| {
            render_setting_item_pure(
                frame,
                info.area,
                item,
                info.index,
                info.skip_top,
                &render_ctx,
                theme,
                max_label_width,
            )
        },
        theme,
    );

    // Transfer item layouts to SettingsLayout
    let page = state.pages.get(state.selected_category).unwrap();
    for item_info in panel_layout.item_layouts {
        layout.add_item(
            item_info.index,
            page.items[item_info.index].path.clone(),
            item_info.area,
            item_info.layout.control,
            item_info.layout.inherit_button,
        );
    }

    // Track the settings panel area for scroll hit testing
    layout.settings_panel_area = Some(panel_layout.content_area);

    // Track scrollbar area for drag detection
    if let Some(sb_area) = panel_layout.scrollbar_area {
        layout.scrollbar_area = Some(sb_area);
    }
}

/// Wrap text to fit within a given width
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    if width == 0 || text.is_empty() {
        return vec![text.to_string()];
    }

    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_len = 0;

    for word in text.split_whitespace() {
        let word_len = word.chars().count();

        if current_len == 0 {
            // First word on line
            current_line = word.to_string();
            current_len = word_len;
        } else if current_len + 1 + word_len <= width {
            // Word fits on current line
            current_line.push(' ');
            current_line.push_str(word);
            current_len += 1 + word_len;
        } else {
            // Start new line
            lines.push(current_line);
            current_line = word.to_string();
            current_len = word_len;
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

/// Pure render function for a setting item (returns layout, doesn't modify external state)
///
/// Driven by `item.layout_box(area.width, &item.style)` — every y-offset comes
/// from the resulting `ItemBox`, so adjusting card chrome (border, padding,
/// section header height) happens by changing `ItemBoxStyle`, not by editing
/// renderer arithmetic.
///
/// # Arguments
/// * `skip_top` - Number of rows to skip at top of item (for partial visibility when scrolling)
/// * `label_width` - Optional label width for column alignment
#[allow(clippy::too_many_arguments)]
fn render_setting_item_pure(
    frame: &mut Frame,
    area: Rect,
    item: &super::items::SettingItem,
    idx: usize,
    skip_top: u16,
    ctx: &RenderContext,
    theme: &Theme,
    label_width: Option<u16>,
) -> SettingItemLayoutInfo {
    let plan = item.layout_box(area.width, &item.style);
    let style = item.style;
    let viewport_end_logical = skip_top.saturating_add(area.height); // exclusive

    // Translate a logical band [logical_y, logical_y + rows) to a physical
    // sub-rectangle of `area`, accounting for `skip_top` clipping. Returns
    // None when the band is entirely outside the visible viewport.
    let band_rect = |logical_y: u16, rows: u16| -> Option<Rect> {
        if rows == 0 {
            return None;
        }
        let band_end = logical_y.saturating_add(rows);
        if band_end <= skip_top || logical_y >= viewport_end_logical {
            return None;
        }
        let visible_top_logical = logical_y.max(skip_top);
        let visible_bottom_logical = band_end.min(viewport_end_logical);
        let physical_y = area.y + (visible_top_logical - skip_top);
        let visible_h = visible_bottom_logical - visible_top_logical;
        Some(Rect::new(area.x, physical_y, area.width, visible_h))
    };

    // ── Section header band ────────────────────────────────────────────────
    // Layout: blank gap on the leading rows, title on the last row of the
    // band. This puts the breathing room above the heading and butts the
    // title against the card it labels, which reads as "title belongs to
    // what's below" rather than "title belongs to what's above".
    if let (Some(section_name), Some(_header_rect)) = (
        item.section.as_deref().filter(|_| item.is_section_start),
        band_rect(0, plan.section_header_rows),
    ) {
        let title_logical_y = plan.section_header_rows.saturating_sub(1);
        if let Some(title_rect) = band_rect(title_logical_y, 1) {
            let header_style = Style::default()
                .fg(theme.editor_fg)
                .add_modifier(Modifier::BOLD);
            frame.render_widget(
                Paragraph::new(section_name).style(header_style),
                Rect::new(title_rect.x, title_rect.y, title_rect.width, 1),
            );
        }
    }

    // ── Card box ───────────────────────────────────────────────────────────
    // The card spans logical rows [card_top_y, total_rows). Render it with a
    // single Block, choosing which edges to draw based on which logical rows
    // are inside the visible viewport.
    let card_logical_top = plan.card_top_y();
    let card_logical_bottom = plan.total_rows();
    if let Some(card_rect) = band_rect(
        card_logical_top,
        card_logical_bottom.saturating_sub(card_logical_top),
    ) {
        let mut borders = Borders::NONE;
        if style.card_border_cols > 0 {
            borders |= Borders::LEFT | Borders::RIGHT;
        }
        if style.card_border_rows > 0 {
            // TOP edge is only visible when its logical row sits inside [skip_top, viewport_end).
            if card_logical_top >= skip_top {
                borders |= Borders::TOP;
            }
            // BOTTOM edge is the last logical row of the card.
            let bottom_logical = card_logical_bottom.saturating_sub(1);
            if bottom_logical >= skip_top && bottom_logical < viewport_end_logical {
                borders |= Borders::BOTTOM;
            }
        }
        if !borders.is_empty() {
            // Subdued color for the card chrome — distinct from the
            // panel/popup border around the modal so the cards read as
            // secondary structure, not nested popups.
            let block = Block::default()
                .borders(borders)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.split_separator_fg));
            frame.render_widget(block, card_rect);
        }
    }

    // ── Content area (control + description) ───────────────────────────────
    let is_selected = ctx.settings_focused && idx == ctx.selected_item;
    let is_item_hovered = matches!(
        ctx.hover_hit,
        Some(SettingsHit::Item(i))
            | Some(SettingsHit::ControlToggle(i))
            | Some(SettingsHit::ControlDecrement(i))
            | Some(SettingsHit::ControlIncrement(i))
            | Some(SettingsHit::ControlDropdown(i))
            | Some(SettingsHit::ControlText(i))
            | Some(SettingsHit::ControlTextListRow(i, _))
            | Some(SettingsHit::ControlMapRow(i, _))
            | Some(SettingsHit::ControlInherit(i))
        if i == idx
    );
    let is_focused_or_hovered = is_selected || is_item_hovered;

    // Inner area is the card minus the side borders. Y-axis is the union of
    // the control + description bands.
    let content_logical_top = plan.control_y();
    let content_logical_bottom = plan.bottom_border_y();
    let mut control_layout = ControlLayoutInfo::default();
    let mut inherit_button_area: Option<Rect> = None;
    if let Some(content_rect) = band_rect(
        content_logical_top,
        content_logical_bottom.saturating_sub(content_logical_top),
    ) {
        // Trim left/right by the card side borders.
        let inner_x = content_rect.x.saturating_add(style.card_border_cols);
        let inner_width = content_rect
            .width
            .saturating_sub(2 * style.card_border_cols);
        let inner_area = Rect::new(inner_x, content_rect.y, inner_width, content_rect.height);

        // Highlight background for focused/hovered items. Limited to the
        // label row so chip / description text below stays on popup_bg
        // and remains legible regardless of how saturated the theme's
        // highlight bg is. The colors come from the theme's
        // `settings_selected_bg` (selected) and `menu_hover_bg` (hovered)
        // — each theme is responsible for picking values that contrast
        // with its own popup_bg AND don't collide with chip text colors.
        let label_visible = skip_top <= content_logical_top;
        if is_focused_or_hovered && inner_width > 0 && label_visible {
            let bg_style = if is_selected {
                Style::default().bg(theme.settings_selected_bg)
            } else {
                Style::default().bg(theme.menu_hover_bg)
            };
            let row_area = Rect::new(inner_area.x, inner_area.y, inner_area.width, 1);
            frame.render_widget(Paragraph::new("").style(bg_style), row_area);
        }

        // skip_top relative to the start of the control band — used by
        // multi-row controls and by the description renderer to know how
        // many leading rows are off-screen.
        let content_skip_top = skip_top.saturating_sub(content_logical_top);

        // Focus indicator (`>`) at column 0 of inner area, modified marker
        // (`●`) at column 1. Only paint them when the control's first row is
        // visible (i.e. nothing has been clipped off the top of the content).
        let label_row_visible = content_skip_top == 0 && inner_area.height > 0;
        if is_selected && label_row_visible {
            frame.render_widget(
                Paragraph::new(">").style(
                    Style::default()
                        .fg(theme.settings_selected_fg)
                        .add_modifier(Modifier::BOLD),
                ),
                Rect::new(inner_area.x, inner_area.y, 1, 1),
            );
        }
        if item.modified && label_row_visible && inner_area.width >= 2 {
            frame.render_widget(
                Paragraph::new("").style(Style::default().fg(theme.settings_selected_fg)),
                Rect::new(inner_area.x + 1, inner_area.y, 1, 1),
            );
        }

        // Control occupies its own band at the top of the content rect.
        let control_logical_rows = plan.control_rows;
        if let Some(control_rect) = band_rect(content_logical_top, control_logical_rows).map(|r| {
            let x =
                r.x.saturating_add(style.card_border_cols + style.focus_indicator_cols);
            let w = r
                .width
                .saturating_sub(2 * style.card_border_cols + style.focus_indicator_cols);
            Rect::new(x, r.y, w, r.height)
        }) {
            control_layout = render_control(
                frame,
                control_rect,
                &item.control,
                &item.name,
                content_skip_top,
                theme,
                label_width
                    .map(|w| w.saturating_sub(style.card_border_cols + style.focus_indicator_cols)),
                item.read_only,
                item.is_null,
            );

            // (Inherited) badge / [Inherit] button: rendered on the same row
            // as the control's first line, at its right edge.
            if item.nullable && content_skip_top == 0 && control_rect.width > 0 {
                if item.is_null {
                    let badge_text = t!("settings.inherited_badge").to_string();
                    let badge_len = badge_text.len() as u16 + 1;
                    let badge_x = control_rect
                        .x
                        .saturating_add(control_rect.width)
                        .saturating_sub(badge_len);
                    if badge_x > control_rect.x {
                        frame.render_widget(
                            Paragraph::new(badge_text).style(
                                Style::default()
                                    .fg(theme.line_number_fg)
                                    .add_modifier(Modifier::ITALIC),
                            ),
                            Rect::new(badge_x, control_rect.y, badge_len, 1),
                        );
                    }
                } else {
                    let btn_text = format!("[{}]", t!("settings.btn_inherit"));
                    let btn_len = btn_text.len() as u16 + 1;
                    let btn_x = control_rect
                        .x
                        .saturating_add(control_rect.width)
                        .saturating_sub(btn_len);
                    if btn_x > control_rect.x {
                        let btn_area = Rect::new(btn_x, control_rect.y, btn_len, 1);
                        let is_hovered = matches!(
                            ctx.hover_hit,
                            Some(SettingsHit::ControlInherit(i)) if i == idx
                        );
                        let btn_style = if is_hovered {
                            Style::default()
                                .fg(theme.menu_hover_fg)
                                .bg(theme.menu_hover_bg)
                        } else {
                            Style::default().fg(theme.line_number_fg)
                        };
                        frame.render_widget(Paragraph::new(btn_text).style(btn_style), btn_area);
                        inherit_button_area = Some(btn_area);
                    }
                }
            }
        }

        // Description band: below the control. Wraps to the inner text width
        // computed by the style, falling back to a layer label when there's
        // no description but we still need to show the source layer.
        let desc_logical_rows = plan.description_rows;
        let layer_label = match item.layer_source {
            crate::config_io::ConfigLayer::System => None,
            crate::config_io::ConfigLayer::User => Some("user"),
            crate::config_io::ConfigLayer::Project => Some("project"),
            crate::config_io::ConfigLayer::Session => Some("session"),
        };

        if desc_logical_rows > 0 {
            if let Some(desc_rect) = band_rect(plan.description_y(), desc_logical_rows).map(|r| {
                let x =
                    r.x.saturating_add(style.card_border_cols + style.focus_indicator_cols);
                let w = r
                    .width
                    .saturating_sub(2 * style.card_border_cols + style.focus_indicator_cols);
                Rect::new(x, r.y, w, r.height)
            }) {
                let desc_skip = skip_top.saturating_sub(plan.description_y());
                let max_text_width = desc_rect
                    .width
                    .saturating_sub(style.description_right_padding_cols)
                    as usize;
                let mut lines = match item.description.as_deref() {
                    Some(d) if !d.is_empty() => wrap_text(d, max_text_width),
                    _ => Vec::new(),
                };
                if let Some(layer) = layer_label {
                    if let Some(last) = lines.last_mut() {
                        last.push_str(&format!(" ({})", layer));
                    } else {
                        lines.push(format!("({})", layer));
                    }
                }
                let desc_style = Style::default().fg(theme.line_number_fg);
                let take = desc_rect.height as usize;
                for (i, line) in lines.iter().skip(desc_skip as usize).take(take).enumerate() {
                    frame.render_widget(
                        Paragraph::new(line.as_str()).style(desc_style),
                        Rect::new(desc_rect.x, desc_rect.y + i as u16, desc_rect.width, 1),
                    );
                }
            }
        } else if let Some(layer) = layer_label {
            // No description, just a layer label on the row immediately
            // below the control.
            if let Some(layer_rect) = band_rect(plan.description_y(), 1).map(|r| {
                let x =
                    r.x.saturating_add(style.card_border_cols + style.focus_indicator_cols);
                let w = r
                    .width
                    .saturating_sub(2 * style.card_border_cols + style.focus_indicator_cols);
                Rect::new(x, r.y, w, r.height)
            }) {
                frame.render_widget(
                    Paragraph::new(format!("({})", layer))
                        .style(Style::default().fg(theme.line_number_fg)),
                    layer_rect,
                );
            }
        }
    }

    SettingItemLayoutInfo {
        control: control_layout,
        inherit_button: inherit_button_area,
    }
}

/// Render the appropriate control for a setting
///
/// # Arguments
/// * `name` - Setting name (for controls that render their own label)
/// * `skip_rows` - Number of rows to skip at top of control (for partial visibility)
/// * `label_width` - Optional label width for column alignment
/// * `read_only` - Whether this field is read-only (displays as plain text instead of input)
#[allow(clippy::too_many_arguments)]
fn render_control(
    frame: &mut Frame,
    area: Rect,
    control: &SettingControl,
    name: &str,
    skip_rows: u16,
    theme: &Theme,
    label_width: Option<u16>,
    read_only: bool,
    is_null: bool,
) -> ControlLayoutInfo {
    match control {
        // Single-row controls: only render if not skipped
        SettingControl::Toggle(state) => {
            if skip_rows > 0 {
                return ControlLayoutInfo::Toggle(Rect::default());
            }
            let colors = ToggleColors::from_theme(theme);
            let toggle_layout = render_toggle_aligned(frame, area, state, &colors, label_width);
            ControlLayoutInfo::Toggle(toggle_layout.full_area)
        }

        SettingControl::Number(state) => {
            if skip_rows > 0 {
                return ControlLayoutInfo::Number {
                    decrement: Rect::default(),
                    increment: Rect::default(),
                    value: Rect::default(),
                };
            }
            let colors = NumberInputColors::from_theme(theme);
            let num_layout = render_number_input_aligned(frame, area, state, &colors, label_width);
            ControlLayoutInfo::Number {
                decrement: num_layout.decrement_area,
                increment: num_layout.increment_area,
                value: num_layout.value_area,
            }
        }

        SettingControl::Dropdown(state) => {
            if skip_rows > 0 {
                return ControlLayoutInfo::Dropdown {
                    button_area: Rect::default(),
                    option_areas: Vec::new(),
                    scroll_offset: 0,
                };
            }
            let colors = DropdownColors::from_theme(theme);
            let drop_layout = render_dropdown_aligned(frame, area, state, &colors, label_width);
            ControlLayoutInfo::Dropdown {
                button_area: drop_layout.button_area,
                option_areas: drop_layout.option_areas,
                scroll_offset: drop_layout.scroll_offset,
            }
        }

        SettingControl::Text(state) => {
            if skip_rows > 0 {
                return ControlLayoutInfo::Text(Rect::default());
            }
            if read_only {
                // Truly read-only fields (e.g., Key: in entry dialogs) render as plain text
                let label_w = label_width.unwrap_or(20);
                let label_style = Style::default().fg(theme.editor_fg);
                let value_style = Style::default().fg(theme.line_number_fg);
                let label = format!("{}: ", state.label);
                let value = &state.value;

                let label_area = Rect::new(area.x, area.y, label_w, 1);
                let value_area = Rect::new(
                    area.x + label_w,
                    area.y,
                    area.width.saturating_sub(label_w),
                    1,
                );

                frame.render_widget(Paragraph::new(label.clone()).style(label_style), label_area);
                frame.render_widget(
                    Paragraph::new(value.as_str()).style(value_style),
                    value_area,
                );
                ControlLayoutInfo::Text(Rect::default())
            } else if is_null {
                // Nullable-null fields render with dimmed brackets to indicate input presence
                let colors = TextInputColors::from_theme_disabled(theme);
                let text_layout =
                    render_text_input_aligned(frame, area, state, &colors, 30, label_width);
                ControlLayoutInfo::Text(text_layout.input_area)
            } else {
                let colors = TextInputColors::from_theme(theme);
                let text_layout =
                    render_text_input_aligned(frame, area, state, &colors, 30, label_width);
                ControlLayoutInfo::Text(text_layout.input_area)
            }
        }

        // Multi-row controls: pass skip_rows to render partial view
        SettingControl::TextList(state) => {
            let colors = TextListColors::from_theme(theme);
            let list_layout = render_text_list_partial(frame, area, state, &colors, 30, skip_rows);
            ControlLayoutInfo::TextList {
                rows: list_layout
                    .rows
                    .iter()
                    .map(|r| (r.index, r.text_area))
                    .collect(),
            }
        }

        SettingControl::DualList(state) => {
            let colors = DualListColors::from_theme(theme);
            let dual_layout = render_dual_list_partial(frame, area, state, &colors, skip_rows);
            ControlLayoutInfo::DualList(dual_layout)
        }

        SettingControl::Map(state) => {
            let colors = MapColors::from_theme(theme);
            let map_layout = render_map_partial(frame, area, state, &colors, 20, skip_rows);
            ControlLayoutInfo::Map {
                entry_rows: map_layout
                    .entry_areas
                    .iter()
                    .map(|e| (e.index, e.row_area))
                    .collect(),
                add_row_area: map_layout.add_row_area,
            }
        }

        SettingControl::ObjectArray(state) => {
            let colors = crate::view::controls::KeybindingListColors {
                label_fg: theme.editor_fg,
                key_fg: theme.help_key_fg,
                action_fg: theme.syntax_function,
                // Match the surrounding settings panel so unfocused rows
                // don't paint a `Color::Reset` strip that falls back to
                // the host terminal's default bg. See issue #2033.
                row_bg: theme.popup_bg,
                // Use settings colors for focused items in settings UI
                focused_bg: theme.settings_selected_bg,
                focused_fg: theme.settings_selected_fg,
                add_fg: theme.syntax_string,
            };
            let kb_layout = render_keybinding_list_partial(frame, area, state, &colors, skip_rows);
            ControlLayoutInfo::ObjectArray {
                entry_rows: kb_layout
                    .entry_rects
                    .iter()
                    .map(|&(idx, rect)| (idx, rect))
                    .collect(),
            }
        }

        SettingControl::Json(state) => {
            render_json_control(frame, area, state, name, skip_rows, theme)
        }

        SettingControl::Complex { type_name } => {
            if skip_rows > 0 {
                return ControlLayoutInfo::Complex;
            }
            // Render label (modified indicator is shown in the row indicator column)
            let label_style = Style::default().fg(theme.editor_fg);
            let value_style = Style::default().fg(theme.line_number_fg);

            let label = Span::styled(format!("{}: ", name), label_style);
            let value = Span::styled(
                format!("<{} - edit in config.toml>", type_name),
                value_style,
            );

            frame.render_widget(Paragraph::new(Line::from(vec![label, value])), area);
            ControlLayoutInfo::Complex
        }
    }
}

/// Render a multiline JSON editor control
fn render_json_control(
    frame: &mut Frame,
    area: Rect,
    state: &super::items::JsonEditState,
    name: &str,
    skip_rows: u16,
    theme: &Theme,
) -> ControlLayoutInfo {
    use crate::view::controls::FocusState;

    let empty_layout = ControlLayoutInfo::Json {
        edit_area: Rect::default(),
    };

    if area.height == 0 || area.width < 10 {
        return empty_layout;
    }

    let is_focused = state.focus == FocusState::Focused;
    let is_valid = state.is_valid();

    let label_color = if is_focused {
        theme.menu_highlight_fg
    } else {
        theme.editor_fg
    };

    let text_color = theme.editor_fg;
    let border_color = if !is_valid {
        theme.diagnostic_error_fg
    } else if is_focused {
        theme.menu_highlight_fg
    } else {
        theme.split_separator_fg
    };

    let mut y = area.y;
    let mut content_row = 0u16;

    // Row 0: label (modified indicator is shown in the row indicator column)
    if content_row >= skip_rows {
        let label_line = Line::from(vec![Span::styled(
            format!("{}:", name),
            Style::default().fg(label_color),
        )]);
        frame.render_widget(
            Paragraph::new(label_line),
            Rect::new(area.x, y, area.width, 1),
        );
        y += 1;
    }
    content_row += 1;

    let indent = 2u16;
    let edit_width = area.width.saturating_sub(indent + 1);
    let edit_x = area.x + indent;
    let edit_start_y = y;

    // Unset JSON values used to render as the literal text `null` inside
    // the editor frame, which read like a stray keyword. Replace it with
    // a muted "(not set — press Enter to add)" hint so the user can tell
    // the field is empty and editable. start_editing() wipes the `null`
    // text so typing doesn't concatenate onto it; the placeholder only
    // disappears once the user has actually started editing.
    if state.is_unset() && content_row >= skip_rows && y < area.y + area.height {
        let hint = "(not set — press Enter to add)";
        let hint_line = Line::from(vec![
            Span::raw(" ".repeat(indent as usize)),
            Span::styled(
                hint,
                Style::default()
                    .fg(theme.line_number_fg)
                    .add_modifier(Modifier::ITALIC),
            ),
        ]);
        frame.render_widget(
            Paragraph::new(hint_line),
            Rect::new(area.x, y, area.width, 1),
        );
        return ControlLayoutInfo::Json {
            edit_area: Rect::new(edit_x, edit_start_y, edit_width, 1),
        };
    }

    // Render all lines (scrolling handled by entry dialog/scroll panel)
    let lines = state.lines();
    let total_lines = lines.len();
    for line_idx in 0..total_lines {
        let actual_line_idx = line_idx;

        if content_row < skip_rows {
            content_row += 1;
            continue;
        }

        if y >= area.y + area.height {
            break;
        }

        let line_content = lines.get(actual_line_idx).map(|s| s.as_str()).unwrap_or("");

        // Truncate line if too long
        let display_len = edit_width.saturating_sub(2) as usize;
        let display_text: String = line_content.chars().take(display_len).collect();

        // Get selection range and cursor position
        let selection = state.selection_range();
        let (cursor_row, cursor_col) = state.cursor_pos();

        // Build content spans with selection highlighting
        let content_spans = if is_focused {
            if let Some(((start_row, start_col), (end_row, end_col))) = selection {
                build_selection_spans(
                    &display_text,
                    display_len,
                    actual_line_idx,
                    start_row,
                    start_col,
                    end_row,
                    end_col,
                    text_color,
                    theme.selection_bg,
                )
            } else {
                vec![Span::styled(
                    format!("{:width$}", display_text, width = display_len),
                    Style::default().fg(text_color),
                )]
            }
        } else {
            vec![Span::styled(
                format!("{:width$}", display_text, width = display_len),
                Style::default().fg(text_color),
            )]
        };

        // Build line with border
        let mut spans = vec![
            Span::raw(" ".repeat(indent as usize)),
            Span::styled("", Style::default().fg(border_color)),
        ];
        spans.extend(content_spans);
        spans.push(Span::styled("", Style::default().fg(border_color)));
        let line = Line::from(spans);

        frame.render_widget(Paragraph::new(line), Rect::new(area.x, y, area.width, 1));

        // Draw cursor if focused and on this line (overlays selection)
        if is_focused && actual_line_idx == cursor_row {
            let cursor_x = edit_x + 1 + cursor_col.min(display_len) as u16;
            if cursor_x < area.x + area.width - 1 {
                let cursor_char = line_content.chars().nth(cursor_col).unwrap_or(' ');
                let cursor_span = Span::styled(
                    cursor_char.to_string(),
                    Style::default()
                        .fg(theme.cursor)
                        .add_modifier(Modifier::REVERSED),
                );
                frame.render_widget(
                    Paragraph::new(Line::from(vec![cursor_span])),
                    Rect::new(cursor_x, y, 1, 1),
                );
            }
        }

        y += 1;
        content_row += 1;
    }

    // Show invalid JSON indicator
    if !is_valid && y < area.y + area.height {
        let warning = Span::styled(
            "  ⚠ Invalid JSON",
            Style::default().fg(theme.diagnostic_warning_fg),
        );
        frame.render_widget(
            Paragraph::new(Line::from(vec![warning])),
            Rect::new(area.x, y, area.width, 1),
        );
    }

    let edit_height = y.saturating_sub(edit_start_y);
    ControlLayoutInfo::Json {
        edit_area: Rect::new(edit_x, edit_start_y, edit_width, edit_height),
    }
}

/// Render TextList with partial visibility (skipping top rows)
fn render_text_list_partial(
    frame: &mut Frame,
    area: Rect,
    state: &crate::view::controls::TextListState,
    colors: &TextListColors,
    field_width: u16,
    skip_rows: u16,
) -> crate::view::controls::TextListLayout {
    use crate::view::controls::text_list::{TextListLayout, TextListRowLayout};
    use crate::view::controls::FocusState;

    let empty_layout = TextListLayout {
        rows: Vec::new(),
        full_area: area,
    };

    if area.height == 0 || area.width < 10 {
        return empty_layout;
    }

    // Use focused_fg for label when focused (not focused, which is the bg color)
    let label_color = match state.focus {
        FocusState::Focused => colors.focused_fg,
        FocusState::Hovered => colors.focused_fg,
        FocusState::Disabled => colors.disabled,
        FocusState::Normal => colors.label,
    };

    let mut rows = Vec::new();
    let mut y = area.y;
    let mut content_row = 0u16; // Which row of content we're at

    // Row 0 is label
    if skip_rows == 0 {
        let label_line = Line::from(vec![
            Span::styled(&state.label, Style::default().fg(label_color)),
            Span::raw(":"),
        ]);
        frame.render_widget(
            Paragraph::new(label_line),
            Rect::new(area.x, y, area.width, 1),
        );
        y += 1;
    }
    content_row += 1;

    let indent = 2u16;
    let actual_field_width = field_width.min(area.width.saturating_sub(indent + 5));

    // Render existing items (rows 1 to N)
    for (idx, item) in state.items.iter().enumerate() {
        if y >= area.y + area.height {
            break;
        }

        // Skip rows before skip_rows
        if content_row < skip_rows {
            content_row += 1;
            continue;
        }

        let is_focused = state.focused_item == Some(idx) && state.focus == FocusState::Focused;
        let (border_color, text_color) = if is_focused {
            (colors.focused, colors.text)
        } else if state.focus == FocusState::Disabled {
            (colors.disabled, colors.disabled)
        } else {
            (colors.border, colors.text)
        };

        let inner_width = actual_field_width.saturating_sub(2) as usize;
        let visible: String = item.chars().take(inner_width).collect();
        let padded = format!("{:width$}", visible, width = inner_width);

        let mut spans = vec![
            Span::raw(" ".repeat(indent as usize)),
            Span::styled("[", Style::default().fg(border_color)),
            Span::styled(padded, Style::default().fg(text_color)),
            Span::styled("]", Style::default().fg(border_color)),
            Span::raw(" "),
            Span::styled("[x]", Style::default().fg(colors.remove_button)),
        ];
        // Inline hint on a focused committed row: tell the user
        // exactly how to remove it. Otherwise the `[x]` looks
        // clickable but offers no keyboard equivalent.
        if is_focused {
            spans.push(Span::styled(
                "  Del:remove  Enter:edit",
                Style::default()
                    .fg(colors.disabled)
                    .add_modifier(ratatui::style::Modifier::ITALIC),
            ));
        }
        let line = Line::from(spans);

        let row_area = Rect::new(area.x, y, area.width, 1);
        frame.render_widget(Paragraph::new(line), row_area);

        let text_area = Rect::new(area.x + indent, y, actual_field_width, 1);
        let button_area = Rect::new(area.x + indent + actual_field_width + 1, y, 3, 1);
        rows.push(TextListRowLayout {
            text_area,
            button_area,
            index: Some(idx),
        });

        y += 1;
        content_row += 1;
    }

    // Add-new row
    if y < area.y + area.height && content_row >= skip_rows {
        // Check if we're focused on the add-new input (focused_item is None and focused)
        let is_add_focused = state.focused_item.is_none() && state.focus == FocusState::Focused;
        // Only show the bracketed input box once the user has explicitly
        // started adding an item — keep `[+] Add new` visible on plain
        // focus so the row doesn't look like it disappeared.
        let show_input_box =
            is_add_focused && (state.pending_active || !state.new_item_text.is_empty());

        if show_input_box {
            // Show input field. When empty (just-activated input), drop
            // a muted "type new item" placeholder INSIDE the box so the
            // empty bracket pair clearly reads as "this is an editable
            // input", not a generic empty cell.
            let inner_width = actual_field_width.saturating_sub(2) as usize;
            let (visible_text, text_style) = if state.new_item_text.is_empty() {
                let placeholder = "type new item";
                let truncated: String = placeholder.chars().take(inner_width).collect();
                (
                    truncated,
                    Style::default()
                        .fg(colors.disabled)
                        .add_modifier(ratatui::style::Modifier::ITALIC),
                )
            } else {
                let visible: String = state.new_item_text.chars().take(inner_width).collect();
                (visible, Style::default().fg(colors.text))
            };
            let padded = format!("{:width$}", visible_text, width = inner_width);

            // Dimmed inline hint to the right of the input — so Enter /
            // Esc semantics are visible next to the row itself instead
            // of only on the bottom helper bar.
            let hint = "  Enter:add  Esc:cancel";
            let line = Line::from(vec![
                Span::raw(" ".repeat(indent as usize)),
                Span::styled(
                    "[",
                    Style::default()
                        .fg(colors.focused)
                        .add_modifier(ratatui::style::Modifier::BOLD),
                ),
                Span::styled(padded, text_style),
                Span::styled(
                    "]",
                    Style::default()
                        .fg(colors.focused)
                        .add_modifier(ratatui::style::Modifier::BOLD),
                ),
                Span::raw(" "),
                Span::styled("[+]", Style::default().fg(colors.add_button)),
                Span::styled(
                    hint,
                    Style::default()
                        .fg(colors.disabled)
                        .add_modifier(ratatui::style::Modifier::ITALIC),
                ),
            ]);
            let row_area = Rect::new(area.x, y, area.width, 1);
            frame.render_widget(Paragraph::new(line), row_area);

            // Render cursor. Skip when showing the placeholder (empty
            // buffer) — the cursor block would otherwise eat the first
            // letter of "type new item" and confuse the placeholder.
            if !state.new_item_text.is_empty() && state.cursor <= inner_width {
                let cursor_x = area.x + indent + 1 + state.cursor as u16;
                let cursor_char = state.new_item_text.chars().nth(state.cursor).unwrap_or(' ');
                let cursor_area = Rect::new(cursor_x, y, 1, 1);
                let cursor_span = Span::styled(
                    cursor_char.to_string(),
                    Style::default()
                        .fg(colors.focused)
                        .add_modifier(ratatui::style::Modifier::REVERSED),
                );
                frame.render_widget(Paragraph::new(Line::from(vec![cursor_span])), cursor_area);
            }

            rows.push(TextListRowLayout {
                text_area: Rect::new(area.x + indent, y, actual_field_width, 1),
                button_area: Rect::new(area.x + indent + actual_field_width + 1, y, 3, 1),
                index: None,
            });
        } else {
            // Show static "[+] Add new" label. When the trailing slot
            // has focus but isn't yet in input mode, mark the label as
            // focused (use the same focused fg the other focused rows
            // use) AND append a dimmed inline hint so the user sees
            // exactly what Enter will do — without having to look at
            // the bottom helper bar.
            let label_fg = if is_add_focused {
                colors.focused_fg
            } else {
                colors.add_button
            };
            let mut spans = vec![
                Span::raw(" ".repeat(indent as usize)),
                Span::styled("[+] Add new", Style::default().fg(label_fg)),
            ];
            if is_add_focused {
                spans.push(Span::styled(
                    "  press Enter (or type) to add a new item",
                    Style::default()
                        .fg(colors.disabled)
                        .add_modifier(ratatui::style::Modifier::ITALIC),
                ));
            }
            let add_line = Line::from(spans);
            let row_area = Rect::new(area.x, y, area.width, 1);
            frame.render_widget(Paragraph::new(add_line), row_area);

            rows.push(TextListRowLayout {
                text_area: Rect::new(area.x + indent, y, 11, 1), // "[+] Add new"
                button_area: Rect::new(area.x + indent, y, 11, 1),
                index: None,
            });
        }
    }

    TextListLayout {
        rows,
        full_area: area,
    }
}

/// Render Map with partial visibility (skipping top rows)
fn render_map_partial(
    frame: &mut Frame,
    area: Rect,
    state: &crate::view::controls::MapState,
    colors: &MapColors,
    key_width: u16,
    skip_rows: u16,
) -> crate::view::controls::MapLayout {
    use crate::view::controls::map_input::{MapEntryLayout, MapLayout};
    use crate::view::controls::FocusState;

    let empty_layout = MapLayout {
        entry_areas: Vec::new(),
        add_row_area: None,
        full_area: area,
    };

    if area.height == 0 || area.width < 15 {
        return empty_layout;
    }

    // Use focused_fg for label when focused (not focused, which is the bg color)
    let label_color = match state.focus {
        FocusState::Focused => colors.focused_fg,
        FocusState::Hovered => colors.focused_fg,
        FocusState::Disabled => colors.disabled,
        FocusState::Normal => colors.label,
    };

    let mut entry_areas = Vec::new();
    let mut y = area.y;
    let mut content_row = 0u16;

    // Row 0 is label
    if skip_rows == 0 {
        let label_line = Line::from(vec![
            Span::styled(&state.label, Style::default().fg(label_color)),
            Span::raw(":"),
        ]);
        frame.render_widget(
            Paragraph::new(label_line),
            Rect::new(area.x, y, area.width, 1),
        );
        y += 1;
    }
    content_row += 1;

    let indent = 2u16;

    // Row 1 is column headers (if display_field is set)
    if state.display_field.is_some() && y < area.y + area.height {
        if content_row >= skip_rows {
            // Derive header name from display_field (e.g., "/enabled" -> "Enabled")
            let value_header = state
                .display_field
                .as_ref()
                .map(|f| {
                    let name = f.trim_start_matches('/');
                    // Capitalize first letter
                    let mut chars = name.chars();
                    match chars.next() {
                        None => String::new(),
                        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                    }
                })
                .unwrap_or_else(|| "Value".to_string());

            let header_style = Style::default()
                .fg(colors.label)
                .add_modifier(Modifier::DIM);
            let header_line = Line::from(vec![
                Span::styled(" ".repeat(indent as usize), header_style),
                Span::styled(
                    format!("{:width$}", "Name", width = key_width as usize),
                    header_style,
                ),
                Span::raw(" "),
                Span::styled(value_header, header_style),
            ]);
            frame.render_widget(
                Paragraph::new(header_line),
                Rect::new(area.x, y, area.width, 1),
            );
            y += 1;
        }
        content_row += 1;
    }

    // Render entries
    for (idx, (key, value)) in state.entries.iter().enumerate() {
        if y >= area.y + area.height {
            break;
        }

        if content_row < skip_rows {
            content_row += 1;
            continue;
        }

        let is_focused = state.focused_entry == Some(idx) && state.focus == FocusState::Focused;

        let row_area = Rect::new(area.x, y, area.width, 1);

        // Full row background highlight for focused entry
        if is_focused {
            let highlight_style = Style::default().bg(colors.focused);
            let bg_line = Line::from(Span::styled(
                " ".repeat(area.width as usize),
                highlight_style,
            ));
            frame.render_widget(Paragraph::new(bg_line), row_area);
        }

        let (key_color, value_color) = if is_focused {
            // Use focused_fg for text on the focused background
            (colors.focused_fg, colors.focused_fg)
        } else if state.focus == FocusState::Disabled {
            (colors.disabled, colors.disabled)
        } else {
            (colors.key, colors.value_preview)
        };

        let base_style = if is_focused {
            Style::default().bg(colors.focused)
        } else {
            Style::default()
        };

        // Get display value. `truncate_chars_with_ellipsis` counts
        // characters (not bytes) so a localized / CJK preview value
        // doesn't panic on truncation (same class as #1718).
        let value_preview = state.get_display_value(value);
        let value_preview = truncate_chars_with_ellipsis(&value_preview, 20);

        let display_key: String = key.chars().take(key_width as usize).collect();
        let mut spans = vec![
            Span::styled(" ".repeat(indent as usize), base_style),
            Span::styled(
                format!("{:width$}", display_key, width = key_width as usize),
                base_style.fg(key_color),
            ),
            Span::raw(" "),
            Span::styled(value_preview, base_style.fg(value_color)),
        ];

        // Add [Edit] hint for focused entry
        if is_focused {
            spans.push(Span::styled(
                "  [Enter to edit]",
                base_style.fg(colors.focused_fg).add_modifier(Modifier::DIM),
            ));
        }

        frame.render_widget(Paragraph::new(Line::from(spans)), row_area);

        entry_areas.push(MapEntryLayout {
            index: idx,
            row_area,
            expand_area: Rect::default(), // Not rendering expand button in partial view
            key_area: Rect::new(area.x + indent, y, key_width, 1),
            remove_area: Rect::new(area.x + indent + key_width + 1, y, 3, 1),
        });

        y += 1;
        content_row += 1;
    }

    // Add-new row (only show if adding is allowed)
    let add_row_area = if !state.no_add && y < area.y + area.height && content_row >= skip_rows {
        let row_area = Rect::new(area.x, y, area.width, 1);
        let is_focused = state.focused_entry.is_none() && state.focus == FocusState::Focused;

        // Highlight row when focused
        if is_focused {
            let highlight_style = Style::default().bg(colors.focused);
            let bg_line = Line::from(Span::styled(
                " ".repeat(area.width as usize),
                highlight_style,
            ));
            frame.render_widget(Paragraph::new(bg_line), row_area);
        }

        let base_style = if is_focused {
            Style::default().bg(colors.focused)
        } else {
            Style::default()
        };

        let mut spans = vec![
            Span::styled(" ".repeat(indent as usize), base_style),
            Span::styled("[+] Add new", base_style.fg(colors.add_button)),
        ];

        if is_focused {
            spans.push(Span::styled(
                "  [Enter to add]",
                base_style.fg(colors.focused_fg).add_modifier(Modifier::DIM),
            ));
        }

        frame.render_widget(Paragraph::new(Line::from(spans)), row_area);
        Some(row_area)
    } else {
        None
    };

    MapLayout {
        entry_areas,
        add_row_area,
        full_area: area,
    }
}

/// Render KeybindingList with partial visibility
fn render_keybinding_list_partial(
    frame: &mut Frame,
    area: Rect,
    state: &crate::view::controls::KeybindingListState,
    colors: &crate::view::controls::KeybindingListColors,
    skip_rows: u16,
) -> crate::view::controls::KeybindingListLayout {
    use crate::view::controls::keybinding_list::format_key_combo;
    use crate::view::controls::FocusState;
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;

    let empty_layout = crate::view::controls::KeybindingListLayout {
        entry_rects: Vec::new(),
        add_rect: None,
    };

    if area.height == 0 {
        return empty_layout;
    }

    let indent = 2u16;
    let is_focused = state.focus == FocusState::Focused;
    let mut entry_rects = Vec::new();
    let mut content_row = 0u16;
    let mut y = area.y;

    // Render label (row 0) - modified indicator is shown in the row indicator column
    if content_row >= skip_rows {
        let label_line = Line::from(vec![Span::styled(
            format!("{}:", state.label),
            Style::default().fg(colors.label_fg),
        )]);
        frame.render_widget(
            Paragraph::new(label_line),
            Rect::new(area.x, y, area.width, 1),
        );
        y += 1;
    }
    content_row += 1;

    // Render each keybinding entry
    for (idx, binding) in state.bindings.iter().enumerate() {
        if y >= area.y + area.height {
            break;
        }

        if content_row >= skip_rows {
            let entry_area = Rect::new(area.x + indent, y, area.width.saturating_sub(indent), 1);
            entry_rects.push((idx, entry_area));

            let is_entry_focused = is_focused && state.focused_index == Some(idx);
            let bg = if is_entry_focused {
                colors.focused_bg
            } else {
                colors.row_bg
            };

            let key_combo = format_key_combo(binding);
            // Use display_field from state if available, otherwise default to "action"
            let field_name = state
                .display_field
                .as_ref()
                .and_then(|p| p.strip_prefix('/'))
                .unwrap_or("action");
            let action = binding
                .get(field_name)
                .and_then(|a| a.as_str())
                .unwrap_or("(no action)");

            let indicator = if is_entry_focused { "> " } else { "  " };
            // Use focused_fg for all text when entry is focused for good contrast
            let (indicator_fg, key_fg, arrow_fg, action_fg) = if is_entry_focused {
                (
                    colors.focused_fg,
                    colors.focused_fg,
                    colors.focused_fg,
                    colors.focused_fg,
                )
            } else {
                (
                    colors.label_fg,
                    colors.key_fg,
                    colors.label_fg,
                    colors.action_fg,
                )
            };
            // The KeybindingList widget is reused for non-keybinding
            // ObjectArrays (e.g. LSP servers under a language), where the
            // `key_combo` column is always empty. Collapse to just the
            // action so the row reads as a single value.
            let line = if key_combo.trim().is_empty() {
                Line::from(vec![
                    Span::styled(indicator, Style::default().fg(indicator_fg).bg(bg)),
                    Span::styled(action, Style::default().fg(action_fg).bg(bg)),
                ])
            } else {
                Line::from(vec![
                    Span::styled(indicator, Style::default().fg(indicator_fg).bg(bg)),
                    Span::styled(
                        format!("{:<20}", key_combo),
                        Style::default().fg(key_fg).bg(bg),
                    ),
                    Span::styled("", Style::default().fg(arrow_fg).bg(bg)),
                    Span::styled(action, Style::default().fg(action_fg).bg(bg)),
                ])
            };
            frame.render_widget(Paragraph::new(line), entry_area);

            y += 1;
        }
        content_row += 1;
    }

    // Render add-new row
    let add_rect = if y < area.y + area.height && content_row >= skip_rows {
        let is_add_focused = is_focused && state.focused_index.is_none();
        let bg = if is_add_focused {
            colors.focused_bg
        } else {
            colors.row_bg
        };

        let indicator = if is_add_focused { "> " } else { "  " };
        // Use focused_fg for text when add row is focused
        let (indicator_fg, add_fg) = if is_add_focused {
            (colors.focused_fg, colors.focused_fg)
        } else {
            (colors.label_fg, colors.add_fg)
        };
        let line = Line::from(vec![
            Span::styled(indicator, Style::default().fg(indicator_fg).bg(bg)),
            Span::styled("[+] Add new", Style::default().fg(add_fg).bg(bg)),
        ]);
        let add_area = Rect::new(area.x + indent, y, area.width.saturating_sub(indent), 1);
        frame.render_widget(Paragraph::new(line), add_area);
        Some(add_area)
    } else {
        None
    };

    crate::view::controls::KeybindingListLayout {
        entry_rects,
        add_rect,
    }
}

/// Combined layout info for a setting item (control + inherit button)
#[derive(Debug, Clone, Default)]
pub struct SettingItemLayoutInfo {
    pub control: ControlLayoutInfo,
    pub inherit_button: Option<Rect>,
}

/// Layout info for a control (for hit testing)
#[derive(Debug, Clone, Default)]
pub enum ControlLayoutInfo {
    Toggle(Rect),
    Number {
        decrement: Rect,
        increment: Rect,
        value: Rect,
    },
    Dropdown {
        button_area: Rect,
        option_areas: Vec<Rect>,
        scroll_offset: usize,
    },
    Text(Rect),
    TextList {
        /// (data_index, screen_area) - None index means "add new" row
        rows: Vec<(Option<usize>, Rect)>,
    },
    DualList(crate::view::controls::DualListLayout),
    Map {
        /// (data_index, screen_area)
        entry_rows: Vec<(usize, Rect)>,
        add_row_area: Option<Rect>,
    },
    ObjectArray {
        /// (data_index, screen_area)
        entry_rows: Vec<(usize, Rect)>,
    },
    Json {
        edit_area: Rect,
    },
    #[default]
    Complex,
}

/// Render a single button with focus/hover states
#[allow(clippy::too_many_arguments)]
fn render_button(
    frame: &mut Frame,
    area: Rect,
    text: &str,
    focused_text: &str,
    is_focused: bool,
    is_hovered: bool,
    theme: &Theme,
    dimmed: bool,
) {
    if is_focused {
        let style = Style::default()
            .fg(theme.menu_highlight_fg)
            .bg(theme.menu_highlight_bg)
            .add_modifier(Modifier::BOLD);
        frame.render_widget(Paragraph::new(focused_text).style(style), area);
    } else if is_hovered {
        let style = Style::default()
            .fg(theme.menu_hover_fg)
            .bg(theme.menu_hover_bg);
        frame.render_widget(Paragraph::new(text).style(style), area);
    } else {
        let fg = if dimmed {
            theme.line_number_fg
        } else {
            theme.popup_text_fg
        };
        frame.render_widget(Paragraph::new(text).style(Style::default().fg(fg)), area);
    }
}

/// Render footer with action buttons
/// When `vertical` is true, buttons are stacked vertically (for narrow mode)
fn render_footer(
    frame: &mut Frame,
    modal_area: Rect,
    state: &SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
    vertical: bool,
) {
    use super::layout::SettingsHit;
    use super::state::FocusPanel;

    // Guard against too-small modal
    if modal_area.height < 4 || modal_area.width < 10 {
        return;
    }

    if vertical {
        render_footer_vertical(frame, modal_area, state, theme, layout);
        return;
    }

    let footer_y = modal_area.y + modal_area.height.saturating_sub(2);
    let footer_width = modal_area.width.saturating_sub(2);
    let footer_area = Rect::new(modal_area.x + 1, footer_y, footer_width, 1);

    // Draw separator line (only if we have room above footer)
    if footer_y > modal_area.y {
        let sep_y = footer_y.saturating_sub(1);
        let sep_area = Rect::new(modal_area.x + 1, sep_y, footer_width, 1);
        let sep_line: String = "".repeat(sep_area.width as usize);
        frame.render_widget(
            Paragraph::new(sep_line).style(Style::default().fg(theme.split_separator_fg)),
            sep_area,
        );
    }

    // Check if footer has keyboard focus
    let footer_focused = state.focus_panel() == FocusPanel::Footer;

    // Determine hover and keyboard focus states for buttons
    // Button indices: 0=Layer, 1=Reset, 2=Save, 3=Cancel, 4=Edit (on left, for advanced users)
    let layer_hovered = matches!(state.hover_hit, Some(SettingsHit::LayerButton));
    let reset_hovered = matches!(state.hover_hit, Some(SettingsHit::ResetButton));
    let save_hovered = matches!(state.hover_hit, Some(SettingsHit::SaveButton));
    let cancel_hovered = matches!(state.hover_hit, Some(SettingsHit::CancelButton));
    let edit_hovered = matches!(state.hover_hit, Some(SettingsHit::EditButton));

    let layer_focused = footer_focused && state.footer_button_index == 0;
    let reset_focused = footer_focused && state.footer_button_index == 1;
    let save_focused = footer_focused && state.footer_button_index == 2;
    let cancel_focused = footer_focused && state.footer_button_index == 3;
    let edit_focused = footer_focused && state.footer_button_index == 4;

    // Get translated button labels
    // Use "Inherit" label instead of "Reset" when current item is nullable and explicitly set
    let current_is_nullable_set = state
        .current_item()
        .map(|item| item.nullable && !item.is_null)
        .unwrap_or(false);
    let save_label = t!("settings.btn_save").to_string();
    let cancel_label = t!("settings.btn_cancel").to_string();
    let reset_label = if current_is_nullable_set {
        t!("settings.btn_inherit").to_string()
    } else {
        t!("settings.btn_reset").to_string()
    };
    let edit_label = t!("settings.btn_edit").to_string();

    // Build button text with brackets (layer button uses layer name)
    let layer_text = format!("[ {} ]", state.target_layer_name());
    let layer_text_focused = format!(">[ {} ]", state.target_layer_name());
    let save_text = format!("[ {} ]", save_label);
    let save_text_focused = format!(">[ {} ]", save_label);
    let cancel_text = format!("[ {} ]", cancel_label);
    let cancel_text_focused = format!(">[ {} ]", cancel_label);
    let reset_text = format!("[ {} ]", reset_label);
    let reset_text_focused = format!(">[ {} ]", reset_label);
    let edit_text = format!("[ {} ]", edit_label);
    let edit_text_focused = format!(">[ {} ]", edit_label);

    // Calculate button widths using display width (handles unicode)
    let cancel_width = str_width(if cancel_focused {
        &cancel_text_focused
    } else {
        &cancel_text
    }) as u16;
    let save_width = str_width(if save_focused {
        &save_text_focused
    } else {
        &save_text
    }) as u16;
    let reset_width = str_width(if reset_focused {
        &reset_text_focused
    } else {
        &reset_text
    }) as u16;
    let layer_width = str_width(if layer_focused {
        &layer_text_focused
    } else {
        &layer_text
    }) as u16;
    let edit_width = str_width(if edit_focused {
        &edit_text_focused
    } else {
        &edit_text
    }) as u16;
    let gap: u16 = 2;

    // Calculate total width needed for all buttons
    // Minimum needed: Save + Cancel
    let min_buttons_width = save_width + gap + cancel_width;
    // Full buttons: Edit + Layer + Reset + Save + Cancel with gaps
    let all_buttons_width =
        edit_width + gap + layer_width + gap + reset_width + gap + save_width + gap + cancel_width;

    // Determine which buttons to show based on available width
    let available = footer_area.width;
    let show_edit = available >= all_buttons_width;
    let show_layer = available >= (layer_width + gap + reset_width + gap + min_buttons_width);
    let show_reset = available >= (reset_width + gap + min_buttons_width);

    // Calculate X positions using saturating_sub to prevent overflow
    let cancel_x = footer_area
        .x
        .saturating_add(footer_area.width.saturating_sub(cancel_width));
    let save_x = cancel_x.saturating_sub(save_width + gap);
    let reset_x = if show_reset {
        save_x.saturating_sub(reset_width + gap)
    } else {
        0
    };
    let layer_x = if show_layer {
        reset_x.saturating_sub(layer_width + gap)
    } else {
        0
    };
    let edit_x = footer_area.x; // Left-aligned

    // Render buttons using helper function
    // Layer button (conditionally shown)
    if show_layer {
        let layer_area = Rect::new(layer_x, footer_y, layer_width, 1);
        render_button(
            frame,
            layer_area,
            &layer_text,
            &layer_text_focused,
            layer_focused,
            layer_hovered,
            theme,
            false,
        );
        layout.layer_button = Some(layer_area);
    }

    // Reset button (conditionally shown)
    if show_reset {
        let reset_area = Rect::new(reset_x, footer_y, reset_width, 1);
        render_button(
            frame,
            reset_area,
            &reset_text,
            &reset_text_focused,
            reset_focused,
            reset_hovered,
            theme,
            false,
        );
        layout.reset_button = Some(reset_area);
    }

    // Save button (always shown)
    let save_area = Rect::new(save_x, footer_y, save_width, 1);
    render_button(
        frame,
        save_area,
        &save_text,
        &save_text_focused,
        save_focused,
        save_hovered,
        theme,
        false,
    );
    layout.save_button = Some(save_area);

    // Cancel button (always shown)
    let cancel_area = Rect::new(cancel_x, footer_y, cancel_width, 1);
    render_button(
        frame,
        cancel_area,
        &cancel_text,
        &cancel_text_focused,
        cancel_focused,
        cancel_hovered,
        theme,
        false,
    );
    layout.cancel_button = Some(cancel_area);

    // Edit button (on left, for advanced users, conditionally shown)
    if show_edit {
        let edit_area = Rect::new(edit_x, footer_y, edit_width, 1);
        render_button(
            frame,
            edit_area,
            &edit_text,
            &edit_text_focused,
            edit_focused,
            edit_hovered,
            theme,
            true, // dimmed for advanced option
        );
        layout.edit_button = Some(edit_area);
    }

    // Help text (between Edit button and main buttons)
    // Calculate position based on which buttons are visible
    let help_start_x = if show_edit {
        edit_x + edit_width + 2
    } else {
        footer_area.x
    };
    let help_end_x = if show_layer {
        layer_x
    } else if show_reset {
        reset_x
    } else {
        save_x
    };
    let help_width = help_end_x.saturating_sub(help_start_x + 1);

    // Get translated help text
    let help = if state.search_active {
        t!("settings.help_search").to_string()
    } else if footer_focused {
        t!("settings.help_footer").to_string()
    } else {
        t!("settings.help_default").to_string()
    };
    // Render help text with reverse-video styling for key hints
    // Parse "Key:Action  Key:Action" format
    let help_line = build_keyhint_line(&help, theme);
    frame.render_widget(
        Paragraph::new(help_line),
        Rect::new(help_start_x, footer_y, help_width, 1),
    );
}

/// Build a Line with reverse-video styled key hints from "Key:Action  Key:Action" format
fn build_keyhint_line<'a>(text: &str, theme: &Theme) -> Line<'a> {
    let key_style = Style::default()
        .fg(theme.popup_text_fg)
        .bg(theme.split_separator_fg);
    let desc_style = Style::default().fg(theme.line_number_fg);
    let sep_style = Style::default().fg(theme.line_number_fg);

    let mut spans: Vec<Span<'a>> = Vec::new();

    // Split by double-space to get individual key hints
    for (i, segment) in text.split("  ").enumerate() {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }
        if i > 0 {
            spans.push(Span::styled(" ", sep_style));
        }
        // Split by first ":" to separate key from description
        if let Some(colon_pos) = segment.find(':') {
            let key = &segment[..colon_pos];
            let action = &segment[colon_pos + 1..];
            spans.push(Span::styled(format!(" {} ", key), key_style));
            spans.push(Span::styled(action.to_string(), desc_style));
        } else {
            // No colon - just render as text
            spans.push(Span::styled(segment.to_string(), desc_style));
        }
    }

    Line::from(spans)
}

/// Render footer with buttons stacked vertically (for narrow mode)
fn render_footer_vertical(
    frame: &mut Frame,
    modal_area: Rect,
    state: &SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    use super::layout::SettingsHit;
    use super::state::FocusPanel;

    // Footer takes bottom 7 lines: separator + 5 buttons + help
    let footer_height = 7u16;
    let footer_y = modal_area
        .y
        .saturating_add(modal_area.height.saturating_sub(footer_height));
    let footer_width = modal_area.width.saturating_sub(2);

    // Draw top separator
    let sep_y = footer_y;
    if sep_y > modal_area.y {
        let sep_line: String = "".repeat(footer_width as usize);
        frame.render_widget(
            Paragraph::new(sep_line).style(Style::default().fg(theme.split_separator_fg)),
            Rect::new(modal_area.x + 1, sep_y, footer_width, 1),
        );
    }

    // Check if footer has keyboard focus
    let footer_focused = state.focus_panel() == FocusPanel::Footer;

    // Determine hover and keyboard focus states for buttons
    let layer_hovered = matches!(state.hover_hit, Some(SettingsHit::LayerButton));
    let reset_hovered = matches!(state.hover_hit, Some(SettingsHit::ResetButton));
    let save_hovered = matches!(state.hover_hit, Some(SettingsHit::SaveButton));
    let cancel_hovered = matches!(state.hover_hit, Some(SettingsHit::CancelButton));
    let edit_hovered = matches!(state.hover_hit, Some(SettingsHit::EditButton));

    let layer_focused = footer_focused && state.footer_button_index == 0;
    let reset_focused = footer_focused && state.footer_button_index == 1;
    let save_focused = footer_focused && state.footer_button_index == 2;
    let cancel_focused = footer_focused && state.footer_button_index == 3;
    let edit_focused = footer_focused && state.footer_button_index == 4;

    // Get translated button labels
    // Use "Inherit" label instead of "Reset" when current item is nullable and explicitly set
    let current_is_nullable_set = state
        .current_item()
        .map(|item| item.nullable && !item.is_null)
        .unwrap_or(false);
    let save_label = t!("settings.btn_save").to_string();
    let cancel_label = t!("settings.btn_cancel").to_string();
    let reset_label = if current_is_nullable_set {
        t!("settings.btn_inherit").to_string()
    } else {
        t!("settings.btn_reset").to_string()
    };
    let edit_label = t!("settings.btn_edit").to_string();

    // Build button text
    let layer_text = format!("[ {} ]", state.target_layer_name());
    let layer_text_focused = format!(">[ {} ]", state.target_layer_name());
    let save_text = format!("[ {} ]", save_label);
    let save_text_focused = format!(">[ {} ]", save_label);
    let cancel_text = format!("[ {} ]", cancel_label);
    let cancel_text_focused = format!(">[ {} ]", cancel_label);
    let reset_text = format!("[ {} ]", reset_label);
    let reset_text_focused = format!(">[ {} ]", reset_label);
    let edit_text = format!("[ {} ]", edit_label);
    let edit_text_focused = format!(">[ {} ]", edit_label);

    // Render buttons vertically, centered
    let button_x = modal_area.x + 2;
    let mut y = sep_y + 1;

    // Layer button
    let layer_width = str_width(if layer_focused {
        &layer_text_focused
    } else {
        &layer_text
    }) as u16;
    let layer_area = Rect::new(button_x, y, layer_width.min(footer_width), 1);
    render_button(
        frame,
        layer_area,
        &layer_text,
        &layer_text_focused,
        layer_focused,
        layer_hovered,
        theme,
        false,
    );
    layout.layer_button = Some(layer_area);
    y += 1;

    // Save button
    let save_width = str_width(if save_focused {
        &save_text_focused
    } else {
        &save_text
    }) as u16;
    let save_area = Rect::new(button_x, y, save_width.min(footer_width), 1);
    render_button(
        frame,
        save_area,
        &save_text,
        &save_text_focused,
        save_focused,
        save_hovered,
        theme,
        false,
    );
    layout.save_button = Some(save_area);
    y += 1;

    // Reset button
    let reset_width = str_width(if reset_focused {
        &reset_text_focused
    } else {
        &reset_text
    }) as u16;
    let reset_area = Rect::new(button_x, y, reset_width.min(footer_width), 1);
    render_button(
        frame,
        reset_area,
        &reset_text,
        &reset_text_focused,
        reset_focused,
        reset_hovered,
        theme,
        false,
    );
    layout.reset_button = Some(reset_area);
    y += 1;

    // Cancel button
    let cancel_width = str_width(if cancel_focused {
        &cancel_text_focused
    } else {
        &cancel_text
    }) as u16;
    let cancel_area = Rect::new(button_x, y, cancel_width.min(footer_width), 1);
    render_button(
        frame,
        cancel_area,
        &cancel_text,
        &cancel_text_focused,
        cancel_focused,
        cancel_hovered,
        theme,
        false,
    );
    layout.cancel_button = Some(cancel_area);
    y += 1;

    // Edit button
    let edit_width = str_width(if edit_focused {
        &edit_text_focused
    } else {
        &edit_text
    }) as u16;
    let edit_area = Rect::new(button_x, y, edit_width.min(footer_width), 1);
    render_button(
        frame,
        edit_area,
        &edit_text,
        &edit_text_focused,
        edit_focused,
        edit_hovered,
        theme,
        true, // dimmed
    );
    layout.edit_button = Some(edit_area);
}

/// Render the search header with query input
fn render_search_header(frame: &mut Frame, area: Rect, state: &SettingsState, theme: &Theme) {
    let search_style = Style::default().fg(theme.settings_selected_fg);
    let cursor_style = Style::default()
        .fg(theme.settings_selected_fg)
        .add_modifier(Modifier::REVERSED);

    // Show result count and scroll position inline after cursor
    let result_count = state.search_results.len();
    let count_text = if state.search_query.is_empty() {
        String::new()
    } else if result_count == 0 {
        " (no results)".to_string()
    } else if result_count == 1 {
        " (1 result)".to_string()
    } else if state.search_max_visible >= result_count {
        // All results visible, no need to show range
        format!(" ({} results)", result_count)
    } else {
        // Show current position in results
        let first = state.search_scroll_offset + 1;
        let last = (state.search_scroll_offset + state.search_max_visible).min(result_count);
        format!(" ({}-{} of {})", first, last, result_count)
    };

    // Add scroll indicators
    let has_more_above = state.search_scroll_offset > 0;
    let has_more_below = state.search_scroll_offset + state.search_max_visible < result_count;
    let scroll_indicator = match (has_more_above, has_more_below) {
        (true, true) => " ↑↓",
        (true, false) => "",
        (false, true) => "",
        (false, false) => "",
    };

    let count_style = Style::default().fg(theme.line_number_fg);
    let indicator_style = Style::default()
        .fg(theme.menu_active_fg)
        .add_modifier(Modifier::BOLD);

    let spans = vec![
        Span::styled("> ", search_style),
        Span::styled(&state.search_query, search_style),
        Span::styled(" ", cursor_style), // Cursor
        Span::styled(count_text, count_style),
        Span::styled(scroll_indicator, indicator_style),
    ];
    let line = Line::from(spans);
    frame.render_widget(Paragraph::new(line), area);
}

/// Render search hint when search is not active
fn render_search_hint(frame: &mut Frame, area: Rect, theme: &Theme) {
    let hint_style = Style::default().fg(theme.line_number_fg);
    let key_style = Style::default()
        .fg(theme.popup_text_fg)
        .bg(theme.split_separator_fg);

    let spans = vec![
        Span::styled("Press ", hint_style),
        Span::styled(" / ", key_style),
        Span::styled(" to search settings...", hint_style),
    ];
    let line = Line::from(spans);
    frame.render_widget(Paragraph::new(line), area);
}

/// Render search results with breadcrumbs
fn render_search_results(
    frame: &mut Frame,
    area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    // Calculate max visible results (each result is 3 rows tall)
    let max_visible = (area.height.saturating_sub(3) / 3) as usize;
    state.search_max_visible = max_visible.max(1);

    // Ensure scroll offset is valid
    if state.search_scroll_offset >= state.search_results.len() {
        state.search_scroll_offset = state.search_results.len().saturating_sub(1);
    }

    // Determine if we need a scrollbar
    let needs_scrollbar = state.search_results.len() > state.search_max_visible;
    let scrollbar_width = if needs_scrollbar { 1 } else { 0 };

    // Reserve space for scrollbar on the right
    let content_area = Rect::new(
        area.x,
        area.y,
        area.width.saturating_sub(scrollbar_width),
        area.height,
    );

    let mut y = content_area.y;

    for (idx, result) in state
        .search_results
        .iter()
        .enumerate()
        .skip(state.search_scroll_offset)
    {
        if y >= content_area.y + content_area.height.saturating_sub(3) {
            break;
        }

        let is_selected = idx == state.selected_search_result;
        let is_hovered = matches!(state.hover_hit, Some(SettingsHit::SearchResult(i)) if i == idx);
        let item_area = Rect::new(content_area.x, y, content_area.width, 3);

        render_search_result_item(
            frame,
            item_area,
            result,
            is_selected,
            is_hovered,
            theme,
            layout,
        );
        y += 3;
    }

    // Track search results area in layout for mouse wheel support
    layout.search_results_area = Some(content_area);

    // Render scrollbar if needed
    if needs_scrollbar {
        let scrollbar_area = Rect::new(
            area.x + area.width - 1,
            area.y,
            1,
            area.height.saturating_sub(3), // Leave space at bottom
        );

        let scrollbar_state = ScrollbarState::new(
            state.search_results.len(),
            state.search_max_visible,
            state.search_scroll_offset,
        );

        let colors = ScrollbarColors::from_theme(theme);
        render_scrollbar(frame, scrollbar_area, &scrollbar_state, &colors);

        // Track scrollbar area in layout for click/drag support
        layout.search_scrollbar_area = Some(scrollbar_area);
    } else {
        layout.search_scrollbar_area = None;
    }
}

/// Render a single search result with breadcrumb
fn render_search_result_item(
    frame: &mut Frame,
    area: Rect,
    result: &SearchResult,
    is_selected: bool,
    is_hovered: bool,
    theme: &Theme,
    layout: &mut SettingsLayout,
) {
    // Draw selection or hover highlight background
    if is_selected {
        // Use dedicated settings colors for selected items
        let bg_style = Style::default().bg(theme.settings_selected_bg);
        for row in 0..area.height.min(3) {
            let row_area = Rect::new(area.x, area.y + row, area.width, 1);
            frame.render_widget(Paragraph::new("").style(bg_style), row_area);
        }
    } else if is_hovered {
        // Subtle hover highlight using menu hover colors
        let bg_style = Style::default().bg(theme.menu_hover_bg);
        for row in 0..area.height.min(3) {
            let row_area = Rect::new(area.x, area.y + row, area.width, 1);
            frame.render_widget(Paragraph::new("").style(bg_style), row_area);
        }
    }

    // Determine display name and description based on deep match
    let (display_name, display_desc) = match &result.deep_match {
        Some(DeepMatch::MapKey { key, .. }) => (key.clone(), Some(result.item.name.clone())),
        Some(DeepMatch::MapValue {
            matched_text, key, ..
        }) => (
            matched_text.clone(),
            Some(format!("{} > {}", result.item.name, key)),
        ),
        Some(DeepMatch::TextListItem { text, .. }) => {
            (text.clone(), Some(result.item.name.clone()))
        }
        None => (result.item.name.clone(), result.item.description.clone()),
    };

    // First line: Setting name with highlighting
    let name_style = if is_selected {
        Style::default().fg(theme.settings_selected_fg)
    } else if is_hovered {
        Style::default().fg(theme.menu_hover_fg)
    } else {
        Style::default().fg(theme.popup_text_fg)
    };

    // Build name with match highlighting, prefixed with selection indicator
    let indicator = if is_selected { "" } else { "  " };
    let indicator_style = if is_selected {
        Style::default()
            .fg(theme.settings_selected_fg)
            .add_modifier(Modifier::BOLD)
    } else {
        name_style
    };
    let mut name_line = build_highlighted_text(
        &display_name,
        &result.name_matches,
        name_style,
        Style::default()
            .fg(theme.diagnostic_warning_fg)
            .add_modifier(Modifier::BOLD),
    );
    name_line
        .spans
        .insert(0, Span::styled(indicator, indicator_style));
    frame.render_widget(
        Paragraph::new(name_line),
        Rect::new(area.x, area.y, area.width, 1),
    );

    // Second line: Breadcrumb
    let breadcrumb_style = Style::default()
        .fg(theme.line_number_fg)
        .add_modifier(Modifier::ITALIC);
    let breadcrumb = format!("  {} > {}", result.breadcrumb, result.item.path);
    let breadcrumb_line = Line::from(Span::styled(breadcrumb, breadcrumb_style));
    frame.render_widget(
        Paragraph::new(breadcrumb_line),
        Rect::new(area.x, area.y + 1, area.width, 1),
    );

    // Third line: Description (if any). Counts characters (not bytes)
    // when checking and truncating: descriptions can be localized (e.g.
    // CJK translations) and a byte-based slice could land inside a
    // multi-byte UTF-8 sequence and panic — same class as #1718.
    if let Some(ref desc) = display_desc {
        let desc_style = Style::default().fg(theme.line_number_fg);
        let max_chars = (area.width as usize).saturating_sub(2);
        let truncated_desc = format!("  {}", truncate_chars_with_ellipsis(desc, max_chars));
        frame.render_widget(
            Paragraph::new(truncated_desc).style(desc_style),
            Rect::new(area.x, area.y + 2, area.width, 1),
        );
    }

    // Track this item in layout
    layout.add_search_result(result.page_index, result.item_index, area);
}

/// Build a line with highlighted match positions
fn build_highlighted_text(
    text: &str,
    matches: &[usize],
    normal_style: Style,
    highlight_style: Style,
) -> Line<'static> {
    if matches.is_empty() {
        return Line::from(Span::styled(text.to_string(), normal_style));
    }

    let chars: Vec<char> = text.chars().collect();
    let mut spans = Vec::new();
    let mut current = String::new();
    let mut in_highlight = false;

    for (idx, ch) in chars.iter().enumerate() {
        let should_highlight = matches.contains(&idx);

        if should_highlight != in_highlight {
            if !current.is_empty() {
                let style = if in_highlight {
                    highlight_style
                } else {
                    normal_style
                };
                spans.push(Span::styled(current, style));
                current = String::new();
            }
            in_highlight = should_highlight;
        }

        current.push(*ch);
    }

    // Push remaining
    if !current.is_empty() {
        let style = if in_highlight {
            highlight_style
        } else {
            normal_style
        };
        spans.push(Span::styled(current, style));
    }

    Line::from(spans)
}

/// Render the unsaved changes confirmation dialog
fn render_confirm_dialog(
    frame: &mut Frame,
    parent_area: Rect,
    state: &SettingsState,
    theme: &Theme,
) {
    // Calculate dialog size
    let changes = state.get_change_descriptions();
    let dialog_width = 50.min(parent_area.width.saturating_sub(4));
    // Base height: 2 borders + 2 prompt lines + 1 separator + 1 buttons + 1 help = 7
    // Plus one line per change
    let dialog_height = (7 + changes.len() as u16)
        .min(20)
        .min(parent_area.height.saturating_sub(4));

    // Center the dialog
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    // Clear and draw border
    frame.render_widget(Clear, dialog_area);

    let title = format!(" {} ", t!("confirm.unsaved_changes_title"));
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.diagnostic_warning_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    // Inner area
    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(2),
    );

    let mut y = inner.y;

    // Prompt text
    let prompt = t!("confirm.unsaved_changes_prompt").to_string();
    let prompt_style = Style::default().fg(theme.popup_text_fg);
    frame.render_widget(
        Paragraph::new(prompt).style(prompt_style),
        Rect::new(inner.x, y, inner.width, 1),
    );
    y += 2;

    // List changes. Character-based truncation here (rather than byte
    // truncation) keeps CJK / emoji change descriptions from byte-slicing
    // through a multi-byte UTF-8 sequence and panicking — same class as
    // #1718.
    let change_style = Style::default().fg(theme.popup_text_fg);
    for change in changes
        .iter()
        .take((dialog_height as usize).saturating_sub(7))
    {
        let max_chars = (inner.width as usize).saturating_sub(2);
        let truncated = format!("{}", truncate_chars_with_ellipsis(change, max_chars));
        frame.render_widget(
            Paragraph::new(truncated).style(change_style),
            Rect::new(inner.x, y, inner.width, 1),
        );
        y += 1;
    }

    // Skip to button row
    let button_y = dialog_area.y + dialog_area.height - 3;

    // Draw separator
    let sep_line: String = "".repeat(inner.width as usize);
    frame.render_widget(
        Paragraph::new(sep_line).style(Style::default().fg(theme.split_separator_fg)),
        Rect::new(inner.x, button_y - 1, inner.width, 1),
    );

    // Render the three options
    let options = [
        t!("confirm.save_and_exit").to_string(),
        t!("confirm.discard").to_string(),
        t!("confirm.cancel").to_string(),
    ];
    let total_width: u16 = options.iter().map(|o| o.len() as u16 + 4).sum::<u16>() + 4; // +4 for gaps
    let mut x = inner.x + (inner.width.saturating_sub(total_width)) / 2;

    for (idx, label) in options.iter().enumerate() {
        let is_selected = idx == state.confirm_dialog_selection;
        let is_hovered = state.confirm_dialog_hover == Some(idx);
        let button_width = label.len() as u16 + 4;

        let style = if is_selected {
            Style::default()
                .fg(theme.menu_highlight_fg)
                .bg(theme.menu_highlight_bg)
                .add_modifier(ratatui::style::Modifier::BOLD)
        } else if is_hovered {
            Style::default()
                .fg(theme.menu_hover_fg)
                .bg(theme.menu_hover_bg)
        } else {
            Style::default().fg(theme.popup_text_fg)
        };

        let text = if is_selected {
            format!(">[ {} ]", label)
        } else {
            format!(" [ {} ]", label)
        };
        frame.render_widget(
            Paragraph::new(text).style(style),
            Rect::new(x, button_y, button_width + 1, 1),
        );

        x += button_width + 3;
    }

    // Help text
    let help = "←/→/Tab: Select   Enter: Confirm   Esc: Cancel";
    let help_style = Style::default().fg(theme.line_number_fg);
    frame.render_widget(
        Paragraph::new(help).style(help_style),
        Rect::new(inner.x, button_y + 1, inner.width, 1),
    );
}

/// Render the reset confirmation dialog
fn render_reset_dialog(frame: &mut Frame, parent_area: Rect, state: &SettingsState, theme: &Theme) {
    let changes = state.get_change_descriptions();
    let dialog_width = 50.min(parent_area.width.saturating_sub(4));
    // Base height: 2 borders + 2 prompt lines + 1 separator + 1 buttons + 1 help = 7
    // Plus one line per change
    let dialog_height = (7 + changes.len() as u16)
        .min(20)
        .min(parent_area.height.saturating_sub(4));

    // Center the dialog
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    // Clear and draw border
    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(" Reset All Changes ")
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.diagnostic_warning_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    // Inner area
    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(2),
    );

    let mut y = inner.y;

    // Prompt text
    let prompt_style = Style::default().fg(theme.popup_text_fg);
    frame.render_widget(
        Paragraph::new("Discard all pending changes?").style(prompt_style),
        Rect::new(inner.x, y, inner.width, 1),
    );
    y += 2;

    // List changes. Character-based truncation here (rather than byte
    // truncation) keeps CJK / emoji change descriptions from byte-slicing
    // through a multi-byte UTF-8 sequence and panicking — same class as
    // #1718.
    let change_style = Style::default().fg(theme.popup_text_fg);
    for change in changes
        .iter()
        .take((dialog_height as usize).saturating_sub(7))
    {
        let max_chars = (inner.width as usize).saturating_sub(2);
        let truncated = format!("{}", truncate_chars_with_ellipsis(change, max_chars));
        frame.render_widget(
            Paragraph::new(truncated).style(change_style),
            Rect::new(inner.x, y, inner.width, 1),
        );
        y += 1;
    }

    // Skip to button row
    let button_y = dialog_area.y + dialog_area.height - 3;

    // Draw separator
    let sep_line: String = "".repeat(inner.width as usize);
    frame.render_widget(
        Paragraph::new(sep_line).style(Style::default().fg(theme.split_separator_fg)),
        Rect::new(inner.x, button_y - 1, inner.width, 1),
    );

    // Render the two options: Reset, Cancel
    let options = ["Reset", "Cancel"];
    let total_width: u16 = options.iter().map(|o| o.len() as u16 + 4).sum::<u16>() + 4;
    let mut x = inner.x + (inner.width.saturating_sub(total_width)) / 2;

    for (idx, label) in options.iter().enumerate() {
        let is_selected = idx == state.reset_dialog_selection;
        let is_hovered = state.reset_dialog_hover == Some(idx);
        let button_width = label.len() as u16 + 4;

        let style = if is_selected {
            Style::default()
                .fg(theme.menu_highlight_fg)
                .bg(theme.menu_highlight_bg)
                .add_modifier(ratatui::style::Modifier::BOLD)
        } else if is_hovered {
            Style::default()
                .fg(theme.menu_hover_fg)
                .bg(theme.menu_hover_bg)
        } else {
            Style::default().fg(theme.popup_text_fg)
        };

        let text = if is_selected {
            format!(">[ {} ]", label)
        } else {
            format!(" [ {} ]", label)
        };
        frame.render_widget(
            Paragraph::new(text).style(style),
            Rect::new(x, button_y, button_width + 1, 1),
        );

        x += button_width + 3;
    }

    // Help text
    let help = "←/→/Tab: Select   Enter: Confirm   Esc: Cancel";
    let help_style = Style::default().fg(theme.line_number_fg);
    frame.render_widget(
        Paragraph::new(help).style(help_style),
        Rect::new(inner.x, button_y + 1, inner.width, 1),
    );
}

/// Render the "Discard changes?" prompt that appears when the user
/// presses Esc on a dirty entry dialog.
fn render_entry_discard_confirm(
    frame: &mut Frame,
    parent_area: Rect,
    state: &SettingsState,
    theme: &Theme,
) {
    let dialog_width = 50.min(parent_area.width.saturating_sub(4));
    let dialog_height = 7u16.min(parent_area.height.saturating_sub(4));
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(" Discard changes? ")
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.diagnostic_warning_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(2),
    );

    let prompt_style = Style::default().fg(theme.popup_text_fg);
    frame.render_widget(
        Paragraph::new("You have uncommitted edits in this dialog.").style(prompt_style),
        Rect::new(inner.x, inner.y, inner.width, 1),
    );

    // Buttons. 0 = Keep editing (default), 1 = Discard. Discard styled
    // in the danger fg to make the destructive choice unmistakable.
    let button_y = dialog_area.y + dialog_area.height - 3;
    let options = ["Keep editing", "Discard"];
    let total_width: u16 = options.iter().map(|o| o.len() as u16 + 4).sum::<u16>() + 4;
    let mut x = inner.x + (inner.width.saturating_sub(total_width)) / 2;

    for (idx, label) in options.iter().enumerate() {
        let is_selected = idx == state.entry_discard_confirm_selection;
        let is_discard = idx == 1;
        let style = if is_selected && is_discard {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_selected {
            Style::default()
                .fg(theme.popup_selection_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_discard {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.popup_text_fg)
        };
        let text = if is_selected {
            format!(">[ {} ]", label)
        } else {
            format!(" [ {} ]", label)
        };
        let w = label.len() as u16 + 5;
        frame.render_widget(
            Paragraph::new(text).style(style),
            Rect::new(x, button_y, w, 1),
        );
        x += w + 2;
    }

    let help = "Tab/←→: Select   Enter: Confirm   Esc: Keep editing";
    let help_style = Style::default().fg(theme.line_number_fg);
    frame.render_widget(
        Paragraph::new(help).style(help_style),
        Rect::new(inner.x, button_y + 1, inner.width, 1),
    );
}

/// Compute the footer Delete-button label for an entry dialog.
///
/// Schema-driven: shows the map key for map entries (e.g.
/// `[ Delete "rust" ]`), a generic "item" for array items (the
/// numeric index isn't meaningful to the user), or a bare fallback
/// when neither is available. The key is truncated so a very long
/// identifier can't blow out the dialog footer.
fn entry_delete_button_label(dialog: &EntryDialogState) -> String {
    const MAX_KEY_IN_LABEL: usize = 24;
    if dialog.is_array_item {
        "[ Delete item ]".to_string()
    } else if dialog.entry_key.is_empty() {
        "[ Delete entry ]".to_string()
    } else {
        let key = if dialog.entry_key.chars().count() > MAX_KEY_IN_LABEL {
            let truncated: String = dialog
                .entry_key
                .chars()
                .take(MAX_KEY_IN_LABEL - 1)
                .collect();
            format!("{}", truncated)
        } else {
            dialog.entry_key.clone()
        };
        format!("[ Delete \"{}\" ]", key)
    }
}

/// Render the "Delete <name>?" prompt that appears when the user
/// activates the Delete button on an entry dialog.
fn render_entry_delete_confirm(
    frame: &mut Frame,
    parent_area: Rect,
    state: &SettingsState,
    theme: &Theme,
) {
    let dialog_width = 60.min(parent_area.width.saturating_sub(4));
    let dialog_height = 7u16.min(parent_area.height.saturating_sub(4));
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    frame.render_widget(Clear, dialog_area);

    let title = if !state.entry_delete_target_name.is_empty() {
        format!(" Delete \"{}\"? ", state.entry_delete_target_name)
    } else if state.entry_delete_target_is_array_item {
        " Delete item? ".to_string()
    } else {
        " Delete entry? ".to_string()
    };

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.diagnostic_error_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(2),
    );

    let body = if !state.entry_delete_target_name.is_empty() {
        format!(
            "This will permanently remove \"{}\".",
            state.entry_delete_target_name
        )
    } else if state.entry_delete_target_is_array_item {
        "This will permanently remove this item.".to_string()
    } else {
        "This will permanently remove the entry.".to_string()
    };
    let prompt_style = Style::default().fg(theme.popup_text_fg);
    frame.render_widget(
        Paragraph::new(body).style(prompt_style),
        Rect::new(inner.x, inner.y, inner.width, 1),
    );

    let button_y = dialog_area.y + dialog_area.height - 3;
    let options = ["Cancel", "Delete"];
    let total_width: u16 = options.iter().map(|o| o.len() as u16 + 5).sum::<u16>() + 2;
    let mut x = inner.x + (inner.width.saturating_sub(total_width)) / 2;

    for (idx, label) in options.iter().enumerate() {
        let is_selected = idx == state.entry_delete_confirm_selection;
        let is_delete = idx == 1;
        let style = if is_selected && is_delete {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_selected {
            Style::default()
                .fg(theme.popup_selection_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_delete {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.popup_text_fg)
        };
        let text = if is_selected {
            format!(">[ {} ]", label)
        } else {
            format!(" [ {} ]", label)
        };
        let w = label.len() as u16 + 5;
        frame.render_widget(
            Paragraph::new(text).style(style),
            Rect::new(x, button_y, w, 1),
        );
        x += w + 2;
    }

    let help = "Tab/←→: Select   Enter: Confirm   Esc: Cancel";
    let help_style = Style::default().fg(theme.line_number_fg);
    frame.render_widget(
        Paragraph::new(help).style(help_style),
        Rect::new(inner.x, button_y + 1, inner.width, 1),
    );
}

/// Render a specific entry dialog from the stack by index.
fn render_entry_dialog_at(
    frame: &mut Frame,
    parent_area: Rect,
    state: &mut SettingsState,
    theme: &Theme,
    dialog_idx: usize,
) {
    let Some(dialog) = state.entry_dialog_stack.get_mut(dialog_idx) else {
        return;
    };
    render_entry_dialog_inner(frame, parent_area, dialog, theme);
}

/// Render the scrolled list of items and (when needed) the scrollbar.
#[allow(clippy::too_many_arguments)]
fn render_entry_items(
    frame: &mut Frame,
    dialog_area: Rect,
    inner: Rect,
    dialog: &super::entry_dialog::EntryDialogState,
    theme: &Theme,
    label_col_width: u16,
    scroll_offset: usize,
    total_content_height: usize,
    viewport_height: usize,
) {
    let needs_scroll = total_content_height > viewport_height;
    let mut content_y: usize = 0;
    let mut screen_y = inner.y;

    let first_editable = dialog.first_editable_index;
    let needs_separator = first_editable > 0 && first_editable < dialog.items.len();

    for (idx, item) in dialog.items.iter().enumerate() {
        // Separator between read-only and editable sections
        if needs_separator && idx == first_editable {
            let separator_end = content_y + 1;
            if separator_end > scroll_offset
                && screen_y < inner.y + inner.height
                && content_y >= scroll_offset
            {
                let sep_style = Style::default().fg(theme.line_number_fg);
                let separator_line = "".repeat(inner.width.saturating_sub(2) as usize);
                frame.render_widget(
                    Paragraph::new(separator_line).style(sep_style),
                    Rect::new(inner.x + 1, screen_y, inner.width.saturating_sub(2), 1),
                );
                screen_y += 1;
            }
            content_y = separator_end;
        }

        // Section header (2 logical rows: title + blank spacer below)
        if item.is_section_start {
            if let Some(ref section_name) = item.section {
                let header_start = content_y;
                let header_end = content_y + 2;
                if header_end > scroll_offset && screen_y < inner.y + inner.height {
                    let skip_h = header_start.saturating_sub(scroll_offset) as u16;
                    if skip_h == 0 {
                        let section_style = Style::default()
                            .fg(theme.line_number_fg)
                            .add_modifier(Modifier::BOLD);
                        frame.render_widget(
                            Paragraph::new(format!("── {} ──", section_name)).style(section_style),
                            Rect::new(inner.x + 1, screen_y, inner.width.saturating_sub(2), 1),
                        );
                        screen_y += 1;
                    }
                    if skip_h <= 1 && screen_y < inner.y + inner.height {
                        screen_y += 1; // blank line after header
                    }
                }
                content_y = header_end;
            }
        }

        let control_height = item.control.control_height() as usize;
        let item_start = content_y;
        let item_end = content_y + control_height;

        if item_end <= scroll_offset {
            content_y = item_end;
            continue;
        }
        if screen_y >= inner.y + inner.height {
            break;
        }

        let skip_rows = if item_start < scroll_offset {
            (scroll_offset - item_start) as u16
        } else {
            0
        };
        let visible_height = control_height.saturating_sub(skip_rows as usize);
        let available_height = (inner.y + inner.height).saturating_sub(screen_y) as usize;
        let render_height = visible_height.min(available_height);

        if render_height == 0 {
            content_y = item_end;
            continue;
        }

        let is_readonly = item.read_only;
        let is_focused = !is_readonly && !dialog.focus_on_buttons && dialog.selected_item == idx;
        let is_hovered = !is_readonly && dialog.hover_item == Some(idx);

        if is_focused || is_hovered {
            let bg_style = if is_focused {
                Style::default().bg(theme.settings_selected_bg)
            } else {
                Style::default().bg(theme.menu_hover_bg)
            };
            if item.control.is_composite() {
                let sub_row = item.control.focused_sub_row();
                if sub_row >= skip_rows && (sub_row - skip_rows) < render_height as u16 {
                    let highlight_y = screen_y + sub_row - skip_rows;
                    frame.render_widget(
                        Paragraph::new("").style(bg_style),
                        Rect::new(inner.x, highlight_y, inner.width, 1),
                    );
                }
            } else {
                for row in 0..render_height as u16 {
                    frame.render_widget(
                        Paragraph::new("").style(bg_style),
                        Rect::new(inner.x, screen_y + row, inner.width, 1),
                    );
                }
            }
        }

        // Indicator column: [>] focus  [●] modified  [ ] spacer
        let focus_indicator_width: u16 = 3;
        if is_focused {
            let indicator_y = if item.control.is_composite() {
                let sub_row = item.control.focused_sub_row();
                let visible_sub = sub_row.saturating_sub(skip_rows);
                if visible_sub < render_height as u16 {
                    screen_y + visible_sub
                } else {
                    screen_y
                }
            } else {
                screen_y
            };
            if indicator_y >= screen_y && indicator_y < screen_y + render_height as u16 {
                let indicator_style = Style::default()
                    .fg(theme.settings_selected_fg)
                    .add_modifier(Modifier::BOLD);
                frame.render_widget(
                    Paragraph::new(">").style(indicator_style),
                    Rect::new(inner.x, indicator_y, 1, 1),
                );
            }
        }
        if item.modified && skip_rows == 0 {
            let modified_style = Style::default().fg(theme.settings_selected_fg);
            frame.render_widget(
                Paragraph::new("").style(modified_style),
                Rect::new(inner.x + 1, screen_y, 1, 1),
            );
        }

        let control_area = Rect::new(
            inner.x + focus_indicator_width,
            screen_y,
            inner.width.saturating_sub(focus_indicator_width),
            render_height as u16,
        );
        let _layout = render_control(
            frame,
            control_area,
            &item.control,
            &item.name,
            skip_rows,
            theme,
            Some(label_col_width.saturating_sub(focus_indicator_width)),
            item.read_only,
            item.is_null,
        );

        screen_y += render_height as u16;
        content_y = item_end;
    }

    if needs_scroll {
        let scrollbar_x = dialog_area.x + dialog_area.width - 3;
        let scrollbar_area = Rect::new(scrollbar_x, inner.y, 1, inner.height);
        let scrollbar_state =
            ScrollbarState::new(total_content_height, viewport_height, scroll_offset);
        let scrollbar_colors = ScrollbarColors::from_theme(theme);
        render_scrollbar(frame, scrollbar_area, &scrollbar_state, &scrollbar_colors);
    }
}

/// Render the Save / Cancel / Delete button row.
///
/// Order: [Save] [Cancel]  [Delete …] — Delete is separated by a wider gap so
/// the destructive action cannot be reached by accidentally pressing Tab one
/// extra time.  Delete uses a per-entry label (map key or generic "item") so
/// the user knows what will be removed before committing.
fn render_entry_buttons(
    frame: &mut Frame,
    dialog_area: Rect,
    dialog: &super::entry_dialog::EntryDialogState,
    theme: &Theme,
) {
    let button_y = dialog_area.y + dialog_area.height - 2;
    let has_delete = !dialog.is_new && !dialog.no_delete;
    let delete_label = entry_delete_button_label(dialog);
    let buttons: Vec<String> = if has_delete {
        vec![
            "[ Save ]".to_string(),
            "[ Cancel ]".to_string(),
            delete_label,
        ]
    } else {
        vec!["[ Save ]".to_string(), "[ Cancel ]".to_string()]
    };
    let delete_idx = if has_delete {
        Some(buttons.len() - 1)
    } else {
        None
    };

    const BUTTON_GAP: u16 = 2;
    const DELETE_GAP: u16 = 6;
    let button_width: u16 = buttons
        .iter()
        .enumerate()
        .map(|(i, b)| {
            let gap = if Some(i) == delete_idx {
                DELETE_GAP
            } else if i == 0 {
                0
            } else {
                BUTTON_GAP
            };
            b.len() as u16 + gap
        })
        .sum();
    let button_x = dialog_area.x + (dialog_area.width.saturating_sub(button_width)) / 2;

    let mut x = button_x;
    for (idx, label) in buttons.iter().enumerate() {
        let is_selected = dialog.focus_on_buttons && dialog.focused_button == idx;
        let is_hovered = dialog.hover_button == Some(idx);
        let is_delete = Some(idx) == delete_idx;

        if idx > 0 {
            x += if is_delete { DELETE_GAP } else { BUTTON_GAP };
        }
        if is_selected {
            let indicator_style = Style::default()
                .fg(theme.settings_selected_fg)
                .add_modifier(Modifier::BOLD);
            frame.render_widget(
                Paragraph::new(">").style(indicator_style),
                Rect::new(x.saturating_sub(2), button_y, 1, 1),
            );
        }

        // Selected Delete keeps red fg as a "still destructive" cue while
        // REVERSED signals keyboard focus — consistent with other selected items.
        let style = if is_selected && is_delete {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD | Modifier::REVERSED)
        } else if is_selected {
            Style::default()
                .fg(theme.popup_selection_fg)
                .bg(theme.popup_selection_bg)
                .add_modifier(Modifier::BOLD | Modifier::REVERSED)
        } else if is_hovered && is_delete {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .bg(theme.menu_hover_bg)
                .add_modifier(Modifier::BOLD)
        } else if is_hovered {
            Style::default()
                .fg(theme.menu_hover_fg)
                .bg(theme.menu_hover_bg)
        } else if is_delete {
            Style::default()
                .fg(theme.diagnostic_error_fg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme.editor_fg)
        };

        frame.render_widget(
            Paragraph::new(label.as_str()).style(style),
            Rect::new(x, button_y, label.len() as u16, 1),
        );
        x += label.len() as u16;
    }
}

/// Render the field-description hint (row above buttons) and the keybinding
/// legend (row below buttons) at the bottom of the entry dialog.
fn render_entry_footer(
    frame: &mut Frame,
    dialog_area: Rect,
    inner: Rect,
    dialog: &super::entry_dialog::EntryDialogState,
    theme: &Theme,
) {
    let button_y = dialog_area.y + dialog_area.height - 2;
    let helper_y = button_y.saturating_sub(1);

    // One line of contextual help immediately above the buttons.
    if !dialog.focus_on_buttons && helper_y > inner.y {
        // When the cursor is on a TextList's "[+] Add new" row the focused
        // item slot is None; surface a caption that names what Enter/Esc do
        // rather than silently absorbing keystrokes.
        let pending_list_caption = dialog.current_item().and_then(|it| {
            if let SettingControl::TextList(state) = &it.control {
                if state.focused_item.is_none() {
                    return Some(if !state.pending_active && state.new_item_text.is_empty() {
                        "Press Enter (or type) to add a new item; ↓/Tab to leave"
                    } else if state.new_item_text.is_empty() {
                        "Type the new item — Enter to add, Esc to cancel"
                    } else {
                        "Editing new item — Enter to add, Esc to cancel"
                    });
                }
            }
            None
        });

        let text: Option<String> = pending_list_caption.map(String::from).or_else(|| {
            dialog
                .current_item()
                .and_then(|it| it.description.as_deref())
                .filter(|d| !d.is_empty())
                .map(String::from)
        });

        if let Some(text) = text {
            let max_width = dialog_area.width.saturating_sub(4) as usize;
            let truncated: String = text.chars().take(max_width).collect();
            let helper_style = Style::default()
                .fg(theme.line_number_fg)
                .add_modifier(Modifier::ITALIC);
            frame.render_widget(
                Paragraph::new(truncated).style(helper_style),
                Rect::new(
                    dialog_area.x + 2,
                    helper_y,
                    dialog_area.width.saturating_sub(4),
                    1,
                ),
            );
        }
    }

    // Keybinding legend / validation warning on the row below the buttons.
    let is_editing_json = dialog.editing_text && dialog.is_editing_json();
    let (has_invalid_json, is_json_control) = dialog
        .current_item()
        .map(|item| match &item.control {
            SettingControl::Text(state) => (!state.is_valid(), false),
            SettingControl::Json(state) => (!state.is_valid(), is_editing_json),
            _ => (false, false),
        })
        .unwrap_or((false, false));

    let help_area = Rect::new(
        dialog_area.x + 2,
        button_y + 1,
        dialog_area.width.saturating_sub(4),
        1,
    );

    let (text, style) = if has_invalid_json && !is_json_control {
        (
            "⚠ Invalid JSON - fix before leaving field",
            Style::default().fg(theme.diagnostic_warning_fg),
        )
    } else if has_invalid_json {
        (
            "⚠ Invalid JSON",
            Style::default().fg(theme.diagnostic_warning_fg),
        )
    } else if is_json_control {
        (
            "↑↓←→:Move  Enter:Newline  Tab/Esc:Exit",
            Style::default().fg(theme.line_number_fg),
        )
    } else if dialog.editing_text {
        (
            "Enter/Tab:Commit field  Esc:Cancel",
            Style::default().fg(theme.line_number_fg),
        )
    } else {
        // The `●:modified` legend is the only place that explains the row-indicator.
        (
            "↑↓:Navigate  Tab:Fields/Buttons  Enter:Edit  Ctrl+S:Save  Ctrl+R:Reset  Esc:Cancel  ●:modified",
            Style::default().fg(theme.line_number_fg),
        )
    };
    frame.render_widget(Paragraph::new(text).style(style), help_area);
}

/// Draw the entry-edit dialog into `parent_area`.
fn render_entry_dialog_inner(
    frame: &mut Frame,
    parent_area: Rect,
    dialog: &mut super::entry_dialog::EntryDialogState,
    theme: &Theme,
) {
    let dialog_width = (parent_area.width * 85 / 100).clamp(50, 90);
    let dialog_height = (parent_area.height * 90 / 100).max(15);
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    frame.render_widget(Clear, dialog_area);

    // Title shows "• modified" when the form has uncommitted edits.
    let title = if dialog.is_dirty() {
        format!(" {} • modified ", dialog.title)
    } else {
        format!(" {} ", dialog.title)
    };
    let border_color = if dialog.is_dirty() {
        theme.diagnostic_warning_fg
    } else {
        theme.popup_border_fg
    };
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(border_color))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    // Reserve 2 lines at the bottom for the button row + keybinding hint.
    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(5),
    );

    let max_label_width = (inner.width / 2).max(20);
    let label_col_width = dialog
        .items
        .iter()
        .map(|item| item.name.len() as u16 + 2)
        .filter(|&w| w <= max_label_width)
        .max()
        .unwrap_or(20)
        .min(max_label_width);

    let total_content_height = dialog.total_content_height();
    let viewport_height = inner.height as usize;
    dialog.viewport_height = viewport_height;
    let scroll_offset = dialog.scroll_offset;

    render_entry_items(
        frame,
        dialog_area,
        inner,
        dialog,
        theme,
        label_col_width,
        scroll_offset,
        total_content_height,
        viewport_height,
    );
    render_entry_buttons(frame, dialog_area, dialog, theme);
    render_entry_footer(frame, dialog_area, inner, dialog, theme);
}

/// Render the help overlay showing keyboard shortcuts
fn render_help_overlay(frame: &mut Frame, parent_area: Rect, theme: &Theme) {
    // Define the help content
    let help_items = [
        (
            "Navigation",
            vec![
                ("↑ / ↓", "Move up/down"),
                ("Tab", "Switch between categories and settings"),
                ("Enter", "Activate/toggle setting"),
            ],
        ),
        (
            "Search",
            vec![
                ("/", "Start search"),
                ("Esc", "Cancel search"),
                ("↑ / ↓", "Navigate results"),
                ("Enter", "Jump to result"),
            ],
        ),
        (
            "Actions",
            vec![
                ("Ctrl+S", "Save settings"),
                ("Esc", "Close settings"),
                ("?", "Toggle this help"),
            ],
        ),
    ];

    // Calculate dialog size
    let dialog_width = 50.min(parent_area.width.saturating_sub(4));
    let dialog_height = 20.min(parent_area.height.saturating_sub(4));

    // Center the dialog
    let dialog_x = parent_area.x + (parent_area.width.saturating_sub(dialog_width)) / 2;
    let dialog_y = parent_area.y + (parent_area.height.saturating_sub(dialog_height)) / 2;
    let dialog_area = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);

    // Clear and draw border
    frame.render_widget(Clear, dialog_area);

    let block = Block::default()
        .title(" Keyboard Shortcuts ")
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.menu_highlight_fg))
        .style(Style::default().bg(theme.popup_bg));
    frame.render_widget(block, dialog_area);

    // Inner area
    let inner = Rect::new(
        dialog_area.x + 2,
        dialog_area.y + 1,
        dialog_area.width.saturating_sub(4),
        dialog_area.height.saturating_sub(2),
    );

    let mut y = inner.y;

    for (section_name, bindings) in &help_items {
        if y >= inner.y + inner.height.saturating_sub(1) {
            break;
        }

        // Section header
        let header_style = Style::default()
            .fg(theme.menu_active_fg)
            .add_modifier(Modifier::BOLD);
        frame.render_widget(
            Paragraph::new(*section_name).style(header_style),
            Rect::new(inner.x, y, inner.width, 1),
        );
        y += 1;

        for (key, description) in bindings {
            if y >= inner.y + inner.height.saturating_sub(1) {
                break;
            }

            let key_style = Style::default()
                .fg(theme.popup_text_fg)
                .bg(theme.split_separator_fg);
            let desc_style = Style::default().fg(theme.popup_text_fg);

            let line = Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled(format!(" {} ", key), key_style),
                Span::styled(format!("  {}", description), desc_style),
            ]);
            frame.render_widget(Paragraph::new(line), Rect::new(inner.x, y, inner.width, 1));
            y += 1;
        }

        y += 1; // Blank line between sections
    }

    // Footer hint
    let footer_y = dialog_area.y + dialog_area.height - 2;
    let footer = "Press ? or Esc or Enter to close";
    let footer_style = Style::default().fg(theme.line_number_fg);
    let centered_x = inner.x + (inner.width.saturating_sub(footer.len() as u16)) / 2;
    frame.render_widget(
        Paragraph::new(footer).style(footer_style),
        Rect::new(centered_x, footer_y, footer.len() as u16, 1),
    );
}

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

    #[test]
    fn truncate_chars_with_ellipsis_ascii_fits() {
        assert_eq!(truncate_chars_with_ellipsis("hi", 10), "hi");
    }

    #[test]
    fn truncate_chars_with_ellipsis_ascii_truncates() {
        assert_eq!(truncate_chars_with_ellipsis("hello world!", 8), "hello...");
    }

    #[test]
    fn truncate_chars_with_ellipsis_multibyte_does_not_panic() {
        // Regression: byte-slicing this string at `max - 3` would land
        // inside the 3-byte UTF-8 sequence for `こ` and panic — same class
        // as #1718.
        let out = truncate_chars_with_ellipsis("こんにちは世界からのテスト", 8);
        assert!(out.ends_with("..."));
        // 5 kept chars + 3 ellipsis chars = 8 total chars.
        assert_eq!(out.chars().count(), 8);
    }

    #[test]
    fn truncate_chars_with_ellipsis_emoji_does_not_panic() {
        let out = truncate_chars_with_ellipsis("📦📦📦📦📦📦📦📦", 5);
        assert!(out.ends_with("..."));
        assert_eq!(out.chars().count(), 5);
    }

    // Basic compile test - actual rendering tests would need a test backend
    #[test]
    fn test_control_layout_info() {
        let toggle = ControlLayoutInfo::Toggle(Rect::new(0, 0, 10, 1));
        assert!(matches!(toggle, ControlLayoutInfo::Toggle(_)));

        let number = ControlLayoutInfo::Number {
            decrement: Rect::new(0, 0, 3, 1),
            increment: Rect::new(4, 0, 3, 1),
            value: Rect::new(8, 0, 5, 1),
        };
        assert!(matches!(number, ControlLayoutInfo::Number { .. }));
    }
}