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
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
use crate::common::harness::{copy_plugin, copy_plugin_lib, EditorTestHarness, HarnessOptions};
use crate::common::tracing::init_tracing_from_env;
use crossterm::event::{KeyCode, KeyModifiers};
use fresh::config_io::DirectoryContext;
use ratatui::style::Color;
use std::fs;

/// Helper function to open the theme editor via command palette
/// After running "Edit Theme" command, this waits for the theme selection prompt
/// and types "dark" to explicitly select the dark builtin theme.
fn open_theme_editor(harness: &mut EditorTestHarness) {
    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type to find the Edit Theme command
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();

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

    // Wait for theme selection prompt to appear
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    // Type "dark" to select the dark builtin theme explicitly
    // (Plugin prompts now use suggestion values when selected, so we type to be explicit)
    harness.type_text("dark").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to fully load.
    //
    // We must wait for the PANEL CONTENT to be populated, not just for the
    // `*Theme Editor*` tab label to appear. The tab bar updates as soon as
    // the buffer group is created, which happens BEFORE the plugin runs
    // `setPanelContent` to populate the tree/picker/footer panels. On slower
    // platforms (e.g. Windows) there's a visible race window in which the
    // tab is in place but every panel is still blank — previously this
    // helper used `screen.contains("Editor")` which matches the `*Theme
    // Editor*` tab label, so the wait returned during that blank window
    // and every subsequent `contains("Theme Editor:")` / `contains("#...")`
    // assertion in the callers raced against a half-rendered UI.
    //
    // Instead, wait for per-panel content the plugin writes via
    // setPanelContent:
    //   - `Theme Editor: ` — the first line of the tree (left) panel,
    //     e.g. "Theme Editor: dark".
    //   - `Select a color field` (when nothing is selected yet) or `Hex:`
    //     (after a color has been picked) — both only appear after the
    //     picker (right) panel has been populated.
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor: ")
                && (screen.contains("Select a color field") || screen.contains("Hex:"))
        })
        .unwrap();
}

/// Test that the theme editor command is registered by the plugin
#[test]
fn test_theme_editor_command_registered() {
    init_tracing_from_env();

    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    // Create themes directory with a test theme
    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    // Create harness with the project directory
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 30, Default::default(), project_root)
            .unwrap();

    // Initial render
    harness.render().unwrap();

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type to find the Edit Theme command
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();

    // The theme editor command should be registered and visible in the palette
    harness.assert_screen_contains("Edit Theme");
    harness.assert_screen_contains("theme_editor");
}

/// Test that the tab bar remains present when opening and closing the theme editor.
/// Verifies buffer group integration: the theme editor appears as a single tab entry,
/// panel splits don't show per-split tab bars, and closing the group restores the
/// previous state.
#[test]
fn test_theme_editor_tab_bar_persists() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    // === Initial state: tab bar present with [No Name] ===
    harness.render().unwrap();
    let initial_screen = harness.screen_to_string();
    assert!(
        initial_screen.contains("[No Name]"),
        "Initial tab bar should show [No Name]. Screen:\n{}",
        initial_screen
    );

    // === Open theme editor: tab bar still present, shows the new tab ===
    open_theme_editor(&mut harness);

    let after_open_screen = harness.screen_to_string();
    assert!(
        after_open_screen.contains("[No Name]"),
        "Tab bar should still show [No Name] after opening theme editor. Screen:\n{}",
        after_open_screen
    );
    assert!(
        after_open_screen.contains("*Theme Editor*"),
        "Theme editor should appear as a new tab entry. Screen:\n{}",
        after_open_screen
    );
    assert!(
        after_open_screen.contains("Theme Editor:"),
        "Theme editor panel content should be visible. Screen:\n{}",
        after_open_screen
    );

    // === Close theme editor: tab bar still present ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Close Theme Editor").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| !h.screen_to_string().contains("Theme Editor:"))
        .unwrap();

    let after_close_screen = harness.screen_to_string();
    assert!(
        after_close_screen.contains("[No Name]"),
        "Tab bar should still show [No Name] after closing theme editor. Screen:\n{}",
        after_close_screen
    );
    assert!(
        !after_close_screen.contains("*Theme Editor*"),
        "Theme editor tab should be gone after close. Screen:\n{}",
        after_close_screen
    );
}

/// Invoking the "Close Buffer" command from the command palette while a
/// group panel is the active/focused target should close the entire group,
/// not just the one panel. Individual panels are internal details that the
/// user should not be able to close piecemeal via the generic Close Buffer
/// command — they close together with the group.
#[test]
fn test_close_buffer_while_in_group_closes_whole_group() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor — the group tab becomes active.
    open_theme_editor(&mut harness);

    let after_open_screen = harness.screen_to_string();
    assert!(
        after_open_screen.contains("*Theme Editor*"),
        "Theme editor should be open. Screen:\n{}",
        after_open_screen
    );
    assert!(
        after_open_screen.contains("Theme Editor:"),
        "Theme editor panel content should be visible. Screen:\n{}",
        after_open_screen
    );

    // Run the generic "Close Buffer" command (not the theme-editor-specific
    // "Theme: Close Editor"). With the theme editor active, this should
    // close the whole group — NOT just close the currently-focused panel
    // buffer while leaving the rest of the group's layout visible.
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Close Buffer").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After close, the group tab, the group's panel content, and the group
    // panels themselves should all be gone.
    harness
        .wait_until(|h| !h.screen_to_string().contains("*Theme Editor*"))
        .unwrap();

    let after_close_screen = harness.screen_to_string();
    assert!(
        !after_close_screen.contains("*Theme Editor*"),
        "Theme editor group tab should be gone after Close Buffer. Screen:\n{}",
        after_close_screen
    );
    assert!(
        !after_close_screen.contains("Theme Editor:"),
        "Theme editor panel content should be gone after Close Buffer. Screen:\n{}",
        after_close_screen
    );
    assert!(
        after_close_screen.contains("[No Name]"),
        "Original [No Name] buffer tab should still be visible. Screen:\n{}",
        after_close_screen
    );
}

/// Next/Previous Buffer should cycle across both regular buffer tabs and
/// group tabs (i.e., top-level tabs in the tab bar). Opening a file +
/// opening the theme editor should give two tabs, and next_buffer should
/// toggle between them regardless of whether the group is currently active.
#[test]
fn test_next_buffer_cycles_across_groups_and_buffers() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let test_file = project_root.join("cycle_test.txt");
    fs::write(&test_file, "UniqueContentMarker\n").unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    // Open the source file.
    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // File is active; screen should show the file's content.
    let after_file_screen = harness.screen_to_string();
    assert!(
        after_file_screen.contains("UniqueContentMarker"),
        "Source file should be visible. Screen:\n{}",
        after_file_screen
    );

    // Open theme editor — this becomes the active tab; the file tab stays
    // in the tab bar.
    open_theme_editor(&mut harness);

    let after_theme_screen = harness.screen_to_string();
    assert!(
        after_theme_screen.contains("cycle_test.txt"),
        "File tab should still be listed. Screen:\n{}",
        after_theme_screen
    );
    assert!(
        after_theme_screen.contains("*Theme Editor*"),
        "Theme editor tab should be listed. Screen:\n{}",
        after_theme_screen
    );
    assert!(
        after_theme_screen.contains("Theme Editor:"),
        "Theme editor content should be visible. Screen:\n{}",
        after_theme_screen
    );

    // Run "Next Buffer" from the command palette. This should cycle from
    // the group tab back to the file tab.
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Next Buffer").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| h.screen_to_string().contains("UniqueContentMarker"))
        .unwrap();

    let back_to_file_screen = harness.screen_to_string();
    assert!(
        back_to_file_screen.contains("UniqueContentMarker"),
        "Next Buffer should switch back to the source file. Screen:\n{}",
        back_to_file_screen
    );
    // The theme editor tab should still be present in the tab bar (the
    // group wasn't closed, just inactive).
    assert!(
        back_to_file_screen.contains("*Theme Editor*"),
        "Theme editor tab should still be visible after switching away. Screen:\n{}",
        back_to_file_screen
    );
    // And the theme editor content should NOT be on screen any more.
    assert!(
        !back_to_file_screen.contains("Theme Editor:"),
        "Theme editor panel content should not be visible after switching away. Screen:\n{}",
        back_to_file_screen
    );

    // Run "Next Buffer" again — should now switch back to the theme editor.
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Next Buffer").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| h.screen_to_string().contains("Theme Editor:"))
        .unwrap();

    let back_to_theme_screen = harness.screen_to_string();
    assert!(
        back_to_theme_screen.contains("Theme Editor:"),
        "Next Buffer should cycle back to the theme editor. Screen:\n{}",
        back_to_theme_screen
    );
}

/// Test that the theme editor opens successfully without crashing
/// This test catches the pathJoin API bug where passing an array instead of
/// variadic args causes a serde_v8 error
#[test]
fn test_theme_editor_opens_without_error() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    // Create themes directory with a test theme
    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "dark",
        "editor": {
            "bg": [30, 30, 30],
            "fg": [212, 212, 212],
            "cursor": [82, 139, 255],
            "selection_bg": [38, 79, 120],
            "current_line_bg": [40, 40, 40],
            "line_number_fg": [100, 100, 100],
            "line_number_bg": [30, 30, 30]
        },
        "ui": {
            "tab_active_fg": "Yellow",
            "tab_active_bg": "Blue",
            "tab_inactive_fg": "White",
            "tab_inactive_bg": "DarkGray",
            "status_bar_fg": "White",
            "status_bar_bg": "DarkGray"
        },
        "search": {
            "match_bg": [100, 100, 20],
            "match_fg": [255, 255, 255]
        },
        "diagnostic": {
            "error_fg": "Red",
            "warning_fg": "Yellow"
        },
        "syntax": {
            "keyword": [86, 156, 214],
            "string": [206, 145, 120],
            "comment": [106, 153, 85]
        }
    }"#;
    fs::write(themes_dir.join("dark.json"), test_theme).unwrap();

    // Create harness with the project directory
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    // Initial render
    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();

    // Verify the editor actually opened with proper content
    assert!(
        screen.contains("Theme Editor") || screen.contains("Editor"),
        "Theme editor should show 'Theme Editor' or 'Editor' section. Got:\n{}",
        screen
    );

    // Should NOT contain error messages about serde_v8 or pathJoin
    assert!(
        !screen.contains("serde_v8"),
        "Should not show serde_v8 error on screen"
    );
    assert!(
        !screen.contains("invalid type"),
        "Should not show 'invalid type' error on screen"
    );
}

/// Test that the theme editor can be opened, closed, and reopened
#[test]
fn test_theme_editor_open_close_reopen() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // === First open ===
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Theme Editor"),
        "Theme editor should be open. Screen:\n{}",
        screen
    );

    // === Close via command palette ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness.type_text("Close Theme Editor").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to close
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            !screen.contains("Theme Editor:")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    assert!(
        !screen.contains("Theme Editor:"),
        "Theme editor should be closed after Escape. Screen:\n{}",
        screen
    );

    // === Reopen ===
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Theme Editor"),
        "Theme editor should reopen successfully. Screen:\n{}",
        screen
    );
}

