fresh-editor 0.2.11

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
//! Encoding support tests for fresh editor
//!
//! Property-based tests for detecting, loading, editing, and saving files with various encodings:
//! - UTF-8 (default)
//! - UTF-8 with BOM
//! - UTF-16 LE (Windows Unicode)
//! - UTF-16 BE
//! - ASCII
//! - Latin-1 (ISO-8859-1)
//! - Windows-1252 (ANSI)
//! - GB18030 (Chinese)
//! - GBK (Chinese simplified)

use crate::common::harness::EditorTestHarness;
use crossterm::event::{KeyCode, KeyModifiers};
use proptest::prelude::*;
use std::path::PathBuf;
use tempfile::TempDir;

// ============================================================================
// Test Data Constants
// ============================================================================

/// UTF-8 BOM bytes
const UTF8_BOM: &[u8] = &[0xEF, 0xBB, 0xBF];

/// UTF-16 LE BOM bytes
const UTF16_LE_BOM: &[u8] = &[0xFF, 0xFE];

/// UTF-16 BE BOM bytes
const UTF16_BE_BOM: &[u8] = &[0xFE, 0xFF];

// ============================================================================
// Encoding Test Utilities
// ============================================================================

/// Represents different text encodings for testing
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TestEncoding {
    Utf8,
    Utf8Bom,
    Utf16Le,
    Utf16Be,
    Latin1,
    Windows1252,
    Windows1250,
    Gb18030,
    Ascii,
}

impl TestEncoding {
    /// Encode a string to bytes in this encoding
    fn encode(&self, text: &str) -> Vec<u8> {
        match self {
            TestEncoding::Utf8 => text.as_bytes().to_vec(),
            TestEncoding::Utf8Bom => {
                let mut result = UTF8_BOM.to_vec();
                result.extend_from_slice(text.as_bytes());
                result
            }
            TestEncoding::Utf16Le => {
                let mut result = UTF16_LE_BOM.to_vec();
                for ch in text.encode_utf16() {
                    result.extend_from_slice(&ch.to_le_bytes());
                }
                result
            }
            TestEncoding::Utf16Be => {
                let mut result = UTF16_BE_BOM.to_vec();
                for ch in text.encode_utf16() {
                    result.extend_from_slice(&ch.to_be_bytes());
                }
                result
            }
            TestEncoding::Latin1 => {
                // Convert to Latin-1 (only works for chars <= 0xFF)
                text.chars()
                    .map(|c| {
                        if c as u32 <= 0xFF {
                            c as u8
                        } else {
                            b'?' // Replacement for non-Latin-1 chars
                        }
                    })
                    .collect()
            }
            TestEncoding::Windows1252 => {
                // Similar to Latin-1, with some differences in 0x80-0x9F range
                text.chars()
                    .map(|c| {
                        if c as u32 <= 0xFF {
                            c as u8
                        } else {
                            b'?' // Replacement
                        }
                    })
                    .collect()
            }
            TestEncoding::Windows1250 => {
                // Windows-1250 (Central European)
                // For testing, we encode common Polish/Czech characters
                let mut result = Vec::new();
                for c in text.chars() {
                    let byte = match c {
                        // Common Central European characters in Windows-1250
                        'ą' => 0xB9,
                        'ć' => 0xE6,
                        'ę' => 0xEA,
                        'ł' => 0xB3,
                        'ń' => 0xF1,
                        'ó' => 0xF3,
                        'ś' => 0x9C,
                        'ź' => 0x9F,
                        'ż' => 0xBF,
                        'Ą' => 0xA5,
                        'Ć' => 0xC6,
                        'Ę' => 0xCA,
                        'Ł' => 0xA3,
                        'Ń' => 0xD1,
                        'Ó' => 0xD3,
                        'Ś' => 0x8C,
                        'Ź' => 0x8F,
                        'Ż' => 0xAF,
                        // Czech characters
                        'á' => 0xE1,
                        'č' => 0xE8,
                        'ď' => 0xEF,
                        'é' => 0xE9,
                        'ě' => 0xEC,
                        'í' => 0xED,
                        'ň' => 0xF2,
                        'ř' => 0xF8,
                        'š' => 0x9A,
                        'ť' => 0x9D,
                        'ú' => 0xFA,
                        'ů' => 0xF9,
                        'ý' => 0xFD,
                        'ž' => 0x9E,
                        'Á' => 0xC1,
                        'Č' => 0xC8,
                        'Ď' => 0xCF,
                        'É' => 0xC9,
                        'Ě' => 0xCC,
                        'Í' => 0xCD,
                        'Ň' => 0xD2,
                        'Ř' => 0xD8,
                        'Š' => 0x8A,
                        'Ť' => 0x8D,
                        'Ú' => 0xDA,
                        'Ů' => 0xD9,
                        'Ý' => 0xDD,
                        'Ž' => 0x8E,
                        c if c.is_ascii() => c as u8,
                        _ => b'?', // Replacement for unmapped chars
                    };
                    result.push(byte);
                }
                result
            }
            TestEncoding::Gb18030 => {
                // For testing, we'll use a simple mapping for common Chinese chars
                // In real implementation, this would use encoding_rs
                let mut result = Vec::new();
                for c in text.chars() {
                    match c {
                        '' => result.extend_from_slice(&[0xC4, 0xE3]),
                        '' => result.extend_from_slice(&[0xBA, 0xC3]),
                        '' => result.extend_from_slice(&[0xCA, 0xC0]),
                        '' => result.extend_from_slice(&[0xBD, 0xE7]),
                        '\n' => result.push(0x0A),
                        '\r' => result.push(0x0D),
                        c if c.is_ascii() => result.push(c as u8),
                        _ => result.push(b'?'),
                    }
                }
                result
            }
            TestEncoding::Ascii => {
                // Only ASCII chars
                text.chars()
                    .map(|c| if c.is_ascii() { c as u8 } else { b'?' })
                    .collect()
            }
        }
    }

    /// Check if this encoding can represent the given text losslessly
    #[allow(dead_code)]
    fn can_encode_losslessly(&self, text: &str) -> bool {
        match self {
            TestEncoding::Utf8
            | TestEncoding::Utf8Bom
            | TestEncoding::Utf16Le
            | TestEncoding::Utf16Be => true,
            TestEncoding::Latin1 | TestEncoding::Windows1252 => {
                text.chars().all(|c| (c as u32) <= 0xFF)
            }
            TestEncoding::Windows1250 => {
                // Windows-1250 can encode ASCII and specific Central European characters
                text.chars().all(|c| {
                    c.is_ascii()
                        || matches!(
                            c,
                            // Polish characters
                            'ą' | 'ć'
                                | 'ę'
                                | 'ł'
                                | 'ń'
                                | 'ó'
                                | 'ś'
                                | 'ź'
                                | 'ż'
                                | 'Ą'
                                | 'Ć'
                                | 'Ę'
                                | 'Ł'
                                | 'Ń'
                                | 'Ó'
                                | 'Ś'
                                | 'Ź'
                                | 'Ż'
                                // Czech characters
                                | 'á'
                                | 'č'
                                | 'ď'
                                | 'é'
                                | 'ě'
                                | 'í'
                                | 'ň'
                                | 'ř'
                                | 'š'
                                | 'ť'
                                | 'ú'
                                | 'ů'
                                | 'ý'
                                | 'ž'
                                | 'Á'
                                | 'Č'
                                | 'Ď'
                                | 'É'
                                | 'Ě'
                                | 'Í'
                                | 'Ň'
                                | 'Ř'
                                | 'Š'
                                | 'Ť'
                                | 'Ú'
                                | 'Ů'
                                | 'Ý'
                                | 'Ž'
                        )
                })
            }
            TestEncoding::Ascii => text.is_ascii(),
            TestEncoding::Gb18030 => {
                // GB18030 can encode all Unicode, but our test implementation is limited
                text.chars().all(|c| {
                    c.is_ascii() || c == '\n' || c == '\r' || matches!(c, '' | '' | '' | '')
                })
            }
        }
    }

