mahbot 0.4.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
use super::*;
use crate::gui::editor_widget::{EditorAction, EditorBuffer};

// ── compute_text_matches ────────────────────────────────────

#[test]
fn test_compute_text_matches() {
    struct Case {
        text: &'static str,
        query: &'static str,
        sensitive: bool,
        expected: &'static [(usize, usize)],
    }
    let cases: &[Case] = &[
        // Empty query
        Case {
            text: "hello",
            query: "",
            sensitive: true,
            expected: &[],
        },
        // Basic match
        Case {
            text: "hello world hello",
            query: "hello",
            sensitive: true,
            expected: &[(0, 5), (12, 17)],
        },
        // No match
        Case {
            text: "hello world",
            query: "xyz",
            sensitive: true,
            expected: &[],
        },
        // Non-overlapping
        Case {
            text: "aaaaa",
            query: "aa",
            sensitive: true,
            expected: &[(0, 2), (2, 4)],
        },
        // Case-insensitive
        Case {
            text: "Hello World hello",
            query: "hello",
            sensitive: false,
            expected: &[(0, 5), (12, 17)],
        },
        // Case-insensitive no match
        Case {
            text: "Hello World",
            query: "xyz",
            sensitive: false,
            expected: &[],
        },
        // Single-char queries return empty (2-char min enforcement)
        Case {
            text: "hello",
            query: "h",
            sensitive: true,
            expected: &[],
        },
        // Boundary: shortest possible match
        Case {
            text: "ab",
            query: "ab",
            sensitive: true,
            expected: &[(0, 2)],
        },
        // Boundary: consecutive matches
        Case {
            text: "abab",
            query: "ab",
            sensitive: true,
            expected: &[(0, 2), (2, 4)],
        },
    ];
    for case in cases {
        let result = compute_text_matches(case.text, case.query, case.sensitive);
        assert_eq!(
            result.len(),
            case.expected.len(),
            "text={:?} query={:?} sensitive={}",
            case.text,
            case.query,
            case.sensitive
        );
        for (i, &(start, end)) in case.expected.iter().enumerate() {
            assert_eq!(
                result[i],
                start..end,
                "match[{i}] text={:?} query={:?} sensitive={}",
                case.text,
                case.query,
                case.sensitive
            );
        }
    }
}

// ── validate_file_content ─────────────────────────────────────

#[test]
fn test_validate_file_content() {
    let big = || vec![b'a'; usize::try_from(MAX_FILE_SIZE).unwrap() + 1];
    let big_bytes = big();
    let mut big_with_null = big();
    big_with_null.push(0);
    // (input, expected error prefix or None for ok)
    let cases: &[(&[u8], Option<&str>)] = &[
        (b"", None),
        (b"hello world", None),
        ("Привет мир 👋".as_bytes(), None),
        (&big_bytes, Some("File too large")),
        (b"hello\0world", Some("Binary file detected")),
        (&big_with_null, Some("File too large")),
    ];
    for &(bytes, expected) in cases {
        match expected {
            Some(prefix) => {
                let err = validate_file_content(bytes).unwrap_err();
                assert!(err.starts_with(prefix), "unexpected error: {err}");
            }
            None => assert!(validate_file_content(bytes).is_ok()),
        }
    }
}

#[test]
fn test_byte_offset_to_line_byte_col_unicode() {
    let text = "Привет **мир**";
    let (line, byte_col, line_start) = byte_offset_to_line_byte_col(text, 13).unwrap();
    assert_eq!(line, 0);
    assert_eq!(byte_col, 13);
    assert_eq!(line_start, 0);
    // End of match on "мир" — byte offset 21.
    let (_, byte_end_col, line_start) = byte_offset_to_line_byte_col(text, 21).unwrap();
    assert_eq!(byte_end_col, 21 - line_start);
}

#[test]
fn test_build_tab_records_persists_dirty_content() {
    let tabs = vec![Tab {
        path: "/tmp/foo.md".to_string(),
        file_name: "foo.md".to_string(),
        is_dirty: true,
        line_ending: LineEnding::Lf,
    }];
    let mut tab_contents = HashMap::new();
    let buffer = EditorBuffer::with_text("unsaved edits", None);
    tab_contents.insert(
        "/tmp/foo.md".to_string(),
        TabData {
            content: buffer,
            undo_stack: RefCell::new(UndoStack::new()),
            find_replace_state: None,
            saved_text_hash: 0,
        },
    );
    let records = build_tab_records(&tabs, 0, &tab_contents);
    assert_eq!(records.len(), 1);
    assert!(records[0].is_dirty);
    assert_eq!(records[0].dirty_content.as_deref(), Some("unsaved edits"));
}

#[test]
fn test_build_tab_records_clears_dirty_content_when_clean() {
    let tabs = vec![Tab {
        path: "/tmp/foo.md".to_string(),
        file_name: "foo.md".to_string(),
        is_dirty: false,
        line_ending: LineEnding::Lf,
    }];
    let records = build_tab_records(&tabs, 0, &HashMap::new());
    assert!(records[0].dirty_content.is_none());
}

#[test]
fn test_save_result_ignores_stale_save() {
    let mut state = EditorState::new();
    let path = "/tmp/stale.md".to_string();
    state.tabs.push(Tab {
        path: path.clone(),
        file_name: "stale.md".to_string(),
        is_dirty: true,
        line_ending: LineEnding::Lf,
    });
    state.tab_contents.insert(
        path.clone(),
        TabData {
            content: EditorBuffer::with_text("edited after save started", None),
            undo_stack: RefCell::new(UndoStack::new()),
            find_replace_state: None,
            saved_text_hash: hash_text("on disk"),
        },
    );
    let saved_hash = hash_text("saved snapshot");
    let _ = state.save_result(&path, Ok(()), saved_hash);
    assert!(
        state.tabs[0].is_dirty,
        "stale save must not clear dirty flag"
    );
}

// ── byte_offset_to_line_col ────────────────────────────────

#[test]
fn test_byte_offset_to_line_col() {
    struct Case {
        text: &'static str,
        byte_offset: usize,
        expected: (usize, usize),
    }
    let cases: &[Case] = &[
        // Unicode multi-byte chars
        Case {
            text: "Привет мир",
            byte_offset: 13, // start of "м"
            expected: (0, 7),
        },
        // Start of content
        Case {
            text: "hello\nworld",
            byte_offset: 0,
            expected: (0, 0),
        },
        // Second line
        Case {
            text: "hello\nworld",
            byte_offset: 6, // after "hello\n"
            expected: (1, 0),
        },
        // Middle of a line
        Case {
            text: "hello\nworld",
            byte_offset: 8, // "wo"
            expected: (1, 2),
        },
        // Beyond text length — clamps to end
        Case {
            text: "hello",
            byte_offset: 100,
            expected: (0, 5),
        },
        // Empty content
        Case {
            text: "",
            byte_offset: 0,
            expected: (0, 0),
        },
        // Empty content with out-of-bounds offset — clamps to start
        Case {
            text: "",
            byte_offset: 100,
            expected: (0, 0),
        },
    ];
    for case in cases {
        let pos = byte_offset_to_line_col(case.text, case.byte_offset);
        assert_eq!(
            pos, case.expected,
            "text={:?} offset={}",
            case.text, case.byte_offset
        );
    }
}

// ── Tree keyboard navigation focus state tests ──────────────────

/// Helper to create a minimal EditorState with a simple tree.
fn make_editor_with_tree() -> EditorState {
    let mut state = EditorState::new();
    state.selected_workspace_path = Some("/tmp".to_string());
    // Populate root dir_entries so build_hierarchical_tree works.
    state.dir_entries.insert(
        String::new(),
        vec![
            FsEntry {
                name: "src".to_string(),
                full_path: "src".to_string(),
                is_dir: true,
                error: None,
            },
            FsEntry {
                name: "Cargo.toml".to_string(),
                full_path: "Cargo.toml".to_string(),
                is_dir: false,
                error: None,
            },
        ],
    );
    // Populate "src" dir_entries so children show when expanded.
    state.dir_entries.insert(
        "src".to_string(),
        vec![FsEntry {
            name: "main.rs".to_string(),
            full_path: "src/main.rs".to_string(),
            is_dir: false,
            error: None,
        }],
    );
    // Build the tree from dir_entries (consistent with real behavior).
    state.rebuild_tree();
    state
}

#[test]
fn test_rebuild_visible_tree_flattens_nodes() {
    let state = make_editor_with_tree();
    assert_eq!(state.file_tree.visible_tree_nodes.len(), 2);
    assert_eq!(state.file_tree.visible_tree_nodes[0].0, "src");
    assert!(state.file_tree.visible_tree_nodes[0].1); // is_dir
    assert_eq!(state.file_tree.visible_tree_nodes[1].0, "Cargo.toml");
    assert!(!state.file_tree.visible_tree_nodes[1].1); // not is_dir
}

#[test]
fn test_rebuild_visible_tree_with_expanded_dir() {
    let mut state = make_editor_with_tree();
    state.file_tree.expanded_dirs.insert("src".to_string());
    // Rebuild tree from dir_entries with expanded state, then flatten.
    state.file_tree.nodes =
        build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
    state.file_tree.rebuild_visible();
    assert_eq!(state.file_tree.visible_tree_nodes.len(), 3);
    assert_eq!(state.file_tree.visible_tree_nodes[0].0, "src");
    assert_eq!(state.file_tree.visible_tree_nodes[1].0, "src/main.rs");
    assert_eq!(state.file_tree.visible_tree_nodes[2].0, "Cargo.toml");
}