/// Test that the theme editor can be closed with "Close Buffer" command and reopened
/// This verifies the stateless approach works when the buffer is closed externally
#[test]
fn test_theme_editor_reopen_after_close_buffer() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // === Step 1: Open theme editor ===
    open_theme_editor(&mut harness);

    // Wait for theme editor to be visible
    harness
        .wait_until(|h| h.screen_to_string().contains("*Theme Editor*"))
        .unwrap();

    // === Step 2: Close with "Close Buffer" from command palette ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness.type_text("Close Buffer").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor buffer to disappear from tabs
    harness
        .wait_until(|h| !h.screen_to_string().contains("*Theme Editor*"))
        .unwrap();

    // === Step 3: Try to reopen - this is where the bug manifests ===
    open_theme_editor(&mut harness);

    // Wait for theme editor to reappear
    harness
        .wait_until(|h| h.screen_to_string().contains("*Theme Editor*"))
        .unwrap();

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Theme Editor"),
        "Theme editor should reopen after Close Buffer. Screen:\n{}",
        screen
    );
}

/// Test that the theme editor displays color fields with swatches
#[test]
fn test_theme_editor_shows_color_sections() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Copy the theme_editor.ts plugin
    copy_plugin(&plugins_dir, "theme_editor");

    // Create themes directory with test themes
    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "dark",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {"keyword": [86, 156, 214]}
    }"#;
    fs::write(themes_dir.join("dark.json"), test_theme).unwrap();

    // Create harness
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();

    // Should show theme sections - the plugin creates sections like "Editor", "Syntax"
    // These are the section headers that should appear
    let has_editor_section = screen.contains("Editor") || screen.contains("editor");
    let has_syntax_section = screen.contains("Syntax") || screen.contains("syntax");

    assert!(
        has_editor_section || has_syntax_section,
        "Theme editor should show color sections. Got:\n{}",
        screen
    );
}

/// Test that the theme editor can open a builtin theme
/// This verifies the open functionality works correctly
#[test]
fn test_theme_editor_open_builtin() {
    // Create isolated directory context for proper test isolation
    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());

    // Create user themes directory and put test theme there
    fs::create_dir_all(dir_context.themes_dir()).unwrap();
    let source_theme = r#"{
        "name": "source",
        "editor": {
            "bg": [10, 20, 30],
            "fg": [240, 240, 240]
        },
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(dir_context.themes_dir().join("source.json"), source_theme).unwrap();

    // Create project directory with plugins
    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    // Create harness with isolated directory context
    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context,
    )
    .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Press Ctrl+O to open a theme (builtin or user)
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Wait for the prompt to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Open theme") || screen.contains("Select theme")
        })
        .unwrap();

    // Type the source theme name
    harness.type_text("source").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for theme to be loaded - should show the theme name "source"
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor: source") || screen.contains("Opened")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Verify the theme editor now shows the opened theme name
    assert!(
        screen.contains("source") && !screen.contains("custom"),
        "Theme editor should show the opened theme name. Screen:\n{}",
        screen
    );
}

/// Test that theme colors from the theme editor are displayed correctly on screen
/// This verifies that the color swatches show RGB values and use RGB colors in rendering
#[test]
fn test_theme_editor_displays_correct_colors() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Copy the theme_editor.ts plugin
    copy_plugin(&plugins_dir, "theme_editor");

    // Create themes directory
    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test-colors",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test-colors.json"), test_theme).unwrap();

    // Create harness
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // The theme editor should now be showing color fields with swatches
    let screen = harness.screen_to_string();

    // Verify the theme editor shows color values in hex format #RRGGBB
    // The default theme has values like #1E1E1E for background [30, 30, 30]
    let has_hex_format = screen.contains("#1E1E1E")
        || screen.contains("#1e1e1e")
        || screen.contains("#D4D4D4")
        || screen.contains("#d4d4d4")
        || screen.contains("#528BFF")
        || screen.contains("#282828")
        || screen.contains("#646464");

    assert!(
        has_hex_format,
        "Theme editor should display RGB color values in #RRGGBB format. Screen:\n{}",
        screen
    );

    // Check that the screen contains color field key names (two-panel layout shows short keys)
    assert!(
        screen.contains("bg") || screen.contains("fg") || screen.contains("cursor"),
        "Theme editor should show color field labels. Screen:\n{}",
        screen
    );

    // Verify some RGB colors are being used in rendering (for swatches, highlights, etc.)
    let buffer = harness.buffer();
    let mut rgb_color_count = 0;

    // Count cells with RGB colors (either foreground or background)
    for y in 0..buffer.area.height {
        for x in 0..buffer.area.width {
            if let Some(style) = harness.get_cell_style(x, y) {
                if matches!(style.fg, Some(Color::Rgb(_, _, _))) {
                    rgb_color_count += 1;
                }
                if matches!(style.bg, Some(Color::Rgb(_, _, _))) {
                    rgb_color_count += 1;
                }
            }
        }
    }

    // The theme editor should use many RGB colors for its UI (section headers, field values, etc.)
    assert!(
        rgb_color_count > 50,
        "Theme editor should use RGB colors for rendering. Found {} RGB-colored cells",
        rgb_color_count
    );
}

/// Test that the editor uses RGB colors from themes
/// This verifies that the editor rendering pipeline supports RGB colors
#[test]
fn test_editor_uses_rgb_colors() {
    // Create a temporary project directory
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create a test file
    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello World\nLine 2\nLine 3").unwrap();

    // Create harness with default config (which uses the dark theme with RGB colors)
    let mut harness =
        EditorTestHarness::with_config_and_working_dir(80, 24, Default::default(), project_root)
            .unwrap();

    // Open the test file
    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Wait for the file content to be rendered
    harness
        .wait_until(|h| h.screen_to_string().contains("Hello World"))
        .unwrap();

    // Count RGB colors used in the rendering
    let buffer = harness.buffer();
    let mut rgb_bg_count = 0;
    let mut rgb_fg_count = 0;

    for y in 0..buffer.area.height {
        for x in 0..buffer.area.width {
            if let Some(style) = harness.get_cell_style(x, y) {
                if matches!(style.bg, Some(Color::Rgb(_, _, _))) {
                    rgb_bg_count += 1;
                }
                if matches!(style.fg, Some(Color::Rgb(_, _, _))) {
                    rgb_fg_count += 1;
                }
            }
        }
    }

    // The editor should use RGB colors for backgrounds and foregrounds
    // The exact count depends on theme, but there should be significant RGB usage
    let total_rgb = rgb_bg_count + rgb_fg_count;

    assert!(
        total_rgb > 100,
        "Editor should use RGB colors from theme. Found {} RGB backgrounds and {} RGB foregrounds (total: {})",
        rgb_bg_count, rgb_fg_count, total_rgb
    );
}

// =============================================================================
// Bug Tests - These tests verify bugs that need to be fixed
// =============================================================================

/// Test that cursor position is preserved when toggling a section with Enter
#[test]
fn test_cursor_position_preserved_after_section_toggle() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    // Create a theme with UI section fields so toggling works
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {"tab_bg": [40, 40, 40], "tab_fg": [180, 180, 180]},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to find "UI Elements" section header
    // Keep pressing down until we see "UI Elements" on screen
    for _ in 0..20 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
        let screen = harness.screen_to_string();
        if screen.contains("UI Elements") {
            break;
        }
    }

    // Get cursor position before toggle
    let (_, _cursor_y_before) = harness.screen_cursor_position();

    // Press Enter to toggle the section
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Process async operations and render to ensure key is handled
    harness.process_async_and_render().unwrap();

    let (_, cursor_y_after) = harness.screen_cursor_position();

    // After toggling, the cursor should still be on a valid line
    // (exact position may vary based on section expansion/collapse)
    assert!(
        cursor_y_after > 0,
        "Cursor should be on a valid line after toggling. Y position: {}",
        cursor_y_after
    );
}

/// Test that color prompt shows suggestions including current value
#[test]
#[ignore = "flaky"]
fn test_color_prompt_shows_suggestions() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to find a color field (Background)
    // The structure is: Title, File path, blank, Section, Section desc, Field desc, Field
    // So we need to navigate down enough to land on a field line (index 6+)
    for _ in 0..8 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }

    // Wait for Background to appear on screen
    harness
        .wait_until(|h| h.screen_to_string().contains("Background:"))
        .unwrap();

    // Keep pressing Down until we're on a field that opens a prompt.
    // After each Enter we wait for the screen to change (no timeout) and
    // then check whether a color prompt appeared.
    let mut prompt_opened = false;
    for _ in 0..10 {
        let before = harness.screen_to_string();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();

        // Wait for the Enter to take effect (screen must change)
        harness
            .wait_until(|h| {
                let screen = h.screen_to_string();
                screen != before
                    || screen.contains("#RRGGBB")
                    || screen.contains("(#RRGGBB or named)")
            })
            .unwrap();

        let screen = harness.screen_to_string();
        if screen.contains("#RRGGBB") || screen.contains("(#RRGGBB or named)") {
            prompt_opened = true;
            break;
        }

        // If no prompt, we might be on description/section, try moving down
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }

    assert!(prompt_opened, "Color prompt should appear");

    let screen = harness.screen_to_string();

    // The prompt should show named color suggestions
    let has_named_colors = screen.contains("Black")
        || screen.contains("Red")
        || screen.contains("White")
        || screen.contains("Green")
        || screen.contains("Blue");

    assert!(
        has_named_colors,
        "Prompt should show named color suggestions. Screen:\n{}",
        screen
    );

    // The current value should appear in suggestions (in hex format)
    let has_current_value =
        screen.contains("#1E1E1E") || screen.contains("#1e1e1e") || screen.contains("current");

    assert!(
        has_current_value,
        "Prompt should show current color value. Screen:\n{}",
        screen
    );
}

/// Test that colors are displayed in HTML hex format (#RRGGBB)
#[test]
fn test_colors_displayed_in_hex_format() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();

    // Should show hex colors like #1E1E1E (30, 30, 30) or #D4D4D4 (212, 212, 212)
    // BUG: Currently shows [r, g, b] format
    let has_hex_format = screen.contains("#1E1E1E")
        || screen.contains("#1e1e1e")
        || screen.contains("#D4D4D4")
        || screen.contains("#d4d4d4")
        || screen.contains("#528BFF")  // cursor color
        || screen.contains("#282828"); // current line bg

    assert!(
        has_hex_format,
        "Colors should be displayed in hex format (#RRGGBB). Screen:\n{}",
        screen
    );

    // Should NOT show [r, g, b] format
    let has_bracket_format = screen.contains("[30, 30, 30]")
        || screen.contains("[212, 212, 212]")
        || screen.contains("[82, 139, 255]");

    assert!(
        !has_bracket_format,
        "Colors should NOT be in [r, g, b] format. Screen:\n{}",
        screen
    );
}