    /// Get the display name for this encoding
    #[allow(dead_code)]
    fn display_name(&self) -> &'static str {
        match self {
            TestEncoding::Utf8 => "UTF-8",
            TestEncoding::Utf8Bom => "UTF-8 BOM",
            TestEncoding::Utf16Le => "UTF-16 LE",
            TestEncoding::Utf16Be => "UTF-16 BE",
            TestEncoding::Latin1 => "Latin-1",
            TestEncoding::Windows1252 => "Windows-1252",
            TestEncoding::Windows1250 => "Windows-1250",
            TestEncoding::Gb18030 => "GB18030",
            TestEncoding::Ascii => "ASCII",
        }
    }
}

/// Create a temporary file with the given content in the specified encoding
fn create_encoded_file(dir: &TempDir, name: &str, encoding: TestEncoding, text: &str) -> PathBuf {
    let path = dir.path().join(name);
    let bytes = encoding.encode(text);
    std::fs::write(&path, &bytes).unwrap();
    path
}

// ============================================================================
// Proptest Strategies
// ============================================================================

/// Strategy for generating ASCII-only text (safe for all encodings)
fn ascii_text_strategy() -> impl Strategy<Value = String> {
    "[a-zA-Z0-9 ,.!?\\-_]{1,100}"
}

/// Strategy for generating text with Latin-1 characters
///
/// Generates realistic Latin-1 text that includes at least some ASCII characters
/// (spaces, punctuation) mixed with extended Latin-1 characters. This ensures
/// the text is distinguishable from CJK encodings, which is important because
/// pure sequences of bytes in the 0xA0-0xFF range are genuinely ambiguous.
///
/// IMPORTANT: The ASCII prefix is mandatory (never empty) to create "space + high byte"
/// patterns that distinguish Latin-1 from CJK encodings.
///
/// IMPORTANT: We only use Latin-1 characters in the 0xC0-0xFF range, NOT 0x80-0xBF.
/// Characters in 0x80-0xBF are valid UTF-8 continuation bytes, so sequences like
/// "飣" (0xE9 0xA3 0xA3) would be valid UTF-8 and detected as such, causing test failures.
/// By using only 0xC0-0xFF characters, sequences like "éé" (0xE9 0xE9) are NOT valid UTF-8.
fn latin1_text_strategy() -> impl Strategy<Value = String> {
    // Generate a prefix with at least one ASCII word (NEVER empty!)
    // The trailing space creates "space + high byte" pattern that signals Latin-1
    let ascii_prefix = prop::sample::select(vec![
        "Hello ", "Cafe ", "Text ", "File ", "Data ", "The ", "A ", "Test ", "Word ",
    ]);

    // Generate middle content with Latin-1 extended characters
    // NOTE: Only use characters in 0xC0-0xFF range to avoid generating valid UTF-8 sequences.
    // Excluded (0xA0-0xBF range, valid UTF-8 continuation bytes): £, ¥, ©, ®, ±, µ, ¶
    let latin1_chars = prop::collection::vec(
        prop::sample::select(vec![
            'é', 'è', 'ê', 'ë', 'à', 'â', 'ä', 'ç', 'ô', 'ö', 'ù', 'û', 'ü', 'ñ', 'ß', 'æ', 'ø',
            'å', 'ÿ', 'þ', 'ý', 'ü', 'û', 'ú', ' ', ' ', ' ',
        ]),
        3..30,
    );

    // Generate an optional ASCII suffix
    let ascii_suffix = prop::sample::select(vec![" end", " ok", ".", "", "", ""]);

    (ascii_prefix, latin1_chars, ascii_suffix).prop_map(|(prefix, chars, suffix)| {
        let middle: String = chars.into_iter().collect();
        format!("{}{}{}", prefix, middle, suffix)
    })
}

/// Strategy for generating text with Chinese characters
fn chinese_text_strategy() -> impl Strategy<Value = String> {
    prop::collection::vec(
        prop::sample::select(vec!['', '', '', '', ' ', '\n']),
        1..20,
    )
    .prop_map(|chars| chars.into_iter().collect())
}

/// Strategy for generating mixed text (ASCII + Chinese)
#[allow(dead_code)]
fn mixed_text_strategy() -> impl Strategy<Value = String> {
    (ascii_text_strategy(), chinese_text_strategy()).prop_map(|(a, b)| format!("{} {}", a, b))
}

/// Strategy for selecting an encoding
fn encoding_strategy() -> impl Strategy<Value = TestEncoding> {
    prop::sample::select(vec![
        TestEncoding::Utf8,
        TestEncoding::Utf8Bom,
        TestEncoding::Utf16Le,
        TestEncoding::Utf16Be,
        TestEncoding::Latin1,
        TestEncoding::Ascii,
    ])
}

/// Strategy for selecting Unicode-capable encodings only
fn unicode_encoding_strategy() -> impl Strategy<Value = TestEncoding> {
    prop::sample::select(vec![
        TestEncoding::Utf8,
        TestEncoding::Utf8Bom,
        TestEncoding::Utf16Le,
        TestEncoding::Utf16Be,
    ])
}