#[test]
fn test_tree_focus_toggled_sets_focus() {
    let mut state = make_editor_with_tree();
    assert!(!state.file_tree.tree_focused);

    // Toggle on
    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(state.file_tree.tree_focused);

    // Toggle off
    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(!state.file_tree.tree_focused);
}

#[test]
fn test_tree_focus_toggled_empty_tree_stays_off() {
    let mut state = EditorState::new();
    assert!(!state.file_tree.tree_focused);

    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(!state.file_tree.tree_focused); // No visible nodes, focus rejected
}

#[test]
fn test_misc_focus_actions() {
    struct Case {
        name: &'static str,
        msg: EditorMessage,
        setup: fn(&mut EditorState),
        check: fn(&EditorState, name: &str),
    }
    let cases: &[Case] = &[
        Case {
            name: "escape_clears_tree_focus",
            msg: EditorMessage::Escape,
            setup: |s| s.file_tree.tree_focused = true,
            check: |s, name| assert!(!s.file_tree.tree_focused, "case: {name}"),
        },
        Case {
            name: "toggle_dir_sets_tree_focus",
            msg: EditorMessage::ToggleDir("src".to_string()),
            setup: |s| {
                s.selected_file = Some("Cargo.toml".to_string());
            },
            check: |s, name| {
                assert!(s.file_tree.tree_focused, "case: {name}");
                assert!(s.selected_file.is_none(), "case: {name}");
            },
        },
        Case {
            name: "select_file_keeps_tree_focus",
            msg: EditorMessage::SelectFile("src/main.rs".to_string()),
            setup: |s| s.file_tree.tree_focused = true,
            check: |s, name| assert!(s.file_tree.tree_focused, "case: {name}"),
        },
        // A mouse-originated EditorAction (like MoveTo from a click)
        // should transfer focus from the file tree to the editor.
        Case {
            name: "editor_action_clears_tree_focus",
            msg: EditorMessage::EditorAction(EditorAction::MoveTo { line: 0, col: 0 }),
            setup: |s| {
                s.file_tree.tree_focused = true;
                s.pending_enter_dir = Some("src".to_string());
                s.active_modal = Some(ModalKind::Rename(RenameTarget {
                    path: "src/main.rs".to_string(),
                    abs_path: String::new(),
                    is_dir: false,
                    ws_root: String::new(),
                    input_text: "main.rs".to_string(),
                    error: None,
                }));
            },
            check: |s, name| {
                assert!(!s.file_tree.tree_focused, "case: {name}");
                assert_eq!(s.pending_enter_dir, None, "case: {name}");
                assert!(s.active_modal.is_none(), "case: {name}");
            },
        },
    ];
    for case in cases {
        let mut state = make_editor_with_tree();
        (case.setup)(&mut state);
        let _ = state.update(case.msg.clone());
        (case.check)(&state, case.name);
    }
}

#[test]
fn test_tree_nav_enter() {
    struct Case {
        name: &'static str,
        focused: bool,
        start_idx: usize,
        /// Set selected_file before the message
        pre_select_file: bool,
        /// Expected tree_focused after
        expect_focused: bool,
        /// Expected focus index after (None = skip check)
        expected_idx: Option<usize>,
        /// Additional per-case assertions
        check: Option<fn(&EditorState, name: &str)>,
    }
    let cases: &[Case] = &[
        // TreeNavEnter on a file dispatches an async load task, but
        // tree_focused stays true in the same-turn state update.
        Case {
            name: "on_file_dispatches_task",
            focused: true,
            start_idx: 1,
            pre_select_file: false,
            expect_focused: true,
            expected_idx: None,
            check: None,
        },
        Case {
            name: "not_focused_ignored",
            focused: false,
            start_idx: 1,
            pre_select_file: false,
            expect_focused: false,
            expected_idx: Some(1),
            check: None,
        },
        Case {
            name: "on_dir_expands_and_advances",
            focused: true,
            start_idx: 0,
            pre_select_file: true,
            expect_focused: true,
            expected_idx: Some(1),
            check: Some(|s, name| {
                assert!(s.file_tree.expanded_dirs.contains("src"), "case: {name}");
                assert!(s.selected_file.is_none(), "case: {name}");
                assert_eq!(s.file_tree.visible_tree_nodes[1].0, "src/main.rs");
            }),
        },
    ];
    for case in cases {
        let mut state = make_editor_with_tree();
        state.file_tree.tree_focused = case.focused;
        state.file_tree.tree_focus_index = case.start_idx;
        if case.pre_select_file {
            state.selected_file = Some("Cargo.toml".to_string());
        }
        let _ = state.update(EditorMessage::TreeNavEnter);
        assert_eq!(
            state.file_tree.tree_focused, case.expect_focused,
            "case: {}",
            case.name
        );
        if let Some(idx) = case.expected_idx {
            assert_eq!(state.file_tree.tree_focus_index, idx, "case: {}", case.name);
        }
        if let Some(check) = case.check {
            check(&state, case.name);
        }
    }
}

#[test]
fn test_visible_tree_clamps_focus_on_rebuild() {
    let mut state = make_editor_with_tree();
    state.file_tree.tree_focus_index = 999; // Way out of range
    state.file_tree.rebuild_visible();
    assert_eq!(
        state.file_tree.tree_focus_index,
        state.file_tree.visible_tree_nodes.len() - 1
    );
}

#[test]
fn test_async_enter_dir_sets_pending_then_advances() {
    let mut state = EditorState::new();
    state.selected_workspace_path = Some("/tmp".to_string());
    // Set up a tree where "src" dir_entries are empty (needs async load).
    state.dir_entries.insert(
        String::new(),
        vec![FsEntry {
            name: "src".to_string(),
            full_path: "src".to_string(),
            is_dir: true,
            error: None,
        }],
    );
    state.rebuild_tree();
    state.file_tree.tree_focused = true;
    state.file_tree.tree_focus_index = 0; // "src"

    let _task = state.update(EditorMessage::TreeNavEnter);
    // "src" needs async loading — pending_enter_dir is set.
    assert_eq!(state.pending_enter_dir.as_deref(), Some("src"));
    assert!(state.file_tree.expanded_dirs.contains("src"));
    // Focus stays on "src" until children load.
    assert_eq!(state.file_tree.tree_focus_index, 0);

    // Simulate DirExpanded completing with children.
    let entries = vec![FsEntry {
        name: "main.rs".to_string(),
        full_path: "src/main.rs".to_string(),
        is_dir: false,
        error: None,
    }];
    let dir_gen = state.generation;
    let _task = state.update(EditorMessage::DirExpanded {
        dir_path: "src".to_string(),
        r#gen: dir_gen,
        entries: Ok(entries),
        quiet: false,
    });
    // Focus should have advanced to the first child.
    assert_eq!(state.pending_enter_dir, None);
    assert_eq!(state.file_tree.tree_focus_index, 1); // "src/main.rs"
}

#[test]
fn test_toggle_dir_async_load_and_complete() {
    let mut state = EditorState::new();
    state.selected_workspace_path = Some("/tmp".to_string());
    // "src" dir has no cached entries → needs async load.
    state.dir_entries.insert(
        String::new(),
        vec![FsEntry {
            name: "src".to_string(),
            full_path: "src".to_string(),
            is_dir: true,
            error: None,
        }],
    );
    state.rebuild_tree();
    state.file_tree.tree_focused = true;
    state.file_tree.tree_focus_index = 0; // "src"

    let _task = state.update(EditorMessage::ToggleDir("src".to_string()));
    // ToggleDir sets loading_dirs and dir_generations.
    assert!(state.loading_dirs.contains("src"));
    assert!(state.dir_generations.contains_key("src"));
    // ToggleDir does NOT set pending_enter_dir.
    assert_eq!(state.pending_enter_dir, None);
    // Focus is on "src".
    assert!(state.file_tree.tree_focused);
    assert_eq!(state.file_tree.tree_focus_index, 0);

    // Simulate DirExpanded completing with children.
    let dir_gen = *state.dir_generations.get("src").unwrap();
    let entries = vec![FsEntry {
        name: "main.rs".to_string(),
        full_path: "src/main.rs".to_string(),
        is_dir: false,
        error: None,
    }];
    let _task = state.update(EditorMessage::DirExpanded {
        dir_path: "src".to_string(),
        r#gen: dir_gen,
        entries: Ok(entries),
        quiet: false,
    });
    // Entries are now cached.
    assert!(state.dir_entries.contains_key("src"));
    assert_eq!(state.dir_entries["src"].len(), 1);
    // loading_dirs is cleared.
    assert!(!state.loading_dirs.contains("src"));
    // pending_enter_dir was never set.
    assert_eq!(state.pending_enter_dir, None);
    // visible_tree_nodes is correctly rebuilt (rebuild_tree was called).
    assert!(state.file_tree.visible_tree_nodes.len() >= 2);
    assert_eq!(state.file_tree.visible_tree_nodes[0].0, "src");
    assert_eq!(state.file_tree.visible_tree_nodes[1].0, "src/main.rs");
}

#[test]
fn test_toggle_dir_no_workspace_returns_none() {
    let mut state = EditorState::new();
    // Precondition: "src" is not yet in expanded_dirs before the call.
    assert!(!state.file_tree.expanded_dirs.contains("src"));
    // No workspace set — async load should return None (early return).
    let _task = state.update(EditorMessage::ToggleDir("src".to_string()));
    // expanded_dirs is modified (insert happens before the workspace guard),
    // but no async load was spawned since there's no workspace path.
    assert!(state.file_tree.expanded_dirs.contains("src"));
    assert_eq!(state.generation, 0);
    assert!(state.loading_dirs.is_empty());
    assert!(state.dir_generations.is_empty());
}