/// Test that comments appear BEFORE the field they describe, not after
/// BUG: Currently comments appear after the field
#[test]
fn test_comments_appear_before_fields() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // In the two-panel layout, field descriptions appear in the right-side picker panel
    // when a field is selected. The Editor section starts expanded by default, so just
    // press Down to navigate from the section header to the first field.
    //
    // The plugin sorts fields alphabetically within a section, so *which* field is
    // first depends on whichever editor color sorts first by key — this must not be
    // hard-coded to any specific name (see #779: adding `after_eof_bg` bumped the
    // alphabetically-first field, breaking the old matcher). Instead, verify that
    // *some* editor field is selected and shown in the picker.
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // The tree panel shows the selection marker `▸` in front of a field row.
            // The picker panel shows the path of the currently-selected field as
            // `editor.<field_name> - <display_name>`. Matching either is enough;
            // on narrow terminals the picker header can be truncated, so accept
            // the tree-panel marker as an equivalent signal.
            screen.contains("\u{25B8} ")
                || screen
                    .lines()
                    .any(|line| line.trim_start().starts_with("editor."))
        })
        .unwrap();
}

/// Test that theme changes are applied immediately after saving
/// Saving a theme automatically applies it
#[test]
#[ignore = "complex test with directory context isolation issues - needs redesign"]
fn test_theme_applied_immediately_after_save() {
    init_tracing_from_env();

    // Create isolated directory context for this test
    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());

    // Create the themes directory and put our test theme there
    fs::create_dir_all(dir_context.themes_dir()).unwrap();
    let test_theme = r#"{
        "name": "red-test",
        "editor": {"bg": [255, 0, 0], "fg": [255, 255, 255]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(dir_context.themes_dir().join("red-test.json"), test_theme).unwrap();

    // Create project directory with plugins
    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    // Create a test file to see theme changes
    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello World").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context,
    )
    .unwrap();

    // Open the test file first
    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Wait for file to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Hello World"))
        .unwrap();

    // Record the initial background color of the editor area
    let buffer = harness.buffer();
    let mut initial_bg_color: Option<Color> = None;
    for y in 2..buffer.area.height - 2 {
        for x in 0..buffer.area.width {
            if let Some(style) = harness.get_cell_style(x, y) {
                if let Some(bg) = style.bg {
                    if matches!(bg, Color::Rgb(_, _, _)) {
                        initial_bg_color = Some(bg);
                        break;
                    }
                }
            }
        }
        if initial_bg_color.is_some() {
            break;
        }
    }

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Open the red-test theme using Ctrl+O
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Wait for the prompt to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Open theme") || screen.contains("Select theme")
        })
        .unwrap();

    // Type the theme name "red-test" and confirm
    harness.type_text("red-test").unwrap();
    harness.render().unwrap();

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

    // Wait for theme to be loaded
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("red-test") || screen.contains("Opened")
        })
        .unwrap();

    // Save the theme with Ctrl+Shift+S (Save As) since it's a builtin
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Wait for save-as prompt
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Save theme")
                || screen.contains("save as")
                || screen.contains("theme as")
        })
        .unwrap();

    // Type a unique name and save (use timestamp to avoid conflicts)
    let unique_name = format!(
        "my-red-theme-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis()
    );
    harness.type_text(&unique_name).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Wait for theme to be saved and applied
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.to_lowercase().contains("changed") || screen.to_lowercase().contains("saved")
        })
        .unwrap();

    // Close the theme editor with Ctrl+Q
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::CONTROL)
        .unwrap();
    harness.process_async_and_render().unwrap();

    harness
        .wait_until(|h| !h.screen_to_string().contains("Theme Editor:"))
        .unwrap();

    // Now check if the editor background color changed
    let buffer = harness.buffer();
    let mut new_bg_color: Option<Color> = None;
    for y in 2..buffer.area.height - 2 {
        for x in 0..buffer.area.width {
            if let Some(style) = harness.get_cell_style(x, y) {
                if let Some(bg) = style.bg {
                    if matches!(bg, Color::Rgb(_, _, _)) {
                        new_bg_color = Some(bg);
                        break;
                    }
                }
            }
        }
        if new_bg_color.is_some() {
            break;
        }
    }

    // The background should have changed (we loaded a red theme)
    if let (Some(Color::Rgb(ir, ig, ib)), Some(Color::Rgb(nr, ng, nb))) =
        (initial_bg_color, new_bg_color)
    {
        // Check that the color actually changed
        let color_changed = ir != nr || ig != ng || ib != nb;

        assert!(
            color_changed,
            "Theme should be applied immediately after save. Initial: ({}, {}, {}), New: ({}, {}, {})",
            ir, ig, ib, nr, ng, nb
        );
    }
    // If we can't find RGB colors, that's okay - the test is just verifying the flow works
}

/// Test that cursor X position is preserved when toggling a section with Enter
/// BUG: Currently cursor moves one character back
#[test]
#[ignore = "flaky test - times out intermittently"]
fn test_cursor_x_position_preserved_after_section_toggle() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {"tab_bg": [40, 40, 40], "tab_fg": [180, 180, 180]},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to find "UI Elements" section header (collapsed by default)
    // Keep pressing Down until cursor is on the UI Elements line
    loop {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
        let screen = harness.screen_to_string();
        let (cx, cy) = harness.screen_cursor_position();
        eprintln!("Navigating down: cursor at ({}, {})", cx, cy);

        if screen.contains("> UI Elements") {
            // Check if we're actually on that line
            let lines: Vec<&str> = screen.lines().collect();
            if cy < lines.len() as u16 {
                let cursor_line = lines[cy as usize];
                eprintln!("Cursor line: {}", cursor_line);
                if cursor_line.contains("> UI Elements") {
                    break;
                }
            }
        }
    }

    // Render and get cursor position before toggle
    harness.render().unwrap();
    let screen_before = harness.screen_to_string();
    let (cursor_x_before, cursor_y_before) = harness.screen_cursor_position();

    eprintln!("=== BEFORE TOGGLE ===");
    eprintln!(
        "Cursor position: ({}, {})",
        cursor_x_before, cursor_y_before
    );
    eprintln!("Screen:\n{}", screen_before);

    // Press Enter to toggle the section (expand) - Enter toggles when on a section header
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for the toggle to complete (> becomes ▼)
    harness
        .wait_until(|h| h.screen_to_string().contains("▼ UI Elements"))
        .unwrap();

    let screen_after = harness.screen_to_string();
    let (cursor_x_after, cursor_y_after) = harness.screen_cursor_position();

    eprintln!("=== AFTER TOGGLE ===");
    eprintln!("Cursor position: ({}, {})", cursor_x_after, cursor_y_after);
    eprintln!("Screen:\n{}", screen_after);

    // Verify we actually toggled (> should become ▼)
    assert!(
        screen_before.contains("> UI Elements"),
        "Before toggle should show collapsed UI Elements (>). Screen:\n{}",
        screen_before
    );
    assert!(
        screen_after.contains("▼ UI Elements"),
        "After toggle should show expanded UI Elements (▼). Screen:\n{}",
        screen_after
    );

    // Extract column from status bar (format: "Ln X, Col Y")
    fn extract_col_from_status(screen: &str) -> Option<u32> {
        for line in screen.lines() {
            if let Some(col_idx) = line.find("Col ") {
                let rest = &line[col_idx + 4..];
                let col_str: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
                return col_str.parse().ok();
            }
        }
        None
    }

    let col_before = extract_col_from_status(&screen_before);
    let col_after = extract_col_from_status(&screen_after);

    eprintln!(
        "Column before: {:?}, Column after: {:?}",
        col_before, col_after
    );

    // The cursor X position should stay the same
    // BUG: Currently cursor moves one character back (cursor_x_after = cursor_x_before - 1)
    assert_eq!(
        cursor_x_before, cursor_x_after,
        "Cursor X should stay at same position after toggling. Before: ({}, {}), After: ({}, {})",
        cursor_x_before, cursor_y_before, cursor_x_after, cursor_y_after
    );

    // Also check the column from status bar
    if let (Some(col_b), Some(col_a)) = (col_before, col_after) {
        assert_eq!(
            col_b, col_a,
            "Column in status bar should stay same after toggling. Before: {}, After: {}",
            col_b, col_a
        );
    }
}

/// Test that color suggestions show hex format (#123456) not [r,g,b]
/// BUG: Currently suggestions show [r, g, b] format
#[test]
#[ignore = "flaky test - timing sensitive"]
fn test_color_suggestions_show_hex_format() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to a color field and open the prompt.
    // After each Down+Enter we wait for the screen to change (no timeout).
    let mut prompt_opened = false;
    for _ in 0..30 {
        // Navigate down and wait for the UI to settle
        let before_down = harness.screen_to_string();
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness
            .wait_until(|h| h.screen_to_string() != before_down)
            .unwrap();

        // Try to open a prompt
        let before_enter = harness.screen_to_string();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();
        harness
            .wait_until(|h| {
                let screen = h.screen_to_string();
                screen != before_enter
                    || screen.contains("#RRGGBB")
                    || screen.contains("(#RRGGBB or named)")
            })
            .unwrap();

        let screen = harness.screen_to_string();
        if screen.contains("#RRGGBB") || screen.contains("(#RRGGBB or named)") {
            prompt_opened = true;
            break;
        }

        // If we opened something that's not a color prompt, close it and try next field
        if screen.contains("Enter:") || screen.contains("select") {
            harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
            harness.process_async_and_render().unwrap();
        }
    }

    assert!(prompt_opened, "Color prompt should appear");

    // Wait for the prompt to fully render (screen stops changing)
    harness
        .wait_until_stable(|h| {
            // Condition: prompt is visible
            h.screen_to_string().contains("#RRGGBB")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    // Check whether suggestions appeared
    let has_suggestions = screen.contains("#000000")
        || screen.contains("#FF0000")
        || screen.contains("[0, 0, 0]")
        || screen.contains("[255, 0, 0]")
        || screen.contains("black")
        || screen.contains("white");

    let screen = harness.screen_to_string();

    // If no suggestions appeared, skip the format check - suggestions may not be implemented
    if !has_suggestions {
        // Just verify the prompt is working (shows hex format hint)
        assert!(
            screen.contains("#RRGGBB"),
            "Color prompt should show format hint. Screen:\n{}",
            screen
        );
        return;
    }

    // The suggestions should show hex format for named colors
    // BUG: Currently shows "[0, 0, 0]" instead of "#000000"
    let has_bracket_format = screen.contains("[0, 0, 0]")
        || screen.contains("[255, 0, 0]")
        || screen.contains("[0, 128, 0]")
        || screen.contains("[255, 255, 0]");

    assert!(
        !has_bracket_format,
        "Color suggestions should NOT show [r, g, b] format. Screen:\n{}",
        screen
    );

    // Should show hex format like #000000, #FF0000, etc.
    let has_hex_format = screen.contains("#000000")
        || screen.contains("#FF0000")
        || screen.contains("#008000")
        || screen.contains("#FFFF00");

    assert!(
        has_hex_format,
        "Color suggestions should show hex format (#RRGGBB). Screen:\n{}",
        screen
    );
}

/// Test that color prompt is pre-filled with current value
/// BUG: Currently prompt starts empty
#[test]
#[ignore = "flaky"]
fn test_color_prompt_prefilled_with_current_value() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to Background field
    for _ in 0..8 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }

    // Keep pressing Down until we're on a field that opens a prompt
    let mut prompt_opened = false;
    for _ in 0..10 {
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();
        harness.render().unwrap();

        let screen = harness.screen_to_string();
        if screen.contains("#RRGGBB") || screen.contains("(#RRGGBB or named)") {
            prompt_opened = true;
            break;
        }

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

    assert!(prompt_opened, "Color prompt should appear");

    // The prompt input should be pre-filled with the current color value
    let screen = harness.screen_to_string();

    // Look for the prompt line which should contain a pre-filled hex value
    // The prompt format is: "FieldName (#RRGGBB or named): #XXXXXX"
    // The test may land on different fields, so check for any hex value in prompt
    let prompt_line = screen
        .lines()
        .find(|line| line.contains("#RRGGBB or named): #"));

    assert!(
        prompt_line.is_some(),
        "Prompt should be pre-filled with current color value in hex format. Screen:\n{}",
        screen
    );
}