// ============================================================================
// Property-Based Tests
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(20))]

    /// Property: Loading an ASCII file in any encoding should display the same content
    #[test]
    fn prop_ascii_roundtrip(
        text in ascii_text_strategy(),
        encoding in encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "test.txt", encoding, &text);

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // The text should be displayed correctly (allowing for line break differences)
        let buffer_content = harness.get_buffer_content().unwrap();

        // Normalize line endings for comparison
        let normalized_text = text.replace("\r\n", "\n").replace('\r', "\n");
        let normalized_buffer = buffer_content.replace("\r\n", "\n").replace('\r', "\n");

        prop_assert!(
            normalized_buffer.contains(&normalized_text.trim()),
            "Buffer should contain the text. Expected: {:?}, Got: {:?}",
            normalized_text,
            normalized_buffer
        );
    }

    /// Property: Editing and saving a file should preserve its encoding
    #[test]
    fn prop_encoding_preserved_on_save(
        text in ascii_text_strategy().prop_filter("need content", |s| !s.is_empty()),
        encoding in unicode_encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "test.txt", encoding, &text);
        let original_bytes = std::fs::read(&file_path).unwrap();

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Make no changes, just save
        harness.send_key(KeyCode::Char('s'), KeyModifiers::CONTROL).unwrap();
        harness.render().unwrap();

        // Wait for save to complete using semantic waiting (not timeout)
        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        // File should be unchanged
        let saved_bytes = std::fs::read(&file_path).unwrap();

        prop_assert_eq!(
            saved_bytes,
            original_bytes,
            "File should be unchanged after save without edits"
        );
    }

    /// Property: Adding text and saving should produce valid content in the same encoding
    #[test]
    fn prop_edit_preserves_encoding(
        initial_text in ascii_text_strategy().prop_filter("need content", |s| s.len() > 5),
        added_text in "[a-zA-Z0-9]{1,20}",
        encoding in unicode_encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "test.txt", encoding, &initial_text);

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Add text at the end
        harness.send_key(KeyCode::End, KeyModifiers::CONTROL).unwrap();
        harness.type_text(&added_text).unwrap();
        harness.render().unwrap();

        // Save
        harness.send_key(KeyCode::Char('s'), KeyModifiers::CONTROL).unwrap();
        harness.render().unwrap();

        // Wait for save
        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        // Read and verify
        let saved_bytes = std::fs::read(&file_path).unwrap();

        // Check encoding markers are preserved
        match encoding {
            TestEncoding::Utf8Bom => {
                prop_assert!(
                    saved_bytes.starts_with(UTF8_BOM),
                    "UTF-8 BOM should be preserved"
                );
            }
            TestEncoding::Utf16Le => {
                prop_assert!(
                    saved_bytes.starts_with(UTF16_LE_BOM),
                    "UTF-16 LE BOM should be preserved"
                );
            }
            TestEncoding::Utf16Be => {
                prop_assert!(
                    saved_bytes.starts_with(UTF16_BE_BOM),
                    "UTF-16 BE BOM should be preserved"
                );
            }
            _ => {}
        }
    }

    /// Property: Chinese text should be preserved when using Unicode encodings
    #[test]
    fn prop_chinese_text_preserved(
        text in chinese_text_strategy(),
        encoding in unicode_encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "chinese.txt", encoding, &text);

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        let buffer_content = harness.get_buffer_content().unwrap();

        // Normalize and compare
        let normalized_text = text.replace("\r\n", "\n").replace('\r', "\n");
        let normalized_buffer = buffer_content.replace("\r\n", "\n").replace('\r', "\n");

        // Check that all non-whitespace characters are preserved
        for c in normalized_text.chars() {
            if !c.is_whitespace() {
                prop_assert!(
                    normalized_buffer.contains(c),
                    "Character {:?} should be in buffer. Buffer: {:?}",
                    c,
                    normalized_buffer
                );
            }
        }
    }

    /// Property: Latin-1 characters should be preserved in Latin-1 encoding
    #[test]
    fn prop_latin1_text_preserved(text in latin1_text_strategy()) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "latin1.txt", TestEncoding::Latin1, &text);

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        let buffer_content = harness.get_buffer_content().unwrap();

        // Check that special Latin-1 characters are preserved
        for c in text.chars() {
            if !c.is_whitespace() && c.is_alphabetic() {
                prop_assert!(
                    buffer_content.contains(c),
                    "Latin-1 character {:?} should be in buffer. Buffer: {:?}",
                    c,
                    buffer_content
                );
            }
        }
    }

    /// Property: UTF-16 files should have correct BOM after save
    #[test]
    fn prop_utf16_bom_preserved(
        text in ascii_text_strategy(),
        le in prop::bool::ANY
    ) {
        let encoding = if le { TestEncoding::Utf16Le } else { TestEncoding::Utf16Be };
        let expected_bom = if le { UTF16_LE_BOM } else { UTF16_BE_BOM };

        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "utf16.txt", encoding, &text);

        // Verify BOM is correct
        let original_bytes = std::fs::read(&file_path).unwrap();
        prop_assert!(
            original_bytes.starts_with(expected_bom),
            "File should start with {:?} BOM",
            if le { "UTF-16 LE" } else { "UTF-16 BE" }
        );

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Edit
        harness.send_key(KeyCode::End, KeyModifiers::CONTROL).unwrap();
        harness.type_text("X").unwrap();

        // Save
        harness.send_key(KeyCode::Char('s'), KeyModifiers::CONTROL).unwrap();
        harness.render().unwrap();

        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        let saved_bytes = std::fs::read(&file_path).unwrap();
        prop_assert!(
            saved_bytes.starts_with(expected_bom),
            "BOM should be preserved after save"
        );
    }

    /// Property: Loading and saving a file in ANY encoding should preserve the exact bytes
    /// This is the comprehensive roundtrip test for all supported encodings.
    #[test]
    fn prop_all_encodings_roundtrip_exact(
        text in ascii_text_strategy().prop_filter("need content", |s| !s.trim().is_empty()),
        encoding in encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "roundtrip.txt", encoding, &text);
        let original_bytes = std::fs::read(&file_path).unwrap();

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Save without making any changes
        harness.send_key(KeyCode::Char('s'), KeyModifiers::CONTROL).unwrap();
        harness.render().unwrap();

        // Wait for save to complete
        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        // Read the saved file
        let saved_bytes = std::fs::read(&file_path).unwrap();

        // The saved bytes should be exactly equal to original
        prop_assert_eq!(
            saved_bytes,
            original_bytes,
            "Saved file should be byte-for-byte identical to original for encoding {:?}",
            encoding
        );
    }

    /// Property: Loading, editing, and saving should produce valid content in the same encoding
    /// Tests that edits are properly encoded in the file's encoding.
    #[test]
    fn prop_all_encodings_edit_roundtrip(
        text in ascii_text_strategy().prop_filter("need content", |s| s.len() >= 3),
        added in "[a-zA-Z]{3,10}",
        encoding in encoding_strategy()
    ) {
        let temp_dir = TempDir::new().unwrap();
        let file_path = create_encoded_file(&temp_dir, "edit_roundtrip.txt", encoding, &text);

        let mut harness = EditorTestHarness::new(120, 30).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Add text at end
        harness.send_key(KeyCode::End, KeyModifiers::CONTROL).unwrap();
        harness.type_text(&added).unwrap();
        harness.render().unwrap();

        // Save
        harness.send_key(KeyCode::Char('s'), KeyModifiers::CONTROL).unwrap();
        harness.render().unwrap();
        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        // Read saved file and decode it
        let saved_bytes = std::fs::read(&file_path).unwrap();

        // Verify encoding markers are preserved
        match encoding {
            TestEncoding::Utf8Bom => {
                prop_assert!(
                    saved_bytes.starts_with(UTF8_BOM),
                    "UTF-8 BOM should be preserved after edit"
                );
            }
            TestEncoding::Utf16Le => {
                prop_assert!(
                    saved_bytes.starts_with(UTF16_LE_BOM),
                    "UTF-16 LE BOM should be preserved after edit"
                );
            }
            TestEncoding::Utf16Be => {
                prop_assert!(
                    saved_bytes.starts_with(UTF16_BE_BOM),
                    "UTF-16 BE BOM should be preserved after edit"
                );
            }
            _ => {}
        }

        // Reload and verify the added text is present
        drop(harness);
        let mut harness2 = EditorTestHarness::new(120, 30).unwrap();
        harness2.open_file(&file_path).unwrap();
        harness2.render().unwrap();

        let buffer_content = harness2.get_buffer_content().unwrap();
        prop_assert!(
            buffer_content.contains(&added),
            "Added text '{}' should be in reloaded buffer. Buffer: {:?}",
            added,
            buffer_content
        );
    }
}

// ============================================================================
// Specific Edge Case Tests (Not Property-Based)
// ============================================================================

/// Test that UTF-8 files without BOM are detected correctly
#[test]
fn test_detect_encoding_utf8() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("utf8.txt");

    // Write UTF-8 content (no BOM)
    std::fs::write(&file_path, "Hello, World!\n你好世界\n").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Should detect as UTF-8 and display correctly
    harness.assert_screen_contains("Hello, World!");
    // Check individual Chinese characters (they may be spaced due to double-width rendering)
    let screen = harness.screen_to_string();
    assert!(screen.contains(''), "Screen should contain '你'");
    assert!(screen.contains(''), "Screen should contain '好'");
    assert!(screen.contains(''), "Screen should contain '世'");
    assert!(screen.contains(''), "Screen should contain '界'");

    // UTF-8 encoding IS now shown in status bar (always visible)
    assert!(
        screen.contains("UTF-8"),
        "UTF-8 should be shown in status bar"
    );
}

/// Test that UTF-8 BOM is hidden from display but preserved on save
#[test]
fn test_utf8_bom_hidden_but_preserved() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("utf8_bom.txt");

    // Write UTF-8 BOM + content
    let mut content = Vec::new();
    content.extend_from_slice(UTF8_BOM);
    content.extend_from_slice("Hello\n".as_bytes());
    std::fs::write(&file_path, &content).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // BOM should NOT be visible in the content area
    let screen = harness.screen_to_string();
    assert!(
        !screen.contains("\u{FEFF}"),
        "BOM character should not be visible in content"
    );

    // Content should be visible
    harness.assert_screen_contains("Hello");

    // Edit and save
    harness.send_key(KeyCode::End, KeyModifiers::NONE).unwrap();
    harness.type_text(" World").unwrap();
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| !h.editor().active_state().buffer.is_modified())
        .unwrap();

    // Verify BOM is preserved
    let saved = std::fs::read(&file_path).unwrap();
    assert!(
        saved.starts_with(UTF8_BOM),
        "BOM should be preserved after save"
    );
}