// ── Git status porcelain parsing tests ─────────────────────────

#[expect(clippy::too_many_lines)]
#[test]
fn test_parse_git_status_porcelain() {
    struct Case {
        /// Short label for failure messages.
        name: &'static str,
        /// Raw git status --porcelain output.
        input: &'static str,
        /// Expected entries: (path, Some(status)) asserts the file has that
        /// status; (path, None) asserts the file is absent from the map.
        /// An empty slice asserts the entire map is empty.
        expected: &'static [(&'static str, Option<GitFileStatus>)],
    }
    let cases: &[Case] = &[
        Case {
            name: "unstaged modified file",
            input: " M src/main.rs\n",
            expected: &[("src/main.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "staged added file",
            input: "A  new_file.rs\n",
            expected: &[("new_file.rs", Some(GitFileStatus::Added))],
        },
        Case {
            name: "untracked file",
            input: "?? new_file.rs\n",
            expected: &[("new_file.rs", Some(GitFileStatus::Added))],
        },
        Case {
            name: "staged and unstaged modified (MM)",
            input: "MM both.rs\n",
            expected: &[("both.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "staged added + unstaged modified (AM)",
            input: "AM partial.rs\n",
            expected: &[("partial.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "rename (old -> new)",
            input: "R  old.rs -> new.rs\n",
            expected: &[("new.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "rename with arrow in old path",
            input: "R  \"old -> name.rs\" -> \"new -> name.rs\"\n",
            expected: &[("new -> name.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "untracked directory (trailing slash stripped)",
            input: "?? new_dir/\n",
            expected: &[("new_dir", Some(GitFileStatus::Added))],
        },
        Case {
            name: "quoted path with spaces",
            input: " M \"path with spaces.rs\"\n",
            expected: &[("path with spaces.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "deleted file (unstaged) skipped",
            input: " D gone.rs\n",
            expected: &[],
        },
        Case {
            name: "deleted file (staged) skipped",
            input: "D  gone.rs\n",
            expected: &[],
        },
        Case {
            name: "clean (unrecognized status) not present",
            input: "   clean.rs\n",
            expected: &[("clean.rs", None)],
        },
        Case {
            name: "multiple entries same file — modified wins over added",
            input: "A  dup.rs\n M dup.rs\n",
            expected: &[("dup.rs", Some(GitFileStatus::Modified))],
        },
        Case {
            name: "multiple entries same file — added sticks",
            input: "?? dup.rs\nA  dup.rs\n",
            expected: &[("dup.rs", Some(GitFileStatus::Added))],
        },
        Case {
            name: "empty output",
            input: "",
            expected: &[],
        },
        Case {
            name: "mixed statuses",
            input: concat!(
                " M src/main.rs\n",
                "?? new_file.rs\n",
                "A  staged.rs\n",
                " D deleted.rs\n",
            ),
            expected: &[
                ("src/main.rs", Some(GitFileStatus::Modified)),
                ("new_file.rs", Some(GitFileStatus::Added)),
                ("staged.rs", Some(GitFileStatus::Added)),
                ("deleted.rs", None),
            ],
        },
    ];

    for case in cases {
        let map = parse_git_status_porcelain(case.input);

        if case.expected.is_empty() {
            assert!(
                map.is_empty(),
                "case '{}' (input={:?}): expected empty map, got {:#?}",
                case.name,
                case.input,
                map
            );
        } else {
            let expected_count = case.expected.iter().filter(|(_, s)| s.is_some()).count();
            assert_eq!(
                map.len(),
                expected_count,
                "case '{}' (input={:?}): map has unexpected entries",
                case.name,
                case.input,
            );
            for &(path, expected_status) in case.expected {
                match expected_status {
                    Some(status) => {
                        assert_eq!(
                            map.get(path),
                            Some(&status),
                            "case '{}' (input={:?}): path={:?}",
                            case.name,
                            case.input,
                            path
                        );
                    }
                    None => {
                        assert!(
                            !map.contains_key(path),
                            "case '{}' (input={:?}): path={:?} should be absent, got {:?}",
                            case.name,
                            case.input,
                            path,
                            map.get(path)
                        );
                    }
                }
            }
        }
    }
}

// ── Find/Replace tests ───────────────────────────────────────────

#[test]
fn test_is_find_bar_open() {
    let state =
        make_editor_with_find_state("fn hello() {}", "hello", std::iter::once(4..9).collect(), 0);
    assert!(state.is_find_bar_open());
    let state = make_editor_with_single_tab("fn hello() {}");
    assert!(!state.is_find_bar_open());
    let state = EditorState::new();
    assert!(!state.is_find_bar_open());
}

#[expect(clippy::too_many_lines)]
#[test]
fn test_find_replace_auto_advance() {
    // Verifies cursor auto-advance after find_replace across five scenarios:
    // same-length replacement, shorter replacement, adjacent matches,
    // longer replacement (wrap-around), and no remaining matches.
    struct Case {
        name: &'static str,
        /// Initial buffer text.
        text: &'static str,
        /// Search query.
        query: &'static str,
        /// Replacement text.
        replace: &'static str,
        /// Pre-seeded match byte-range pairs.
        initial_matches: &'static [(usize, usize)],
        /// Expected text after replacement.
        expected_text: &'static str,
        /// Expected remaining match byte-range pairs.
        expected_matches: &'static [(usize, usize)],
        /// Expected cursor line after replacement.
        expected_cursor_line: usize,
        /// Expected cursor column after replacement.
        expected_cursor_col: usize,
        /// Expected current_match_idx after replacement.
        expected_current_match_idx: usize,
    }

    let cases: &[Case] = &[
        // Same-length replacement: "ab cd ab" → "xy cd ab".
        // After replacing first "ab" (0..2) with "xy" (len=2), remaining "ab"
        // at 6..8 is found by advancing past replace_end (= 0 + 2 = 2).
        Case {
            name: "same_length",
            text: "ab cd ab",
            query: "ab",
            replace: "xy",
            initial_matches: &[(0, 2), (6, 8)],
            expected_text: "xy cd ab",
            expected_matches: &[(6, 8)],
            expected_cursor_line: 0,
            expected_cursor_col: 6,
            expected_current_match_idx: 0,
        },
        // replace_end = 0 + 1 = 1. Remaining "aaa" at byte 6 in new text.
        Case {
            name: "shorter_replacement",
            text: "aaa bbb aaa",
            query: "aaa",
            replace: "a",
            initial_matches: &[(0, 3), (8, 11)],
            expected_text: "a bbb aaa",
            expected_matches: &[(6, 9)],
            expected_cursor_line: 0,
            expected_cursor_col: 6,
            expected_current_match_idx: 0,
        },
        // Adjacent matches: "aaaa" → "xaa".
        // Using range.end (= 2) as the advance point would incorrectly skip
        // the remaining match at 1..3 (1 >= 2 is false, so position() returns
        // None → wraps to 0, not 1). Using replace_end (= 1) correctly finds
        // the match at position 1.
        Case {
            name: "adjacent_matches",
            text: "aaaa",
            query: "aa",
            replace: "x",
            initial_matches: &[(0, 2), (2, 4)],
            expected_text: "xaa",
            expected_matches: &[(1, 3)],
            expected_cursor_line: 0,
            expected_cursor_col: 1,
            expected_current_match_idx: 0,
        },
        // Longer replacement: "ab" → "abc".
        // replace_end = 0 + 3 = 3. Remaining "ab" at 0..2 has start=0 < 3,
        // so position() returns None → wraps to index 0.
        Case {
            name: "longer_replacement",
            text: "ab",
            query: "ab",
            replace: "abc",
            initial_matches: &[(0, 2)],
            expected_text: "abc",
            expected_matches: &[(0, 2)],
            expected_cursor_line: 0,
            expected_cursor_col: 0,
            expected_current_match_idx: 0,
        },
        // No remaining matches: "ab" → "xy".
        // Matches is empty, current_match_idx resets to 0, cursor moves to
        // the end of the replacement (replace_end = 0 + 2 = 2).
        Case {
            name: "no_more_matches",
            text: "ab",
            query: "ab",
            replace: "xy",
            initial_matches: &[(0, 2)],
            expected_text: "xy",
            expected_matches: &[],
            expected_cursor_line: 0,
            expected_cursor_col: 2,
            expected_current_match_idx: 0,
        },
    ];

    let path = "/test.rs".to_string();
    for c in cases {
        let mut state = make_editor_with_single_tab(c.text);
        if let Some(tab) = state.tab_contents.get_mut(&path) {
            tab.find_replace_state = Some(FindReplaceState {
                query: c.query.to_string(),
                replace: c.replace.to_string(),
                matches: c.initial_matches.iter().map(|&(s, e)| s..e).collect(),
                current_match_idx: 0,
                case_sensitive: true,
            });
        }
        let _ = state.update(EditorMessage::FindReplace);
        let tab = state.tab_contents.get(&path).unwrap();
        let frs = tab.find_replace_state.as_ref().unwrap();

        assert_eq!(tab.content.text(), c.expected_text, "{}: text", c.name);
        assert_eq!(
            frs.matches.len(),
            c.expected_matches.len(),
            "{}: match count",
            c.name,
        );
        for (i, &(s, e)) in c.expected_matches.iter().enumerate() {
            assert_eq!(frs.matches[i], s..e, "{}: match {i} range", c.name);
        }
        let cursor = tab.content.cursor();
        assert_eq!(
            cursor.line, c.expected_cursor_line,
            "{}: cursor line",
            c.name
        );
        assert_eq!(
            cursor.column, c.expected_cursor_col,
            "{}: cursor col",
            c.name
        );
        assert_eq!(
            frs.current_match_idx, c.expected_current_match_idx,
            "{}: current_match_idx",
            c.name,
        );
    }
}

/// Helper to create an [`EditorState`] with a single tab at `/test.rs`
/// that has an active [`FindReplaceState`].
fn make_editor_with_find_state(
    text: &str,
    query: &str,
    matches: Vec<Range<usize>>,
    current_match_idx: usize,
) -> EditorState {
    let mut state = EditorState::new();
    state.tabs.push(Tab {
        path: "/test.rs".to_string(),
        file_name: "test.rs".to_string(),
        is_dirty: false,
        line_ending: LineEnding::Lf,
    });
    state.active_tab_index = 0;
    state.tab_contents.insert(
        "/test.rs".to_string(),
        TabData {
            content: EditorBuffer::with_text(text, None),
            undo_stack: RefCell::new(UndoStack::new()),
            find_replace_state: Some(FindReplaceState {
                query: query.to_string(),
                replace: String::new(),
                matches,
                current_match_idx,
                case_sensitive: true,
            }),
            saved_text_hash: 0,
        },
    );
    state
}

#[test]
fn test_navigate_find_match_wraps() {
    for direction in [FindDirection::Next, FindDirection::Prev] {
        let mut state = make_editor_with_find_state("a b c", " ", vec![1..2, 3..4], 0);
        for want in [1, 0] {
            let _ = state.navigate_find_match(direction);
            let s = state.tab_contents.get("/test.rs").unwrap();
            let s = s.find_replace_state.as_ref().unwrap();
            assert_eq!(s.current_match_idx, want, "{direction:?}");
        }
    }
}

#[test]
fn test_navigate_find_match_no_matches() {
    let mut state = make_editor_with_find_state("no matches", "zzz", vec![], 0);

    // Navigating with no matches should not crash.
    let _ = state.navigate_find_match(FindDirection::Next);
    let _ = state.navigate_find_match(FindDirection::Prev);
    let s = state.tab_contents.get("/test.rs").unwrap();
    let s = s.find_replace_state.as_ref().unwrap();
    assert_eq!(s.current_match_idx, 0);
}

#[test]
fn test_navigate_find_match_only_affects_find_tab() {
    // Tab without find state should not be affected.
    let mut state = make_editor_with_single_tab("hello");

    // Should not panic.
    let _ = state.navigate_find_match(FindDirection::Next);
    let _ = state.navigate_find_match(FindDirection::Prev);
}

// ── Tree arrow-key navigation tests ─────────────────────────────

#[expect(clippy::too_many_lines)]
#[test]
fn test_tree_nav_left_right() {
    struct Case {
        name: &'static str,
        msg: EditorMessage,
        start_idx: usize,
        /// Pre-expand "src" before sending the message
        pre_expand_src: bool,
        /// Set selected_file to Some("Cargo.toml") before sending the message
        pre_select_file: bool,
        /// Expected focus index after the message
        expected_idx: usize,
        /// Additional per-case assertions beyond focus index
        check: Option<fn(&EditorState, name: &str)>,
    }
    let cases: &[Case] = &[
        Case {
            name: "left_on_expanded_dir_collapses",
            msg: EditorMessage::TreeNavLeft,
            start_idx: 0,
            pre_expand_src: true,
            pre_select_file: false,
            expected_idx: 0,
            check: Some(|s, name| {
                assert!(!s.file_tree.expanded_dirs.contains("src"), "case: {name}");
            }),
        },
        Case {
            name: "left_on_file_navigates_to_parent",
            msg: EditorMessage::TreeNavLeft,
            start_idx: 1,
            pre_expand_src: true,
            pre_select_file: false,
            expected_idx: 0,
            check: Some(|s, name| {
                assert_eq!(s.file_tree.visible_tree_nodes[0].0, "src", "case: {name}");
            }),
        },
        Case {
            name: "left_on_root_collapsed_dir_noop",
            msg: EditorMessage::TreeNavLeft,
            start_idx: 0,
            pre_expand_src: false,
            pre_select_file: false,
            expected_idx: 0,
            check: None,
        },
        Case {
            name: "left_on_root_file_noop",
            msg: EditorMessage::TreeNavLeft,
            start_idx: 1,
            pre_expand_src: false,
            pre_select_file: false,
            expected_idx: 1,
            check: None,
        },
        Case {
            name: "right_on_collapsed_dir_expands_and_advances",
            msg: EditorMessage::TreeNavRight,
            start_idx: 0,
            pre_expand_src: false,
            pre_select_file: true,
            expected_idx: 1,
            check: Some(|s, name| {
                assert!(s.file_tree.expanded_dirs.contains("src"), "case: {name}");
                assert!(s.selected_file.is_none(), "case: {name}");
                assert_eq!(s.file_tree.visible_tree_nodes[1].0, "src/main.rs");
            }),
        },
        Case {
            name: "right_on_expanded_dir_moves_to_first_child",
            msg: EditorMessage::TreeNavRight,
            start_idx: 0,
            pre_expand_src: true,
            pre_select_file: false,
            expected_idx: 1,
            check: Some(|s, name| {
                assert_eq!(
                    s.file_tree.visible_tree_nodes[1].0, "src/main.rs",
                    "case: {name}"
                );
            }),
        },
        Case {
            name: "right_on_file_noop",
            msg: EditorMessage::TreeNavRight,
            start_idx: 1,
            pre_expand_src: false,
            pre_select_file: false,
            expected_idx: 1,
            check: None,
        },
    ];
    for case in cases {
        let mut state = make_editor_with_tree();
        if case.pre_expand_src {
            state.file_tree.expanded_dirs.insert("src".to_string());
            state.file_tree.nodes =
                build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
            state.file_tree.rebuild_visible();
        }
        state.file_tree.tree_focused = true;
        state.file_tree.tree_focus_index = case.start_idx;
        if case.pre_select_file {
            state.selected_file = Some("Cargo.toml".to_string());
        }
        let _ = state.update(case.msg.clone());
        assert_eq!(
            state.file_tree.tree_focus_index, case.expected_idx,
            "case: {}",
            case.name
        );
        if let Some(check) = case.check {
            check(&state, case.name);
        }
    }
}

// ── Click-to-select focus index tests ────────────────────────────

#[test]
fn test_toggle_dir_sets_tree_focus_index() {
    let mut state = make_editor_with_tree();
    // Select a file first so we can verify it gets cleared.
    state.selected_file = Some("Cargo.toml".to_string());
    let _ = state.update(EditorMessage::ToggleDir("src".to_string()));
    // ToggleDir should set tree_focus_index to "src"'s position
    assert!(state.file_tree.tree_focused);
    assert_eq!(state.file_tree.tree_focus_index, 0);
    assert_eq!(state.file_tree.visible_tree_nodes[0].0, "src");
    assert!(
        state.selected_file.is_none(),
        "ToggleDir should clear selected_file"
    );
}

#[test]
fn test_select_file_sets_tree_focus_index() {
    let mut state = make_editor_with_tree();
    // Expand "src" so "src/main.rs" is visible in the flat list.
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.file_tree.nodes =
        build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
    state.file_tree.rebuild_visible();
    state.file_tree.tree_focused = true;
    let _ = state.update(EditorMessage::SelectFile("src/main.rs".to_string()));
    // SelectFile keeps tree_focused and remembers focus index.
    assert!(state.file_tree.tree_focused);
    // tree_focus_index should point to "src/main.rs" for Ctrl+B re-focus.
    assert_eq!(
        state.file_tree.visible_tree_nodes[state.file_tree.tree_focus_index].0,
        "src/main.rs"
    );
}

#[test]
fn test_select_file_sets_tree_focused_when_not_focused() {
    // When tree_focused starts false, clicking a file should set it true.
    let mut state = make_editor_with_tree();
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.file_tree.nodes =
        build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
    state.file_tree.rebuild_visible();
    state.file_tree.tree_focused = false;
    let _ = state.update(EditorMessage::SelectFile("src/main.rs".to_string()));
    assert!(
        state.file_tree.tree_focused,
        "SelectFile should set tree_focused to true"
    );
}

// ── Focus gating and find/replace cursor tests ───────────────────

fn make_editor_with_single_tab(text: &str) -> EditorState {
    let mut state = EditorState::new();
    state.tabs.push(Tab {
        path: "/test.rs".to_string(),
        file_name: "test.rs".to_string(),
        is_dirty: false,
        line_ending: LineEnding::Lf,
    });
    state.active_tab_index = 0;
    state.tab_contents.insert(
        "/test.rs".to_string(),
        TabData {
            content: EditorBuffer::with_text(text, None),
            undo_stack: RefCell::new(UndoStack::new()),
            find_replace_state: None,
            saved_text_hash: hash_text(text),
        },
    );
    state
}

#[test]
fn test_undo_noop_when_quick_open_active() {
    let mut state = make_editor_with_single_tab("hello");
    let path = "/test.rs".to_string();
    if let Some(tab_data) = state.tab_contents.get_mut(&path) {
        tab_data
            .undo_stack
            .borrow_mut()
            .snap_before_edit(&tab_data.content);
        tab_data.content.perform_action(EditorAction::Insert('!'));
    }
    state.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
        filter: String::new(),
        selected_index: 0,
        results: Vec::new(),
    }));
    let _ = state.update(EditorMessage::Undo);
    assert_eq!(
        state.tab_contents.get(&path).unwrap().content.text(),
        "!hello"
    );
}

#[test]
fn test_refresh_file_tree_noop_when_quick_open_active() {
    let mut state = make_editor_with_tree();
    // Pre-populate dir_generations so we can detect new entries.
    let initial_gen_count = state.dir_generations.len();
    assert!(state.selected_workspace_path.is_some());

    // Activate a modal overlay (QuickOpen).
    state.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
        filter: String::new(),
        selected_index: 0,
        results: Vec::new(),
    }));

    // RefreshFileTree should be suppressed — no new dir generations added.
    let _ = state.update(EditorMessage::RefreshFileTree);
    assert_eq!(
        state.dir_generations.len(),
        initial_gen_count,
        "RefreshFileTree must not spawn directory refreshes when a modal overlay is active"
    );
}

#[test]
fn test_tree_focus_toggled_noop_during_modal_overlay() {
    let mut state = make_editor_with_tree();
    // First toggle tree focus ON.
    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(state.file_tree.tree_focused);

    // Activate a modal overlay (QuickOpen).
    state.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
        filter: String::new(),
        selected_index: 0,
        results: Vec::new(),
    }));

    // TreeFocusToggled should be suppressed — focus stays ON.
    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(
        state.file_tree.tree_focused,
        "TreeFocusToggled must not toggle focus when a modal overlay is active"
    );
}

#[test]
fn test_tree_nav_suppressed_during_goto_line_overlay() {
    let mut state = make_editor_with_tree();
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.file_tree.nodes =
        build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
    state.file_tree.rebuild_visible();
    state.file_tree.tree_focused = true;
    state.file_tree.tree_focus_index = 0; // "src"

    // Activate a non-search modal overlay (GotoLine).
    state.active_modal = Some(ModalKind::GotoLine(String::new()));

    let prev_focus = state.file_tree.tree_focus_index;
    // Up/Down/Enter/Left/Right — assert tree_focus_index unchanged.
    let nav_msgs: &[EditorMessage] = &[
        EditorMessage::TreeNavUp,
        EditorMessage::TreeNavDown,
        EditorMessage::TreeNavEnter,
        EditorMessage::TreeNavLeft,
        EditorMessage::TreeNavRight,
    ];
    for msg in nav_msgs {
        let _ = state.update(msg.clone());
        assert_eq!(
            state.file_tree.tree_focus_index, prev_focus,
            "{msg:?} should be suppressed during GotoLine overlay"
        );
    }

    // TreeFocusToggled is handled separately because it toggles
    // tree_focused, not tree_focus_index.
    let _ = state.update(EditorMessage::TreeFocusToggled);
    assert!(
        state.file_tree.tree_focused,
        "TreeFocusToggled should be suppressed during GotoLine overlay"
    );
}

#[test]
fn test_find_replace_all_preserves_cursor() {
    let mut state = make_editor_with_single_tab("ab cd ab");
    let path = "/test.rs".to_string();
    if let Some(tab_data) = state.tab_contents.get_mut(&path) {
        tab_data.content.move_to(0, 5);
        tab_data.find_replace_state = Some(FindReplaceState {
            query: "ab".to_string(),
            replace: "xy".to_string(),
            matches: vec![0..2, 6..8],
            current_match_idx: 0,
            case_sensitive: true,
        });
    }
    let _ = state.update(EditorMessage::FindReplaceAll);
    let cursor = state.tab_contents.get(&path).unwrap().content.cursor();
    assert_eq!(cursor.line, 0);
    assert_eq!(cursor.column, 5);
}

#[test]
fn test_quick_open_toggle_blocked_when_goto_line_open() {
    let mut state = make_editor_with_single_tab("hello");
    state.active_modal = Some(ModalKind::GotoLine(String::new()));
    let _ = state.update(EditorMessage::QuickOpenToggle);
    assert!(!matches!(state.active_modal, Some(ModalKind::QuickOpen(_))));
}

#[test]
fn test_quick_open_toggle_closes_when_already_open() {
    let mut state = make_editor_with_single_tab("hello");
    state.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
        filter: "foo".to_string(),
        selected_index: 0,
        results: Vec::new(),
    }));
    let _ = state.update(EditorMessage::QuickOpenToggle);
    assert!(state.active_modal.is_none());
}