/// Test that color values in the theme editor are rendered without extra internal spaces
/// This tests the fix for a bug where virtual text spacing caused "R  ed" instead of "Red"
#[test]
fn test_theme_editor_color_values_no_internal_spaces() {
    use regex::Regex;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Wait for swatches to appear (indicated by "██" swatch blocks)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("██") || screen.contains("Theme Editor")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // The bug causes hex colors to render as "#  XXXXXX" (spaces after #) instead of "#XXXXXX"
    // This is because the buggy code used two addVirtualText calls:
    // - One with before:true for the swatch
    // - One with before:false for the space, which inserts AFTER the # character

    // Check for the bug pattern: # followed by spaces then hex digits
    let broken_pattern = Regex::new(r"#\s+[0-9A-Fa-f]").unwrap();

    // Find lines that have color fields (contain "██" swatch and "#" hex value)
    let color_lines: Vec<&str> = screen
        .lines()
        .filter(|line| line.contains("██") && line.contains("#"))
        .collect();

    assert!(
        !color_lines.is_empty(),
        "Should find color field lines in theme editor. Screen:\n{}",
        screen
    );

    // Check that none of the color lines have the bug pattern
    for line in &color_lines {
        assert!(
            !broken_pattern.is_match(line),
            "Found broken color value with spaces after # (virtual text spacing bug): '{}'\n\nFull screen:\n{}",
            line,
            screen
        );
    }

    // Also verify we have proper hex colors (no spaces between # and digits)
    let proper_hex_pattern = Regex::new(r"#[0-9A-Fa-f]{6}").unwrap();
    let has_proper_hex = color_lines
        .iter()
        .any(|line| proper_hex_pattern.is_match(line));

    assert!(
        has_proper_hex,
        "Should find properly formatted hex colors (#XXXXXX). Screen:\n{}",
        screen
    );
}

/// Test that navigation skips non-selectable lines and only lands on fields/sections
/// Navigation should work with Up/Down arrows and Tab/Shift-Tab for section jumping
#[test]
#[ignore = "flaky test - times out intermittently"]
fn test_theme_editor_navigation_skips_non_selectable_lines() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {"tab_active_bg": [50, 50, 50]},
        "search": {},
        "diagnostic": {},
        "syntax": {"keyword": [100, 150, 200]}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Initial position
    let (_, cursor_y_initial) = harness.screen_cursor_position();

    // Press Down multiple times to navigate through fields, waiting for screen to change each time
    for _ in 0..6 {
        let screen_before = harness.screen_to_string();
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        // Wait for screen to change (semantic waiting - cursor movement changes highlighting)
        harness
            .wait_until(|h| h.screen_to_string() != screen_before)
            .unwrap();
    }

    let (_, cursor_y_after_multiple) = harness.screen_cursor_position();

    // After multiple Down presses, cursor should have moved
    // (navigating through selectable lines)
    assert!(
        cursor_y_after_multiple > cursor_y_initial || cursor_y_initial > 2,
        "Cursor should navigate through theme editor. Initial Y: {}, Final Y: {}",
        cursor_y_initial,
        cursor_y_after_multiple
    );

    // Now press Up to go back - wait for screen to change
    let screen_before_up = harness.screen_to_string();
    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness
        .wait_until(|h| h.screen_to_string() != screen_before_up)
        .unwrap();

    let (_, cursor_y_after_up) = harness.screen_cursor_position();

    // Cursor should have moved up
    assert!(
        cursor_y_after_up < cursor_y_after_multiple,
        "Cursor should move up after pressing Up. After multiple down Y: {}, After up Y: {}",
        cursor_y_after_multiple,
        cursor_y_after_up
    );

    // Test Tab navigation - should jump to next section
    // First, go back to beginning
    for _ in 0..20 {
        harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
    }

    let _screen_at_start = harness.screen_to_string();

    // Press Tab to navigate to next selectable element (field or section)
    harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let (_, _cursor_y_after_tab) = harness.screen_cursor_position();
    let (_, _cursor_y_before_tab) = harness.screen_cursor_position();

    // Tab should move the cursor (it navigates through all fields and sections)
    // Note: With wrapping, it might wrap back to start if we're at the end

    // Press Tab multiple times to verify wrapping works
    let (_, _cursor_y_initial_for_wrap) = harness.screen_cursor_position();
    for _ in 0..50 {
        harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
    }

    // After many Tabs, cursor should have wrapped back to somewhere
    // (We can't assert exact position, but it shouldn't crash)

    // Test Shift+Tab navigation - should navigate backwards with wrapping
    let (_, _cursor_y_before_backtab) = harness.screen_cursor_position();
    harness
        .send_key(KeyCode::BackTab, KeyModifiers::SHIFT)
        .unwrap();
    harness.process_async_and_render().unwrap();

    let (_, _cursor_y_after_backtab) = harness.screen_cursor_position();

    // Shift+Tab should also move the cursor
    // (exact behavior depends on current position due to wrapping)

    // Verify that pressing Enter on a section toggles it (expand/collapse)
    // Find a collapsed section first
    for _ in 0..10 {
        harness.send_key(KeyCode::Tab, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
        let screen = harness.screen_to_string();
        if screen.contains("> UI")
            || screen.contains("> Search")
            || screen.contains("> Diagnostics")
        {
            break;
        }
    }

    let screen_before_toggle = harness.screen_to_string();
    let has_collapsed_section = screen_before_toggle.contains("> ");

    if has_collapsed_section {
        // Press Enter to toggle (expand)
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();
        harness.process_async_and_render().unwrap();

        let screen_after_toggle = harness.screen_to_string();

        // After toggle, the section should be expanded (shows ▼ instead of >)
        // Note: This depends on which section we landed on
        let has_expanded = screen_after_toggle.contains("");
        assert!(
            has_expanded || screen_after_toggle != screen_before_toggle,
            "Enter on section should toggle expansion. Before toggle screen had '>' for collapsed sections."
        );
    }
}

/// Test that cursor position is preserved after editing a color value
/// The cursor should return to the same field after confirming a color change
#[test]
fn test_cursor_position_preserved_after_color_edit() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200], "cursor": [255, 255, 255]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Wait for theme editor to be fully loaded with color fields
    harness
        .wait_until(|h| h.screen_to_string().contains("editor"))
        .unwrap();

    // Navigate down to reach a color field (skip section headers)
    // The first few items are section headers, we need to get to actual color fields
    for _ in 0..5 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.render().unwrap();
    }

    // Now we should be on a color field. Open the prompt.
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for color prompt to appear (semantic waiting, no timeout)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("#RRGGBB") || screen.contains("(#RRGGBB or named)")
        })
        .unwrap();

    // Cancel the prompt to go back to the field
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Wait for prompt to close
    harness
        .wait_until(|h| !h.screen_to_string().contains("#RRGGBB"))
        .unwrap();

    // NOW record the cursor position - we know we're on a valid color field
    let (cursor_x_before, cursor_y_before) = harness.screen_cursor_position();

    // Open the color prompt again
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for color prompt to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("#RRGGBB") || screen.contains("(#RRGGBB or named)")
        })
        .unwrap();

    // Clear the pre-filled value and type a new color value
    // The prompt opens with the current value pre-filled, so we need to select all and replace
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness.type_text("#FF0000").unwrap();
    harness.render().unwrap();

    // Confirm the color change
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Wait for the prompt to close and display to update
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            !screen.contains("#RRGGBB") && screen.contains("#FF0000")
        })
        .unwrap();

    // Record cursor position after editing
    let (cursor_x_after, cursor_y_after) = harness.screen_cursor_position();

    // The cursor should be near the same position (within 2 lines due to possible display changes)
    let y_diff = (cursor_y_after as i32 - cursor_y_before as i32).abs();
    assert!(
        y_diff <= 2,
        "Cursor Y should stay near same position after editing color. Before: ({}, {}), After: ({}, {}), Diff: {}",
        cursor_x_before, cursor_y_before, cursor_x_after, cursor_y_after, y_diff
    );

    // The color should have been updated
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("#FF0000"),
        "Color should be updated to #FF0000. Screen:\n{}",
        screen
    );
}

/// Test that cursor is positioned on the value field (not first column) when navigating
/// When moving to a color field, cursor should be on the value, not at the line start
#[test]
fn test_cursor_on_value_field_when_navigating() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Navigate down to a color field
    for _ in 0..5 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
    }

    // Get cursor position
    let (cursor_x, _cursor_y) = harness.screen_cursor_position();

    // The cursor X should NOT be at the first column (0)
    // It should be positioned after "FieldName: " on the value
    // The exact position depends on field name length and indentation
    // But it should definitely be > 10 (past indentation + field name + colon)
    assert!(
        cursor_x > 5,
        "Cursor X should be positioned on the value field, not at first column. Got X={}",
        cursor_x
    );

    // Navigate to another field and check again
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let (cursor_x_2, _) = harness.screen_cursor_position();

    // Should still be positioned on value
    assert!(
        cursor_x_2 > 5,
        "Cursor X should be positioned on value after navigating. Got X={}",
        cursor_x_2
    );
}