/// Test handling of empty file
#[test]
fn test_empty_file_defaults_to_utf8() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("empty.txt");

    std::fs::write(&file_path, "").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Should default to UTF-8 (but encoding is hidden in status bar for UTF-8/ASCII)
    // Just verify no other encoding is shown
    let screen = harness.screen_to_string();
    assert!(
        !screen.contains("UTF-16") && !screen.contains("GB18030") && !screen.contains("Latin"),
        "Empty file should default to UTF-8, not show other encodings"
    );

    // Should be able to type and save
    harness.type_text("New content\n").unwrap();
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness
        .wait_until(|h| !h.editor().active_state().buffer.is_modified())
        .unwrap();

    // Verify saved as UTF-8 (no BOM)
    let saved = std::fs::read(&file_path).unwrap();
    assert!(
        !saved.starts_with(UTF8_BOM),
        "New files should not have BOM by default"
    );
    assert_eq!(String::from_utf8(saved).unwrap(), "New content\n");
}

/// Test that binary files with encoding markers are handled correctly
#[test]
fn test_binary_with_fake_bom_detected() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("fake_bom.bin");

    // Create a file that starts like UTF-16 LE BOM but contains binary data
    let mut content = Vec::new();
    content.extend_from_slice(UTF16_LE_BOM);
    content.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Null bytes indicate binary
    content.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47]); // PNG magic
    std::fs::write(&file_path, &content).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Should not crash and should show something
    let screen = harness.screen_to_string();
    assert!(!screen.is_empty(), "Editor should display something");
}

/// Test GB18030 encoding detection and display
#[test]
fn test_gb18030_chinese_display() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("gb18030.txt");

    // GB18030 encoding of "你好世界"
    let gb18030_bytes: &[u8] = &[
        0xC4, 0xE3, //        0xBA, 0xC3, //        0xCA, 0xC0, //        0xBD, 0xE7, //        0x0A, // newline
    ];
    std::fs::write(&file_path, gb18030_bytes).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Check individual Chinese characters (they may be spaced due to double-width rendering)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains(''),
        "Screen should contain '你': {}",
        screen
    );
    assert!(
        screen.contains(''),
        "Screen should contain '好': {}",
        screen
    );
    assert!(
        screen.contains(''),
        "Screen should contain '世': {}",
        screen
    );
    assert!(
        screen.contains(''),
        "Screen should contain '界': {}",
        screen
    );
}

/// Test Latin-1 special characters are displayed correctly
#[test]
fn test_latin1_special_chars_display() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("latin1.txt");

    // Latin-1 encoded: "Héllo Wörld Café résumé naïve"
    // Using Latin-1 byte values for accented characters
    let latin1_bytes: &[u8] = &[
        0x48, 0xE9, 0x6C, 0x6C, 0x6F, 0x20, // "Héllo "
        0x57, 0xF6, 0x72, 0x6C, 0x64, 0x20, // "Wörld "
        0x43, 0x61, 0x66, 0xE9, 0x20, // "Café "
        0x72, 0xE9, 0x73, 0x75, 0x6D, 0xE9, 0x20, // "résumé "
        0x6E, 0x61, 0xEF, 0x76, 0x65, // "naïve"
        0x0A, // newline
    ];
    std::fs::write(&file_path, latin1_bytes).unwrap();

    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Should display correctly (converted to UTF-8 internally)
    harness.assert_screen_contains("Héllo");
    harness.assert_screen_contains("Wörld");
    harness.assert_screen_contains("Café");
}

/// Test encoding display in status bar
/// Note: UTF-8 and ASCII are hidden from status bar (as they're the expected defaults)
/// This test verifies encoding is shown for non-default encodings like UTF-16
#[test]
fn test_encoding_shown_in_status_bar() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");

    // Create a UTF-16 LE file with BOM - encoding WILL be shown in status bar
    let content = "Hello UTF-16";
    let mut utf16_bytes = vec![0xFF, 0xFE]; // UTF-16 LE BOM
    for ch in content.encode_utf16() {
        utf16_bytes.extend_from_slice(&ch.to_le_bytes());
    }
    std::fs::write(&file_path, utf16_bytes).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Status bar should show encoding for non-UTF-8 files
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("UTF-16")
            || screen.contains("utf-16")
            || screen.contains("UTF16")
            || screen.contains("utf16"),
        "Status bar should show UTF-16 encoding: {}",
        screen
    );
}

/// Test clipboard operations preserve content with special characters
#[test]
fn test_clipboard_preserves_encoded_content() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("clipboard_test.txt");

    // UTF-8 file with special characters
    std::fs::write(&file_path, "Café résumé\n").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.editor_mut().set_clipboard_for_test("".to_string());
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Select all and copy
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('c'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Go to end and paste
    harness
        .send_key(KeyCode::End, KeyModifiers::CONTROL)
        .unwrap();
    harness
        .send_key(KeyCode::Char('v'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should have duplicated content correctly
    let buffer = harness.get_buffer_content().unwrap();
    assert!(
        buffer.matches("Café").count() == 2,
        "Should have two copies of Café: {}",
        buffer
    );
}

/// Test creating a large UTF-16 file and navigating it
#[test]
fn test_large_utf16_file_navigation() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_utf16.txt");

    // Create a reasonably large UTF-16 LE file
    let line = "This is a test line with content\r\n";
    let num_lines = 500;

    let mut content = Vec::new();
    content.extend_from_slice(UTF16_LE_BOM);
    for _ in 0..num_lines {
        for ch in line.encode_utf16() {
            content.extend_from_slice(&ch.to_le_bytes());
        }
    }
    std::fs::write(&file_path, &content).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Should display content
    harness.assert_screen_contains("test line");

    // Navigate to end
    harness
        .send_key(KeyCode::End, KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Should still show content
    harness.assert_screen_contains("test line");
}

// ============================================================================
// Status Bar Encoding Indicator Click Tests
// ============================================================================

/// Test that clicking on the encoding indicator in the status bar opens the encoding selector.
/// This test will fail if the click handler is not implemented.
#[test]
fn test_encoding_indicator_click_opens_selector() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");
    // Use non-ASCII content to ensure UTF-8 detection (not ASCII)
    std::fs::write(&file_path, "Hello, World! こんにちは").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Verify UTF-8 encoding is shown in status bar
    harness.assert_screen_contains("UTF-8");

    // Find the position of "UTF-8" on screen
    let (col, row) = harness
        .find_text_on_screen("UTF-8")
        .expect("UTF-8 encoding indicator should be visible in status bar");

    // Click on the encoding indicator
    harness.mouse_click(col, row).unwrap();

    // After clicking, the encoding selector prompt should open
    // The prompt should show encoding options (UTF-16 is one of the available encodings)
    harness.assert_screen_contains("UTF-16");
}

/// Test that the encoding indicator is displayed for all files (ASCII and UTF-8).
#[test]
fn test_encoding_indicator_always_visible() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");
    std::fs::write(&file_path, "Hello, World!").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Encoding indicator should be visible in status bar
    // ASCII files are detected as ASCII, not UTF-8
    harness.assert_screen_contains("ASCII");
}