#[test]
fn test_global_search_toggle_blocked_when_quick_open_open() {
    let mut state = make_editor_with_single_tab("hello");
    state.selected_workspace_name = Some("ws".to_string());
    state.selected_workspace_path = Some("/tmp/ws".to_string());
    state.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
        filter: String::new(),
        selected_index: 0,
        results: Vec::new(),
    }));
    let _ = state.update(EditorMessage::GlobalSearchToggle);
    assert!(!matches!(
        state.active_modal,
        Some(ModalKind::GlobalSearch(_))
    ));
}

// ── Inline rename tests ────────────────────────────────────

#[test]
fn test_rename_request_sets_target() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    assert!(matches!(state.active_modal, Some(ModalKind::Rename(_))));
    let rt = match state.active_modal {
        Some(ModalKind::Rename(ref rt)) => rt.clone(),
        _ => panic!("expected Rename modal"),
    };
    assert_eq!(rt.path, "Cargo.toml");
    assert_eq!(rt.input_text, "Cargo.toml");
    assert!(!rt.is_dir);
}

#[test]
fn test_rename_request_on_directory_sets_is_dir() {
    // Use a real temp directory so Path::is_dir() returns true.
    let tmp_dir = tempfile::tempdir().unwrap();
    let dir_path = tmp_dir.path().join("src");
    std::fs::create_dir(&dir_path).unwrap();
    let mut state = EditorState::new();
    state.selected_workspace_path = Some(tmp_dir.path().to_string_lossy().to_string());
    state.dir_entries.insert(
        String::new(),
        vec![FsEntry {
            name: "src".to_string(),
            full_path: "src".to_string(),
            is_dir: true,
            error: None,
        }],
    );
    let _ = state.update(EditorMessage::RenameRequested("src".into()));
    assert!(matches!(state.active_modal, Some(ModalKind::Rename(_))));
    let rt = match state.active_modal {
        Some(ModalKind::Rename(ref rt)) => rt.clone(),
        _ => panic!("expected Rename modal"),
    };
    assert_eq!(rt.path, "src");
    assert_eq!(rt.input_text, "src");
    assert!(rt.is_dir);
}