/// Test that builtin themes require Save As (cannot overwrite builtins)
#[test]
fn test_builtin_theme_requires_save_as() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    // Create a DirectoryContext so we know where config_dir/themes is
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // Write the test theme into the config themes dir (where ThemeLoader looks)
    let themes_dir = dir_context.themes_dir();
    fs::create_dir_all(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "builtin-test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("builtin-test.json"), test_theme).unwrap();

    let mut harness = EditorTestHarness::create(
        120,
        40,
        HarnessOptions::new()
            .with_config(Default::default())
            .with_working_dir(project_root.clone())
            .without_empty_plugins_dir()
            .with_shared_dir_context(dir_context),
    )
    .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    // Open the builtin theme with Ctrl+O
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Open theme") || screen.contains("Select theme")
        })
        .unwrap();

    harness.type_text("builtin-test").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for theme to load
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("builtin-test") || screen.contains("Opened")
        })
        .unwrap();

    // Navigate to a field and make a change
    for _ in 0..5 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
    }

    // Try to open a color prompt and make a change
    for _ in 0..10 {
        let before = harness.screen_to_string();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();

        harness
            .wait_until(|h| {
                let screen = h.screen_to_string();
                screen != before || screen.contains("#RRGGBB")
            })
            .unwrap();

        if harness.screen_to_string().contains("#RRGGBB") {
            break;
        }

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

    // Type a color change
    harness.type_text("#AA0000").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Now try to save with Ctrl+S - should prompt for Save As since it's a builtin
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();

    // Wait for Save As prompt to appear (async plugin handler)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Save theme as") || screen.contains("save as")
        })
        .unwrap();
}

/// Test that color swatches are displayed next to color values
#[test]
fn test_color_swatches_displayed() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "test",
        "editor": {"bg": [30, 30, 30], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor using helper (handles theme selection prompt)
    open_theme_editor(&mut harness);

    let screen = harness.screen_to_string();

    // Color swatches should be displayed as "██" blocks next to field values
    assert!(
        screen.contains("██"),
        "Color swatches should be displayed next to color values. Screen:\n{}",
        screen
    );

    // Should also have hex color values visible
    let has_hex = screen.contains("#");
    assert!(
        has_hex,
        "Hex color values should be visible. Screen:\n{}",
        screen
    );
}

/// Test that selecting the built-in "nostalgia" theme displays its actual colors
/// Bug reproduction: when selecting Nostalgia from the Edit Theme suggestion list,
/// the theme that opens should have Nostalgia's colors (blue background #0000AA),
/// not Dark theme colors (#1E1E1E)
///
/// This test types the theme name to select it.
#[test]
fn test_theme_editor_nostalgia_builtin_shows_correct_colors() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    // Don't create a themes directory - we want to use the built-in themes only

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type to find the Edit Theme command
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();

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

    // Wait for theme selection prompt to appear
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    // Type "nostalgia" to filter/select the nostalgia theme
    harness.type_text("nostalgia").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to fully load with the nostalgia theme
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor") && screen.contains("nostalgia")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Nostalgia theme has editor.bg = [0, 0, 170] which is #0000AA in hex
    // The theme editor should display this value
    let has_nostalgia_bg = screen.contains("#0000AA") || screen.contains("#0000aa");

    // Dark theme has editor.bg = [30, 30, 30] which is #1E1E1E in hex
    // This should NOT appear if nostalgia was loaded correctly
    let has_dark_bg = screen.contains("#1E1E1E") || screen.contains("#1e1e1e");

    assert!(
        has_nostalgia_bg,
        "Theme editor should show Nostalgia's background color #0000AA. Screen:\n{}",
        screen
    );

    assert!(
        !has_dark_bg,
        "Theme editor should NOT show Dark theme's background color #1E1E1E when Nostalgia is selected. Screen:\n{}",
        screen
    );
}

/// Test that selecting nostalgia theme via arrow navigation displays its actual colors
/// This tests the case where user navigates the suggestions list with arrow keys
/// and selects a suggestion (which sends the suggestion's `value` field, not `text`)
#[test]
fn test_theme_editor_nostalgia_builtin_via_arrow_selection() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    // Create plugins directory
    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    // Don't create a themes directory - we want to use the built-in themes only

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type to find the Edit Theme command
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();

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

    // Wait for theme selection prompt to appear
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    // Type "nostalgia" to filter suggestions to just nostalgia
    harness.type_text("nostalgia").unwrap();
    harness.render().unwrap();

    // Wait for suggestions to update
    harness
        .wait_until(|h| h.screen_to_string().contains("nostalgia"))
        .unwrap();

    // Press Down arrow to select the suggestion from the list
    // This should send the `value` field from the suggestion (e.g., "builtin:nostalgia")
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to fully load with the nostalgia theme
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor") && screen.contains("nostalgia")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Nostalgia theme has editor.bg = [0, 0, 170] which is #0000AA in hex
    let has_nostalgia_bg = screen.contains("#0000AA") || screen.contains("#0000aa");

    // Dark theme has editor.bg = [30, 30, 30] which is #1E1E1E in hex
    let has_dark_bg = screen.contains("#1E1E1E") || screen.contains("#1e1e1e");

    assert!(
        has_nostalgia_bg,
        "Theme editor should show Nostalgia's background color #0000AA when selected via arrow navigation. Screen:\n{}",
        screen
    );

    assert!(
        !has_dark_bg,
        "Theme editor should NOT show Dark theme's background color #1E1E1E when Nostalgia is selected. Screen:\n{}",
        screen
    );
}

/// Bug regression test: selecting nostalgia from suggestion dropdown should load nostalgia colors
/// The bug was that plugin prompts didn't use the suggestion's `value` field when a suggestion
/// was selected, so "builtin:nostalgia" was not being passed correctly to the handler.
#[test]
fn test_theme_editor_select_nostalgia_from_dropdown() {
    init_tracing_from_env();
    eprintln!("[TEST] test_theme_editor_select_nostalgia_from_dropdown: starting");

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();
    eprintln!("[TEST] harness created and rendered");

    // Open command palette
    eprintln!("[TEST] opening command palette...");
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] command palette opened");

    eprintln!("[TEST] typing 'Edit Theme'...");
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] typed 'Edit Theme'");

    eprintln!("[TEST] pressing Enter to execute command...");
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] Enter pressed, waiting for theme selection prompt...");

    // Wait for theme selection prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();
    eprintln!("[TEST] theme selection prompt appeared");

    // Type "nostalgia" to filter the list
    eprintln!("[TEST] typing 'nostalgia'...");
    harness.type_text("nostalgia").unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] typed 'nostalgia'");

    // Press Down to select the nostalgia suggestion from the dropdown
    // This is the key part - selecting from dropdown sends the suggestion's `value`
    eprintln!("[TEST] pressing Down to select suggestion...");
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] Down pressed");

    // Confirm selection
    eprintln!("[TEST] pressing Enter to confirm selection...");
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    eprintln!("[TEST] Enter pressed, waiting for Theme Editor to load...");

    // Wait for theme editor to fully load.
    //
    // Must wait for per-panel content (populated by setPanelContent) rather
    // than just the `*Theme Editor*` tab label — see `open_theme_editor` for
    // the full rationale. The tab label appears as soon as the buffer group
    // is created, which is BEFORE the plugin populates the tree/picker
    // panels, and on Windows CI that race window is wide enough that the
    // subsequent assertions below consistently observed blank panels.
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor: ")
                && (screen.contains("Select a color field") || screen.contains("Hex:"))
        })
        .unwrap();
    eprintln!("[TEST] Theme Editor loaded");

    let screen = harness.screen_to_string();

    // Verify nostalgia theme loaded correctly:
    // 1. Title should show "Theme Editor: nostalgia"
    // 2. Background color should be #0000AA (nostalgia's blue), NOT #1E1E1E (dark's gray)

    assert!(
        screen.contains("Theme Editor: nostalgia"),
        "Title should show 'Theme Editor: nostalgia'. Screen:\n{}",
        screen
    );

    // Nostalgia has bg = [0, 0, 170] = #0000AA
    assert!(
        screen.contains("#0000AA") || screen.contains("#0000aa"),
        "Should show Nostalgia's blue background #0000AA. Screen:\n{}",
        screen
    );

    // Should NOT have dark theme's background color
    assert!(
        !screen.contains("#1E1E1E"),
        "Should NOT show Dark theme's background #1E1E1E. Screen:\n{}",
        screen
    );
}

/// Test that deleteTheme API correctly deletes a user theme
/// This tests the full lifecycle: create theme, verify it exists, delete it, verify it's gone
#[test]
fn test_delete_theme_api() {
    // Create isolated directory context for proper test isolation
    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());

    // Create user themes directory
    fs::create_dir_all(dir_context.themes_dir()).unwrap();

    // Create a test theme that we'll delete
    let test_theme = r#"{
        "name": "to-be-deleted",
        "editor": {"bg": [100, 100, 100], "fg": [200, 200, 200]},
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    let theme_path = dir_context.themes_dir().join("to-be-deleted.json");
    fs::write(&theme_path, test_theme).unwrap();

    // Verify the theme file exists
    assert!(
        theme_path.exists(),
        "Theme file should exist before deletion"
    );

    // Create project directory with a test plugin that calls deleteTheme
    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    // Create a test plugin that will delete the theme
    let delete_plugin = r#"
const editor = getEditor();

// Global state to track deletion result
let deleteResult: string = "not_run";

globalThis.test_delete_theme = async function(): Promise<void> {
    try {
        await editor.deleteTheme("to-be-deleted");
        deleteResult = "success";
        editor.setStatus("Theme deleted successfully");
    } catch (e) {
        deleteResult = "error: " + String(e);
        editor.setStatus("Delete failed: " + String(e));
    }
};

globalThis.test_check_result = function(): void {
    editor.setStatus("Result: " + deleteResult);
};

editor.registerCommand(
    "Test: Delete Theme",
    "Delete the to-be-deleted theme",
    "test_delete_theme",
    null
);

editor.registerCommand(
    "Test: Check Result",
    "Check delete result",
    "test_check_result",
    null
);

editor.setStatus("Delete theme test plugin loaded");
"#;
    fs::write(plugins_dir.join("delete_test.ts"), delete_plugin).unwrap();

    // Copy plugin lib for TypeScript support
    copy_plugin_lib(&plugins_dir);

    // Create harness with isolated directory context
    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context.clone(),
    )
    .unwrap();

    harness.render().unwrap();

    // Run the delete command via Quick Open
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Test: Delete Theme").unwrap();
    harness
        .wait_until(|h| h.screen_to_string().contains("Delete Theme"))
        .unwrap();

    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Wait for deletion to complete
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("deleted successfully") || screen.contains("Delete failed")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Verify deletion was successful
    assert!(
        screen.contains("deleted successfully"),
        "Theme deletion should succeed. Screen:\n{}",
        screen
    );

    // Verify the theme file no longer exists
    assert!(
        !theme_path.exists(),
        "Theme file should be deleted (moved to trash)"
    );
}