/// Test that clicking on UTF-16 encoding indicator opens selector and can change encoding.
/// This is a complete flow test: load UTF-16 file, change encoding to UTF-8 via click, save.
#[test]
fn test_utf16_encoding_indicator_click_and_change() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test_utf16.txt");

    // Create UTF-16 LE file with test content
    let text = "Hello UTF-16!\nLine 2\n";
    let mut content = UTF16_LE_BOM.to_vec();
    for ch in text.encode_utf16() {
        content.extend_from_slice(&ch.to_le_bytes());
    }
    std::fs::write(&file_path, &content).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Verify UTF-16 LE encoding is shown in status bar
    harness.assert_screen_contains("UTF-16 LE");

    // Find the position of "UTF-16 LE" on screen
    let (col, row) = harness
        .find_text_on_screen("UTF-16 LE")
        .expect("UTF-16 LE encoding indicator should be visible in status bar");

    // Click on the encoding indicator to open encoding selector
    harness.mouse_click(col, row).unwrap();

    // After clicking, the encoding selector prompt should open
    harness.assert_screen_contains("Encoding:");

    // Type "UTF-8" to filter and select UTF-8 encoding
    // Ctrl+A selects all existing text, then typing replaces it
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("UTF-8").unwrap();
    harness.render().unwrap();

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

    // Verify encoding changed to UTF-8 in status bar
    harness.assert_screen_contains("UTF-8");
    // Status bar should not show "UTF-16 LE" indicator anymore
    // (the content still contains "UTF-16" text, so we check for the indicator format)
    harness.assert_screen_not_contains("UTF-16 LE");

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

    // Read the saved file and verify it's now UTF-8 (no BOM, plain text)
    let saved_content = std::fs::read(&file_path).unwrap();

    // UTF-8 file should NOT have UTF-16 BOM
    assert!(
        !saved_content.starts_with(UTF16_LE_BOM),
        "Saved file should not have UTF-16 LE BOM"
    );

    // Content should be plain UTF-8
    let saved_text = String::from_utf8(saved_content).expect("Saved file should be valid UTF-8");
    assert!(
        saved_text.contains("Hello UTF-16!"),
        "Saved file should contain the original text"
    );
    assert!(
        saved_text.contains("Line 2"),
        "Saved file should contain all lines"
    );
}

/// Test changing encoding from UTF-8 to UTF-16 LE via click on status bar indicator.
/// This tests the opposite direction: UTF-8 → UTF-16 LE.
#[test]
fn test_utf8_to_utf16_encoding_change() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test_utf8.txt");

    // Create a UTF-8 file with non-ASCII content (to ensure it's detected as UTF-8, not ASCII)
    let text = "Hello World! こんにちは\nLine 2\n";
    std::fs::write(&file_path, text).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Verify UTF-8 encoding is shown in status bar
    harness.assert_screen_contains("UTF-8");

    // Find the position of "UTF-8" on screen - should be in the status bar (last lines)
    let (col, row) = harness
        .find_text_on_screen("UTF-8")
        .expect("UTF-8 encoding indicator should be visible in status bar");

    // Verify we found it in the status bar area (bottom of screen)
    assert!(
        row >= 20,
        "UTF-8 should be in status bar (bottom of screen), found at row {}",
        row
    );

    // Click on the encoding indicator to open encoding selector
    harness.mouse_click(col, row).unwrap();

    // After clicking, the encoding selector prompt should open
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Encoding:"),
        "Encoding selector should open after clicking. Screen:\n{}",
        screen
    );

    // Navigate to UTF-16 LE using arrow keys
    // The encoding list order is: UTF-8, UTF-8 BOM, UTF-16 LE, UTF-16 BE, ASCII, ...
    // Current selection is UTF-8 (index 0), UTF-16 LE is at index 2
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Move to UTF-8 BOM
    harness.render().unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap(); // Move to UTF-16 LE
    harness.render().unwrap();

    // Check what's shown after navigation
    let screen_after_nav = harness.screen_to_string();
    assert!(
        screen_after_nav.contains("UTF-16 LE"),
        "UTF-16 LE should be visible after navigating. Screen:\n{}",
        screen_after_nav
    );

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

    // Verify encoding changed to UTF-16 LE in status bar
    let final_screen = harness.screen_to_string();
    assert!(
        final_screen.contains("UTF-16 LE"),
        "Encoding should be UTF-16 LE after confirmation. Screen:\n{}",
        final_screen
    );
    // Content should still be visible
    harness.assert_screen_contains("Hello World!");

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

    // Read the saved file and verify it's now UTF-16 LE
    let saved_content = std::fs::read(&file_path).unwrap();

    // UTF-16 LE file should start with BOM
    assert!(
        saved_content.starts_with(UTF16_LE_BOM),
        "Saved file should have UTF-16 LE BOM. Got first bytes: {:?}",
        &saved_content[..saved_content.len().min(10)]
    );

    // Decode UTF-16 LE content (skip BOM)
    let utf16_bytes = &saved_content[2..];
    let utf16_units: Vec<u16> = utf16_bytes
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
        .collect();
    let decoded = String::from_utf16(&utf16_units).expect("Should be valid UTF-16 LE");

    assert!(
        decoded.contains("Hello World!"),
        "Saved file should contain the original text. Got: {}",
        decoded
    );
    assert!(
        decoded.contains("こんにちは"),
        "Saved file should preserve Japanese characters"
    );
}

// ============================================================================
// Windows-1250 (Central European) Encoding Tests
// ============================================================================

/// Comprehensive test for Windows-1250 encoding:
/// - Display of Polish diacritical characters
/// - Encoding selector shows Windows-1250 (Central European)
/// - Encoding change via selector works
#[test]
fn test_windows1250_display_and_selector() {
    let temp_dir = TempDir::new().unwrap();

    // Test 1: Display Windows-1250 encoded Polish characters
    let polish_file = temp_dir.path().join("polish.txt");
    // "Zażółć gęślą jaźń" - famous Polish pangram in Windows-1250
    let windows1250_bytes: &[u8] = &[
        0x5A, 0x61, 0xBF, 0xF3, 0xB3, 0xE6, // "Zażółć"
        0x20, 0x67, 0xEA, 0x9C, 0x6C, 0xB9, // " gęślą"
        0x20, 0x6A, 0x61, 0x9F, 0xF1, 0x0A, // " jaźń\n"
    ];
    std::fs::write(&polish_file, windows1250_bytes).unwrap();

    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&polish_file).unwrap();
    harness.render().unwrap();

    // Verify Polish characters are displayed (converted to UTF-8 internally)
    let screen = harness.screen_to_string();
    assert!(
        screen.contains('ż') || screen.contains('ó') || screen.contains('ł'),
        "Screen should contain Polish diacritical characters"
    );

    // Test 2: Encoding selector and change
    let utf8_file = temp_dir.path().join("utf8.txt");
    std::fs::write(&utf8_file, "Hello World!\n").unwrap();

    drop(harness);
    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&utf8_file).unwrap();
    harness.render().unwrap();

    // Click on encoding indicator to open selector
    let (col, row) = harness
        .find_text_on_screen("ASCII")
        .expect("Encoding indicator should be visible");
    harness.mouse_click(col, row).unwrap();
    harness.assert_screen_contains("Encoding:");

    // Filter for Windows-1250 and verify it shows with description
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("1250").unwrap();
    harness.render().unwrap();

    let screen = harness.screen_to_string();
    assert!(
        screen.contains("Windows-1250") && screen.contains("Central European"),
        "Selector should show Windows-1250 / CP1250 – Central European"
    );

    // Select and verify encoding changed
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("Windows-1250");
}