#[test]
fn test_rename_request_on_root_dir_rejected() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());
    let _ = state.update(EditorMessage::RenameRequested(String::new()));
    assert!(
        state.active_modal.is_none() || !matches!(state.active_modal, Some(ModalKind::Rename(_)))
    );
}

#[test]
fn test_rename_input_updates_text_and_clears_error() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    // Simulate a validation error
    if let Some(ModalKind::Rename(ref mut rt)) = state.active_modal {
        rt.error = Some("bad".into());
    }
    // Type new text
    let _ = state.update(EditorMessage::RenameInput("new_name".into()));
    if let Some(ModalKind::Rename(ref rt)) = state.active_modal {
        assert_eq!(rt.input_text, "new_name");
        // Error should be cleared when user types
        assert!(rt.error.is_none());
    } else {
        panic!("expected Rename modal");
    }
}

#[test]
fn test_rename_cancel_and_escape() {
    for msg in [EditorMessage::RenameCancel, EditorMessage::Escape] {
        let mut state = make_editor_with_tree();
        state.selected_workspace_path = Some("/tmp".to_string());
        let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
        assert!(matches!(state.active_modal, Some(ModalKind::Rename(_))));
        let _ = state.update(msg.clone());
        assert!(
            state.active_modal.is_none(),
            "{msg:?} must close the Rename modal"
        );
    }
}

#[test]
fn test_tree_nav_suppressed_during_rename() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());
    // Expand "src" so TreeNavEnter/TreeNavLeft/TreeNavRight have targets.
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.file_tree.nodes =
        build_hierarchical_tree(&state.dir_entries, &state.file_tree.expanded_dirs, "");
    state.file_tree.rebuild_visible();
    state.file_tree.tree_focused = true;
    // Focus on "src" so TreeNavLeft (collapse) and TreeNavRight (expand)
    // have an effect when not suppressed.
    state.file_tree.tree_focus_index = 0; // "src"

    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    let prev_focus = state.file_tree.tree_focus_index;
    // All 6 tree-navigation messages must be suppressed during rename.
    let nav_msgs: &[EditorMessage] = &[
        EditorMessage::TreeNavUp,
        EditorMessage::TreeNavDown,
        EditorMessage::TreeNavEnter,
        EditorMessage::TreeNavLeft,
        EditorMessage::TreeNavRight,
        EditorMessage::TreeFocusToggled,
    ];
    for msg in nav_msgs {
        let _ = state.update(msg.clone());
        assert_eq!(
            state.file_tree.tree_focus_index, prev_focus,
            "{msg:?} should be suppressed during rename"
        );
    }
    // After the rename is cancelled, navigation should work again.
    let _ = state.update(EditorMessage::RenameCancel);
    let _ = state.update(EditorMessage::TreeNavDown);
    // Focus should have moved now that rename is gone.
    assert_ne!(state.file_tree.tree_focus_index, prev_focus);
}

#[test]
fn test_rename_mutual_exclusion_with_new_item() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());

    // Start rename, then NewFileRequested should cancel it.
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    assert!(matches!(state.active_modal, Some(ModalKind::Rename(_))));
    let _ = state.update(EditorMessage::NewFileRequested("src".into()));
    assert!(
        state.active_modal.is_none() || !matches!(state.active_modal, Some(ModalKind::Rename(_)))
    );
    assert!(matches!(state.active_modal, Some(ModalKind::NewItem(_))));

    // Start new item again — and confirm rename cancels new_item.
    let _ = state.update(EditorMessage::NewFileRequested(String::new()));
    assert!(matches!(state.active_modal, Some(ModalKind::NewItem(_))));
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    assert!(matches!(state.active_modal, Some(ModalKind::Rename(_))));
}