/// Test that "Inspect Theme at Cursor" command opens the theme editor
/// at the correct field for the theme key under the cursor.
#[test]
fn test_inspect_theme_at_cursor_opens_theme_editor() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    // Create a test file so the cursor is on editor content
    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello world\nLine two\nLine three\n").unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Cursor is now on editor content — run "Inspect Theme at Cursor"
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness.type_text("Inspect Theme at Cursor").unwrap();
    harness.render().unwrap();

    harness.assert_screen_contains("Inspect Theme at Cursor");

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

    // Wait for the theme editor to open and auto-navigate to the editor field
    // (the resolved key will be editor.fg or editor.bg, so "Editor" section expands).
    // On macOS the long temp-dir path can push "editor.fg"/"editor.bg" off the right
    // panel header, so also match the selected-field indicator (▸) next to the field name.
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("editor.fg")
                || screen.contains("editor.bg")
                || screen.contains("\u{25B8} fg")
                || screen.contains("\u{25B8} bg")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // The theme editor should auto-load the current theme (no "Select theme" prompt)
    assert!(
        !screen.contains("Select theme to edit"),
        "Should NOT prompt for theme selection — should auto-load current theme. Screen:\n{}",
        screen
    );
}

/// Test multiple rounds of inspect → focus source buffer → inspect again.
/// Verifies the theme editor re-navigates correctly when already open.
#[test]
fn test_inspect_theme_at_cursor_multiple_rounds() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello world\nLine two\nLine three\n").unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // === Round 1: First inspect ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Inspect Theme at Cursor").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("editor.fg")
                || screen.contains("editor.bg")
                || screen.contains("\u{25B8} fg")
                || screen.contains("\u{25B8} bg")
        })
        .unwrap();

    // === Switch back to source buffer (Ctrl+PageDown = next_buffer) ===
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Verify we're back on the source file
    harness
        .wait_until(|h| h.screen_to_string().contains("Hello world"))
        .unwrap();

    // === Round 2: Inspect again while theme editor is already open ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Inspect Theme at Cursor").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Theme editor should re-focus (the hook navigates when already open)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("editor.fg")
                || screen.contains("editor.bg")
                || screen.contains("\u{25B8} fg")
                || screen.contains("\u{25B8} bg")
        })
        .unwrap();

    // === Switch back to source again ===
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| h.screen_to_string().contains("Hello world"))
        .unwrap();

    // === Round 3: One more inspect to confirm stability ===
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Inspect Theme at Cursor").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("editor.fg")
                || screen.contains("editor.bg")
                || screen.contains("\u{25B8} fg")
                || screen.contains("\u{25B8} bg")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Should still not have prompted for theme selection at any point
    assert!(
        !screen.contains("Select theme to edit"),
        "Should never prompt for theme selection during inspect. Screen:\n{}",
        screen
    );
}

/// Test that saving a built-in theme as a new name produces a complete, valid theme file.
/// Reproduces a bug where the saved file was incomplete (only the edited field + name),
/// causing it to fail ThemeFile deserialization and not appear in Select Theme.
#[test]
fn test_save_builtin_theme_produces_valid_file() {
    init_tracing_from_env();

    // Create isolated directory context so we control the themes directory
    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());
    fs::create_dir_all(dir_context.themes_dir()).unwrap();

    // Create project directory with plugins
    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello world\n").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context.clone(),
    )
    .unwrap();

    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Open theme editor via command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for theme selection prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    // Select the "light" builtin theme
    harness.type_text("light").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for theme editor to load
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor") || screen.contains("*Theme Editor*")
        })
        .unwrap();

    // Navigate to a color field and edit it (press Enter on the first field)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for color input prompt (should show a # hex prefix)
    harness
        .wait_until(|h| h.screen_to_string().contains("#"))
        .unwrap();

    // Clear input and type a new color
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("#FF0000").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to redisplay
    harness
        .wait_until(|h| h.screen_to_string().contains("Theme Editor"))
        .unwrap();

    // Save with Ctrl+S — since it's a builtin theme, this triggers Save As
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Wait for save-as prompt
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Save") || screen.contains("name")
        })
        .unwrap();

    // Type a new name (prompt starts empty)
    harness.render().unwrap();
    harness.type_text("light-custom").unwrap();
    harness.render().unwrap();

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

    // Wait for save confirmation
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("saved") || screen.contains("Saved") || screen.contains("applied")
        })
        .unwrap();

    // Now verify the saved file is a valid, complete theme
    let saved_path = dir_context.themes_dir().join("light-custom.json");
    assert!(
        saved_path.exists(),
        "Saved theme file should exist at {:?}.\nFiles in themes dir: {:?}",
        saved_path,
        fs::read_dir(dir_context.themes_dir())
            .map(|entries| entries
                .filter_map(|e| e.ok())
                .map(|e| e.file_name())
                .collect::<Vec<_>>())
            .unwrap_or_default()
    );

    let content = fs::read_to_string(&saved_path).unwrap();

    // The file must deserialize as a valid ThemeFile
    let theme_file: Result<fresh::view::theme::ThemeFile, _> = serde_json::from_str(&content);
    assert!(
        theme_file.is_ok(),
        "Saved theme must be a valid ThemeFile. Got error: {:?}\nFile content ({} bytes):\n{}",
        theme_file.err(),
        content.len(),
        content
    );

    let theme = theme_file.unwrap();
    assert_eq!(theme.name, "light-custom");

    // The file must contain all required sections — not just the edited field
    let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
    for section in &["editor", "ui", "search", "diagnostic", "syntax"] {
        assert!(
            parsed.get(section).is_some(),
            "Saved theme is missing required section '{}'. File content:\n{}",
            section,
            content
        );
    }

    // The editor section should have more than just the one edited field
    let editor_obj = parsed.get("editor").unwrap().as_object().unwrap();
    assert!(
        editor_obj.len() > 1,
        "Editor section should contain all original fields, not just the edited one. \
         Got {} fields: {:?}\nFile content:\n{}",
        editor_obj.len(),
        editor_obj.keys().collect::<Vec<_>>(),
        content
    );
}

/// Test that saving a theme works when the themes directory does not exist yet
/// (fresh install scenario). Reproduces #1180 where Save As fails because
/// ~/.config/fresh/themes is not created by the editor.
#[test]
fn test_issue_1180_save_theme_creates_themes_directory() {
    init_tracing_from_env();

    // Create isolated directory context but do NOT create the themes directory.
    // This simulates a fresh install where ~/.config/fresh/themes doesn't exist.
    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());
    // Intentionally NOT calling: fs::create_dir_all(dir_context.themes_dir())

    // Verify the themes directory really doesn't exist
    assert!(
        !dir_context.themes_dir().exists(),
        "Themes directory should not exist before save"
    );

    // Create project directory with plugins
    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello world\n").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context.clone(),
    )
    .unwrap();

    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();

    // Open theme editor via command palette
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for theme selection prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    // Select the "light" builtin theme
    harness.type_text("light").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for theme editor to load
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor") || screen.contains("*Theme Editor*")
        })
        .unwrap();

    // Navigate to a color field and edit it
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for color input prompt
    harness
        .wait_until(|h| h.screen_to_string().contains("#"))
        .unwrap();

    // Clear input and type a new color
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("#FF0000").unwrap();
    harness.render().unwrap();

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

    // Wait for theme editor to redisplay
    harness
        .wait_until(|h| h.screen_to_string().contains("Theme Editor"))
        .unwrap();

    // Save with Ctrl+Shift+S (Save As) to trigger the save-as flow
    harness
        .send_key(
            KeyCode::Char('S'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        )
        .unwrap();
    harness.render().unwrap();

    // Wait for save-as prompt
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Save") || screen.contains("name")
        })
        .unwrap();

    // Type a new name for the theme
    harness.type_text("my-fresh-theme").unwrap();
    harness.render().unwrap();

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

    // Wait for save confirmation
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("saved") || screen.contains("Saved") || screen.contains("applied")
        })
        .unwrap();

    // Verify the themes directory was created
    assert!(
        dir_context.themes_dir().exists(),
        "Themes directory should have been created by the save operation"
    );

    // Verify the saved theme file exists and is valid
    let saved_path = dir_context.themes_dir().join("my-fresh-theme.json");
    assert!(
        saved_path.exists(),
        "Saved theme file should exist at {:?}.\nThemes dir exists: {}\nFiles in themes dir: {:?}",
        saved_path,
        dir_context.themes_dir().exists(),
        fs::read_dir(dir_context.themes_dir())
            .map(|entries| entries
                .filter_map(|e| e.ok())
                .map(|e| e.file_name())
                .collect::<Vec<_>>())
            .unwrap_or_default()
    );

    let content = fs::read_to_string(&saved_path).unwrap();
    let theme_file: Result<fresh::view::theme::ThemeFile, _> = serde_json::from_str(&content);
    assert!(
        theme_file.is_ok(),
        "Saved theme must be a valid ThemeFile. Got error: {:?}\nFile content:\n{}",
        theme_file.err(),
        content
    );

    let theme = theme_file.unwrap();
    assert_eq!(theme.name, "my-fresh-theme");
}

/// Test that after saving a custom theme, "Inspect Theme at Cursor" works
/// with the newly saved theme active. Reproduces a bug where the normalized
/// theme name (underscores→hyphens) didn't match the filename on disk.
#[test]
fn test_inspect_after_saving_custom_theme() {
    init_tracing_from_env();
    fresh::services::signal_handler::install_signal_handlers();

    let context_temp = tempfile::TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(context_temp.path());
    fs::create_dir_all(dir_context.themes_dir()).unwrap();

    let project_temp = tempfile::TempDir::new().unwrap();
    let project_root = project_temp.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let test_file = project_root.join("test.txt");
    fs::write(&test_file, "Hello world\n").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        120,
        40,
        Default::default(),
        project_root.clone(),
        dir_context.clone(),
    )
    .unwrap();

    harness.open_file(&test_file).unwrap();
    harness.render().unwrap();
    tracing::warn!("[test] file opened, starting step 1");

    // === Step 1: Open theme editor, select builtin, edit a color, save as custom ===

    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Edit Theme").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    tracing::warn!("[test] waiting for 'Select theme to edit'");
    harness
        .wait_until(|h| h.screen_to_string().contains("Select theme to edit"))
        .unwrap();

    tracing::warn!("[test] typing 'light' and pressing Enter");
    harness.type_text("light").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    tracing::warn!("[test] waiting for Theme Editor tab");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Theme Editor") || screen.contains("*Theme Editor*")
        })
        .unwrap();

    // Expand Editor section and navigate to the first color field (bg)
    tracing::warn!("[test] expanding Editor section");
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Edit the color field
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    tracing::warn!("[test] waiting for '#' (color edit field)");
    harness
        .wait_until(|h| h.screen_to_string().contains("#"))
        .unwrap();
    tracing::warn!("[test] typing color #FF0000");
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("#FF0000").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    tracing::warn!("[test] waiting for Theme Editor after color edit");
    harness
        .wait_until(|h| h.screen_to_string().contains("Theme Editor"))
        .unwrap();

    // Save as "light_custom" (with underscore to test normalization)
    tracing::warn!("[test] pressing Ctrl+S to save");
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    tracing::warn!("[test] waiting for 'Save theme as' dialog");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Save theme as")
        })
        .unwrap();
    harness.render().unwrap();
    tracing::warn!("[test] typing 'light_custom' and pressing Enter");
    harness.type_text("light_custom").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    tracing::warn!("[test] waiting for saved/applied confirmation");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("saved") || screen.contains("Saved") || screen.contains("applied")
        })
        .unwrap();

    // === Step 2: Close theme editor via Escape ===
    tracing::warn!("[test] step 2: closing theme editor via Escape");
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    tracing::warn!("[test] waiting for 'Hello world' (main editor)");
    harness
        .wait_until(|h| h.screen_to_string().contains("Hello world"))
        .unwrap();

    // === Step 3: Inspect Theme at Cursor — should work with the custom theme ===
    tracing::warn!("[test] step 3: opening Inspect Theme at Cursor");
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Inspect Theme at Cursor").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for theme editor to reopen and auto-navigate to editor fields.
    // The full qualified name (editor.fg / editor.bg) appears in the right panel
    // header, but on macOS the long temp-dir path in the left header can push it
    // off-screen.  Fall back to checking for the selected-field indicator (▸)
    // next to the short field name in the tree panel.
    tracing::warn!("[test] waiting for editor.fg/editor.bg fields");
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("editor.fg")
                || screen.contains("editor.bg")
                || screen.contains("\u{25B8} fg")
                || screen.contains("\u{25B8} bg")
        })
        .unwrap();

    let screen = harness.screen_to_string();

    // Should NOT show "Failed to load" error
    assert!(
        !screen.contains("Failed to load"),
        "Should not fail to load the custom theme. Screen:\n{}",
        screen
    );
}