/// Test Windows-1250 encoding conversions:
/// - UTF-8 → Windows-1250 → save → verify on disk
/// - Continue: Windows-1250 → UTF-8 → save → verify on disk (bidirectional)
/// - Fresh load: Load Windows-1250 from disk → UTF-8 → save → verify on disk
#[test]
fn test_windows1250_encoding_conversions() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("conversion_test.txt");

    // Start with UTF-8 file containing Polish text
    std::fs::write(&file_path, "Zażółć gęślą\n").unwrap();

    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Part 1: UTF-8 → Windows-1250 → save
    let (col, row) = harness
        .find_text_on_screen("UTF-8")
        .expect("UTF-8 indicator should be visible");
    harness.mouse_click(col, row).unwrap();
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("Windows-1250").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

    // Verify file is Windows-1250 encoded ('ż'=0xBF, 'ł'=0xB3)
    let saved = std::fs::read(&file_path).unwrap();
    assert!(
        saved.contains(&0xBF) || saved.contains(&0xB3),
        "File should be Windows-1250 encoded"
    );
    let (decoded, _) = encoding_rs::WINDOWS_1250.decode_without_bom_handling(&saved);
    assert!(decoded.contains("Zażółć"), "Should preserve Polish text");

    // Part 2: Fresh load Windows-1250 from disk → UTF-8 → save
    // Close and reopen to simulate loading from disk
    drop(harness);
    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // File may be detected as Windows-1252 (chardetng can't distinguish 1250 vs 1252)
    // Find encoding indicator and change to UTF-8
    let (col, row) = harness
        .find_text_on_screen("Windows")
        .expect("Windows encoding indicator should be visible");
    harness.mouse_click(col, row).unwrap();
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("UTF-8").unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

    // Verify file is now valid UTF-8
    // Note: If detected as Windows-1252, some chars may differ (ś→œ, ć→æ)
    // but the file should be valid UTF-8 regardless
    let saved = std::fs::read(&file_path).unwrap();
    let utf8_str = std::str::from_utf8(&saved).expect("File should be valid UTF-8");
    // Check that common chars (ó, ł) that are same in both encodings are preserved
    assert!(
        utf8_str.contains('ó') || utf8_str.contains('ł'),
        "UTF-8 file should contain some Polish chars. Got: {}",
        utf8_str
    );
}

/// Test loading and detecting Windows-1250 encoding with Czech pangram.
/// Uses the famous Czech pangram "Příliš žluťoučký kůň úpěl ďábelské ódy"
/// which contains all Czech diacritical characters.
///
/// Note: chardetng may detect Windows-1250 as Windows-1252 since many byte values
/// overlap. However, the Czech-specific characters (ř, ů, ě, etc.) that differ
/// between encodings should help with detection or at least display correctly.
#[test]
fn test_windows1250_czech_pangram() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("czech_pangram.txt");

    // "Příliš žluťoučký kůň úpěl ďábelské ódy" in Windows-1250 encoding
    // P=0x50, ř=0xF8, í=0xED, l=0x6C, i=0x69, š=0x9A, space=0x20
    // ž=0x9E, l=0x6C, u=0x75, ť=0x9D, o=0x6F, u=0x75, č=0xE8, k=0x6B, ý=0xFD
    // k=0x6B, ů=0xF9, ň=0xF2, space=0x20
    // ú=0xFA, p=0x70, ě=0xEC, l=0x6C, space=0x20
    // ď=0xEF, á=0xE1, b=0x62, e=0x65, l=0x6C, s=0x73, k=0x6B, é=0xE9, space=0x20
    // ó=0xF3, d=0x64, y=0x79
    let windows1250_bytes: &[u8] = &[
        0x50, 0xF8, 0xED, 0x6C, 0x69, 0x9A, 0x20, // "Příliš "
        0x9E, 0x6C, 0x75, 0x9D, 0x6F, 0x75, 0xE8, 0x6B, 0xFD, 0x20, // "žluťoučký "
        0x6B, 0xF9, 0xF2, 0x20, // "kůň "
        0xFA, 0x70, 0xEC, 0x6C, 0x20, // "úpěl "
        0xEF, 0xE1, 0x62, 0x65, 0x6C, 0x73, 0x6B, 0xE9, 0x20, // "ďábelské "
        0xF3, 0x64, 0x79, 0x0A, // "ódy\n"
    ];
    std::fs::write(&file_path, windows1250_bytes).unwrap();

    let mut harness = EditorTestHarness::new(100, 24).unwrap();
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    let screen = harness.screen_to_string();

    // The file should be detected as Windows-1250 because it contains ť (0x9D)
    // which is a definitive Windows-1250 indicator (undefined in Windows-1252)
    assert!(
        screen.contains("Windows-1250"),
        "Should detect as Windows-1250 (contains ť = 0x9D). Screen:\n{}",
        screen
    );

    // Verify the Czech pangram is displayed correctly
    // Now that Windows-1250 is properly detected, all Czech characters should display correctly
    assert!(screen.contains('í'), "Screen should contain 'í'");
    assert!(screen.contains('á'), "Screen should contain 'á'");
    assert!(screen.contains('é'), "Screen should contain 'é'");
    assert!(screen.contains('ó'), "Screen should contain 'ó'");
    assert!(screen.contains('š'), "Screen should contain 'š'");
    assert!(screen.contains('ž'), "Screen should contain 'ž'");

    // Czech-specific characters that differ from Windows-1252
    // These would be wrong if detected as Windows-1252, but should be correct now
    assert!(
        screen.contains('ř'),
        "Screen should contain 'ř' (Windows-1250 specific)"
    );
    assert!(
        screen.contains('ů'),
        "Screen should contain 'ů' (Windows-1250 specific)"
    );
    assert!(
        screen.contains('ě'),
        "Screen should contain 'ě' (Windows-1250 specific)"
    );
    assert!(
        screen.contains('č'),
        "Screen should contain 'č' (Windows-1250 specific)"
    );
    assert!(
        screen.contains('ť'),
        "Screen should contain 'ť' (Windows-1250 specific)"
    );

    // Verify buffer content contains the full Czech pangram
    let buffer = harness.get_buffer_content().unwrap();
    assert!(
        buffer.contains("Příliš") || buffer.contains("P"),
        "Buffer should contain the pangram. Got: {}",
        buffer
    );
}