// ── Rename validation tests ────────────────────────────────

/// Helper: set up state for rename validation tests.
fn setup_rename_state(state: &mut EditorState, input_text: &str) {
    state.selected_workspace_path = Some("/tmp".to_string());
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    if let Some(ModalKind::Rename(ref mut rt)) = state.active_modal {
        rt.input_text = input_text.to_string();
    }
}

/// Helper: set up a rename with `input`, submit it, and assert that
/// the resulting error equals `expected`.
fn assert_rename_rejects(input: &str, expected: Option<&'static str>) {
    let mut state = make_editor_with_tree();
    setup_rename_state(&mut state, input);
    let _ = state.update(EditorMessage::RenameSubmit);
    let err = match &state.active_modal {
        Some(ModalKind::Rename(rt)) => rt.error.as_deref(),
        _ => None,
    };
    assert_eq!(err, expected, "rejection of {input:?}");
}

#[test]
fn test_rename_validation() {
    struct Case {
        input: &'static str,
        expected: Option<&'static str>,
    }
    let cases: &[Case] = &[
        // Empty / whitespace-only
        Case {
            input: "   ",
            expected: Some("Name cannot be empty"),
        },
        // Path separators
        Case {
            input: "foo/bar.rs",
            expected: Some("Name cannot contain path separators"),
        },
        Case {
            input: "foo\\bar.rs",
            expected: Some("Name cannot contain path separators"),
        },
        Case {
            input: "foo\0bar.rs",
            expected: Some("Name cannot contain path separators"),
        },
        // Dot / dot-dot
        Case {
            input: ".",
            expected: Some("Invalid name"),
        },
        Case {
            input: "..",
            expected: Some("Invalid name"),
        },
    ];
    for case in cases {
        assert_rename_rejects(case.input, case.expected);
    }
}

#[cfg(target_os = "windows")]
#[test]
fn test_rename_validation_os_reserved_names() {
    let reserved = ["con", "NUL", "prn", "AUX", "com1", "lpt3"];
    for name in &reserved {
        assert_rename_rejects(name, Some("Name is reserved by the operating system"));
    }
}

#[test]
fn test_rename_validation_target_already_exists() {
    let tmp_dir = tempfile::tempdir().unwrap();
    let ws = tmp_dir.path().to_string_lossy().to_string();
    // Create a file that would conflict.
    let existing = tmp_dir.path().join("existing.txt");
    std::fs::write(&existing, "").unwrap();

    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some(ws.clone());
    let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
    if let Some(ModalKind::Rename(ref mut rt)) = state.active_modal {
        rt.input_text = "existing.txt".to_string();
    }
    let _ = state.update(EditorMessage::RenameSubmit);
    let err = match &state.active_modal {
        Some(ModalKind::Rename(rt)) => rt.error.as_deref(),
        _ => None,
    };
    assert_eq!(
        err,
        Some("A file or directory with that name already exists")
    );
}

#[test]
fn test_rename_stale_generation_discarded() {
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());
    // Expand src so it's visible for RenameRequested.
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.rebuild_tree();

    // Dispatch a rename for a non-root path (src/main.rs) so that the
    // staleness check in RenameCompleted (which only applies when the
    // parent dir is non-empty) is actually exercised.
    let _ = state.update(EditorMessage::RenameRequested("src/main.rs".into()));
    if let Some(ModalKind::Rename(ref mut rt)) = state.active_modal {
        rt.input_text = "lib.rs".to_string();
    }
    let _ = state.update(EditorMessage::RenameSubmit);

    // Simulate a stale RenameCompleted whose rename_gen does not
    // match the current dir_generations entry for the parent dir ("src").
    // It passes dir_entries: Ok(vec![]) — if the staleness guard fails and
    // this result is applied, it would overwrite dir_entries["src"] with
    // an empty vec, losing the original children.
    let task = state.update(EditorMessage::RenameCompleted {
        old_path: "src/main.rs".into(),
        new_path: "src/lib.rs".into(),
        is_dir: false,
        result: Ok(()),
        dir_entries: Ok(vec![]),
        rename_gen: 0, // stale — doesn't match dir_generations["src"]
    });
    // The stale result should be a no-op (discarded silently).
    let _ = task;
    // dir_entries["src"] must still contain its original entries — if
    // the stale result were applied, the empty vec would have replaced them.
    let src_entries = state.dir_entries.get("src");
    assert!(
        src_entries.is_some(),
        "dir_entries[\"src\"] should still exist"
    );
    if let Some(entries) = src_entries {
        assert_eq!(entries.len(), 1, "should still have one entry");
        assert_eq!(entries[0].name, "main.rs");
        assert_eq!(entries[0].full_path, "src/main.rs");
    }
    // selected_file should not have been updated.
    assert_eq!(state.selected_file, None);
}

// ── Click-outside cancel tests (consolidated) ───────────────

#[test]
fn test_rename_cancelled_by_tree_click() {
    // Both ToggleDir and SelectFile should cancel a pending rename.
    let triggers: &[EditorMessage] = &[
        EditorMessage::ToggleDir("src".into()),
        EditorMessage::SelectFile("src/main.rs".into()),
    ];
    for trigger in triggers {
        let mut state = make_editor_with_tree();
        state.selected_workspace_path = Some("/tmp".to_string());
        let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
        assert!(
            matches!(state.active_modal, Some(ModalKind::Rename(_))),
            "rename should be active before {trigger:?}"
        );
        let _ = state.update(trigger.clone());
        assert!(
            state.active_modal.is_none()
                || !matches!(state.active_modal, Some(ModalKind::Rename(_))),
            "rename should be cancelled by {trigger:?}"
        );
    }
}

#[test]
fn test_rename_mutual_exclusion_cancelled_by_other_modals() {
    // Starting a different modal operation should cancel an active rename.
    // Each test case carries a message to dispatch and a check closure
    // that verifies the expected modal state after the message fires.
    struct Case {
        msg: EditorMessage,
        /// Assert the expected modal state after the message fires.
        check: fn(&EditorState),
    }
    let cases: &[Case] = &[
        Case {
            msg: EditorMessage::NewFileRequested("src".into()),
            check: |s| assert!(matches!(s.active_modal, Some(ModalKind::NewItem(_)))),
        },
        Case {
            msg: EditorMessage::NewDirectoryRequested("src".into()),
            check: |s| assert!(matches!(s.active_modal, Some(ModalKind::NewItem(_)))),
        },
        Case {
            msg: EditorMessage::DeleteFileRequested("other.rs".into()),
            check: |s| {
                assert!(matches!(s.active_modal, Some(ModalKind::DeleteConfirm(_))));
                if let Some(ModalKind::DeleteConfirm(ref target)) = s.active_modal {
                    assert_eq!(target.path, "other.rs");
                }
            },
        },
        Case {
            msg: EditorMessage::DeleteDirectoryRequested("src".into()),
            check: |s| {
                assert!(matches!(s.active_modal, Some(ModalKind::DeleteConfirm(_))));
                if let Some(ModalKind::DeleteConfirm(ref target)) = s.active_modal {
                    assert_eq!(target.path, "src");
                }
            },
        },
    ];
    for case in cases {
        let mut state = make_editor_with_tree();
        state.selected_workspace_path = Some("/tmp".to_string());

        // Start rename.
        let _ = state.update(EditorMessage::RenameRequested("Cargo.toml".into()));
        assert!(
            matches!(state.active_modal, Some(ModalKind::Rename(_))),
            "case {:?}",
            case.msg
        );

        // Fire the competing modal message.
        let _ = state.update(case.msg.clone());
        assert!(
            !matches!(state.active_modal, Some(ModalKind::Rename(_))),
            "rename should be cancelled by {:?}",
            case.msg
        );
        (case.check)(&state);
    }
}

// ── rekey helpers ──────────────────────────────────────────

#[test]
fn test_rekey_keys() {
    // (name, old_prefix, new_prefix, keys, expected pairs)
    #[rustfmt::skip]
    #[expect(clippy::type_complexity)]
    let cases: &[(&str, &str, &str, &[&str], &[(&str, &str)])] = &[
        ("empty", "old/", "new/", &[], &[]),
        ("no_match", "old/", "new/", &["a", "b"], &[]),
        (
            "some_match",
            "old/",
            "new",
            &["old/foo", "other", "old/bar/baz"],
            &[("old/bar/baz", "new/bar/baz"), ("old/foo", "new/foo")],
        ),
        ("exact_prefix", "dir", "newdir", &["dir"], &[("dir", "newdir")]),
    ];
    for &(name, old_prefix, new_prefix, keys, expected) in cases {
        let mut pairs = rekey_keys(
            old_prefix,
            new_prefix,
            keys.iter().map(std::string::ToString::to_string),
        );
        pairs.sort_by(|a, b| a.0.cmp(&b.0));
        let got: Vec<(&str, &str)> = pairs
            .iter()
            .map(|(a, b)| (a.as_str(), b.as_str()))
            .collect();
        assert_eq!(got, expected, "case: {name}");
    }
}

#[test]
fn test_rekey_map_prefix_no_modify() {
    let mut map = HashMap::from([
        ("dir/file.rs".to_string(), "content_a".to_string()),
        ("dir/sub/file.rs".to_string(), "content_b".to_string()),
        ("other".to_string(), "content_c".to_string()),
    ]);
    rekey_map_prefix(&mut map, "dir/", "newdir", |_| {});
    assert_eq!(map.len(), 3);
    assert_eq!(map.get("newdir/file.rs"), Some(&"content_a".to_string()));
    assert_eq!(
        map.get("newdir/sub/file.rs"),
        Some(&"content_b".to_string())
    );
    assert_eq!(map.get("other"), Some(&"content_c".to_string()));
    assert!(!map.contains_key("dir/file.rs"));
}

