fresh-editor 0.3.2

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
//! E2E tests for the settings modal

use crate::common::harness::EditorTestHarness;
use crossterm::event::{KeyCode, KeyModifiers};

/// Test opening settings modal with Ctrl+,
#[test]
fn test_open_settings_modal() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Render initial state
    harness.render().unwrap();

    // Settings should not be visible initially
    harness.assert_screen_not_contains("Settings");

    // Open settings with Ctrl+,
    harness.open_settings().unwrap();

    // Settings modal should now be visible
    harness.assert_screen_contains("Settings");
}

/// Test closing settings modal with Escape
#[test]
fn test_close_settings_with_escape() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();
    harness.assert_screen_contains("Settings");

    // Close with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Settings should be closed
    harness.assert_screen_not_contains("Settings");
}

/// Test settings navigation with arrow keys
#[test]
fn test_settings_navigation() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate down in categories
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Switch to settings panel with Tab
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Navigate down in settings
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test settings search with /
#[test]
fn test_settings_search() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Start search with /
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type a search query
    harness
        .send_key(KeyCode::Char('t'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('h'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('m'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show search results
    // The search query "theme" should match theme-related settings

    // Cancel search with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test settings help overlay with ?
#[test]
fn test_settings_help_overlay() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Open help with ?
    harness
        .send_key(KeyCode::Char('?'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Help overlay should be visible
    harness.assert_screen_contains("Keyboard Shortcuts");

    // Close help with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Settings should still be visible
    harness.assert_screen_contains("Settings");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test search text input is displayed in search box
#[test]
fn test_settings_search_text_displays() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Start search with /
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show search mode indicator
    harness.assert_screen_contains("Type to search");

    // Type search query "tab"
    harness
        .send_key(KeyCode::Char('t'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('b'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Search text should be visible in the search box
    harness.assert_screen_contains("tab");

    // Should show results count (format: "X-Y of Z" when scrollable, or "N results" when all visible)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(" of ") || screen.contains("results"),
        "Should show result count indicator"
    );

    // Close with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test toggling a setting shows modified indicator
#[test]
fn test_settings_toggle_shows_modified() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find "Check For Updates" (a toggle setting)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Toggle the setting
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator in title
    harness.assert_screen_contains("modified");

    // Close and discard
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    // Select "Discard" (one right from "Save and Exit")
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test confirmation dialog shows pending changes
#[test]
fn test_confirmation_dialog_shows_changes() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find "Check For Updates"
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Press Escape to trigger confirmation dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Dialog should show
    harness.assert_screen_contains("Unsaved Changes");
    harness.assert_screen_contains("You have unsaved changes");

    // Should show the actual change (path contains "check_for_updates")
    harness.assert_screen_contains("check_for_updates");

    // Cancel dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test confirmation dialog button navigation
#[test]
fn test_confirmation_dialog_button_navigation() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find and toggle a setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Open confirmation dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // First button should be selected (Save and Exit has > indicator)
    harness.assert_screen_contains(">[ Save and Exit ]");

    // Navigate right to Discard
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Discard should now be selected
    harness.assert_screen_contains(">[ Discard ]");

    // Navigate right to Cancel
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Cancel should now be selected
    harness.assert_screen_contains(">[ Cancel ]");

    // Press Enter on Cancel to close dialog
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Dialog should be closed but settings still open
    harness.assert_screen_not_contains("Unsaved Changes");
    harness.assert_screen_contains("Settings");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test selection via keyboard navigation works
/// Settings panel shows focus indicator ">" on focused item
#[test]
fn test_settings_selection_indicator() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Switch to settings panel with Tab
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Settings panel should show focus indicator ">" on selected item
    // General category has: Active Keybinding Map (first item)
    // Format: ">  " (3-char indicator area: focus, modified, space)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Active Keybinding Map"),
        "Focus indicator '>' should appear before focused item in settings panel. Screen:\n{}",
        screen
    );

    // Navigate down
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Now Check For Updates should have the focus indicator
    // Format: ">  " (3-char indicator area: focus, modified, space)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Check For Updates"),
        "Focus indicator '>' should move to Check For Updates. Screen:\n{}",
        screen
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test number input increment with Right arrow
#[test]
fn test_settings_number_increment() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for a number setting (mouse hover delay)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The default value is 500
    harness.assert_screen_contains("500");

    // Press Right arrow to increment
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Value should now be 501
    harness.assert_screen_contains("501");

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Press Left arrow to decrement back
    harness.send_key(KeyCode::Left, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Value should be back to 500
    harness.assert_screen_contains("500");

    // Close settings (no changes now)
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test number input decrement with Left arrow
#[test]
fn test_settings_number_decrement() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay (number setting) - same as increment test but decrement
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The default value is 500
    harness.assert_screen_contains("500");

    // Press Left arrow to decrement
    harness.send_key(KeyCode::Left, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Value should now be 499
    harness.assert_screen_contains("499");

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test dropdown cycling with Enter key
#[test]
fn test_settings_dropdown_cycle() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "theme" (a dropdown setting)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "theme".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Check initial theme value (should be "dark")
    let initial_screen = harness.screen_to_string();
    let has_dark = initial_screen.contains("dark");

    // Press Enter to cycle to next option
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // If it was "dark", it should now be "light" or another theme option
    // The exact value depends on available themes, but it should change
    if has_dark {
        // Should show modified indicator since we changed the value
        harness.assert_screen_contains("modified");
    }

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test dropdown cycling with Right arrow
#[test]
fn test_settings_dropdown_increment() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "theme" (a dropdown setting)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "theme".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Get initial screen
    let initial_screen = harness.screen_to_string();

    // Open dropdown with Enter, navigate down, confirm with Enter
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Get new screen
    let new_screen = harness.screen_to_string();

    // The dropdown value should have changed (screens should differ)
    // We can check that modified indicator appears
    if initial_screen != new_screen {
        harness.assert_screen_contains("modified");
    }

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test scrolling through settings list
#[test]
fn test_settings_scrolling() {
    // Use a smaller height to ensure scrolling is needed
    let mut harness = EditorTestHarness::new(100, 25).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate to Editor category which has many settings
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Switch to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Get initial screen to check first item
    let initial_screen = harness.screen_to_string();

    // Navigate down many times to trigger scrolling
    for _ in 0..15 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Get new screen - should have scrolled, showing different items
    let scrolled_screen = harness.screen_to_string();

    // The screens should be different due to scrolling
    assert_ne!(
        initial_screen, scrolled_screen,
        "Screen should change after scrolling down"
    );

    // Some setting items should still be visible after scrolling
    // (selection is shown via background highlight, not a text indicator)

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test scrollbar appears when there are many settings
#[test]
fn test_settings_scrollbar_visible() {
    // Use a smaller height to ensure scrollbar is needed
    let mut harness = EditorTestHarness::new(100, 25).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate to Editor category which has many settings
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Switch to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Scrollbar should be visible (rendered with background colors)
    // Settings panel uses a popup layout, so the scrollbar may be at the right edge
    // of the settings area, not necessarily the rightmost terminal column.
    // Check any column in the settings area for scrollbar presence.
    let has_scrollbar = (40..100).any(|col| harness.has_scrollbar_at_column(col));
    assert!(
        has_scrollbar,
        "Settings panel should have a visible scrollbar (checked columns 40-99)"
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test search jump scrolls to selected item
#[test]
fn test_settings_search_jump_scrolls() {
    // Use a smaller height to ensure scrolling is needed
    let mut harness = EditorTestHarness::new(100, 25).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for a setting that's likely at the bottom of a category
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "wrap".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The searched term should be visible after jumping
    // (selection is shown via background highlight, not a text indicator)
    harness.assert_screen_contains("Wrap");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that clicking on a search result navigates to that setting
///
/// When search results are displayed, clicking on one should:
/// 1. Navigate to that setting (same as pressing Enter)
/// 2. Exit search mode
/// 3. Show the setting in the settings panel
#[test]
fn test_settings_search_result_click_navigates() {
    let mut harness = EditorTestHarness::new(100, 30).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "tab" which should match "Tab Size" in Editor category
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "tab".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Should show search results with "Tab Size"
    harness.assert_screen_contains("Tab Size");

    // Find the position of "Tab Size" on screen
    let screen = harness.screen_to_string();
    let result_pos = screen
        .lines()
        .enumerate()
        .find_map(|(row, line)| line.find("Tab Size").map(|col| (col as u16, row as u16)))
        .expect("Should find Tab Size in search results");

    // Click on the search result
    harness.mouse_click(result_pos.0 + 2, result_pos.1).unwrap();
    harness.render().unwrap();

    // After clicking, search mode should be closed
    // "Type to search" appears in search mode - should not be visible now
    assert!(
        !harness.screen_to_string().contains("Type to search"),
        "Search mode should be closed after clicking a result"
    );

    // The setting should be visible in the settings panel (not search results)
    // We should see "Tab Size" as the selected setting with its control
    harness.assert_screen_contains("Tab Size");

    // We should be in the Editor category now (Tab Size is an Editor setting)
    harness.assert_screen_contains("Editor");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test theme dropdown can be cycled with Enter or Right arrow
/// BUG: Theme dropdown doesn't cycle - it stays on the same value
#[test]
#[ignore] // TODO: Fix theme dropdown cycling - currently broken
fn test_settings_theme_dropdown_cycle() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for theme setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "theme".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to theme setting
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should be on Theme setting with current value (high-contrast is default)
    harness.assert_screen_contains("Theme");
    let initial_screen = harness.screen_to_string();
    let has_high_contrast = initial_screen.contains("high-contrast");

    // Press Enter to cycle to next theme option
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The theme should have changed - this is currently broken
    // Expected: theme changes to next option (e.g., monokai, solarized-dark)
    // Actual: theme stays on high-contrast
    let after_enter = harness.screen_to_string();

    if has_high_contrast {
        // After pressing Enter, it should cycle to a different theme
        // This assertion will fail with the current bug
        assert!(
            !after_enter.contains("high-contrast") || after_enter.contains("modified"),
            "Theme should change after pressing Enter, but it stayed the same"
        );
    }

    // Try Right arrow as well
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    let after_right = harness.screen_to_string();

    // Should show modified indicator if theme changed
    // This will also fail with the current bug
    assert!(
        after_right.contains("modified"),
        "Theme dropdown should cycle with Right arrow and show modified indicator"
    );

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

// =============================================================================
// CRITICAL BUG TESTS - These tests should fail until the bugs are fixed
// =============================================================================

/// BUG: Opening Settings from terminal mode causes keystrokes to go to terminal
///
/// When the user is in terminal mode and opens the Settings dialog (via Ctrl+,
/// or command palette), keyboard input should go to the Settings dialog, not
/// to the terminal behind it. Currently, the terminal continues to capture
/// input even when Settings is open, requiring users to manually exit terminal
/// mode first.
///
/// Expected behavior: Settings dialog captures all keyboard input when open
/// Actual behavior: Terminal behind dialog receives keystrokes
#[test]
fn test_settings_from_terminal_mode_captures_input() {
    use portable_pty::{native_pty_system, PtySize};

    // Skip if PTY not available
    if native_pty_system()
        .openpty(PtySize {
            rows: 1,
            cols: 1,
            pixel_width: 0,
            pixel_height: 0,
        })
        .is_err()
    {
        eprintln!("Skipping test: PTY not available");
        return;
    }

    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open a terminal (this enters terminal mode automatically)
    harness.editor_mut().open_terminal();
    harness.render().unwrap();

    // Verify we're in terminal mode
    assert!(
        harness.editor().is_terminal_mode(),
        "Should be in terminal mode after opening terminal"
    );

    // Open settings with Ctrl+, (this should work even in terminal mode)
    harness.open_settings().unwrap();

    // Settings should be visible
    harness.assert_screen_contains("Settings");

    // Now try to use Settings navigation - press Down to navigate categories
    // Categories: General, Clipboard, Editor, ...
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Clipboard
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Editor
    harness.render().unwrap();

    // The Settings should respond to navigation, not the terminal
    // If the bug exists, the Down key would have gone to the terminal shell
    // and the Settings category wouldn't have changed

    // Navigate down should move from General to Editor
    // We can verify by switching to settings panel and checking we see Editor settings
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Editor category has settings organized by sections - Completion section comes first
    // If Down key worked in Settings, we should now be viewing Editor settings
    // Check for a setting in the visible Completion section
    harness.assert_screen_contains("Quick Suggestions");

    // Clean up - close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // If there's an unsaved changes dialog, dismiss it
    if harness.screen_to_string().contains("Unsaved Changes") {
        // Select Discard
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();
    }
}

/// Test footer buttons (Reset/Save/Cancel) are accessible via keyboard
///
/// The Settings dialog has footer buttons [Reset] [Save] [Cancel] that can
/// be reached using Tab navigation.
///
/// Tab cycles through: categories -> settings -> footer buttons
#[test]
fn test_settings_footer_buttons_keyboard_accessible() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();
    harness.assert_screen_contains("Settings");

    // Make a change so footer buttons become relevant
    // Search for and toggle a setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Tab to footer - from settings panel, Tab goes to footer
    // First button (Layer) should be selected
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Layer button should be selected (has > indicator)
    harness.assert_screen_contains(">[ User ]");

    // Tab through all footer buttons: Layer(0) → Reset(1) → Save(2) → Cancel(3)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Reset ]");

    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Save ]");

    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Cancel button should now be selected
    harness.assert_screen_contains(">[ Cancel ]");

    // Press Enter on Cancel - this shows confirmation dialog when there are changes
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Confirmation dialog should appear
    harness.assert_screen_contains("Unsaved Changes");

    // Navigate to Discard button (Right from Save)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Press Enter to discard and close
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Settings should be closed
    harness.assert_screen_not_contains("Settings");
}

/// Test changing theme, saving, and verifying the theme is applied
#[test]
fn test_settings_change_theme_and_save() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Get initial theme name
    let initial_theme = harness.editor().theme().name.clone();

    // Open settings
    harness.open_settings().unwrap();

    // Verify settings is open via state check
    assert!(
        harness.editor().is_settings_open(),
        "Settings should be open after Ctrl+,"
    );

    // Search for theme setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "theme".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to theme setting
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Open dropdown with Enter, navigate to a different theme, confirm
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Navigate down one option to select a different theme
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Confirm selection with Enter
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Save with Ctrl+S (works from any panel)
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify settings is closed via state check
    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after saving"
    );

    // Verify theme changed via state check
    let new_theme = harness.editor().theme().name.clone();
    assert_ne!(
        new_theme, initial_theme,
        "Theme should have changed after saving. Was: {}, Now: {}",
        initial_theme, new_theme
    );
}

/// Test settings descriptions are rendered properly
///
/// Descriptions should:
/// 1. Not be cut off mid-word (e.g., "hether" instead of "whether")
/// 2. Start with lowercase letter (since they're not sentence-initial)
/// 3. Contain meaningful info (not just repeat the name)
#[test]
fn test_settings_descriptions_render_properly() {
    let mut harness = EditorTestHarness::new(120, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate to Editor category which has settings with descriptions
    // Categories: General, Clipboard, Editor, ...
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Clipboard
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Editor
    harness.render().unwrap();

    // Switch to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    let screen = harness.screen_to_string();

    // Check that descriptions are NOT cut off mid-word at the start
    // These patterns would indicate broken descriptions (word starting with cut-off text):
    // We check for patterns like " hether" (space + truncated word) to find words starting wrong
    assert!(
        !screen.contains(" hether") && !screen.contains("|hether"), // should be "whether"
        "Description should not be cut mid-word (found 'hether' at start of word)"
    );
    assert!(
        !screen.contains(" oll interval"), // should be "poll interval"
        "Description should not be cut mid-word (found 'oll interval')"
    );
    assert!(
        !screen.contains(" yntax "), // should be "syntax"
        "Description should not be cut mid-word"
    );

    // Check that we can see some expected description content
    // Settings are now organized by section, so we check for Completion section content
    // (which comes first alphabetically)
    assert!(
        screen.contains("completion")
            || screen.contains("Completion")
            || screen.contains("suggest"),
        "Should show completion-related description (first visible section)"
    );

    // Verify descriptions are rendered - check for section header or setting content
    assert!(
        screen.contains("Enter") || screen.contains("trigger") || screen.contains("suggestions"),
        "Description containing completion behavior should be visible"
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that global shortcuts (Ctrl+P, Ctrl+Q) are consumed by settings dialog
///
/// When the settings dialog is open, it should capture all keyboard input
/// and not let shortcuts like Ctrl+P (command palette) or Ctrl+Q (quit) through.
#[test]
fn test_settings_consumes_global_shortcuts() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Verify settings is open
    assert!(
        harness.editor().is_settings_open(),
        "Settings should be open"
    );

    // Try Ctrl+P (command palette) - should be consumed, not open palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Settings should still be open (Ctrl+P was consumed)
    assert!(
        harness.editor().is_settings_open(),
        "Settings should still be open after Ctrl+P - shortcut should be consumed"
    );

    // Verify command palette is NOT open
    harness.assert_screen_not_contains("Command Palette");

    // Try Ctrl+Q (quit) - should be consumed, not quit
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Settings should still be open (Ctrl+Q was consumed)
    assert!(
        harness.editor().is_settings_open(),
        "Settings should still be open after Ctrl+Q - shortcut should be consumed"
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test Map control "[+] Add new" shows text input when Enter is pressed
#[test]
#[ignore] // TODO: Entry dialog now requires pressing Enter to start editing the Key field
fn test_map_control_add_new_shows_text_input() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "Keybinding Maps" which is a Map control
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "keybinding maps".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show "[+] Add new" for the empty map
    harness.assert_screen_contains("[+] Add new");

    // Press Enter to start editing
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The "[+] Add new" for Keybinding Maps should be replaced with a text input field
    // We can't check for absence of "[+] Add new" because other Map controls still show it
    // Instead, check that the text input field brackets appear (the underlined input area)
    // The input field shows as "[" followed by spaces and "]"

    // Type a name
    for c in "vim".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Should see "vim" in the input field
    harness.assert_screen_contains("vim");

    // Press Enter to add the entry
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Entry should be added and "[+] Add new" should appear below it
    harness.assert_screen_contains("vim");
    harness.assert_screen_contains("[+] Add new");

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Exit editing mode
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Close settings and verify confirm dialog shows the change
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Confirm dialog should show the map change
    harness.assert_screen_contains("Unsaved Changes");
    harness.assert_screen_contains("keybinding_maps");

    // Discard changes
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Smoke test: the File Explorer Width field renders with the default
/// 30% displayed as `"30%"` in the settings UI.
///
/// The field is a free-form string now ("30%" or "24" for columns),
/// so detailed parse/round-trip behavior lives in config unit tests.
#[test]
fn test_settings_file_explorer_width_shows_percent_suffix() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    assert_eq!(
        harness.config().file_explorer.width,
        fresh::config::ExplorerWidth::Percent(30),
    );

    harness.open_settings().unwrap();

    // Navigate to File Explorer category.
    // Categories in order: General, Clipboard, Editor, File Browser, File Explorer, ...
    for _ in 0..4 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();
    // Switch to the settings panel.
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    // File Explorer items (alphabetical): Auto Open On Last Buffer Close,
    // Custom Ignore Patterns, Preview Tabs, Respect Gitignore, Show Gitignored,
    // Show Hidden, Side, Width.
    for _ in 0..7 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    harness.assert_screen_contains("Width");
    harness.assert_screen_contains("30%");
}

/// Changing File Explorer Width through the Settings UI must take effect
/// immediately — the running editor's rendered explorer panel resizes without
/// a restart. Pre-fix, the Settings save path updated `config.file_explorer
/// .width` but left `self.file_explorer_width` stale, so the change appeared
/// to be silently ignored until next launch (and was then clobbered by the
/// workspace's saved width anyway — so effectively never).
#[test]
fn test_settings_file_explorer_width_applies_live() {
    use fresh::config::ExplorerWidth;
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open the file explorer at the default 30% width so it's actually
    // rendered and measurable before we touch settings.
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_file_explorer().unwrap();
    harness.render().unwrap();
    assert!(harness.editor().file_explorer_visible());

    // Sanity: on a 100-col terminal, 30% = 30 cols.
    let before = find_settings_explorer_border_col(&harness) + 1;
    assert_eq!(
        before, 30,
        "baseline: default 30% should render 30 cols on a 100-col terminal"
    );

    harness.open_settings().unwrap();

    // Navigate to File Explorer category (see
    // `test_settings_file_explorer_width_shows_percent_suffix` for the same
    // navigation pattern).
    for _ in 0..4 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    // File Explorer items (alphabetical): Auto Open On Last Buffer Close,
    // Custom Ignore Patterns, Preview Tabs, Respect Gitignore, Show Gitignored,
    // Show Hidden, Side, Width.
    for _ in 0..7 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();
    harness.assert_screen_contains("Width");

    // Enter editing mode on the Width field, type the columns form "24",
    // confirm, then save settings with Ctrl+S. The text input arms
    // replace-on-type when editing starts, so the first printable key
    // clears "30%" automatically — no separate select-all is needed.
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    for c in "24".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    assert!(
        !harness.editor().is_settings_open(),
        "Ctrl+S should close the settings dialog after saving"
    );

    // The config record must now reflect the new value…
    assert_eq!(
        harness.config().file_explorer.width,
        ExplorerWidth::Columns(24),
        "Settings save path must write Columns(24) to config"
    );

    // …and the rendered explorer panel must reflect it too — live, without a
    // restart.
    let after = find_settings_explorer_border_col(&harness) + 1;
    assert_eq!(
        after, 24,
        "explorer panel should re-render at 24 columns immediately after saving settings.\nScreen:\n{}",
        harness.screen_to_string()
    );
}

/// Helper: find the right border column of the file explorer on screen.
/// (Local copy so this test file doesn't depend on `file_explorer.rs`.)
fn find_settings_explorer_border_col(harness: &EditorTestHarness) -> u16 {
    for row in 0..40u16 {
        let text = harness.get_row_text(row);
        for (i, ch) in text.chars().enumerate() {
            if ch == '' {
                return i as u16;
            }
        }
    }
    for row in (0..40u16).rev() {
        let text = harness.get_row_text(row);
        for (i, ch) in text.chars().enumerate() {
            if ch == '' {
                return i as u16;
            }
        }
    }
    panic!(
        "Could not find file explorer border on screen.\nScreen:\n{}",
        harness.screen_to_string()
    );
}

/// Regression: toggling File Explorer → Show Hidden in the Settings UI and
/// saving must update the live file explorer's IgnorePatterns, not just the
/// config on disk. Width must also be propagated to the live explorer width.
#[test]
fn test_settings_file_explorer_toggles_propagate_to_runtime() {
    let mut harness = EditorTestHarness::with_temp_project(120, 40).unwrap();

    harness.editor_mut().focus_file_explorer();
    harness.wait_for_file_explorer().unwrap();

    // Sanity: both toggles start off.
    assert!(!harness
        .editor()
        .file_explorer()
        .unwrap()
        .ignore_patterns()
        .show_hidden());
    assert!(!harness
        .editor()
        .file_explorer()
        .unwrap()
        .ignore_patterns()
        .show_gitignored());

    harness.open_settings().unwrap();

    // Navigate to File Explorer category. Order (from test_settings_percentage):
    // General, Clipboard, Editor, File Browser, File Explorer.
    for _ in 0..4 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // File Explorer items (alphabetical): Auto Open On Last Buffer Close,
    // Custom Ignore Patterns, Preview Tabs, Respect Gitignore, Show Gitignored,
    // Show Hidden, Side, Width. Land on Show Gitignored and toggle.
    for _ in 0..4 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    // Move to Show Hidden and toggle.
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Tab to footer then navigate to Save (index 2) and press Enter.
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Reset
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Save
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after saving"
    );

    // Config persisted.
    assert!(harness.config().file_explorer.show_hidden);
    assert!(harness.config().file_explorer.show_gitignored);

    // Live IgnorePatterns updated — the bug was that only the config changed
    // and the running explorer kept its old state until next restart.
    let patterns = harness.editor().file_explorer().unwrap().ignore_patterns();
    assert!(
        patterns.show_hidden(),
        "live IgnorePatterns.show_hidden was not propagated from Settings save"
    );
    assert!(
        patterns.show_gitignored(),
        "live IgnorePatterns.show_gitignored was not propagated from Settings save"
    );
}

/// Test number input editing mode - enter editing, type value, confirm
#[test]
fn test_number_input_enter_editing_mode() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay (a number setting)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The default value is 500
    harness.assert_screen_contains("500");

    // Press Enter to start editing mode
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type Ctrl+A to select all, then type new value
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    for c in "750".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Should show 750
    harness.assert_screen_contains("750");

    // Press Enter to confirm
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test number input editing - Escape cancels and reverts value
#[test]
fn test_number_input_escape_cancels_editing() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Start editing mode
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Select all and type a new value
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    for c in "999".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Should show 999
    harness.assert_screen_contains("999");

    // Press Escape to cancel
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should revert back to 500
    harness.assert_screen_contains("500");

    // Close settings without changes
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test number input editing - cursor navigation works
#[test]
fn test_number_input_cursor_navigation() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Value is 500, start editing
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Move cursor to beginning with Home
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();

    // Type 1 at the beginning
    harness
        .send_key(KeyCode::Char('1'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show 1500 (1 inserted at beginning)
    harness.assert_screen_contains("1500");

    // Confirm the value
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test number input editing - backspace works
#[test]
fn test_number_input_backspace() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Value is 500, start editing (Enter selects all text)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Move cursor to end (deselects text so backspace deletes one char)
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();

    // Backspace should delete the last digit (0)
    harness
        .send_key(KeyCode::Backspace, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show 50
    harness.assert_screen_contains("50");

    // Backspace again should delete another digit (0)
    harness
        .send_key(KeyCode::Backspace, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show 5
    harness.assert_screen_contains("5");

    // Cancel editing
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should revert to 500
    harness.assert_screen_contains("500");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// BUG: Settings UI doesn't load saved values when reopened
///
/// When the user changes a setting, saves, closes settings, and reopens,
/// the Settings UI should show the saved value. Instead, it shows the
/// default value from when the editor was first started.
///
/// Expected: After saving tab_size = 5 and reopening, show 5
/// Actual: Shows 4 (the default)
#[test]
fn test_settings_loads_saved_values_on_reopen() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Verify initial tab_size is 4 (default)
    let initial_value = harness.config().editor.tab_size;
    assert_eq!(initial_value, 4, "Initial tab_size should be 4");

    // Open settings
    harness.open_settings().unwrap();

    // Search for "tab size" to find the setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "tab size".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show the default value of 4
    harness.assert_screen_contains("4");

    // Increment the value 1 time (4 -> 5)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should now show 5
    harness.assert_screen_contains("5");

    // Tab to footer (Layer button), then Tab to Save
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Reset
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Save
    harness.render().unwrap();

    // Press Enter to save
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Settings should be closed after saving
    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after saving"
    );

    // Verify the config was updated
    let saved_value = harness.config().editor.tab_size;
    assert_eq!(saved_value, 5, "tab_size should be 5 after saving");

    // CRITICAL TEST: Reopen settings and verify the saved value is displayed
    harness.open_settings().unwrap();

    // Search for the same setting again
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "tab size".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify the saved value is displayed (not the default)
    harness.assert_screen_contains("5");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that entering edit mode on a numeric field selects all text
///
/// When the user presses Enter on a numeric field to edit it, the text
/// should be selected so that typing immediately replaces the value,
/// rather than appending to the existing value.
///
/// Expected: Press Enter → type "100" → value becomes "100"
/// Actual (bug): Press Enter → type "100" → value becomes "500100"
#[test]
fn test_number_input_enter_selects_all_text() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for hover delay (a number setting with value 500)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "hover delay".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify initial value is 500
    harness.assert_screen_contains("500");

    // Press Enter to start editing mode
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type "100" - this should REPLACE the value, not append
    for c in "100".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Should show 100, not 500100 (the bug behavior)
    harness.assert_screen_contains("100");
    harness.assert_screen_not_contains("500100");

    // Press Enter to confirm
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test that the focused category shows a ">" selection indicator
///
/// When the categories panel is focused, the selected category should
/// have a ">" prefix to make the selection more visible.
/// Format is: "{selection}{modified} {name}" where:
/// - selection is ">" when selected and focused, " " otherwise
/// - modified is "●" when category has changes, " " otherwise
#[test]
fn test_category_selection_indicator_visible() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Categories panel is focused by default, should show ">" before General
    // General may have "●" modified indicator due to test defaults
    // Category format: "> " + modified_indicator + icon + name
    let screen = harness.screen_to_string();
    assert!(
        screen
            .lines()
            .any(|l| l.contains(">") && l.contains("General") && l.find(">") < l.find("General")),
        "Expected '>' indicator on General category when focused. Screen: {}",
        screen
    );

    // Navigate down to Clipboard category
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Now Clipboard should have the ">" indicator
    let screen = harness.screen_to_string();
    assert!(
        screen.lines().any(|l| l.contains(">")
            && l.contains("Clipboard")
            && l.find(">") < l.find("Clipboard")),
        "Expected '>' indicator on Clipboard category when focused. Screen: {}",
        screen
    );

    // Tab to settings panel (categories panel loses focus)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Now the ">" indicator before Clipboard should be gone (categories panel not focused)
    // The ">" may still appear as the item selection indicator in the settings panel,
    // so check that no line has ">" before "Clipboard"
    let screen = harness.screen_to_string();
    let has_focused_clipboard = screen.lines().any(|l| {
        if let (Some(gt_pos), Some(cb_pos)) = (l.find("> "), l.find("Clipboard")) {
            gt_pos < cb_pos
        } else {
            false
        }
    });
    assert!(
        !has_focused_clipboard,
        "Clipboard should not have '>' indicator when categories panel is unfocused. Screen: {}",
        screen
    );

    // But Clipboard should still be visible (just highlighted differently)
    harness.assert_screen_contains("Clipboard");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that Ctrl+S saves settings from any panel
///
/// Ctrl+S is a global shortcut that should save settings regardless
/// of which panel is currently focused.
#[test]
fn test_ctrl_s_saves_settings() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Verify initial check_for_updates is false (test default)
    assert!(!harness.config().check_for_updates);

    // Open settings
    harness.open_settings().unwrap();

    // Search for "check for updates" and toggle it
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Press Ctrl+S to save (should work from any panel)
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Settings should be closed after Ctrl+S
    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after Ctrl+S"
    );

    // Verify the setting was saved
    assert!(
        harness.config().check_for_updates,
        "check_for_updates should be true after saving"
    );
}

/// Test that entry dialog (Edit Value) shows focus indicator on focused field
#[test]
fn test_entry_dialog_focus_indicator() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // We're in General category. Tab to content panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Navigate down to find a language entry in the Languages list
    // Languages section is after Keybinding Maps and Keybindings sections
    // Navigate down many times to reach Languages
    for _ in 0..11 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Should see language items like "bash", "c", "rust", etc.
    let screen = harness.screen_to_string();
    // Find any language item that shows "[Enter to edit]" - that means we're on it
    if !screen.contains("[Enter to edit]") {
        // Navigate more to find language items
        for _ in 0..5 {
            harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        }
        harness.render().unwrap();
    }

    // Press Enter to open the Edit Value dialog on the current language
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Entry dialog should be open
    harness.assert_screen_contains("Edit Value");

    // Read-only fields (Key) are displayed first but not focusable
    // Key should be visible without focus indicator
    harness.assert_screen_contains("Key:");

    // The focused field should have a ">" indicator
    // First editable field (Auto Close) should be focused by default
    // (fields are sorted alphabetically within a language entry dialog)
    // Format: ">  " or ">● " (3-char indicator area: focus, modified, space)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Auto Close") || screen.contains(">● Auto Close"),
        "Focus indicator '>' should appear before Auto Close. Screen:\n{}",
        screen
    );

    // Navigate down to next editable field
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Now "Auto Indent" should be focused with ">" indicator
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Auto Indent") || screen.contains(">● Auto Indent"),
        "Focus indicator '>' should appear before Auto Indent. Screen:\n{}",
        screen
    );

    // Close dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that [+] Add new button in entry dialog works for TextList items
#[test]
fn test_entry_dialog_add_new_textlist_item() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate to Languages section - Tab to content, then down to a language
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    for _ in 0..10 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Open a language entry dialog
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("Edit Value");

    // Navigate to Extensions section which has "[+] Add new"
    // Fields in order: Key, Auto Indent, Comment Prefix, Extensions (3 downs)
    for _ in 0..3 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // The Extensions section should have items and "[+] Add new"
    harness.assert_screen_contains("[+] Add new");

    // Get current screen to compare after adding
    let before_add = harness.screen_to_string();

    // Press Enter to start editing the "[+] Add new" field
    // This focuses the add-new input and enables typing
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type a new extension value
    for c in "test_ext".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // The typed text should be visible
    harness.assert_screen_contains("test_ext");

    // Press Enter to add the item
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After adding, the item should appear in the list
    let after_add = harness.screen_to_string();
    assert_ne!(
        before_add, after_add,
        "Screen should change after adding item"
    );

    // The new item should be visible
    harness.assert_screen_contains("test_ext");

    // Close dialog without saving
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that [x] delete button in entry dialog works via keyboard (Delete key)
#[test]
fn test_entry_dialog_delete_textlist_item() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Navigate to Languages section - Tab to content, then down to a language
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    for _ in 0..10 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Open a language entry dialog
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("Edit Value");

    // Navigate to Extensions section which has existing items
    // The ">" focus indicator may be on the section header or on a sub-item line
    // below it (for composite controls like TextList).
    let mut attempts = 0;
    loop {
        harness.render().unwrap();
        let screen = harness.screen_to_string();
        // Check if Extensions header is focused directly
        if screen.contains(">  Extensions") || screen.contains(">● Extensions") {
            break;
        }
        // Also check if ">" is on a sub-item line near the Extensions header
        let lines: Vec<&str> = screen.lines().collect();
        let mut found_near = false;
        for (i, line) in lines.iter().enumerate() {
            if line.contains(">") && !line.contains("Extensions") {
                for offset in 1..=3 {
                    if i >= offset && lines[i - offset].contains("Extensions:") {
                        found_near = true;
                        break;
                    }
                }
            }
            if found_near {
                break;
            }
        }
        if found_near {
            break;
        }
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        attempts += 1;
        assert!(
            attempts < 100,
            "Could not find Extensions section after {} Down presses.\nScreen:\n{}",
            attempts,
            screen
        );
    }

    // The Extensions section should have items and "[x]" delete buttons
    harness.assert_screen_contains("[x]");

    // First, add an item so we have something to delete
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type a new extension value
    for c in "to_delete".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Press Enter to add the item
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify the item was added
    harness.assert_screen_contains("to_delete");

    // Now navigate UP to focus on the newly added item
    // (we should be on the add-new row, so Up goes to the last item)
    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Get screen before delete
    let before_delete = harness.screen_to_string();
    assert!(
        before_delete.contains("to_delete"),
        "Item should be visible before delete"
    );

    // Press Delete to remove the focused item
    harness
        .send_key(KeyCode::Delete, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The item should be removed
    let after_delete = harness.screen_to_string();
    assert!(
        !after_delete.contains("to_delete"),
        "Item should be removed after Delete key"
    );

    // Close dialog without saving
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Regression test for issue #474: Settings not persisting after save
///
/// This test verifies that when a boolean setting is toggled and saved,
/// reopening the settings dialog shows the saved value (not the original).
///
/// The bug was: after save, discard_changes() rebuilt the UI from
/// original_config instead of the saved config, resetting displayed values.
#[test]
fn test_settings_toggle_persists_after_save_and_reopen() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Test harness sets check_for_updates = false by default
    assert!(
        !harness.config().check_for_updates,
        "check_for_updates should be false in test harness"
    );

    // Open settings
    harness.open_settings().unwrap();

    // Switch to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Navigate down to "Check For Updates" (second item in General)
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Verify we're on Check For Updates and it shows as unchecked [ ]
    // Format is ">  Check For Updates" (3-char indicator area: focus, modified, space)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Check For Updates") && screen.contains(": [ ]"),
        "Check For Updates should be focused and unchecked. Screen:\n{}",
        screen
    );

    // Toggle it ON
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify it now shows as checked [✓]
    // After toggling, the item is modified so it shows ">● " (3-char indicator area)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">● Check For Updates") && screen.contains(": [✓]"),
        "Check For Updates should now be checked (with modified indicator). Screen:\n{}",
        screen
    );

    // Save: Tab to footer (Layer), Tab to Save, Enter
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Reset
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // Save
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify settings closed and config updated
    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after save"
    );
    assert!(
        harness.config().check_for_updates,
        "check_for_updates should be true after save"
    );

    // CRITICAL: Reopen settings and verify the saved value is displayed
    harness.open_settings().unwrap();

    // Switch to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Navigate to Check For Updates
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // This is the key assertion: the toggle should show the SAVED value [✓]
    // not the ORIGINAL value [ ]
    // Note: The item shows the correct [✓] value; the "●" indicator may or may not
    // appear depending on layer detection
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Check For Updates") && screen.contains(": [✓]"),
        "BUG #474: After save and reopen, Check For Updates should still be checked [✓], \
         but it shows the original value [ ]. Screen:\n{}",
        screen
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that line_numbers config is applied when opening new files.
///
/// When line_numbers is set to false via settings, newly opened files
/// should not show line numbers.
#[test]
fn test_line_numbers_config_applied_to_new_buffers() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.render().unwrap();

    // Verify initial state has line numbers (default is true)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("1 │"),
        "Initial buffer should show line numbers by default"
    );

    // Open settings and disable line numbers
    harness.open_settings().unwrap();

    // Search for line numbers setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    for c in "line numbers".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Toggle it off (it's on by default)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Save settings with Ctrl+S
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify config was updated
    assert!(
        !harness.config().editor.line_numbers,
        "line_numbers should be false after saving"
    );

    // Open a new buffer - it should respect the new config
    harness
        .send_key(KeyCode::Char('n'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // The new buffer should NOT show line numbers
    let screen = harness.screen_to_string();
    assert!(
        !screen.contains("1 │") && !screen.contains("2 │"),
        "New buffer should not show line numbers when config.editor.line_numbers=false. Screen:\n{}",
        screen
    );
}

/// Test that line_wrap config is applied when opening new files.
///
/// When line_wrap is set to false via settings, newly opened files
/// should not wrap long lines.
#[test]
fn test_line_wrap_config_applied_to_new_buffers() {
    let mut harness = EditorTestHarness::new(80, 40).unwrap();
    harness.render().unwrap();

    // Open settings and disable line wrap
    harness.open_settings().unwrap();

    // Search for line wrap setting
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    for c in "line wrap".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Toggle it off (it's on by default)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Save settings with Ctrl+S
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify config was updated
    assert!(
        !harness.config().editor.line_wrap,
        "line_wrap should be false after saving"
    );

    // Open a new buffer
    harness
        .send_key(KeyCode::Char('n'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type a line longer than the screen width (80 chars)
    let long_text = "X".repeat(100);
    for c in long_text.chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // With line_wrap=false, the text should stay on one line (with horizontal scroll)
    // When wrapped, line 2 would show the continuation (no line number, just "│ XXX...")
    let screen = harness.screen_to_string();
    let lines: Vec<&str> = screen.lines().collect();

    // Find the content area (after menu bar and tab bar)
    // Line 2 should be a tilde (empty line marker) when not wrapping
    // When wrapped, it would contain X's
    let line2_content = lines.get(3).unwrap_or(&""); // 0=menu, 1=tabs, 2=line1, 3=line2
    assert!(
        !line2_content.contains("X"),
        "Long line should not wrap when config.editor.line_wrap=false. Line 2: '{}'. Screen:\n{}",
        line2_content,
        screen
    );
}

// =============================================================================
// JSON EDITOR TESTS - Testing the JSON text box in entry dialogs
// =============================================================================

/// Helper function to navigate to the LSP Initialization Options JSON editor
/// Opens settings, searches for "lsp", opens the first LSP entry, and navigates to Initialization Options
fn navigate_to_lsp_json_editor(harness: &mut EditorTestHarness) {
    // Open settings via Ctrl+,
    harness.open_settings().unwrap();

    // Use search to find "lsp" section
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.type_text("lsp").unwrap();
    harness.render().unwrap();

    // Press Enter to jump to the first result (the Lsp map)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in the LSP section
    harness.assert_screen_contains("Lsp");

    // Press Enter to open the first LSP entry dialog (e.g., clangd for c)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in an Edit dialog
    harness.assert_screen_contains("Edit Value");

    // LSP values are now arrays of server configs. The dialog shows the array.
    // Press Enter to drill into the first server item's nested dialog.
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Navigate down to "Initialization Options" field
    // Navigate until we see the focus indicator on Initialization Options
    // Format: ">  " (3-char indicator area: focus, modified, space)
    // (cargo nextest handles external timeout)
    loop {
        harness.render().unwrap();
        let screen = harness.screen_to_string();
        if screen.contains(">  Initialization Options")
            || screen.contains(">● Initialization Options")
        {
            break;
        }
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
}

/// Test that Delete key works in JSON editor (deletes character at cursor)
///
/// BUG: Delete key in JSON editor calls delete_list_item() instead of
/// deleting the character at the cursor position.
///
/// Expected: Delete key removes character after cursor
/// Actual: Delete key does nothing (or removes TextList item if in TextList mode)
#[test]
fn test_json_editor_delete_key_works() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    navigate_to_lsp_json_editor(&mut harness);

    // Press Enter to start editing the JSON field
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The help line should change to indicate JSON editing mode
    harness.assert_screen_contains("Enter:Newline");

    // When entering edit mode, cursor is at position 0
    // Type "ABC" which will be inserted at the start, resulting in "ABCnull"
    harness.type_text("ABC").unwrap();
    harness.render().unwrap();

    // Should see "ABCnull" (typed at cursor position 0)
    harness.assert_screen_contains("ABCnull");

    // Cursor is now after 'C'. Move left 3 times to position before 'A'
    for _ in 0..3 {
        harness.send_key(KeyCode::Left, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Press Delete key - should delete 'A'
    harness
        .send_key(KeyCode::Delete, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After deleting 'A', should show "BCnull"
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("BCnull") && !screen.contains("ABCnull"),
        "Delete key should remove character at cursor. Expected 'BCnull', got:\n{}",
        screen
    );

    // Close dialogs
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that Home and End keys work in JSON editor
///
/// BUG: Home and End keys are not handled in JSON editor.
#[test]
fn test_json_editor_home_end_keys_work() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    navigate_to_lsp_json_editor(&mut harness);

    // Press Enter to start editing the JSON field
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // When entering edit mode, cursor is at position 0
    // Type "XYZ" which results in "XYZnull"
    harness.type_text("XYZ").unwrap();
    harness.render().unwrap();

    // Should see "XYZnull" (typed at cursor position 0)
    harness.assert_screen_contains("XYZnull");

    // Cursor is now after 'Z'. Press End - should go to the end of text
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Type 'B' - should appear at the end
    harness
        .send_key(KeyCode::Char('B'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should now show "XYZnullB" (B appended at end)
    harness.assert_screen_contains("XYZnullB");

    // Press Home - cursor should go to beginning
    harness.send_key(KeyCode::Home, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Type 'A' - should appear at the beginning
    harness
        .send_key(KeyCode::Char('A'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should now show "AXYZnullB" (A inserted at beginning)
    harness.assert_screen_contains("AXYZnullB");

    // Close dialogs
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that Ctrl+A selects all text in JSON editor
///
/// BUG: Ctrl+A is not handled in JSON editor.
#[test]
fn test_json_editor_ctrl_a_selects_all() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    navigate_to_lsp_json_editor(&mut harness);

    // Press Enter to start editing the JSON field
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // When entering edit mode, cursor is at position 0
    // Type "OLD" which results in "OLDnull"
    harness.type_text("OLD").unwrap();
    harness.render().unwrap();

    // Should see "OLDnull"
    harness.assert_screen_contains("OLDnull");

    // Press Ctrl+A to select all
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type new text - should replace all selected text
    harness.type_text("NEW").unwrap();
    harness.render().unwrap();

    // Should now show "NEW" only (replaced "OLDnull")
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("NEW") && !screen.contains("OLDnull") && !screen.contains("OLD"),
        "Ctrl+A should select all, then typing should replace. Expected only 'NEW', got:\n{}",
        screen
    );

    // Close dialogs
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that Ctrl+C copies selected text in JSON editor to clipboard
///
/// BUG: Selecting text with Shift+Arrow in the JSON editor and pressing Ctrl+C
/// does not copy the selected text to the clipboard.
#[test]
fn test_json_editor_ctrl_c_copies_selected_text() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    // Enable internal-only clipboard for test isolation
    harness.editor_mut().set_clipboard_for_test("".to_string());

    navigate_to_lsp_json_editor(&mut harness);

    // Press Enter to start editing the JSON field
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in JSON editing mode
    harness.assert_screen_contains("Enter:Newline");

    // Select all with Ctrl+A, then type known text to have predictable content
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("HELLO").unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("HELLO");

    // Select all text with Ctrl+A
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Copy with Ctrl+C
    harness
        .send_key(KeyCode::Char('c'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify clipboard contains the selected text
    let clipboard_content = harness.editor_mut().clipboard_content_for_test();
    assert!(
        clipboard_content.contains("HELLO"),
        "Ctrl+C should copy selected JSON text to clipboard. Clipboard content: {:?}",
        clipboard_content
    );
}

// =============================================================================
// EDIT CONFIG FILE BUTTON TESTS
// =============================================================================

/// Test that the Edit button is visible in the settings footer
///
/// The Edit button allows advanced users to directly edit the config file
/// for the selected layer. It should be visible on the left side of the footer,
/// separated from the main action buttons.
#[test]
fn test_settings_edit_button_visible() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Edit button should be visible in footer (on the left, dimmed style)
    harness.assert_screen_contains("[ Edit ]");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that the Edit button can be navigated to via keyboard
///
/// Tab from the settings panel should eventually reach the Edit button.
/// Button order in footer: Layer, Reset, Save, Cancel, Edit (on left for advanced users)
#[test]
fn test_settings_edit_button_keyboard_navigation() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Tab to settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Tab to footer (defaults to Layer button, index 0)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should show Layer button focused
    harness.assert_screen_contains(">[ User ]");

    // Navigate with Right arrow: Layer -> Reset -> Save -> Cancel -> Edit
    // Footer order: 0=Layer, 1=Reset, 2=Save, 3=Cancel, 4=Edit
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Reset ]");

    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Save ]");

    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Cancel ]");

    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Edit button should now be focused
    harness.assert_screen_contains(">[ Edit ]");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that Edit button opens the config file for the selected layer
///
/// When the Edit button is activated, it should:
/// 1. Close the settings modal
/// 2. Open the config file for the current layer
/// 3. Show a status message indicating which file was opened
#[test]
fn test_settings_edit_button_opens_config_file() {
    // Width 120 (not 100) because the status bar's right side now includes
    // the color-coded "LSP (off)" dormant-indicator for any language with
    // a default LSP config (json has one), which truncates the "Editing
    // User config" status message to "Editing User ..." at 100 cols.
    let mut harness = EditorTestHarness::new(120, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Verify settings is open
    assert!(
        harness.editor().is_settings_open(),
        "Settings should be open"
    );

    // Navigate to Edit button: Tab -> Tab -> Tab*4 (through all footer buttons)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Settings
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Footer (Layer)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Reset
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Save
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Cancel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Edit
    harness.render().unwrap();

    // Verify Edit button is focused
    harness.assert_screen_contains(">[ Edit ]");

    // Press Enter to activate Edit button
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Settings should be closed
    assert!(
        !harness.editor().is_settings_open(),
        "Settings should be closed after Edit"
    );

    // A config file should be open (User layer by default)
    // The file path should contain "config.json"
    harness.assert_screen_contains("config.json");

    // Status message should indicate which layer was opened
    harness.assert_screen_contains("Editing User config");
}

/// Test that Edit button is blocked when there are pending changes
///
/// If the user has made changes in the Settings UI that haven't been saved,
/// the Edit button should not open the config file and should show a warning.
#[test]
fn test_settings_edit_button_blocked_with_pending_changes() {
    // 140×40 instead of 100×40: with `{remote}` on the default
    // status bar at 100 cols the "Save or discard pending
    // changes" message gets truncated. Other settings tests in
    // this file also use 100×40 but don't read status messages.
    let mut harness = EditorTestHarness::new(140, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Make a change: toggle "Check For Updates"
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Navigate to Edit button (Footer now starts at Layer, index 0)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap(); // to Footer (Layer)
                                                                 // Tab through Layer -> Reset -> Save -> Cancel -> Edit
    for _ in 0..4 {
        harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Press Enter to try to activate Edit button
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Settings should STILL be open (Edit was blocked)
    assert!(
        harness.editor().is_settings_open(),
        "Settings should still be open when Edit is blocked due to pending changes"
    );

    // Should show warning message about pending changes
    harness.assert_screen_contains("Save or discard pending changes");

    // Discard changes and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test that clicking "[+] Add new" button on a Map control opens entry dialog with single click
/// Reproduces issue #604: LSP Config "Add New" button is not clickable by mouse
#[test]
fn test_map_add_new_button_clickable_with_mouse() {
    let mut harness = EditorTestHarness::new(120, 45).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "Keybinding Maps" which is a Map control
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "keybinding maps".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for the "[+] Add new" button to be visible after search navigation
    harness
        .wait_until(|h| h.screen_to_string().contains("[+] Add new"))
        .unwrap();

    // Find the position of "[+] Add new" on screen and click it
    let screen = harness.screen_to_string();
    let add_new_pos = screen
        .lines()
        .enumerate()
        .find_map(|(row, line)| line.find("[+] Add new").map(|col| (col as u16, row as u16)))
        .expect("Should find [+] Add new on screen");

    // Single click should activate the add-new functionality (this is the fix for #604)
    harness
        .mouse_click(add_new_pos.0 + 2, add_new_pos.1)
        .unwrap();
    harness.render().unwrap();

    // After clicking, the entry dialog should open (for Map with schema) or input mode should start
    // For Keybinding Maps, it shows an entry dialog - check for entry dialog elements
    // The entry dialog has a "Key" label or shows brackets for text input

    // The test passes if clicking works - before the fix, a single click wouldn't activate
    // and the "[+] Add new" would remain just focused without any action

    // Close everything and clean up
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that "[+] Add new" button is visible for LSP map which doesn't have x-no-add
///
/// The LSP config is a Map type with additionalProperties that should allow adding new entries.
/// Unlike plugins (which has x-no-add: true), LSP should show the "[+] Add new" button.
#[test]
fn test_lsp_map_has_add_new_button() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    // Open settings via Ctrl+,
    harness.open_settings().unwrap();

    // Search for "lsp" to navigate to the LSP section
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.type_text("lsp").unwrap();
    harness.render().unwrap();

    // Press Enter to jump to the LSP map
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in the LSP section
    harness.assert_screen_contains("Lsp");

    // The "[+] Add new" button should be visible for LSP since it doesn't have x-no-add
    // This will fail if the add button is not being rendered
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("[+] Add new"),
        "LSP map should show '[+] Add new' button since it doesn't have x-no-add.\n\
         The LSP section should allow users to add new language server configurations.\n\
         Screen contents:\n{}",
        screen
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that "[+] Add new" button is visible for Languages map which doesn't have x-no-add
///
/// The Languages config is a Map type with additionalProperties that should allow adding new entries.
/// Unlike plugins (which has x-no-add: true), Languages should show the "[+] Add new" button.
#[test]
fn test_languages_map_has_add_new_button() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    // Open settings via Ctrl+,
    harness.open_settings().unwrap();

    // Search for "languages" to navigate to the Languages section
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.type_text("languages").unwrap();
    harness.render().unwrap();

    // Press Enter to jump to the Languages map
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in the Languages section
    harness.assert_screen_contains("Languages");

    // Check that the focus is on Languages (indicated by ">")
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(">  Languages"),
        "Focus should be on Languages section. Screen:\n{}",
        screen
    );

    // Navigate down through the Languages entries to reach the "[+] Add new" row
    // The Languages map has many built-in entries, so we need to scroll to see the add button
    for _ in 0..30 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();

        let screen = harness.screen_to_string();
        // Check if we can see "[+] Add new" in the visible Languages section
        if screen.contains("[+] Add new") && screen.contains("Languages") {
            // Found it! The add button is visible for Languages
            break;
        }
    }

    let screen = harness.screen_to_string();

    // The "[+] Add new" button should now be visible after scrolling
    assert!(
        screen.contains("[+] Add new"),
        "Languages map should show '[+] Add new' button after scrolling to the end.\n\
         The Languages section should allow users to add new language configurations.\n\
         Full screen:\n{}",
        screen
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that clicking "[+] Add new" on the LSP map opens the entry dialog
///
/// This verifies that mouse clicks on the add-new row of Map controls work correctly.
#[test]
fn test_lsp_map_add_new_button_click_opens_dialog() {
    let mut harness = EditorTestHarness::new(120, 50).unwrap();
    harness.render().unwrap();

    // Open settings via Ctrl+,
    harness.open_settings().unwrap();

    // Search for "lsp" to navigate to the LSP section
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.type_text("lsp").unwrap();
    harness.render().unwrap();

    // Press Enter to jump to the LSP map
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in the LSP section
    harness.assert_screen_contains("Lsp");

    // Navigate down through the LSP entries to reach the "[+] Add new" row
    // if it's not immediately visible
    for _ in 0..30 {
        let screen = harness.screen_to_string();
        if screen.contains("[+] Add new") && screen.contains("Lsp") {
            break;
        }
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }

    harness.assert_screen_contains("[+] Add new");

    // Find the position of "[+] Add new" that appears after "Lsp:" label
    // Need to find the one specifically in the LSP section, not Languages
    let screen = harness.screen_to_string();
    let lines: Vec<&str> = screen.lines().collect();

    // Find the line with "[+] Add new" (it should be visible now after scrolling)
    // The add-new row might not be immediately after the label due to entries
    let add_new_pos = lines
        .iter()
        .enumerate()
        .find_map(|(row, line)| line.find("[+] Add new").map(|col| (col as u16, row as u16)))
        .expect("Should find [+] Add new after scrolling to it");

    eprintln!("Clicking at ({}, {})", add_new_pos.0 + 2, add_new_pos.1);

    // Click on the "[+] Add new" button
    harness
        .mouse_click(add_new_pos.0 + 2, add_new_pos.1)
        .unwrap();
    harness.render().unwrap();

    // After clicking, the add-new row should be in edit mode
    // This shows as a text input field (brackets with cursor) for entering the key name
    // When in edit mode, the help line changes to show "Enter:Add"
    let screen = harness.screen_to_string();
    eprintln!("Screen after click:\n{}", screen);

    // Check that we're in editing mode - the help text should show Enter:Add or similar
    // indicating we can type a key name and press Enter to add it
    assert!(
        screen.contains("Enter:Add") || screen.contains("[") && screen.contains("]"),
        "Clicking '[+] Add new' on LSP map should start text input mode for key name.\n\
         The screen should show a text input field or 'Enter:Add' help text.\n\
         Screen contents:\n{}",
        screen
    );

    // Close the dialog and settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that navigating through map entries scrolls to keep the focused entry visible
///
/// This tests the bug where pressing Down to navigate through entries in a Map control
/// (like Languages) would move the focus but not scroll the view, causing the focused
/// entry to go off-screen.
#[test]
fn test_map_entry_navigation_scrolls_to_focused_entry() {
    // Use a small height to ensure the Languages list needs scrolling
    let mut harness = EditorTestHarness::new(120, 30).unwrap();
    harness.render().unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Search for "languages" to navigate to the Languages section
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    harness.type_text("languages").unwrap();
    harness.render().unwrap();

    // Press Enter to jump to the Languages map
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify we're in the Languages section and the first entry is focused
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Languages"),
        "Should show Languages section. Screen:\n{}",
        screen
    );

    // The first entry should be focused immediately after jumping
    assert!(
        screen.contains("[Enter to edit]") || screen.contains("[+] Add new"),
        "After jumping to Languages, the first entry should show '[Enter to edit]'.\n\
         This indicates the Map control's focus state is properly set.\n\
         Screen contents:\n{}",
        screen
    );

    // Navigate down through multiple entries and verify each one shows "[Enter to edit]"
    // which indicates it's the focused entry and is visible on screen
    for i in 0..15 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();

        let screen = harness.screen_to_string();

        // The focused entry should be visible and show "[Enter to edit]"
        // If the scroll isn't working, the focused entry will be off-screen
        // and we won't see "[Enter to edit]" OR we should at least see "[+] Add new"
        // when we reach the end of the list
        let has_focused_entry = screen.contains("[Enter to edit]");
        let has_add_new_focused = screen.contains("[+] Add new");

        // Either we're focused on an entry (shows [Enter to edit]) or
        // we've reached the add-new row (shows [+] Add new as focused)
        assert!(
            has_focused_entry || has_add_new_focused,
            "After pressing Down {} times, the focused entry should be visible.\n\
             Expected to see '[Enter to edit]' for a focused language entry or \n\
             '[+] Add new' for the add-new row, but neither was found.\n\
             This indicates the view didn't scroll to keep the focused entry visible.\n\
             Screen contents:\n{}",
            i + 1,
            screen
        );
    }

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that search results can be scrolled when there are many results
/// This tests issue #905: Settings UI doesn't scroll down in filter search results
#[test]
fn test_settings_search_results_scroll() {
    // Use a small terminal to ensure we need to scroll
    let mut harness = EditorTestHarness::new(80, 20).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Start search with /
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();

    // Search for "e" which should match many settings
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Get the first visible result
    let screen_before = harness.screen_to_string();

    // Press Down many times to scroll through results
    for _ in 0..15 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // The screen should have changed - different results should be visible
    let screen_after = harness.screen_to_string();

    // The screens should be different because we scrolled
    // (the first result should no longer be the top one)
    assert_ne!(
        screen_before, screen_after,
        "Screen should change after scrolling through search results"
    );

    // The selected result should still be visible (highlighted)
    // Check that there's a selection highlight in the results area
    // We should see at least one result with the selection indicator

    // Press Up to scroll back
    for _ in 0..15 {
        harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    }
    harness.render().unwrap();

    // Should be back at the top
    let screen_back = harness.screen_to_string();
    assert_eq!(
        screen_before, screen_back,
        "Screen should return to original state after scrolling back up"
    );

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

// =============================================================================
// Settings usability regression tests
// =============================================================================

/// Test: Shift+Tab (BackTab) navigates backward between panels.
///
/// Before fix: Shift+Tab was not handled in Categories or Settings panels.
/// After fix: Shift+Tab cycles: Categories → Footer → Settings → Categories.
#[test]
fn test_usability_backtab_backward_navigation() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Start in Categories panel. Tab forward to Settings.
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Now in Settings. Shift+Tab should go back to Categories.
    harness
        .send_key(KeyCode::BackTab, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // We should be back in Categories. Tab forward to verify we're at Categories
    // (Tab from Categories goes to Settings).
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Tab to Footer
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Should be in Footer - Layer button visible with focus
    harness.assert_screen_contains(">[ User ]");

    // Shift+Tab from Footer should go to Settings
    harness
        .send_key(KeyCode::BackTab, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Shift+Tab from Settings should go to Categories
    harness
        .send_key(KeyCode::BackTab, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Shift+Tab from Categories should wrap to Footer
    harness
        .send_key(KeyCode::BackTab, KeyModifiers::SHIFT)
        .unwrap();
    harness.render().unwrap();

    // Should be in Footer with Edit button focused (last button when entering backward)
    harness.assert_screen_contains(">[ Edit ]");

    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test: Tab in footer visits ALL 5 buttons (Layer, Reset, Save, Cancel, Edit).
///
/// Before fix: Footer always started at Save (index 2), skipping Layer and Reset.
/// After fix: Footer starts at Layer (index 0), Tab visits all 5 buttons.
#[test]
fn test_usability_footer_tab_visits_all_buttons() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Tab to Settings, then Tab to Footer
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Button 0: Layer
    harness.assert_screen_contains(">[ User ]");

    // Button 1: Reset
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Reset ]");

    // Button 2: Save
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Save ]");

    // Button 3: Cancel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Cancel ]");

    // Button 4: Edit
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Edit ]");

    // Tab again should wrap to Categories
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    // Verify we left footer (no > indicator on any button)
    harness.assert_screen_not_contains(">[ Edit ]");

    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test: Left arrow from Settings navigates back to Categories.
///
/// Before fix: Left on non-number controls called handle_control_decrement
/// (which changed dropdown values).
/// After fix: Left on non-number controls navigates to Categories panel.
#[test]
fn test_usability_left_arrow_to_categories() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Tab to Settings panel
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // We're now on a setting item. Press Left to go back to Categories.
    harness.send_key(KeyCode::Left, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Verify we're back in Categories by pressing Tab (which goes to Settings)
    // then Tab again (which goes to Footer)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // We should be in Footer now
    harness.assert_screen_contains(">[ User ]");

    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test: Left/Right on dropdown does NOT change the value.
///
/// Before fix: Right/Left on a focused dropdown cycled through options.
/// After fix: Right/Left are ignored for dropdowns (user must press Enter to open).
#[test]
fn test_usability_dropdown_no_left_right_change() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Search for a dropdown setting (theme)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "theme".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Capture the current screen with the dropdown value
    let before = harness.screen_to_string();

    // Press Right - should NOT change the dropdown value
    // (Left would navigate to categories which is also correct behavior)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    let after = harness.screen_to_string();

    // The screen should be the same (no dropdown cycling happened)
    // Note: Right on non-number controls is now a no-op
    assert_eq!(
        before, after,
        "Right arrow should not change dropdown value"
    );

    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test: Rulers setting (IntegerArray) renders as TextList and survives Enter/Escape.
///
/// Before fix: Rulers was rendered as a JSON editor (Complex type).
/// Enter/Escape would destroy saved data.
/// After fix: Rulers renders as TextList with integer mode.
#[test]
fn test_usability_rulers_integer_array_no_data_loss() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Search for "rulers"
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "rulers".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The rulers setting should be visible
    harness.assert_screen_contains("Rulers");

    // It should render as a TextList (with "Add item" field), NOT as a JSON editor
    // TextList shows "[Enter to edit]" when focused
    let screen = harness.screen_to_string();
    // It should NOT show JSON brackets like "[" "]" for editing
    // Instead, it should show a text list control
    assert!(
        !screen.contains("[Enter to edit JSON]"),
        "Rulers should NOT render as JSON editor. Screen:\n{}",
        screen
    );

    // Enter editing mode (focus into the TextList)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type a ruler value
    for c in "80".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Press Enter to add the item
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // "80" should be visible as an item
    harness.assert_screen_contains("80");

    // Press Escape to exit editing mode
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // "80" should STILL be visible (no data loss on Escape)
    harness.assert_screen_contains("80");

    // Close settings
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    if harness.screen_to_string().contains("Unsaved Changes") {
        // Discard
        harness
            .send_key(KeyCode::Right, KeyModifiers::NONE)
            .unwrap();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();
    }
}

/// Test: Descriptions are always fully rendered (not truncated).
///
/// Before fix: Non-focused items showed truncated 1-line descriptions with "...".
/// After fix: All items always show their full description text.
#[test]
fn test_usability_descriptions_always_full() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    harness.render().unwrap();
    let screen = harness.screen_to_string();

    // Descriptions should NOT be truncated with "..."
    // Count occurrences of "..." in the settings area
    // There should be very few or none (only if description actually ends with "...")
    let truncation_markers: Vec<&str> = screen
        .lines()
        .filter(|line| {
            // Look for truncation pattern: text followed by "..." but not if it's actual ellipsis in content
            let trimmed = line.trim();
            trimmed.ends_with("...")
                && !trimmed.ends_with("e.g., ...")
                && !trimmed.ends_with("etc...")
                && trimmed.len() > 10
        })
        .collect();

    // With full descriptions, there should be no truncation markers
    assert!(
        truncation_markers.len() <= 1,
        "Descriptions should not be truncated. Found {} lines ending with '...': {:?}",
        truncation_markers.len(),
        truncation_markers
    );

    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test: Entry dialog buttons show ">" focus indicator.
///
/// Before fix: Entry dialog buttons used REVERSED text but no ">" prefix.
/// After fix: Entry dialog buttons show ">" prefix for consistency.
#[test]
fn test_usability_entry_dialog_button_focus_indicator() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();
    harness.open_settings().unwrap();

    // Search for "languages" (which has an entry dialog)
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "languages".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Enter the languages map - press Enter to edit first entry
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Tab cycles through all fields and buttons — press Tab until we reach a button
    let mut has_focused_button = false;
    for _ in 0..60 {
        harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();

        let screen = harness.screen_to_string();
        // The ">" indicator is rendered with a gap before the button bracket
        if screen.contains("> [ Save ]")
            || screen.contains("> [ Delete ]")
            || screen.contains("> [ Cancel ]")
        {
            has_focused_button = true;
            break;
        }
        // Also check for button focus via REVERSED style (> may be in separate cell)
        if screen.contains("[ Save ]") || screen.contains("[ Cancel ]") {
            // Check if any button row has a focus indicator nearby
            for line in screen.lines() {
                if (line.contains("[ Save ]") || line.contains("[ Cancel ]")) && line.contains(">")
                {
                    has_focused_button = true;
                    break;
                }
            }
            if has_focused_button {
                break;
            }
        }
    }

    assert!(
        has_focused_button,
        "Entry dialog buttons should show > focus indicator after Tab cycling. Screen:\n{}",
        harness.screen_to_string()
    );

    // Close the dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
}

/// Test that discarding changes via confirmation dialog doesn't persist dialog on reopen
///
/// Regression test: After opening settings, making changes, pressing Escape to trigger
/// the confirmation dialog, then clicking Discard to close, re-opening settings should
/// show a clean settings view, not the confirmation dialog again.
#[test]
fn test_discard_dialog_does_not_persist_on_reopen() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find "Check For Updates" and toggle it to create a pending change
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Press Escape to trigger confirmation dialog
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("Unsaved Changes");

    // Navigate to Discard button (one Right from Save)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains(">[ Discard ]");

    // Press Enter to discard and close settings
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Settings should be closed
    harness.assert_screen_not_contains("Settings");
    harness.assert_screen_not_contains("Unsaved Changes");

    // Re-open settings
    harness.open_settings().unwrap();

    // Settings should show clean, without the confirmation dialog
    harness.assert_screen_contains("Settings");
    harness.assert_screen_not_contains("Unsaved Changes");
}

/// Test that the Reset button shows a confirmation dialog listing changed settings
///
/// When there are pending changes, pressing Reset should show a dialog listing
/// all pending changes and asking for confirmation before discarding them.
#[test]
fn test_reset_button_shows_confirmation_dialog() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find "Check For Updates" and toggle it to create a pending change
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Navigate to footer: Tab from Settings goes to Footer (starts at Layer/Project, index 0)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Go Right from Layer (index 0) to Reset (index 1)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Press Enter on Reset button
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Reset confirmation dialog should appear
    harness.assert_screen_contains("Reset All Changes");
    harness.assert_screen_contains("check_for_updates");

    // Should show Reset and Cancel buttons
    harness.assert_screen_contains("Reset");
    harness.assert_screen_contains("Cancel");

    // Cancel the dialog with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Dialog should be dismissed, settings still open with changes
    harness.assert_screen_not_contains("Reset All Changes");
    harness.assert_screen_contains("Settings");
    harness.assert_screen_contains("modified");

    // Discard and close
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
}

/// Test that confirming the Reset dialog actually discards all pending changes
#[test]
fn test_reset_dialog_confirm_discards_changes() {
    let mut harness = EditorTestHarness::new(100, 40).unwrap();

    // Open settings
    harness.open_settings().unwrap();

    // Use search to find "Check For Updates" and toggle it to create a pending change
    harness
        .send_key(KeyCode::Char('/'), KeyModifiers::NONE)
        .unwrap();
    for c in "check".chars() {
        harness
            .send_key(KeyCode::Char(c), KeyModifiers::NONE)
            .unwrap();
    }
    harness.render().unwrap();

    // Jump to result and toggle
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show modified indicator
    harness.assert_screen_contains("modified");

    // Navigate to footer: Tab from Settings goes to Footer (starts at Layer/Project, index 0)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Go Right from Layer (index 0) to Reset (index 1)
    harness
        .send_key(KeyCode::Right, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Press Enter on Reset button
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Reset confirmation dialog should appear
    harness.assert_screen_contains("Reset All Changes");

    // Confirm reset (Reset button is selected by default at index 0)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Dialog should be dismissed
    harness.assert_screen_not_contains("Reset All Changes");

    // Settings should still be open but without the modified indicator
    harness.assert_screen_contains("Settings");
    harness.assert_screen_not_contains("modified");

    // Closing settings should NOT show Unsaved Changes dialog since all changes were reset
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    harness.assert_screen_not_contains("Unsaved Changes");
}