/// Test that clicking on a palette swatch in the right panel applies the correct color.
/// Bug reproduction: clicking on the 5th palette swatch was applying the 1st swatch's color
/// because the byte offset calculation for click column detection was wrong.
#[test]
fn test_palette_swatch_click_targets_correct_column() {
    init_tracing_from_env();
    fresh::services::signal_handler::install_signal_handlers();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "dark",
        "editor": {
            "bg": [30, 30, 30],
            "fg": [212, 212, 212],
            "cursor": [82, 139, 255],
            "selection_bg": [38, 79, 120],
            "current_line_bg": [40, 40, 40],
            "line_number_fg": [100, 100, 100],
            "line_number_bg": [30, 30, 30]
        },
        "ui": {},
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("dark.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();
    open_theme_editor(&mut harness);

    // Navigate down from section header to first color field (bg)
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Wait for theme editor to fully render with color palette
    harness
        .wait_until(|h| h.screen_to_string().contains("Color Palette"))
        .unwrap();

    // Find the first row of palette swatches (██ characters in the right panel area).
    // The left panel is 38 chars wide + 1 divider = 39, so right panel starts at col 39.
    // The palette row text is " " + " ██ ██ ██..." with a " " prefix, so first swatch
    // starts at approximately col 41.
    // Each swatch pattern: prefix(1 char) + "██"(2 chars) = 3 chars per swatch.
    // col N swatch starts at screen column 41 + 3*N.

    // Find the screen row that contains "Color Palette:" to locate palette rows
    let screen = harness.screen_to_string();
    let lines: Vec<&str> = screen.lines().collect();
    let palette_label_row = lines
        .iter()
        .position(|line| line.contains("Color Palette:"))
        .expect("Should find 'Color Palette:' label on screen");

    // Palette rows start right after the label
    let palette_row_y = (palette_label_row + 1) as u16;

    // Verify palette swatches are visible at this row
    assert!(
        lines[palette_row_y as usize].contains("██"),
        "Palette row should contain swatch characters. Row {}: '{}'",
        palette_row_y,
        lines[palette_row_y as usize]
    );

    // Locate the first palette swatch (`██`) on the palette row at runtime,
    // then compute sibling swatch columns. The buffer-group theme editor
    // renders the palette inside the right panel (picker), so the absolute
    // screen column of col 0 depends on the tree/picker split ratio and is
    // not fixed. Each swatch is 2 chars of `██` followed by 1 char of
    // separator, so col N is col 0 + 3*N. Previously the test hardcoded
    // x=41 which happened to be the `fg` row's swatch column in the LEFT
    // (tree) panel — clicking there would move the tree selection instead
    // of applying a palette color.
    let swatch_col_0_x: u16 = {
        // The left panel also contains `██` (field swatches). We must find
        // the palette swatches in the RIGHT panel — i.e. the first `██`
        // that appears AFTER the vertical divider `│` in the palette row.
        let row_cells: Vec<String> = (0..120)
            .map(|x| {
                harness
                    .get_cell(x, palette_row_y)
                    .unwrap_or_else(|| " ".to_string())
            })
            .collect();
        let divider_col = row_cells
            .iter()
            .position(|s| s == "")
            .expect("palette row should contain a `│` divider") as u16;
        // Scan after the divider for two adjacent `█` cells.
        let mut found = None;
        let mut x = divider_col + 1;
        while x + 1 < 120 {
            if row_cells[x as usize] == "" && row_cells[(x + 1) as usize] == "" {
                found = Some(x);
                break;
            }
            x += 1;
        }
        found.expect("palette row should contain `██` after the divider")
    };
    let swatch_col_4_x: u16 = swatch_col_0_x + 3 * 4;

    let color_at_col0 = harness
        .get_cell_style(swatch_col_0_x, palette_row_y)
        .and_then(|s| s.fg);
    let color_at_col4 = harness
        .get_cell_style(swatch_col_4_x, palette_row_y)
        .and_then(|s| s.fg);

    // The two swatches should have different colors (hue 0 vs hue 120)
    assert_ne!(
        color_at_col0, color_at_col4,
        "Col 0 and col 4 palette swatches should be different colors: {:?} vs {:?}",
        color_at_col0, color_at_col4
    );

    // Click on col 4 swatch (the 5th one)
    harness.mouse_click(swatch_col_4_x, palette_row_y).unwrap();
    harness.render().unwrap();

    // Wait for click to be processed and display updated
    harness
        .wait_until(|h| {
            // The Hex: line should change from the initial bg color (#1E1E1E)
            let s = h.screen_to_string();
            s.lines()
                .any(|l| l.contains("Hex:") && !l.contains("#1E1E1E"))
        })
        .unwrap();

    let screen_after_click = harness.screen_to_string();

    // Now click on col 0 swatch (should apply a different color)
    harness.mouse_click(swatch_col_0_x, palette_row_y).unwrap();
    harness.render().unwrap();

    // Wait for the hex to change again
    let hex_after_col4 = screen_after_click
        .lines()
        .find(|l| l.contains("Hex:"))
        .unwrap_or("")
        .to_string();

    harness
        .wait_until(|h| {
            let s = h.screen_to_string();
            if let Some(hex_line) = s.lines().find(|l| l.contains("Hex:")) {
                hex_line != hex_after_col4
            } else {
                false
            }
        })
        .unwrap();

    let screen_after_second_click = harness.screen_to_string();
    let hex_after_col0 = screen_after_second_click
        .lines()
        .find(|l| l.contains("Hex:"))
        .unwrap_or("")
        .to_string();

    // The two clicks should have produced different hex values
    assert_ne!(
        hex_after_col4, hex_after_col0,
        "Clicking col 4 and col 0 palette swatches should apply different colors.\nAfter col 4: {}\nAfter col 0: {}",
        hex_after_col4, hex_after_col0
    );

    harness.assert_no_plugin_errors();
}

/// Test that PageUp/PageDown keys work for navigating the theme editor's left sidebar.
/// Bug: PageUp/PageDown keys were not bound in the theme editor mode,
/// so pressing them did nothing.
#[test]
fn test_theme_editor_page_up_page_down() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();

    copy_plugin(&plugins_dir, "theme_editor");

    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    // Use a theme with enough fields so PageDown has room to move
    let test_theme = r#"{
        "name": "test",
        "editor": {
            "bg": [30, 30, 30],
            "fg": [200, 200, 200],
            "cursor": [255, 255, 255],
            "selection_bg": [38, 79, 120],
            "current_line_bg": [40, 40, 40],
            "line_number_fg": [100, 100, 100],
            "line_number_bg": [30, 30, 30],
            "ruler_bg": [50, 50, 50],
            "whitespace_indicator": [70, 70, 70],
            "diff_add_bg": [35, 60, 35],
            "diff_remove_bg": [70, 35, 35],
            "diff_modify_bg": [40, 38, 30],
            "inactive_cursor": [100, 100, 100]
        },
        "ui": {
            "tab_active_bg": [50, 50, 50],
            "tab_inactive_bg": [30, 30, 30],
            "tab_active_fg": [200, 200, 200],
            "tab_inactive_fg": [128, 128, 128],
            "statusbar_bg": [0, 95, 135],
            "statusbar_fg": [200, 200, 200],
            "menu_bg": [37, 37, 38],
            "menu_fg": [200, 200, 200],
            "menu_selected_bg": [4, 57, 94],
            "menu_selected_fg": [255, 255, 255],
            "menu_border": [69, 69, 69],
            "prompt_bg": [37, 37, 38],
            "prompt_fg": [200, 200, 200]
        },
        "syntax": {
            "keyword": [86, 156, 214],
            "string": [206, 145, 120],
            "comment": [106, 153, 85],
            "function": [220, 220, 170],
            "type": [78, 201, 176],
            "constant": [79, 193, 255],
            "variable": [156, 220, 254],
            "operator": [200, 200, 200]
        }
    }"#;
    fs::write(themes_dir.join("test.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();

    harness.render().unwrap();

    // Open theme editor
    open_theme_editor(&mut harness);

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

    // The initial selection should be on the first field (e.g. bg under Editor)
    // Press PageDown - it should jump multiple fields at once
    harness
        .send_key(KeyCode::PageDown, KeyModifiers::NONE)
        .unwrap();
    harness
        .wait_until(|h| h.screen_to_string() != screen_initial)
        .unwrap();

    let screen_after_pagedown = harness.screen_to_string();

    // After PageDown the selection indicator (▸) should have moved significantly
    // Find the selected line (contains ▸) in each screen
    let _initial_selected = screen_initial
        .lines()
        .position(|l| l.contains('\u{25B8}'))
        .expect("Should have a selected line initially");
    let after_pagedown_selected = screen_after_pagedown
        .lines()
        .position(|l| l.contains('\u{25B8}'))
        .expect("Should have a selected line after PageDown");

    // PageDown should have moved by more than 1 line (i.e. it's not just Down)
    // OR the view should have scrolled (selected item on a different logical index)
    // The key point: the screen should have changed after pressing PageDown.
    assert!(
        screen_after_pagedown != screen_initial,
        "PageDown should change the screen"
    );

    // Now press PageUp to go back
    let screen_before_pageup = harness.screen_to_string();
    harness
        .send_key(KeyCode::PageUp, KeyModifiers::NONE)
        .unwrap();
    harness
        .wait_until(|h| h.screen_to_string() != screen_before_pageup)
        .unwrap();

    let screen_after_pageup = harness.screen_to_string();

    // After PageUp, the selection should have moved back up
    let after_pageup_selected = screen_after_pageup
        .lines()
        .position(|l| l.contains('\u{25B8}'))
        .expect("Should have a selected line after PageUp");

    // PageUp should move selection upward (or at least change the display)
    assert!(
        after_pageup_selected <= after_pagedown_selected
            || screen_after_pageup != screen_after_pagedown,
        "PageUp should move selection up. After PageDown line: {}, After PageUp line: {}",
        after_pagedown_selected,
        after_pageup_selected
    );

    harness.assert_no_plugin_errors();
}

/// Test that named color swatches in the theme editor use the native ANSI
/// color (e.g. Color::Yellow) rather than an RGB approximation.
///
/// BUG: When a theme field uses a named color like "Yellow", the swatch (██)
/// in the theme editor was rendered as Color::Rgb(255, 255, 0) instead of
/// Color::Yellow. This is wrong because the actual theme renders Color::Yellow
/// as ANSI color 3 (via crossterm), which terminals display as a different
/// shade than RGB(255, 255, 0). The swatch should use the native ANSI color
/// so it matches what the user actually sees.
#[test]
fn test_named_color_swatch_uses_native_ansi_color() {
    init_tracing_from_env();
    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    // Create a theme with a named color "Yellow" for tab_active_fg.
    // The swatch should render as Color::Yellow (native ANSI),
    // not Color::Rgb(255, 255, 0).
    let themes_dir = project_root.join("themes");
    fs::create_dir(&themes_dir).unwrap();
    let test_theme = r#"{
        "name": "dark",
        "editor": {
            "bg": [30, 30, 30],
            "fg": [212, 212, 212]
        },
        "ui": {
            "tab_active_fg": "Yellow",
            "tab_active_bg": [0, 0, 200]
        },
        "search": {},
        "diagnostic": {},
        "syntax": {}
    }"#;
    fs::write(themes_dir.join("dark.json"), test_theme).unwrap();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(120, 40, Default::default(), project_root)
            .unwrap();
    harness.render().unwrap();

    // Open theme editor
    open_theme_editor(&mut harness);

    // Wait for the theme editor to fully display
    harness
        .wait_until(|h| h.screen_to_string().contains("Theme Editor"))
        .unwrap();

    // The "ui" section is collapsed by default. Navigate down until the
    // selection indicator (▸) lands on the UI Elements section header.
    //
    // Use true semantic waiting: after each Down press, wait until the
    // *selected line's content* (the line containing ▸) actually changes.
    // Waiting on "screen changed" is unreliable because unrelated async
    // work (timers, async redraws, etc.) can flip a cell between the
    // key-press and the real selection update, making the previous wait
    // return early and letting the test race ahead of the plugin thread —
    // which was the source of this test's intermittent timeouts.
    let selection_indicator = '\u{25B8}'; //    let selected_line = |h: &EditorTestHarness| -> Option<String> {
        h.screen_to_string()
            .lines()
            .find(|l| l.contains(selection_indicator))
            .map(|s| s.to_string())
    };
    let line_is_collapsed_ui_section = |l: &str| l.contains("> UI") || l.contains("> ui");
    let line_is_expanded_ui_section = |l: &str| l.contains("▼ UI") || l.contains("▼ ui");

    loop {
        if selected_line(&harness)
            .as_deref()
            .map(line_is_collapsed_ui_section)
            .unwrap_or(false)
        {
            break;
        }
        let before = selected_line(&harness);
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        // Wait until ▸ is visible AND on a different line. Without the
        // is_some() guard, a transient scroll-lag frame (where ▸ is
        // off-viewport) would satisfy `None != Some(old)`, letting the
        // loop capture `before = None` on the next iteration and then
        // block forever on `None != None`.
        harness
            .wait_until(|h| {
                let cur = selected_line(h);
                cur.is_some() && cur != before
            })
            .unwrap();
    }

    // Expand the UI section and wait semantically for the selected line
    // to flip from collapsed (▸> UI) to expanded (▸▼ UI).
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .wait_until(|h| {
            selected_line(h)
                .as_deref()
                .map(line_is_expanded_ui_section)
                .unwrap_or(false)
        })
        .unwrap();

    // Navigate down to tab_active_fg within the expanded UI section.
    // Same semantic-wait pattern: wait for the selected line's content to
    // change after each Down press, not just for any screen cell to flip.
    loop {
        if selected_line(&harness)
            .as_deref()
            .map(|l| l.contains("tab_active_fg"))
            .unwrap_or(false)
        {
            break;
        }
        let before = selected_line(&harness);
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness
            .wait_until(|h| {
                let cur = selected_line(h);
                cur.is_some() && cur != before
            })
            .unwrap();
    }

    // Move selection away so the tab_active_fg row renders without the
    // selection highlight (which adds a bg overlay that breaks the
    // fg==bg swatch detection).
    let before = selected_line(&harness);
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness
        .wait_until(|h| {
            let cur = selected_line(h);
            cur.is_some() && cur != before
        })
        .unwrap();

    // Wait for the tab_active_fg swatch to render with the correct native
    // ANSI Yellow color. On slow CI the plugin may not have finished
    // painting the inline overlay yet.
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            let lines: Vec<&str> = screen.lines().collect();
            let Some(row) = lines
                .iter()
                .position(|l| l.contains("tab_active_fg") && l.contains("██"))
            else {
                return false;
            };
            find_swatch_color(h, row as u16) == Some(Color::Yellow)
        })
        .unwrap();
}