#[test]
fn test_rekey_map_prefix_with_modify() {
    let mut map = HashMap::from([
        ("old/key".to_string(), vec![1, 2]),
        ("old/other".to_string(), vec![3]),
        ("keep".to_string(), vec![4]),
    ]);
    rekey_map_prefix(&mut map, "old/", "new", |v: &mut Vec<i32>| v.push(99));
    assert_eq!(map.len(), 3);
    assert_eq!(map.get("new/key"), Some(&vec![1, 2, 99]));
    assert_eq!(map.get("new/other"), Some(&vec![3, 99]));
    assert_eq!(map.get("keep"), Some(&vec![4]));
}

#[test]
fn test_rekey_set_prefix_basic() {
    let mut set = HashSet::from(["a/x".to_string(), "a/y".to_string(), "b/z".to_string()]);
    rekey_set_prefix(&mut set, "a/", "b");
    assert_eq!(set.len(), 3);
    assert!(set.contains("b/x"));
    assert!(set.contains("b/y"));
    assert!(set.contains("b/z"));
}

#[test]
fn test_rekey_set_prefix_exact() {
    let mut set = HashSet::from(["dir".to_string()]);
    rekey_set_prefix(&mut set, "dir", "newdir");
    assert_eq!(set.len(), 1);
    assert!(set.contains("newdir"));
    assert!(!set.contains("dir"));
}

#[test]
fn test_rename_dir_entries_migration_own_entry_and_full_path() {
    // Verify that after a directory rename completes, the renamed
    // directory's own dir_entries key is migrated (old_path -> new_path)
    // and child entries have their full_path fields updated.
    let mut state = make_editor_with_tree();
    state.selected_workspace_path = Some("/tmp".to_string());

    // Set up state as if the user expanded "src" and we have its children.
    state.file_tree.expanded_dirs.insert("src".to_string());
    // Add a subdirectory entry for recursive testing.
    state.dir_entries.insert(
        "src/subdir".to_string(),
        vec![FsEntry {
            name: "helper.rs".to_string(),
            full_path: "src/subdir/helper.rs".to_string(),
            is_dir: false,
            error: None,
        }],
    );

    // Simulate a rename of "src" -> "lib" completing successfully.
    // Pre-populate dir_generations so the staleness guard passes
    // (rename_submit would have registered this generation before
    // firing the async operation).
    state.dir_generations.insert(String::new(), 0);
    let _ = state.update(EditorMessage::RenameCompleted {
        old_path: "src".into(),
        new_path: "lib".into(),
        is_dir: true,
        result: Ok(()),
        dir_entries: Ok(vec![FsEntry {
            name: "lib".to_string(),
            full_path: "lib".to_string(),
            is_dir: true,
            error: None,
        }]),
        rename_gen: 0,
    });

    // The directory's own dir_entries entry should be migrated.
    assert!(
        !state.dir_entries.contains_key("src"),
        "old path key should be removed"
    );
    let own_entries = state.dir_entries.get("lib");
    assert!(
        own_entries.is_some(),
        "new path key should exist for the renamed directory"
    );
    // The own-key entry's children must have their full_path updated.
    if let Some(entries) = own_entries {
        assert_eq!(entries.len(), 1, "src had one child (main.rs)");
        assert_eq!(entries[0].full_path, "lib/main.rs");
    }

    // The child directory entry should be migrated with updated full_path.
    let child_entries = state.dir_entries.get("lib/subdir");
    assert!(
        child_entries.is_some(),
        "child dir_entries key should be migrated"
    );
    if let Some(entries) = child_entries {
        if let Some(entry) = entries.first() {
            assert_eq!(
                entry.full_path, "lib/subdir/helper.rs",
                "entry full_path should be updated to new prefix"
            );
        }
    }

    // The expanded_dirs should have been migrated.
    assert!(
        !state.file_tree.expanded_dirs.contains("src"),
        "old expanded_dir should be removed"
    );
    assert!(
        state.file_tree.expanded_dirs.contains("lib"),
        "new expanded_dir should exist"
    );
}

/// Creates an [`EditorState`] with `count` tabs, each with a unique path and
/// file name. The active tab is set to `active`. The caller must ensure
/// `active < count`.
fn make_editor_with_tabs(count: usize, active: usize) -> EditorState {
    assert!(
        active < count,
        "active tab index must be less than tab count"
    );
    let mut state = EditorState::new();
    for i in 0..count {
        state.tabs.push(Tab {
            path: format!("/tmp/test_{i}.rs"),
            file_name: format!("test_{i}.rs"),
            is_dirty: false,
            line_ending: LineEnding::Lf,
        });
        state.tab_contents.insert(
            format!("/tmp/test_{i}.rs"),
            TabData {
                content: EditorBuffer::with_text("", None),
                undo_stack: RefCell::new(UndoStack::new()),
                find_replace_state: None,
                saved_text_hash: 0,
            },
        );
    }
    state.active_tab_index = active;
    state
}

#[test]
fn test_switch_tab_relative() {
    struct Case {
        name: &'static str,
        tabs: usize,
        start: usize,
        direction: TabDirection,
        expected: usize,
    }
    let cases: &[Case] = &[
        Case {
            name: "single tab next",
            tabs: 1,
            start: 0,
            direction: TabDirection::Next,
            expected: 0,
        },
        Case {
            name: "single tab prev",
            tabs: 1,
            start: 0,
            direction: TabDirection::Prev,
            expected: 0,
        },
        Case {
            name: "next wraps to first",
            tabs: 3,
            start: 2,
            direction: TabDirection::Next,
            expected: 0,
        },
        Case {
            name: "prev wraps to last",
            tabs: 3,
            start: 0,
            direction: TabDirection::Prev,
            expected: 2,
        },
        Case {
            name: "middle next",
            tabs: 3,
            start: 1,
            direction: TabDirection::Next,
            expected: 2,
        },
        Case {
            name: "middle prev",
            tabs: 3,
            start: 1,
            direction: TabDirection::Prev,
            expected: 0,
        },
    ];
    for case in cases {
        let mut state = make_editor_with_tabs(case.tabs, case.start);
        let _ = state.switch_tab_relative(case.direction);
        assert_eq!(state.active_tab_index, case.expected, "{}", case.name);
    }
}

#[test]
fn test_switch_tab_relative_two_tabs() {
    // With exactly two tabs, Next and Prev toggle between them.
    let mut state = make_editor_with_tabs(2, 0);
    let _ = state.switch_tab_relative(TabDirection::Next);
    assert_eq!(state.active_tab_index, 1);

    let _ = state.switch_tab_relative(TabDirection::Next);
    assert_eq!(state.active_tab_index, 0);

    let _ = state.switch_tab_relative(TabDirection::Prev);
    assert_eq!(state.active_tab_index, 1);
}

// ── Directory forgetting (deleted directories) ─────────────────

#[test]
fn test_classify_read_dir_error_not_found_vs_other() {
    use std::io::ErrorKind;
    // ENOENT / ENOTDIR mean the directory is gone or was never a
    // directory — normal and forgettable.
    assert!(matches!(
        classify_read_dir_error(&std::io::Error::new(ErrorKind::NotFound, "gone")),
        ReadDirError::NotFound
    ));
    assert!(matches!(
        classify_read_dir_error(&std::io::Error::new(ErrorKind::NotADirectory, "file")),
        ReadDirError::NotFound
    ));
    // Everything else means the directory exists but cannot be read —
    // a real problem that must keep warning.
    assert!(matches!(
        classify_read_dir_error(&std::io::Error::new(ErrorKind::PermissionDenied, "locked")),
        ReadDirError::Other(_)
    ));
}

/// Set up an EditorState with "src" and "src/sub" expanded, a cached
/// quick-open file list, and per-file absolute-path caches, so a
/// directory-forget can be asserted against all of them.
fn make_editor_with_expanded_subdir() -> EditorState {
    let mut state = make_editor_with_tree();
    state.file_tree.expanded_dirs.insert("src".to_string());
    state.file_tree.expanded_dirs.insert("src/sub".to_string());
    state.dir_entries.insert(
        "src/sub".to_string(),
        vec![FsEntry {
            name: "deep.rs".to_string(),
            full_path: "src/sub/deep.rs".to_string(),
            is_dir: false,
            error: None,
        }],
    );
    state.dir_entries.get_mut("src").unwrap().push(FsEntry {
        name: "sub".to_string(),
        full_path: "src/sub".to_string(),
        is_dir: true,
        error: None,
    });
    state.loading_dirs.insert("src/sub".to_string());
    state.dir_generations.insert("src".to_string(), 3);
    state.dir_generations.insert("src/sub".to_string(), 7);
    state.selected_file = Some("src/sub/deep.rs".to_string());
    state.all_workspace_files = vec![
        "Cargo.toml".to_string(),
        "src/main.rs".to_string(),
        "src/sub/deep.rs".to_string(),
    ];
    // Absolute-path-keyed caches (workspace root is "/tmp").
    state
        .file_mtimes
        .insert("/tmp/src/main.rs".to_string(), std::time::SystemTime::now());
    state
        .file_generations
        .insert("/tmp/src/main.rs".to_string(), 1);
    state
        .deleted_file_toasted
        .insert("/tmp/src/main.rs".to_string());
    state
}