/// Test loading files in various encodings from disk and saving as UTF-8
/// This tests the full flow: create encoded file → load → save as UTF-8 → verify
/// Covers all supported encodings with detectable content.
#[test]
fn test_all_encodings_load_and_save_as_utf8() {
    struct TestCase {
        desc: &'static str,
        bytes: &'static [u8],
        expected_substr: &'static str,
    }

    let test_cases: &[TestCase] = &[
        // UTF-16 LE with BOM: "Héllo"
        TestCase {
            desc: "UTF-16 LE",
            bytes: &[
                0xFF, 0xFE, // BOM
                0x48, 0x00, 0xE9, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x0A, 0x00,
            ],
            expected_substr: "H",
        },
        // UTF-16 BE with BOM: "Héllo"
        TestCase {
            desc: "UTF-16 BE",
            bytes: &[
                0xFE, 0xFF, // BOM
                0x00, 0x48, 0x00, 0xE9, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x0A,
            ],
            expected_substr: "H",
        },
        // UTF-8 with BOM: "Café"
        TestCase {
            desc: "UTF-8 BOM",
            bytes: &[0xEF, 0xBB, 0xBF, 0x43, 0x61, 0x66, 0xC3, 0xA9, 0x0A],
            expected_substr: "Café",
        },
        // UTF-8 without BOM: "Cześć" (Polish greeting)
        TestCase {
            desc: "UTF-8",
            bytes: &[0x43, 0x7A, 0x65, 0xC5, 0x9B, 0xC4, 0x87, 0x0A], // "Cześć\n"
            expected_substr: "Cze",
        },
        // Windows-1252: "Café" (é = 0xE9 in Windows-1252)
        TestCase {
            desc: "Windows-1252",
            bytes: &[0x43, 0x61, 0x66, 0xE9, 0x0A],
            expected_substr: "Café",
        },
        // Windows-1250: Polish "ółć" (ó=0xF3, ł=0xB3, ć=0xE6)
        // These bytes are same in Win-1252, so detection may vary, but conversion works
        TestCase {
            desc: "Windows-1250",
            bytes: &[0xF3, 0xB3, 0xE6, 0x0A],
            expected_substr: "ó",
        },
        // Note: CJK encodings (GB18030, GBK, Shift-JIS, EUC-KR) have ambiguous
        // detection - the same bytes can be valid in multiple encodings.
        // These are tested in property tests (prop_all_encodings_roundtrip_exact)
        // which use encoding_rs directly without relying on auto-detection.
    ];

    let temp_dir = TempDir::new().unwrap();

    for (i, tc) in test_cases.iter().enumerate() {
        let file_path = temp_dir.path().join(format!("test_{}.txt", i));
        std::fs::write(&file_path, tc.bytes).unwrap();

        let mut harness = EditorTestHarness::new(100, 24).unwrap();
        harness.open_file(&file_path).unwrap();
        harness.render().unwrap();

        // Find encoding indicator and change to UTF-8
        let encoding_pos = harness
            .find_text_on_screen("UTF-16")
            .or_else(|| harness.find_text_on_screen("UTF-8"))
            .or_else(|| harness.find_text_on_screen("Windows"))
            .or_else(|| harness.find_text_on_screen("Latin"))
            .or_else(|| harness.find_text_on_screen("GB18030"))
            .or_else(|| harness.find_text_on_screen("GBK"))
            .or_else(|| harness.find_text_on_screen("Shift"))
            .or_else(|| harness.find_text_on_screen("EUC"))
            .or_else(|| harness.find_text_on_screen("ASCII"));

        let (col, row) = encoding_pos.unwrap_or_else(|| {
            panic!(
                "Test {} ({}): Could not find encoding indicator",
                i, tc.desc
            )
        });

        harness.mouse_click(col, row).unwrap();
        harness
            .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
            .unwrap();
        harness.type_text("UTF-8").unwrap();
        harness.render().unwrap();
        harness
            .send_key(KeyCode::Enter, KeyModifiers::NONE)
            .unwrap();

        // Save
        harness
            .send_key(KeyCode::Char('s'), KeyModifiers::CONTROL)
            .unwrap();
        harness.render().unwrap();
        let _ = harness.wait_until(|h| !h.editor().active_state().buffer.is_modified());

        // Verify saved file is valid UTF-8 and contains expected content
        let saved = std::fs::read(&file_path).unwrap();
        let utf8_str = std::str::from_utf8(&saved).unwrap_or_else(|e| {
            panic!(
                "Test {} ({}): File should be valid UTF-8. Error: {}. Bytes: {:?}",
                i, tc.desc, e, saved
            )
        });
        assert!(
            utf8_str.contains(tc.expected_substr),
            "Test {} ({}): Expected '{}' in saved file. Got: {}",
            i,
            tc.desc,
            tc.expected_substr,
            utf8_str
        );

        drop(harness);
    }
}

// ============================================================================
// Large File Encoding Confirmation Tests
// ============================================================================

/// Test that opening a large file with GBK encoding via file browser shows confirmation prompt
/// and pressing Enter (default = Load) loads the file.
///
/// Uses a small `large_file_threshold_bytes` to avoid creating huge test files.
/// The file browser flow (Ctrl+O) catches the LargeFileEncodingConfirmation error and shows a prompt.
#[test]
fn test_large_file_gbk_encoding_confirmation_prompt() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_gbk.txt");

    // Create a GBK-encoded file larger than our test threshold (500 bytes)
    // GBK encoding of Chinese characters: 你好 = 0xC4E3 0xBAC3
    let mut gbk_bytes = Vec::new();
    // Create ~600 bytes of GBK content (60 repetitions of "你好世界\n" = 9 bytes each = 540 bytes)
    for _ in 0..60 {
        gbk_bytes.extend_from_slice(&[
            0xC4, 0xE3, //            0xBA, 0xC3, //            0xCA, 0xC0, //            0xBD, 0xE7, //            0x0A, // \n
        ]);
    }
    assert!(
        gbk_bytes.len() >= 500,
        "File should be at least 500 bytes (got {})",
        gbk_bytes.len()
    );
    std::fs::write(&file_path, &gbk_bytes).unwrap();

    // Create harness with small threshold to trigger large file mode
    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500, // Force large file mode
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Use Ctrl+O to open file browser, then type path and Enter
    // This triggers the flow that catches LargeFileEncodingConfirmation and shows a prompt
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type the file path in the file browser
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();

    // Press Enter to open the file - this should show the confirmation prompt
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Check that the confirmation prompt is shown
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("GB18030"),
        "Should show confirmation prompt for GBK encoding. Screen:\n{}",
        screen
    );

    // Press Enter to accept the default (Load)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After loading, the file content should be visible
    let screen_after = harness.screen_to_string();
    assert!(
        screen_after.contains('') || screen_after.contains(''),
        "Chinese characters should be visible after loading. Screen:\n{}",
        screen_after
    );

    // Verify the status bar shows GB18030 encoding (GBK is detected as GB18030 since
    // it's a subset and the 8KB sample may not contain GB18030-only code points)
    assert!(
        screen_after.contains("GB18030"),
        "Status bar should show GB18030 encoding. Screen:\n{}",
        screen_after
    );
}

/// Test that pressing 'c' (cancel) on the large file encoding prompt cancels the operation
#[test]
fn test_large_file_gbk_encoding_cancel() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_gbk_cancel.txt");

    // Create a GBK-encoded file larger than threshold (60 * 9 = 540 bytes)
    let mut gbk_bytes = Vec::new();
    for _ in 0..60 {
        gbk_bytes.extend_from_slice(&[
            0xC4, 0xE3, //            0xBA, 0xC3, //            0xCA, 0xC0, //            0xBD, 0xE7, //            0x0A, // \n
        ]);
    }
    std::fs::write(&file_path, &gbk_bytes).unwrap();

    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Use Ctrl+O to open file browser
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type the file path
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();

    // Press Enter to open - this should show the confirmation prompt
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify prompt is shown
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("GB18030"),
        "Should show confirmation prompt. Screen:\n{}",
        screen
    );

    // Press 'c' and then Enter to cancel
    harness
        .send_key(KeyCode::Char('c'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After cancelling, the file should NOT be loaded
    // The status message should indicate cancellation
    let screen_after = harness.screen_to_string();
    assert!(
        screen_after.contains("cancel") || screen_after.contains("Cancel"),
        "Should show cancellation message. Screen:\n{}",
        screen_after
    );
}

/// Test that pressing 'e' (encoding) on the large file encoding prompt opens encoding selector
#[test]
fn test_large_file_gbk_encoding_change() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_gbk_encoding.txt");

    // Create a GBK-encoded file larger than threshold (60 * 9 = 540 bytes)
    let mut gbk_bytes = Vec::new();
    for _ in 0..60 {
        gbk_bytes.extend_from_slice(&[
            0xC4, 0xE3, //            0xBA, 0xC3, //            0xCA, 0xC0, //            0xBD, 0xE7, //            0x0A, // \n
        ]);
    }
    std::fs::write(&file_path, &gbk_bytes).unwrap();

    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Use Ctrl+O to open file browser
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type the file path
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();

    // Press Enter to open - this should show the confirmation prompt
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Verify prompt is shown
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("GB18030"),
        "Should show confirmation prompt. Screen:\n{}",
        screen
    );

    // Press 'e' and Enter to open encoding selector
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // The encoding selector should now be open
    let screen_after = harness.screen_to_string();
    assert!(
        screen_after.contains("Encoding:") || screen_after.contains("UTF-16"),
        "Encoding selector should be open. Screen:\n{}",
        screen_after
    );
}