/// Regression test: switching the active theme via "Select Theme" while a
/// theme-editor plugin buffer is open must refresh the overlay colors the
/// plugin painted with.
///
/// The bug was that the plugin resolved its UI palette client-side — it
/// read `editor.getThemeData()` in JS, dug out the RGB tuple for
/// `syntax.keyword`, and handed the RGB array to `setVirtualBufferContent`.
/// That made the overlay an `OverlayFace::Style` with baked RGB, so the
/// core's render-time theme-key resolver (`split_rendering.rs` →
/// `ThemedStyle` branch) was bypassed and a theme switch left the buffer
/// painted in the old theme's colors.
///
/// The fix is to pass theme-key strings (e.g. `"syntax.keyword"`) straight
/// through to the core. `OverlayFace::from_options` then stores the key
/// in `ThemedStyle { fg_theme: Some("syntax.keyword"), .. }` and the next
/// render resolves it against `ctx.theme` — which is the new theme after
/// `apply_theme`.
#[test]
fn test_theme_editor_colors_update_on_theme_change() {
    init_tracing_from_env();

    let temp_dir = tempfile::TempDir::new().unwrap();
    let project_root = temp_dir.path().join("project_root");
    fs::create_dir(&project_root).unwrap();

    let plugins_dir = project_root.join("plugins");
    fs::create_dir(&plugins_dir).unwrap();
    copy_plugin(&plugins_dir, "theme_editor");

    let mut config = fresh::config::Config::default();
    config.theme = "dark".into();

    let mut harness =
        EditorTestHarness::with_config_and_working_dir(140, 40, config, project_root).unwrap();

    harness.render().unwrap();

    // Open the theme editor with "dark" selected.
    open_theme_editor(&mut harness);

    // The "Theme Editor:" header row carries a hardcoded `colors.header`
    // fg of [100, 180, 255] (blue) AND the buffer's default editor.bg.
    // Record both the text-cell and an empty cell on the same row.
    let header_pos = harness
        .find_text_on_screen("Theme Editor:")
        .expect("'Theme Editor:' header should be visible in the theme editor buffer");
    let dark_header_fg = harness
        .get_cell_style(header_pos.0, header_pos.1)
        .expect("header cell should have a style")
        .fg;

    // Sample a cell well to the right on the same row where there's no text
    // (so we get the buffer's default bg, not an overlay).
    let empty_col = header_pos.0.saturating_add(60);
    let dark_row_empty_bg = harness
        .get_cell_style(empty_col, header_pos.1)
        .expect("cell should have a style")
        .bg;
    assert_eq!(
        dark_row_empty_bg,
        Some(Color::Rgb(30, 30, 30)),
        "With dark theme, theme editor buffer empty cells should have bg [30,30,30], got {:?}. \
         Screen:\n{}",
        dark_row_empty_bg,
        harness.screen_to_string(),
    );

    // --- Switch to the light theme via the command palette ---
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    harness.type_text("Select Theme").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.wait_for_screen_contains("Select theme").unwrap();

    for _ in 0..20 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
    }
    harness.type_text("light").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.wait_for_prompt_closed().unwrap();
    harness.render().unwrap();

    // After the switch, both the buffer background AND the hardcoded header
    // fg should reflect the new theme. In particular, the plugin's cached
    // overlay-styles (baked RGB) should be refreshed so they don't stay as
    // the dark theme's values against the new light bg.
    let header_pos = harness
        .find_text_on_screen("Theme Editor:")
        .expect("'Theme Editor:' header should still be visible after theme switch");
    let empty_col = header_pos.0.saturating_add(60);
    let light_row_empty_bg = harness
        .get_cell_style(empty_col, header_pos.1)
        .expect("cell should have a style")
        .bg;
    assert_eq!(
        light_row_empty_bg,
        Some(Color::Rgb(255, 255, 255)),
        "After switching to light theme, theme editor buffer empty cells should have \
         bg [255,255,255], got {:?}. Screen:\n{}",
        light_row_empty_bg,
        harness.screen_to_string(),
    );

    let light_header_fg = harness
        .get_cell_style(header_pos.0, header_pos.1)
        .expect("header cell should have a style")
        .fg;

    // BUG REPRODUCTION: the plugin-provided header highlight fg is baked at
    // `setVirtualBufferContent` time and does not refresh when the theme
    // changes. We assert that the fg DOES change — this is the behaviour
    // the user expects, and it currently fails because the plugin's
    // hardcoded RGB highlights never get re-applied.
    assert_ne!(
        light_header_fg,
        dark_header_fg,
        "After switching themes, the theme editor's header-text fg should be refreshed \
         (expected it to differ from the dark-theme value {:?}). The plugin-provided \
         overlay colors appear to be baked at creation time and never refreshed on \
         theme change. Screen:\n{}",
        dark_header_fg,
        harness.screen_to_string(),
    );
}

/// Find the fg color of the swatch (██) on a given screen row.
/// Scans the left panel area (columns 0-37) for cells where fg == bg,
/// which indicates a color swatch.
fn find_swatch_color(harness: &EditorTestHarness, row: u16) -> Option<Color> {
    for col in 0..38 {
        if let Some(cell_text) = harness.get_cell(col, row) {
            if cell_text == "" {
                if let Some(style) = harness.get_cell_style(col, row) {
                    // Swatch cells have fg == bg (same color)
                    if style.fg.is_some() && style.fg == style.bg {
                        return style.fg;
                    }
                }
            }
        }
    }
    None
}