#[test]
fn test_dir_expanded_not_found_forgets_silently() {
    // A missing directory must be forgotten regardless of the quiet flag:
    // no toast and no warning, whether the deletion came from the GUI,
    // external tooling, or a script.
    for quiet in [true, false] {
        let mut state = make_editor_with_expanded_subdir();
        let r#gen = state.bump_generation();
        state.dir_generations.insert("src".to_string(), r#gen);
        let _ = state.update(EditorMessage::DirExpanded {
            dir_path: "src".to_string(),
            r#gen,
            entries: Err(ReadDirError::NotFound),
            quiet,
        });

        // The deleted directory and its descendants are forgotten from the
        // expanded set, the cached listings, in-flight loads/generations,
        // the quick-open cache, and the selection.
        assert!(!state.file_tree.expanded_dirs.contains("src"));
        assert!(!state.file_tree.expanded_dirs.contains("src/sub"));
        assert!(!state.dir_entries.contains_key("src"));
        assert!(!state.dir_entries.contains_key("src/sub"));
        assert!(!state.loading_dirs.contains("src/sub"));
        assert!(!state.dir_generations.contains_key("src"));
        assert!(!state.dir_generations.contains_key("src/sub"));
        assert_eq!(state.selected_file, None);
        assert!(
            !state
                .all_workspace_files
                .iter()
                .any(|p| p.starts_with("src/"))
        );

        // The stale node is pruned from the parent's listing too, so the
        // tree no longer shows the deleted directory.
        let root_entries = state.dir_entries.get("").unwrap();
        assert!(!root_entries.iter().any(|e| e.full_path == "src"));
        assert!(
            !state
                .file_tree
                .visible_tree_nodes
                .iter()
                .any(|(p, _)| p == "src")
        );
    }
}

#[test]
fn test_dir_expanded_other_error_keeps_path() {
    // A directory that still exists but cannot be read must NOT be
    // forgotten — it stays in the refresh/cache state so the problem
    // keeps surfacing as a warning.
    let mut state = make_editor_with_expanded_subdir();
    let r#gen = state.bump_generation();
    state.dir_generations.insert("src".to_string(), r#gen);
    let _ = state.update(EditorMessage::DirExpanded {
        dir_path: "src".to_string(),
        r#gen,
        entries: Err(ReadDirError::Other("Permission denied".to_string())),
        quiet: true,
    });

    assert!(state.file_tree.expanded_dirs.contains("src"));
    assert!(state.file_tree.expanded_dirs.contains("src/sub"));
    assert!(state.dir_entries.contains_key("src"));
    assert!(state.dir_entries.contains_key("src/sub"));
    assert_eq!(state.selected_file.as_deref(), Some("src/sub/deep.rs"));
    assert!(state.all_workspace_files.iter().any(|p| p == "src/main.rs"));
}

#[test]
fn test_forget_directory_prunes_path_descendants_and_root() {
    // Phase 1: forgetting a subdirectory prunes it and its descendants from
    // every refresh/cache structure while preserving the parent's state.
    let mut state = make_editor_with_expanded_subdir();
    state.dir_generations.insert(String::new(), 9); // parent (root) gen must survive
    state.forget_directory("src");

    assert!(state.file_tree.expanded_dirs.is_empty());
    assert!(!state.dir_entries.contains_key("src"));
    assert!(!state.dir_entries.contains_key("src/sub"));
    assert!(state.loading_dirs.is_empty());
    assert!(!state.dir_generations.contains_key("src"));
    assert!(!state.dir_generations.contains_key("src/sub"));
    assert_eq!(state.dir_generations.get(""), Some(&9));
    assert_eq!(state.selected_file, None);
    assert_eq!(state.all_workspace_files, vec!["Cargo.toml".to_string()]);

    // Root listing keeps unrelated entries but drops the deleted node.
    let root_entries = state.dir_entries.get("").unwrap();
    assert_eq!(root_entries.len(), 1);
    assert_eq!(root_entries[0].full_path, "Cargo.toml");

    // Absolute-path-keyed caches are pruned as well.
    assert!(state.file_mtimes.is_empty());
    assert!(state.file_generations.is_empty());
    assert!(state.deleted_file_toasted.is_empty());

    state.rebuild_tree();
    assert!(
        !state
            .file_tree
            .visible_tree_nodes
            .iter()
            .any(|(p, _)| p == "src")
    );

    // Phase 2: forgetting the root (workspace itself gone) clears the whole
    // tree — including the surviving root listing and, per the doc contract,
    // the absolute-path-keyed caches under the workspace.
    state
        .file_mtimes
        .insert("/tmp/Cargo.toml".to_string(), std::time::SystemTime::now());
    state
        .file_generations
        .insert("/tmp/Cargo.toml".to_string(), 4);
    state
        .deleted_file_toasted
        .insert("/tmp/Cargo.toml".to_string());
    state.forget_directory("");

    assert!(state.dir_entries.is_empty());
    assert!(state.file_tree.expanded_dirs.is_empty());
    assert!(state.loading_dirs.is_empty());
    assert!(state.dir_generations.is_empty());
    assert_eq!(state.selected_file, None);
    assert!(state.all_workspace_files.is_empty());
    assert!(state.file_mtimes.is_empty());
    assert!(state.file_generations.is_empty());
    assert!(state.deleted_file_toasted.is_empty());

    state.rebuild_tree();
    assert!(state.file_tree.nodes.is_empty());
    assert!(state.file_tree.visible_tree_nodes.is_empty());
}

#[test]
fn test_dir_deleted_prunes_and_refreshes_parent() {
    // The DirDeleted message is emitted by the GUI-delete success path: it
    // must prune the deleted directory (and descendants) from the tree state
    // and register a parent re-read generation so the tree refreshes.
    let mut state = make_editor_with_expanded_subdir();
    let _ = state.update(EditorMessage::DirDeleted {
        dir_path: "src".to_string(),
        workspace_path: "/tmp".to_string(),
    });

    assert!(!state.file_tree.expanded_dirs.contains("src"));
    assert!(!state.file_tree.expanded_dirs.contains("src/sub"));
    assert!(!state.dir_entries.contains_key("src"));
    assert!(!state.dir_entries.contains_key("src/sub"));
    assert_eq!(state.selected_file, None);
    assert!(
        !state
            .all_workspace_files
            .iter()
            .any(|p| p.starts_with("src/"))
    );

    // The parent (root) listing survives but no longer shows the deleted dir.
    let root_entries = state.dir_entries.get("").unwrap();
    assert!(!root_entries.iter().any(|e| e.full_path == "src"));
    assert_eq!(root_entries.len(), 1);
    assert_eq!(root_entries[0].full_path, "Cargo.toml");

    // A fresh generation slot for the parent re-read task was registered.
    assert!(state.dir_generations.contains_key(""));
}

#[test]
fn test_dir_deleted_stale_workspace_guard() {
    // The delete was started in another workspace: the completion must not
    // prune the currently selected workspace's state at the same relative
    // path (the user switched workspaces while remove_dir_all was running).
    let mut state = make_editor_with_expanded_subdir();
    let _ = state.update(EditorMessage::DirDeleted {
        dir_path: "src".to_string(),
        workspace_path: "/some/other/workspace".to_string(),
    });

    // Everything stays intact: no prune, no parent re-read registration.
    assert!(state.file_tree.expanded_dirs.contains("src"));
    assert!(state.file_tree.expanded_dirs.contains("src/sub"));
    assert!(state.dir_entries.contains_key("src"));
    assert!(state.dir_entries.contains_key("src/sub"));
    assert_eq!(state.selected_file.as_deref(), Some("src/sub/deep.rs"));
    assert_eq!(state.all_workspace_files.len(), 3);
    assert!(!state.dir_generations.contains_key(""));
    assert!(
        state
            .file_tree
            .visible_tree_nodes
            .iter()
            .any(|(p, _)| p == "src")
    );
}

#[test]
fn test_confirm_delete_dir_defers_prune_until_success() {
    // ConfirmDelete starts the async remove_dir_all but must NOT prune tree
    // state yet: if the delete fails (e.g. permission denied), the
    // still-existing directory must be fully intact in the tree. The prune
    // only happens in the DirDeleted success message, so asserting the tree
    // is untouched at delete-start is the testable proxy for the failure
    // path (the async task is not executed in tests).
    let mut state = make_editor_with_expanded_subdir();
    state.active_modal = Some(ModalKind::DeleteConfirm(DeleteConfirmTarget {
        path: "src".to_string(),
        is_dir: true,
        dirty_tab_count: 0,
        abs_path: "/tmp/src".to_string(),
    }));

    let _ = state.update(EditorMessage::ConfirmDelete);

    // Modal closed, but all tree/cache state survives the delete-start.
    assert!(state.active_modal.is_none());
    assert!(state.file_tree.expanded_dirs.contains("src"));
    assert!(state.file_tree.expanded_dirs.contains("src/sub"));
    assert!(state.dir_entries.contains_key("src"));
    assert!(state.dir_entries.contains_key("src/sub"));
    assert_eq!(state.selected_file.as_deref(), Some("src/sub/deep.rs"));
    assert_eq!(state.all_workspace_files.len(), 3);
    assert!(state.file_mtimes.contains_key("/tmp/src/main.rs"));
    assert!(state.file_generations.contains_key("/tmp/src/main.rs"));

    // No orphaned parent generation: the dir-delete path registers the
    // parent slot only when the delete succeeds (via DirDeleted).
    assert!(!state.dir_generations.contains_key(""));
    assert_eq!(state.dir_generations.len(), 2); // fixture: "src" and "src/sub"
}