/// Test with Shift-JIS encoding (another non-resynchronizable encoding)
#[test]
fn test_large_file_shift_jis_encoding_confirmation() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_shift_jis.txt");

    // Create a Shift-JIS encoded file larger than threshold
    // Shift-JIS encoding of こんにちは (konnichiha):
    // こ=0x82B1, ん=0x82F1, に=0x82C9, ち=0x82BF, は=0x82CD
    let mut sjis_bytes = Vec::new();
    for _ in 0..50 {
        sjis_bytes.extend_from_slice(&[
            0x82, 0xB1, //            0x82, 0xF1, //            0x82, 0xC9, //            0x82, 0xBF, //            0x82, 0xCD, //            0x0A, // \n
        ]);
    }
    assert!(
        sjis_bytes.len() >= 500,
        "File should be at least 500 bytes (got {})",
        sjis_bytes.len()
    );
    std::fs::write(&file_path, &sjis_bytes).unwrap();

    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Use Ctrl+O to open file browser
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    // Type the file path
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();

    // Press Enter to open - this should show the confirmation prompt
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Check that the confirmation prompt is shown
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("Shift-JIS"),
        "Should show confirmation prompt for Shift-JIS encoding. Screen:\n{}",
        screen
    );

    // Press 'L' (explicit load key) to load
    harness
        .send_key(KeyCode::Char('L'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // After loading, the file content should be visible (Japanese hiragana)
    let screen_after = harness.screen_to_string();
    assert!(
        screen_after.contains('')
            || screen_after.contains('')
            || screen_after.contains("Shift-JIS"),
        "Should show Shift-JIS content or encoding indicator. Screen:\n{}",
        screen_after
    );
}

/// Test that selecting a non-resynchronizable encoding from the encoding selector
/// shows the confirmation prompt again
#[test]
fn test_large_file_encoding_selector_non_sync_shows_prompt() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_gbk_resync.txt");

    // Create a GBK-encoded file larger than threshold
    let mut gbk_bytes = Vec::new();
    for _ in 0..60 {
        gbk_bytes.extend_from_slice(&[
            0xC4, 0xE3, //            0xBA, 0xC3, //            0xCA, 0xC0, //            0xBD, 0xE7, //            0x0A, // \n
        ]);
    }
    std::fs::write(&file_path, &gbk_bytes).unwrap();

    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Open file via Ctrl+O
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // First prompt for GBK
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("GB18030"),
        "Should show first confirmation prompt. Screen:\n{}",
        screen
    );

    // Press 'e' to select encoding
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Type "Shift-JIS" (another non-resynchronizable encoding)
    // Clear the current input first
    for _ in 0..30 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
    }
    harness.type_text("Shift-JIS").unwrap();
    harness.render().unwrap();

    // Press Enter to select Shift-JIS
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should show confirmation prompt again for Shift-JIS
    let screen_after = harness.screen_to_string();
    assert!(
        screen_after.contains("requires full load") || screen_after.contains("Shift-JIS"),
        "Should show confirmation prompt again for Shift-JIS. Screen:\n{}",
        screen_after
    );
}

/// Test that selecting a synchronizable encoding (UTF-8) from the encoding selector
/// loads the file directly without showing confirmation prompt again
#[test]
fn test_large_file_encoding_selector_sync_no_prompt() {
    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large_gbk_utf8.txt");

    // Create a GBK-encoded file larger than threshold
    let mut gbk_bytes = Vec::new();
    for _ in 0..60 {
        gbk_bytes.extend_from_slice(&[
            0xC4, 0xE3, //            0xBA, 0xC3, //            0xCA, 0xC0, //            0xBD, 0xE7, //            0x0A, // \n
        ]);
    }
    std::fs::write(&file_path, &gbk_bytes).unwrap();

    let mut harness = EditorTestHarness::with_config(
        100,
        30,
        fresh::config::Config {
            editor: fresh::config::EditorConfig {
                large_file_threshold_bytes: 500,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    harness.render().unwrap();

    // Open file via Ctrl+O
    harness
        .send_key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text(file_path.to_str().unwrap()).unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // First prompt for GBK
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("requires full load") || screen.contains("GB18030"),
        "Should show first confirmation prompt. Screen:\n{}",
        screen
    );

    // Press 'e' to select encoding
    harness
        .send_key(KeyCode::Char('e'), KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // UTF-8 should already be selected, just press Enter
    // (or clear and type UTF-8)
    for _ in 0..30 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
    }
    harness.type_text("UTF-8").unwrap();
    harness.render().unwrap();

    // Press Enter to select UTF-8
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Should NOT show confirmation prompt - file should be loaded directly
    // (UTF-8 is resynchronizable, so no full load needed)
    let screen_after = harness.screen_to_string();
    // The file will be loaded with UTF-8 encoding (will show garbled content but that's ok)
    // The key assertion is that we don't see another "requires full load" prompt
    assert!(
        !screen_after.contains("requires full load"),
        "Should NOT show confirmation prompt for UTF-8 (synchronizable). Screen:\n{}",
        screen_after
    );
    // Should show UTF-8 in status bar (file is open)
    assert!(
        screen_after.contains("UTF-8"),
        "File should be opened with UTF-8 encoding. Screen:\n{}",
        screen_after
    );
}

// ============================================================================
// Reload with Encoding Command Tests
// ============================================================================

/// Test that "Reload with Encoding..." command is available in the command palette
/// and can reload a file with a different encoding.
#[test]
fn test_reload_with_encoding_command() {
    let mut harness = EditorTestHarness::with_temp_project(100, 24).unwrap();
    let file_path = harness.project_dir().unwrap().join("test_reload.txt");

    // Create a file with Latin-1 content (bytes 0xE0-0xFF are valid Latin-1)
    // "café" in Latin-1: c=0x63, a=0x61, f=0x66, é=0xE9
    let latin1_content: Vec<u8> = vec![0x63, 0x61, 0x66, 0xE9, 0x0A]; // "café\n"
    std::fs::write(&file_path, &latin1_content).unwrap();

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

    // File is detected as Latin-1 or Windows-1252 (both decode 0xE9 as é)
    // Status bar shows the detected encoding
    let initial_screen = harness.screen_to_string();
    assert!(
        initial_screen.contains("Latin-1") || initial_screen.contains("Windows-1252"),
        "File should be detected as Latin-1 or Windows-1252. Screen:\n{}",
        initial_screen
    );

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

    // Type "Reload with" to find the command
    harness.type_text("Reload with").unwrap();
    harness.render().unwrap();

    // Verify the command appears in the palette
    harness.assert_screen_contains("Reload with Encoding");

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

    // The encoding selector prompt should open
    harness.assert_screen_contains("Reload with encoding:");

    // Select UTF-8 (will misinterpret the Latin-1 bytes, but tests the command works)
    // Use arrow keys to navigate since the prompt already has suggestions
    // First, clear existing text and type UTF-8
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::CONTROL)
        .unwrap();
    harness.type_text("UTF-8").unwrap();
    harness.render().unwrap();

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

    // After reload, encoding should show UTF-8 in status bar
    harness.assert_screen_contains("UTF-8");

    // Status message should confirm the reload (may be truncated, so just check prefix)
    harness.assert_screen_contains("Reloaded with");
}

/// Test "Reload with Encoding..." from the File menu
#[test]
fn test_reload_with_encoding_menu_item() {
    let mut harness = EditorTestHarness::with_temp_project(100, 24).unwrap();
    let file_path = harness.project_dir().unwrap().join("test_menu.txt");

    // Create a simple UTF-8 file
    std::fs::write(&file_path, "Hello World\n").unwrap();

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

    // Open File menu with Alt+F
    harness
        .send_key(KeyCode::Char('f'), KeyModifiers::ALT)
        .unwrap();
    harness.render().unwrap();

    // Verify the menu item is present
    harness.assert_screen_contains("Reload with Encoding...");
}