mahbot 0.4.0

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
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
//! Code editor dashboard page — tabbed code editor with file tree, syntax-aware
//! editing, and workspace-backed tab persistence.
//!
//! Layout: split view of a fixed-width file tree (left) and a tabbed editor
//! (right, filling the remaining width). Workspace selection is handled by
//! the Dashboard sidebar/global picker. Tabs persist to the workspace
//! database and are restored on workspace selection.
//! Key bindings: Ctrl+S/Cmd+S to save, Tab/Shift+Tab for indent/outdent,
//! Ctrl+B for tree focus toggle.
//!
//! Tree keyboard navigation: when tree is focused, Arrow Up/Down navigate
//! entries, Enter opens files or expands directories, Escape exits focus.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime};

use iced::widget::{Space, button, column, container, row, scrollable, text, text_input};
use iced::{
    Alignment, Element, Length, Subscription, Task,
    keyboard::{self},
    widget::Id,
};

use iced_fonts::lucide;

use fff_search::grep::{GrepMode, GrepSearchOptions};
use fff_search::parse_grep_query;

use super::context_menu::{ContextMenu, MenuItem};

use crate::git_commands::{is_git_repo, run_git_check_ignore, run_git_output, run_git_status};
use crate::util::unquote_c_style;

use super::common::{UndoSnapshot, UndoStack};
use super::editor_widget::{LineEnding, detect_line_ending};
use crate::tools::MAX_FILE_SIZE_BYTES as MAX_FILE_SIZE;

use super::editor_widget::{EditorBuffer, byte_offset_to_line_col};
use super::theme;
use super::widget_helpers;
use super::widgets::{self, FileTree, TreeNavDirection};

mod editor_dialog;

// ── Constants ─────────────────────────────────────────────────────

/// Estimated advance width of one glyph in JetBrains Mono at the tab-label
/// size (12px): 0.6em × 12 = 7.2px. Tab labels render in the dashboard's
/// default font (JetBrains Mono, see [`super::JETBRAINS_MONO`]), so every
/// ASCII filename character contributes this width.
const TAB_CHAR_ADVANCE: f32 = 7.2;

/// Fixed non-text chrome per tab: button padding (`[8, 8]`) + the 2px row
/// spacing to the close button + the 12px close button itself.
const TAB_FIXED_CHROME: f32 = 16.0 + 2.0 + 12.0;

/// Extra width for the dirty-indicator dot (8px) plus its 2px row spacing.
const TAB_DIRTY_EXTRA: f32 = 8.0 + 2.0;

/// Estimate the rendered width of a tab in px for scroll-into-view decisions.
///
/// JetBrains Mono is monospace, so char count × [`TAB_CHAR_ADVANCE`] closely
/// approximates the label width; [`TAB_FIXED_CHROME`] covers padding, spacing
/// and the close button, plus [`TAB_DIRTY_EXTRA`] for the dirty dot. Unlike
/// the old flat 140px-per-tab constant (which overestimated every tab and
/// made the cumulative left-edge error huge), per-tab estimates keep the
/// error to a few px per tab, and the delta-based reveal in
/// [`EditorState::scroll_to_active_tab`] never amplifies it into a
/// right-edge clamp.
#[expect(clippy::cast_precision_loss)]
fn estimate_tab_width(tab: &Tab) -> f32 {
    let name_w = tab.file_name.chars().count() as f32 * TAB_CHAR_ADVANCE;
    let dirty = if tab.is_dirty { TAB_DIRTY_EXTRA } else { 0.0 };
    name_w + TAB_FIXED_CHROME + dirty
}

/// Estimated content-space left edge of tab `idx`: the sum of the estimated
/// widths of all tabs before it.
fn estimated_tab_left(tabs: &[Tab], idx: usize) -> f32 {
    tabs.iter().take(idx).map(estimate_tab_width).sum()
}

/// Estimated total content width of the tab strip (sum of all tab widths).
fn estimated_content_width(tabs: &[Tab]) -> f32 {
    tabs.iter().map(estimate_tab_width).sum()
}

/// Tick interval (keeps consistency with other dashboard pages).
const TICK_INTERVAL_SECS: u64 = 5;

/// Interval for re-reading expanded directory entries from disk.
const DIR_REFRESH_INTERVAL_SECS: u64 = 30;

/// Base font size for the editor.
const EDITOR_FONT_SIZE: f32 = 13.0;

/// Widget IDs for find/replace text inputs (used for auto-focus).
const FIND_SEARCH_ID: &str = "find_search_input";
const FIND_REPLACE_ID: &str = "find_replace_input";

/// Widget ID for the global search input.
const GLOBAL_SEARCH_INPUT_ID: &str = "global_search_input";

/// Widget ID for the go-to-line input.
const GOTO_LINE_INPUT_ID: &str = "goto_line_input";

/// Widget ID for the quick-open filter input.
const QUICK_OPEN_INPUT_ID: &str = "quick_open_input";

/// Widget ID for the new file/directory name input.
const NEW_ITEM_INPUT_ID: &str = "new_item_input";

/// Maximum number of global search results to display.
const MAX_GLOBAL_SEARCH_RESULTS: usize = 200;

/// Maximum matches per file for global search — spread results across files.
const GLOBAL_SEARCH_MATCHES_PER_FILE: usize = 20;

/// Debounce delay for global search query input (milliseconds).
const GLOBAL_SEARCH_DEBOUNCE_MS: u64 = 300;

/// Check whether a file name is an OS-generated metadata file that should
/// be hidden from the file tree.
#[must_use]
fn is_os_file(name: &str) -> bool {
    name.eq_ignore_ascii_case(".ds_store")
        || name.eq_ignore_ascii_case("thumbs.db")
        || name.eq_ignore_ascii_case("desktop.ini")
}

/// Render a centered empty-state placeholder with text content.
///
/// The caller passes a fully-configured `text()` widget (with size, color,
/// optional font, etc.) and this helper wraps it in the standard centered
/// container pattern used throughout the editor panel.
fn empty_placeholder(
    text: iced::widget::Text<'_, iced::Theme, iced::Renderer>,
) -> Element<'_, EditorMessage> {
    container(text)
        .width(Length::Fill)
        .height(Length::Fill)
        .center_x(Length::Fill)
        .center_y(Length::Fill)
        .into()
}

// ── Types ─────────────────────────────────────────────────────────

/// File-system entry for the directory tree.
#[derive(Debug, Clone)]
pub struct FsEntry {
    pub name: String,
    /// Path relative to the workspace root.
    pub full_path: String,
    pub is_dir: bool,
    /// Error message if this entry couldn't be properly inspected
    /// (broken symlink, permission denied, etc.).
    pub error: Option<String>,
}

/// Git file status for coloring the file tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitFileStatus {
    /// File has uncommitted modifications (M in porcelain output).
    Modified,
    /// File is untracked (?? in porcelain output) or newly added (A).
    Added,
}

/// A single editor tab (metadata, no content).
#[derive(Debug, Clone)]
struct Tab {
    /// Full filesystem path to the file.
    path: String,
    /// Display name (file name component only).
    file_name: String,
    /// Whether the file has unsaved changes.
    is_dirty: bool,
    /// Detected line ending convention.
    line_ending: LineEnding,
}

/// Content data for a tab, keyed by full path.
struct TabData {
    content: super::editor_widget::EditorBuffer,
    /// Undo/redo stack for this tab.
    undo_stack: RefCell<UndoStack>,
    /// Find/replace state (None when bar is hidden).
    find_replace_state: Option<FindReplaceState>,
    /// Hash of the last saved (or loaded) text. Used by undo/redo to
    /// detect when the editor returns to the saved state.
    saved_text_hash: u64,
}

/// Fast non-crypto hash of a string for dirty-state comparison.
fn hash_text(text: &str) -> u64 {
    use std::hash::Hasher;
    let mut h = std::collections::hash_map::DefaultHasher::new();
    h.write(text.as_bytes());
    h.finish()
}

/// Shared helper to construct a `Tab` + `TabData` pair from file text
/// and metadata.  Returns the pair together with the file's mtime (if
/// readable) so the caller can record it in `file_mtimes`.
fn make_tab_and_data(
    path: &str,
    text: &str,
    line_ending: LineEnding,
    is_dirty: bool,
    saved_text_hash: u64,
) -> (Tab, TabData, Option<SystemTime>) {
    let content = EditorBuffer::from_file(text, path);
    let file_name = Path::new(path)
        .file_name()
        .map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string());

    let tab = Tab {
        path: path.to_string(),
        file_name,
        is_dirty,
        line_ending,
    };

    let tab_data = TabData {
        content,
        undo_stack: RefCell::new(UndoStack::new()),
        find_replace_state: None,
        saved_text_hash,
    };

    let mtime = std::fs::metadata(path)
        .ok()
        .and_then(|meta| meta.modified().ok());

    (tab, tab_data, mtime)
}

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

/// State for the find/replace search bar.
#[derive(Debug, Clone)]
struct FindReplaceState {
    /// Current search query string.
    query: String,
    /// Replace-with string.
    replace: String,
    /// Byte ranges of all matches in the file.
    matches: Vec<std::ops::Range<usize>>,
    /// Index of the currently focused match.
    current_match_idx: usize,
    /// Whether matching is case-sensitive (default: false).
    case_sensitive: bool,
}

// ── Global Search ──────────────────────────────────────────────────

/// Status of the global (find-in-files) search.
#[derive(Debug, Clone, PartialEq, Eq)]
enum GlobalSearchStatus {
    /// Search panel is open but no query entered yet.
    Idle,
    /// Search is in progress.
    Searching,
    /// Search completed with results.
    Done,
    /// Search completed with no results.
    NoResults,
    /// Search encountered an error.
    Error(String),
}

/// Owned representation of a single grep match, extracted from
/// `fff_search::GrepResult` so it can cross async boundaries.
#[derive(Debug, Clone)]
pub struct OwnedGrepMatch {
    /// Absolute filesystem path to the matched file.
    abs_path: String,
    /// Relative path (for display).
    rel_path: String,
    /// 1-based line number.
    line_number: u64,
    /// Content of the matching line.
    line_content: String,
    /// Byte offsets of the matched portion within `line_content`,
    /// as `(start, end)` pairs (for highlighting).
    match_byte_offsets: Vec<(u32, u32)>,
}

/// State for the global search (Cmd+Shift+F) panel.
#[derive(Debug, Clone)]
struct GlobalSearchState {
    /// Current query text in the search input.
    query: String,
    /// Search results (empty when no search has been performed).
    results: Vec<OwnedGrepMatch>,
    /// Index of the currently selected result in the list.
    selected_index: usize,
    /// Current search status.
    status: GlobalSearchStatus,
}

use std::ops::Range;

/// Compute byte-range matches of `query` in `text`. Returns empty
/// when query is shorter than 2 characters.
///
/// When `case_sensitive` is `false`, matching uses ASCII-only case
/// folding via [`str::to_ascii_lowercase`] — this is length-preserving
/// so returned byte ranges are valid for the original `text`.
/// Non-ASCII queries are matched literally in case-insensitive mode
/// (standard editor convention).
#[must_use]
fn compute_text_matches(text: &str, query: &str, case_sensitive: bool) -> Vec<Range<usize>> {
    if query.len() < 2 {
        return Vec::new();
    }
    let mut matches = Vec::new();

    if case_sensitive {
        for (start, _) in text.match_indices(query) {
            matches.push(start..start + query.len());
        }
    } else {
        // Case-insensitive: lowercase both strings (ASCII-only, length-preserving).
        let text_lower = text.to_ascii_lowercase();
        let query_lower = query.to_ascii_lowercase();
        for (start, _) in text_lower.match_indices(&query_lower) {
            matches.push(start..start + query.len());
        }
    }

    matches
}

/// Direction for navigating between find matches.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FindDirection {
    Next,
    Prev,
}

/// Direction for switching tabs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TabDirection {
    Next,
    Prev,
}

/// Data returned from the async file load operation.
#[derive(Debug, Clone)]
pub struct FileLoadData {
    path: String,
    text: String,
    line_ending: LineEnding,
}

/// What to do with a dirty tab when closing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseAction {
    Save,
    Discard,
    Cancel,
}

/// Pending close action to execute after the next successful save.
/// Only one such action can be pending at a time.
#[derive(Debug, Clone)]
enum PendingCloseAction {
    /// Close this tab index.
    CloseTab(usize),
    /// Close all tabs except `keep_idx`; these dirty tab indices
    /// still need to be saved first.
    CloseOthers {
        keep_idx: usize,
        remaining_dirty: Vec<usize>,
    },
}

/// Raw data loaded from a saved tab entry (string content, not Content).
#[derive(Debug, Clone)]
pub struct SavedTabData {
    file_path: String,
    text: String,
    was_dirty: bool,
    line_ending: LineEnding,
    /// Whether this tab was the active one when saved.
    is_active: bool,
}

// ── Messages ─────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub enum EditorMessage {
    /// Workspace selected via the Dashboard sidebar/global picker (name,
    /// optional filesystem path).
    WorkspaceSelected(String, Option<String>),
    /// A directory's listing was loaded from the filesystem.
    DirExpanded {
        dir_path: String,
        r#gen: u64,
        entries: Result<Vec<FsEntry>, ReadDirError>,
        /// When `true`, read errors are logged instead of shown as a toast.
        /// Used by background (periodic/manual) refresh to avoid noise.
        /// Missing directories are forgotten silently either way.
        quiet: bool,
    },
    /// A GUI-initiated directory deletion succeeded in `workspace_path`.
    /// The editor prunes the deleted path and its descendants from the tree
    /// refresh/cache state and re-reads the parent directory.
    ///
    /// `workspace_path` is a staleness guard: the user can switch workspaces
    /// while the async delete is in flight (large trees can take seconds),
    /// so the completion must only prune the workspace it was started in —
    /// applying it against a newly selected workspace would drop that
    /// workspace's same-relative-path state.
    DirDeleted {
        dir_path: String,
        workspace_path: String,
    },
    /// User toggled a directory in the file tree.
    ToggleDir(String),
    /// User selected a file in the file tree.
    SelectFile(String),
    /// Ctrl+B toggled tree keyboard focus on/off.
    TreeFocusToggled,
    /// Arrow Up in tree keyboard navigation.
    TreeNavUp,
    /// Arrow Down in tree keyboard navigation.
    TreeNavDown,
    /// Enter key in tree navigation — open file or expand directory.
    TreeNavEnter,
    /// Arrow Left in tree navigation — collapse directory or go to parent.
    TreeNavLeft,
    /// Arrow Right in tree navigation — expand directory or go to first child.
    TreeNavRight,
    /// Scroll position changed in the tree panel. First element is the
    /// absolute vertical scroll offset, second is the visible viewport height.
    TreeScrolled(f32, f32),
    /// Scroll position changed in the tab bar. First element is the absolute
    /// horizontal scroll offset, second is the visible viewport width.
    TabBarScrolled(f32, f32),
    /// Escape key — dismiss find bar, go-to-line, quick open, tree focus, or close dialog.
    Escape,
    /// A file's contents were loaded from disk.
    FileLoaded {
        path: String,
        r#gen: u64,
        result: Result<FileLoadData, String>,
    },
    /// Saved tabs were loaded from the database with file contents.
    SavedTabsLoaded {
        tabs_data: Vec<SavedTabData>,
        r#gen: u64,
    },
    /// User selected an existing tab.
    TabSelected(usize),
    /// User closed a tab.
    TabClosed(usize),
    /// User performed an editing action in the text editor.
    EditorAction(super::editor_widget::EditorAction),
    /// User requested to save the active tab.
    SaveActiveTab,
    /// Result of a save operation.
    SaveResult {
        path: String,
        result: Result<(), String>,
        /// Hash of the content that was written to disk, so we can
        /// update `TabData::saved_text_hash` for undo/redo comparison.
        saved_hash: u64,
    },
    /// User interacted with the close-dirty-tab dialog.
    CloseDialog {
        tab_index: usize,
        action: CloseAction,
    },
    /// User interacted with the close-others dirty-tab dialog.
    CloseOthersDialog {
        keep_idx: usize,
        action: CloseAction,
    },
    /// Periodic tick — refreshes git status and gitignore for file tree coloring.
    Tick,
    /// Git status has been loaded for the current workspace's file tree.
    /// `r#gen` is captured at spawn time for stale-result prevention.
    GitStatusLoaded {
        r#gen: u64,
        result: Result<HashMap<String, GitFileStatus>, String>,
    },
    /// Git ignore status has been loaded for the current workspace's file tree.
    /// `r#gen` is captured at spawn time for stale-result prevention.
    GitIgnoredLoaded {
        r#gen: u64,
        result: Result<HashSet<String>, String>,
    },
    /// Toast message to show.
    Toast(super::ToastMessage),
    /// Undo the last edit.
    Undo,
    /// Redo a previously undone edit.
    Redo,
    /// Open/toggle the find/replace bar.
    FindToggle,
    /// Search query text changed.
    FindQueryInput(String),
    /// Replace text changed.
    FindReplaceInput(String),
    /// Navigate to the next match.
    FindNext,
    /// Navigate to the previous match.
    FindPrev,
    /// Replace the current match with the replace text.
    FindReplace,
    /// Replace all matches.
    FindReplaceAll,
    /// Toggle case-sensitive matching.
    FindToggleCaseSensitivity,
    /// Manual or periodic refresh of all expanded directory listings from disk.
    /// Also triggers a git status refresh so newly discovered files get colors.
    RefreshFileTree,
    /// Close all tabs except the given index.
    CloseOtherTabs(usize),
    /// Periodic check (every 300 ms) for external file changes on the active tab.
    /// Only fires when a workspace is selected.
    CheckFileChanges,
    /// A file was reloaded after being detected as changed on disk.
    /// The cursor position was captured *before* the async read and should
    /// be restored (clamped to new file bounds) on success.
    FileReloaded {
        /// Path of the reloaded file.
        path: String,
        /// Ok(text) on success, Err(msg) on failure.
        result: Result<String, String>,
        /// Cursor line before reload (preserved, clamped to new bounds).
        cursor_line: usize,
        /// Cursor column before reload (preserved, clamped to new bounds).
        cursor_col: usize,
    },
    /// Toggle the go-to-line input bar.
    GoToLineToggle,
    /// Input text for the go-to-line bar.
    GoToLineInput(String),
    /// Jump to the entered line number.
    GoToLineGo,
    /// Toggle the quick-open file picker.
    QuickOpenToggle,
    /// Filter text for the quick-open file picker.
    QuickOpenInput(String),
    /// Select a file from the quick-open list by index.
    QuickOpenSelect(usize),
    /// Switch to the next tab (Ctrl+Tab).
    TabSwitchNext,
    /// Switch to the previous tab (Ctrl+Shift+Tab).
    TabSwitchPrev,
    /// Close the active tab (Ctrl+W).
    CloseActiveTab,
    /// Toggle the global search panel (Cmd+Shift+F / Ctrl+Shift+F).
    GlobalSearchToggle,
    /// Query text changed in the global search input.
    GlobalSearchInput(String),
    /// Results returned from the async global search.
    GlobalSearchResults {
        /// Generation counter for stale-result prevention.
        r#gen: u64,
        /// Owned grep match results.
        results: Vec<OwnedGrepMatch>,
        /// Error message if the search failed.
        error: Option<String>,
    },
    /// A result was clicked or selected in the global search list.
    GlobalSearchSelect(usize),
    // ── Context menu actions ────────────────────────────────────────
    /// Context menu: delete a file (shows confirmation dialog).
    DeleteFileRequested(String),
    /// Context menu: delete a directory (shows confirmation dialog).
    DeleteDirectoryRequested(String),
    /// Context menu: create a new file in the given parent directory.
    NewFileRequested(String),
    /// Context menu: create a new directory in the given parent directory.
    NewDirectoryRequested(String),
    /// Context menu: reveal the path in the system file manager.
    RevealInFinder(String),
    /// Context menu: copy a relative path to clipboard.
    CopyRelativePath(String),
    /// Context menu: copy an absolute path to clipboard.
    CopyAbsolutePath(String),
    /// User confirmed the delete operation.
    ConfirmDelete,
    /// User cancelled the delete dialog.
    CancelDelete,
    /// User submitted a name for a new file or directory.
    NewItemSubmit(String),
    /// User changed the new-item name input.
    NewItemInput(String),
    // ── Inline rename ───────────────────────────────────────────
    /// Context menu: rename a file or directory (starts inline rename).
    RenameRequested(String),
    /// User changed the rename input text.
    RenameInput(String),
    /// User submitted the rename (Enter pressed in inline input).
    RenameSubmit,
    /// User cancelled the inline rename.
    RenameCancel,
    /// Async rename operation completed.
    RenameCompleted {
        /// Old relative path (workspace-relative).
        old_path: String,
        /// New relative path (workspace-relative).
        new_path: String,
        /// Whether the renamed item was a directory.
        is_dir: bool,
        /// Result of the filesystem rename.
        result: Result<(), String>,
        /// Re-read parent directory entries.
        dir_entries: Result<Vec<FsEntry>, ReadDirError>,
        /// Generation counter for the parent directory's `dir_generations`
        /// slot.  Used for stale-result prevention via the standard
        /// generation invalidation protocol (see `dir_expanded`).
        rename_gen: u64,
    },
}

// ── Context menu types ──────────────────────────────────────────

/// Target for the delete confirmation dialog.
#[derive(Debug, Clone)]
struct DeleteConfirmTarget {
    /// Full path (relative to workspace root).
    path: String,
    /// Whether this is a directory.
    is_dir: bool,
    /// Number of dirty tabs that would be affected (directory deletes only).
    dirty_tab_count: usize,
    /// Absolute path for filesystem operations.
    abs_path: String,
}

/// Target for the new file/directory name input.
#[derive(Debug, Clone)]
struct NewItemTarget {
    /// Parent directory path (relative to workspace root; empty = root).
    parent_dir: String,
    /// Whether to create a directory (vs a file).
    is_dir: bool,
    /// Absolute path of the parent directory.
    abs_parent: String,
    /// Absolute path of the workspace root.
    ws_root: String,
    /// Current input text.
    input_text: String,
}

/// Target for the inline rename operation.
#[derive(Debug, Clone)]
struct RenameTarget {
    /// Full path (relative to workspace root) of the item being renamed.
    path: String,
    /// Absolute path of the item being renamed.
    abs_path: String,
    /// Whether this is a directory.
    is_dir: bool,
    /// Absolute path of the workspace root.
    ws_root: String,
    /// Current input text (the new name being edited).
    input_text: String,
    /// Optional inline error message (e.g., "File already exists").
    error: Option<String>,
}

/// Style for the inline rename text input — transparent background, no border,
/// matching the appearance of the tree node label it replaces.
#[must_use]
fn rename_input_style(_theme: &iced::Theme, _status: text_input::Status) -> text_input::Style {
    text_input::Style {
        background: iced::Background::Color(iced::Color::TRANSPARENT),
        border: iced::Border {
            radius: 0.0.into(),
            width: 0.0,
            color: iced::Color::TRANSPARENT,
        },
        icon: theme::TEXT_MUTED,
        placeholder: theme::TEXT_MUTED,
        value: theme::TEXT_PRIMARY,
        selection: theme::ACCENT_DIM,
    }
}

/// Validate a user-supplied file/directory name for new-item or rename operations.
///
/// Returns `Some(error_message)` when the name is invalid, `None` when it passes
/// all checks.  Used by both [`NewItemSubmit`] and [`RenameSubmit`] to avoid
/// duplicating the common validation rules.
///
/// Checks performed:
/// - Empty (or all-whitespace) name
/// - Path separators (`/`, `\`, NUL)
/// - Reserved path components (`.`, `..`)
/// - OS-reserved names (CON, NUL, PRN, AUX, COM1–COM9, LPT1–LPT9) — Windows only
#[must_use]
fn validate_item_name(name: &str) -> Option<&'static str> {
    if name.is_empty() {
        return Some("Name cannot be empty");
    }
    if name.contains('/') || name.contains('\\') || name.contains('\0') {
        return Some("Name cannot contain path separators");
    }
    if name == "." || name == ".." {
        return Some("Invalid name");
    }
    #[cfg(target_os = "windows")]
    {
        let reserved = [
            "con", "nul", "prn", "aux", "com1", "com2", "com3", "com4", "com5", "com6", "com7",
            "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
        ];
        let stem = name.split('.').next().unwrap_or(name);
        if reserved.contains(&stem.to_lowercase().as_str()) {
            return Some("Name is reserved by the operating system");
        }
    }
    None
}

// ── Helpers — prefix-based collection re-keying ───────────────────

/// Join a `rest` portion (already stripped of the old prefix) with
/// `new_prefix` to form the new key.  `rest` is the portion of the
/// original key after the removed prefix; callers obtain it via
/// `strip_prefix` before calling this function.
fn rekey_compute_new_key(rest: &str, new_prefix: &str) -> String {
    if rest.is_empty() {
        new_prefix.to_string()
    } else {
        format!("{new_prefix}/{rest}")
    }
}

/// Collect all keys matching `old_prefix` and compute their new key with
/// `new_prefix` substituted.  Returns a vec of `(old_key, new_key)` pairs.
/// Used by [`rekey_map_prefix`] and [`rekey_set_prefix`] to avoid
/// duplicating the filter-and-collect logic.
fn rekey_keys(
    old_prefix: &str,
    new_prefix: &str,
    keys: impl IntoIterator<Item = String>,
) -> Vec<(String, String)> {
    keys.into_iter()
        .filter_map(|k| {
            let rest = k.strip_prefix(old_prefix)?;
            let new_key = rekey_compute_new_key(rest, new_prefix);
            Some((k, new_key))
        })
        .collect()
}

/// Re-key entries in a `HashMap<String, V>` whose keys start with
/// `old_prefix` to use `new_prefix` instead.  Each value passes through
/// `modify` before re-insertion (use `|_| {}` when no modification is
/// needed).  The old prefix should include a trailing separator (e.g.
/// `"old_dir/"`), and `rest` is the portion of the key after it; the
/// new key is `"{new_prefix}/{rest}"` (or just `new_prefix` when
/// `rest` is empty — i.e. when the key exactly equals `old_prefix`).
fn rekey_map_prefix<V>(
    map: &mut HashMap<String, V>,
    old_prefix: &str,
    new_prefix: &str,
    modify: impl Fn(&mut V),
) {
    let key_pairs = rekey_keys(old_prefix, new_prefix, map.keys().cloned());
    for (old_key, new_key) in key_pairs {
        if let Some(mut v) = map.remove(&old_key) {
            modify(&mut v);
            map.insert(new_key, v);
        }
    }
}

/// Re-key entries in a `HashSet<String>` whose keys start with
/// `old_prefix` to use `new_prefix` instead.  Same prefix conventions
/// as [`rekey_map_prefix`].
fn rekey_set_prefix(set: &mut HashSet<String>, old_prefix: &str, new_prefix: &str) {
    let key_pairs = rekey_keys(old_prefix, new_prefix, set.iter().cloned());
    for (old_key, new_key) in key_pairs {
        set.remove(&old_key);
        set.insert(new_key);
    }
}

/// Update the `full_path` of a single [`FsEntry`] by replacing `old_prefix`
/// with `new_prefix` when the path starts with `old_prefix`.  Used during
/// directory-rename migrations to keep `FsEntry` paths in sync with their
/// new directory key.
fn update_entry_path(entry: &mut FsEntry, old_prefix: &str, new_prefix: &str) {
    if let Some(rest) = entry.full_path.strip_prefix(old_prefix) {
        entry.full_path = rekey_compute_new_key(rest, new_prefix);
    }
}

// ── Helpers — async I/O ──────────────────────────────────────────

/// Error classifying a failed directory read so callers can tell the
/// normal "directory no longer exists" case (which the GUI must forget
/// silently) apart from real problems (permission denied, I/O errors)
/// that still need to be surfaced.
#[derive(Debug, Clone)]
pub enum ReadDirError {
    /// The directory does not exist, or is not a directory. This is a
    /// routine scenario — callers should silently forget the path.
    NotFound,
    /// The directory exists but could not be read.
    Other(String),
}

/// Map an [`std::io::Error`] from a directory read to a [`ReadDirError`].
/// ENOENT / ENOTDIR mean the directory is gone (or was never a directory) —
/// a normal, forgettable scenario. Everything else means the directory
/// exists but cannot be read — a real problem that must keep warning.
fn classify_read_dir_error(e: &std::io::Error) -> ReadDirError {
    if matches!(
        e.kind(),
        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
    ) {
        ReadDirError::NotFound
    } else {
        ReadDirError::Other(format!("{e}"))
    }
}

/// Read a flat list of directory entries for a given path relative to the
/// workspace root. The `root` is the workspace's filesystem path; `rel_path`
/// is the subdirectory relative to root (empty string for root).
///
/// A missing directory or a path that is not a directory yields
/// [`ReadDirError::NotFound`]; any other read failure yields
/// [`ReadDirError::Other`].
async fn read_directory_entries(root: &str, rel_path: &str) -> Result<Vec<FsEntry>, ReadDirError> {
    let dir_path = if rel_path.is_empty() {
        root.to_string()
    } else {
        let p = Path::new(root).join(rel_path);
        p.to_string_lossy().to_string()
    };
    let mut entries = match tokio::fs::read_dir(&dir_path).await {
        Ok(rd) => rd,
        Err(e) => return Err(classify_read_dir_error(&e)),
    };

    let mut result: Vec<FsEntry> = Vec::new();
    let mut dirs: Vec<FsEntry> = Vec::new();
    let mut files: Vec<FsEntry> = Vec::new();

    loop {
        let entry = match entries.next_entry().await {
            Ok(Some(entry)) => entry,
            Ok(None) => break,
            // The directory can vanish while the listing is in flight
            // (deleted mid-read). Classify it like a not-found instead of
            // caching a partial listing.
            Err(e) => return Err(classify_read_dir_error(&e)),
        };
        let name = entry.file_name().to_string_lossy().to_string();
        // Filter out .git directory — it's not a user-editable file.
        if name == ".git" {
            continue;
        }
        // Filter out OS-generated metadata files.
        if is_os_file(&name) {
            continue;
        }
        let full_path = if rel_path.is_empty() {
            name.clone()
        } else {
            format!("{rel_path}/{name}")
        };
        // Use tokio::fs::metadata() on the absolute path to follow symlinks.
        // DirEntry::file_type() does NOT traverse symlinks (per Rust docs).
        let abs_path = Path::new(&dir_path).join(&name);
        let (is_dir, err) = match tokio::fs::metadata(&abs_path).await {
            Ok(m) => (m.is_dir(), None),
            Err(e) => (false, Some(format!("{e}"))),
        };
        let fs_entry = FsEntry {
            name,
            full_path,
            is_dir: is_dir && err.is_none(),
            error: err,
        };
        if fs_entry.is_dir {
            dirs.push(fs_entry);
        } else {
            files.push(fs_entry);
        }
    }

    // Sort: directories first, then files, alphabetical within each group.
    dirs.sort_by_key(|e| e.name.to_lowercase());
    files.sort_by_key(|e| e.name.to_lowercase());
    result.extend(dirs);
    result.extend(files);
    Ok(result)
}

/// Read `dir_path` entries and build a [`DirExpanded`] message.
async fn dir_expanded_msg(
    ws_path: String,
    dir_path: String,
    r#gen: u64,
    quiet: bool,
) -> EditorMessage {
    let entries = read_directory_entries(&ws_path, &dir_path).await;
    EditorMessage::DirExpanded {
        dir_path,
        r#gen,
        entries,
        quiet,
    }
}

/// Spawn an async directory read that emits a [`DirExpanded`] message.
fn dir_expanded_task(
    ws_path: String,
    dir_path: String,
    r#gen: u64,
    quiet: bool,
) -> Task<EditorMessage> {
    Task::perform(dir_expanded_msg(ws_path, dir_path, r#gen, quiet), |msg| msg)
}

/// Validate file content for size and binary content.
///
/// Returns `Ok(())` if the bytes pass size and null-byte checks,
/// or `Err` with a user-facing error message.
fn validate_file_content(bytes: &[u8]) -> Result<(), String> {
    if (bytes.len() as u64) > MAX_FILE_SIZE {
        return Err(format!(
            "File too large ({} bytes, max {MAX_FILE_SIZE})",
            bytes.len()
        ));
    }
    if bytes.contains(&0) {
        return Err("Binary file detected (contains null bytes)".to_string());
    }
    Ok(())
}

/// Helper to construct a `FileLoaded` message.
fn file_loaded_msg(
    path: String,
    r#gen: u64,
    result: Result<FileLoadData, String>,
) -> EditorMessage {
    EditorMessage::FileLoaded {
        path,
        r#gen,
        result,
    }
}

/// Load a file's contents from disk with detection of indent style, line
/// ending, and trailing newline.
async fn load_file_data(full_path: String, r#gen: u64) -> EditorMessage {
    let bytes = match tokio::fs::read(&full_path).await {
        Ok(b) => b,
        Err(e) => {
            return file_loaded_msg(full_path, r#gen, Err(format!("Cannot read file: {e}")));
        }
    };

    // Validate size and detect binary content (null bytes).
    if let Err(e) = validate_file_content(&bytes) {
        return file_loaded_msg(full_path, r#gen, Err(e));
    }
    // Reject invalid UTF-8 — the null-byte check above catches one class of
    // binary content, but binary data can still contain valid UTF-8 with no
    // null bytes (e.g. some encoded payloads, structured binary formats).
    let Ok(text) = String::from_utf8(bytes) else {
        return file_loaded_msg(
            full_path,
            r#gen,
            Err("Binary file detected (invalid UTF-8)".to_string()),
        );
    };

    let data = FileLoadData {
        path: full_path,
        line_ending: detect_line_ending(&text),
        text,
    };
    file_loaded_msg(data.path.clone(), r#gen, Ok(data))
}

/// Spawn a file load from disk and return a `Task` that produces
/// `EditorMessage::FileLoaded` when the data is ready.
///
/// This is extracted as a free function because the two callers
/// (`open_file_in_editor` and `select_file`) have different
/// generation-bumping strategies but share the same spawn logic.
fn spawn_file_load(abs_path: String, file_gen: u64) -> Task<EditorMessage> {
    Task::perform(load_file_data(abs_path, file_gen), |msg| msg)
}

/// Build the `EditorTabRecord` list from the current tab state.
#[must_use]
fn build_tab_records(
    tabs: &[Tab],
    active_index: usize,
    tab_contents: &HashMap<String, TabData>,
) -> Vec<crate::workspace::EditorTabRecord> {
    tabs.iter()
        .enumerate()
        .map(|(i, t)| crate::workspace::EditorTabRecord {
            file_path: t.path.clone(),
            tab_order: i,
            is_active: i == active_index,
            is_dirty: t.is_dirty,
            dirty_content: if t.is_dirty {
                tab_contents.get(&t.path).map(|d| d.content.text())
            } else {
                None
            },
        })
        .collect()
}

/// Save current tabs to the database for a workspace.
///
/// Checks `gen_counter` for staleness before writing (pre-write guard): if a
/// newer save has superseded this one, the DB write is skipped.  The write is
/// fire-and-forget — completion is not tracked since the pre-write guard is the
/// only staleness protection needed.
fn save_tabs_to_db(
    workspace_name: String,
    records: Vec<crate::workspace::EditorTabRecord>,
    save_gen: u64,
    gen_counter: Arc<AtomicU64>,
) -> Task<EditorMessage> {
    tokio::spawn(async move {
        if gen_counter.load(Ordering::Acquire) != save_gen {
            return;
        }
        let store = crate::workspace::store();
        if let Err(e) = store.save_editor_tabs(&workspace_name, &records).await {
            tracing::warn!("Failed to save editor tabs: {e}");
        }
    });
    Task::none()
}

/// Save a single file to disk (async).
async fn save_file_to_disk(
    path: String,
    content: String,
    line_ending: LineEnding,
) -> Result<(), String> {
    // Normalize to LF first to handle mixed line endings safely.
    let lf = content.replace("\r\n", "\n");
    let normalized = if line_ending == LineEnding::Crlf {
        lf.replace('\n', "\r\n")
    } else {
        lf
    };

    tokio::fs::write(&path, &normalized)
        .await
        .map_err(|e| format!("Failed to write file: {e}"))
}

/// Build a `Task` that saves the tab at `idx` to disk asynchronously.
///
/// # Panics
///
/// Panics in debug builds if `idx` is out of bounds (`idx >= tabs.len()`).
/// All current callers validate the index before calling.
fn build_save_task(
    tabs: &[Tab],
    tab_contents: &HashMap<String, TabData>,
    idx: usize,
) -> Task<EditorMessage> {
    debug_assert!(
        idx < tabs.len(),
        "idx {idx} out of bounds (len {})",
        tabs.len()
    );
    let path = tabs[idx].path.clone();
    let line_ending = tabs[idx].line_ending;
    let Some(content) = tab_contents.get(&path).map(|d| d.content.text()) else {
        tracing::error!(
            ?path,
            idx,
            "build_save_task: path not found in tab_contents — invariant violation"
        );
        return Task::perform(
            async move {
                EditorMessage::SaveResult {
                    path,
                    result: Err("Internal error: file content not found for save".into()),
                    saved_hash: 0,
                }
            },
            |msg| msg,
        );
    };
    let saved_hash = hash_text(&content);
    Task::perform(
        async move {
            let result = save_file_to_disk(path.clone(), content, line_ending).await;
            EditorMessage::SaveResult {
                path,
                result,
                saved_hash,
            }
        },
        |msg| msg,
    )
}

/// Update the dirty flag for a tab by comparing current text hash against
/// the saved hash.  A free function (not a `&mut self` method) so callers
/// can avoid borrow-checker conflicts from simultaneous mutable borrows
/// of `self.tabs` and immutable borrows of `self.tab_contents`.
fn update_dirty_flag(
    tabs: &mut [Tab],
    tab_contents: &HashMap<String, TabData>,
    idx: usize,
    path: &str,
) {
    if let (Some(tab), Some(tab_data)) = (tabs.get_mut(idx), tab_contents.get(path)) {
        let current_hash = hash_text(&tab_data.content.text());
        tab.is_dirty = current_hash != tab_data.saved_text_hash;
    }
}

// ── Helpers — tree building ──────────────────────────────────────

/// Recursively build a hierarchical tree from flat directory entries.
/// Only expanded directories have their children populated.
fn build_hierarchical_tree(
    dir_entries: &HashMap<String, Vec<FsEntry>>,
    expanded_dirs: &HashSet<String>,
    parent_path: &str,
) -> Vec<widgets::TreeNode> {
    let Some(entries) = dir_entries.get(parent_path) else {
        return Vec::new();
    };

    let mut nodes: Vec<widgets::TreeNode> = entries
        .iter()
        .map(|entry| {
            let mut node = widgets::TreeNode {
                name: entry.name.clone(),
                full_path: entry.full_path.clone(),
                is_dir: entry.is_dir,
                children: Vec::new(),
                error: entry.error.clone(),
            };
            if node.is_dir && expanded_dirs.contains(&node.full_path) {
                node.children =
                    build_hierarchical_tree(dir_entries, expanded_dirs, &node.full_path);
            }
            node
        })
        .collect();

    FileTree::sort_nodes(&mut nodes);
    nodes
}

// ── Git status utilities ──────────────────────────────────────────

/// Parse `git status --porcelain` output into a map of file path → `GitFileStatus`.
///
/// The porcelain format uses a two-column status (index + worktree).
/// Precedence: modified > added > untracked. Rename entries (`R`) extract
/// the new path after ` -> `. Deleted files (`D`) are ignored. Handles
/// git's C-style quoting for paths with special characters.
fn parse_git_status_porcelain(output: &str) -> HashMap<String, GitFileStatus> {
    let mut map: HashMap<String, GitFileStatus> = HashMap::new();

    for line in output.lines() {
        let trimmed = line.trim_end();
        if trimmed.len() < 2 {
            continue;
        }

        let chars: Vec<char> = trimmed.chars().take(2).collect();
        if chars.len() < 2 {
            continue;
        }

        let ix = chars[0];
        let wt = chars[1];

        // Skip deleted files — they don't appear in the working tree.
        if ix == 'D' || wt == 'D' {
            continue;
        }

        // Rename entries: "R  old_path -> new_path"
        // Both paths may be individually C-quoted by git. The separator
        // ` -> ` appears at the boundary between the two paths.
        if ix == 'R' {
            let rest = &trimmed[2..];
            let rest = rest.trim_start();
            let new_path: String = if rest.starts_with('"') {
                // Both paths are quoted. The boundary is `" -> "`.
                // rsplit_once on `" -> "` strips the opening quote of the
                // new path — add it back so `unquote_c_style` can strip both.
                if let Some((_, tail)) = rest.rsplit_once("\" -> \"") {
                    format!("\"{tail}")
                } else {
                    // Malformed — skip.
                    continue;
                }
            } else {
                // Unquoted paths: split on ` -> `.
                if let Some((_, tail)) = rest.rsplit_once(" -> ") {
                    tail.to_string()
                } else {
                    continue;
                }
            };
            if let Some(unquoted) = unquote_c_style(&new_path) {
                map.insert(unquoted, GitFileStatus::Modified);
            }
            continue;
        }

        // Extract path: strip first 2 chars (status columns) and leading space.
        let path = trimmed[2..].trim_start();
        if path.is_empty() {
            continue;
        }

        let status = if ix == 'M' || wt == 'M' {
            GitFileStatus::Modified
        } else if ix == 'A' || wt == 'A' || (ix == '?' && wt == '?') {
            GitFileStatus::Added
        } else {
            // Clean or ignored — don't store.
            continue;
        };

        let Some(path) = unquote_c_style(path) else {
            continue;
        };
        // Strip trailing slash — git appends '/' for untracked directories
        // (e.g., `?? new_dir/`), but tree node full_path has no trailing slash.
        let path = path.strip_suffix('/').unwrap_or(&path).to_string();

        // For entries with multiple lines referencing the same file (e.g., staged +
        // unstaged), keep the most "interesting" status: Modified > Added.
        let entry = map.entry(path).or_insert(status);
        if status == GitFileStatus::Modified && *entry == GitFileStatus::Added {
            *entry = GitFileStatus::Modified;
        }
    }

    map
}

/// Load git status for a workspace. Returns an empty map if the workspace
/// is not a git repo or if git is not installed.
async fn load_git_status(workspace_path: String) -> Result<HashMap<String, GitFileStatus>, String> {
    let ws_path = Path::new(&workspace_path);
    if !is_git_repo(ws_path) {
        tracing::debug!("Workspace '{workspace_path}' is not a git repo — skipping git status");
        return Ok(HashMap::new());
    }

    let output = run_git_status(ws_path).await.map_err(|e| e.to_string())?;
    Ok(parse_git_status_porcelain(&output))
}

/// Collect all file and directory paths from the tree recursively.
fn collect_tree_paths(nodes: &[widgets::TreeNode]) -> Vec<String> {
    let mut paths = Vec::new();
    for node in nodes {
        paths.push(node.full_path.clone());
        if node.is_dir {
            paths.extend(collect_tree_paths(&node.children));
        }
    }
    paths
}

/// Load git ignore status for the given tree paths.
/// Handles workspaces that are subdirectories of a git repo by detecting
/// the repo root and adjusting paths accordingly.
/// Returns an empty set if the workspace is not in a git repo.
async fn load_git_ignore(
    workspace_path: String,
    tree_paths: Vec<String>,
) -> Result<HashSet<String>, String> {
    if tree_paths.is_empty() {
        return Ok(HashSet::new());
    }

    let ws_path = Path::new(&workspace_path);

    // Find the git repo root (handles subdirectory-of-repo workspaces).
    let output = run_git_output(ws_path, &["rev-parse", "--show-toplevel"])
        .await
        .map_err(|e| format!("Failed to run git rev-parse: {e}"))?;

    if !output.status.success() {
        tracing::debug!(
            "Workspace '{workspace_path}' is not in a git repo — skipping git ignore check"
        );
        return Ok(HashSet::new());
    }

    let repo_root = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let repo_path = Path::new(&repo_root);

    // Compute the relative prefix from repo root to workspace.
    // When workspace is the repo root itself, prefix is empty.
    let ws_canonical = ws_path
        .canonicalize()
        .map_err(|e| format!("Failed to canonicalize workspace path: {e}"))?;

    let prefix = ws_canonical
        .strip_prefix(repo_path)
        .map_err(|e| format!("Workspace is not inside git repo: {e}"))?;

    let prefix_empty = prefix.as_os_str().is_empty();

    // Adjust tree paths to be repo-root-relative for git check-ignore.
    let adjusted_paths: Vec<String> = if prefix_empty {
        tree_paths
    } else {
        let prefix_str = prefix.to_string_lossy();
        tree_paths
            .iter()
            .map(|p| format!("{prefix_str}/{p}"))
            .collect()
    };

    let raw_ignored = run_git_check_ignore(repo_path, &adjusted_paths)
        .await
        .map_err(|e| e.to_string())?;

    // Strip the prefix back to get workspace-relative paths for the cache.
    let ignored: HashSet<String> = if prefix_empty {
        raw_ignored
    } else {
        let prefix_str = prefix.to_string_lossy();
        let prefix_slash = format!("{prefix_str}/");
        raw_ignored
            .into_iter()
            .filter_map(|p| {
                p.strip_prefix(&prefix_slash)
                    .or_else(|| (p == prefix_str).then_some(""))
                    .map(ToString::to_string)
            })
            .collect()
    };

    Ok(ignored)
}

/// Handle git-status/git-ignore-loaded — updates the corresponding cache.
/// Discards stale results via the shared `git_status_gen` counter.
fn finish_git_load<T: Default>(
    loading: &mut bool,
    current_gen: u64,
    r#gen: u64,
    result: Result<T, String>,
    cache: &mut T,
    label: &str,
) -> Task<EditorMessage> {
    *loading = false;
    // Stale result from a previous workspace or refresh? Discard.
    if r#gen != current_gen {
        return Task::none();
    }
    match result {
        Ok(value) => *cache = value,
        Err(e) => {
            tracing::warn!("Failed to load {label}: {e}");
            *cache = T::default();
        }
    }
    Task::none()
}

// ── Global search helpers ──────────────────────────────────────────

/// Run a global (find-in-files) grep search with debounce.
///
/// 1. Debounce: waits 300ms (cancelled if a newer generation supersedes).
/// 2. Initialises the search engine if needed.
/// 3. Runs `picker.grep()` on the blocking thread pool.
/// 4. Extracts owned data from `GrepResult` while holding the picker lock.
async fn run_global_search(
    ws_path: String,
    ws_name: String,
    query: String,
    gs_gen: u64,
) -> EditorMessage {
    // Step 1: Debounce.
    tokio::time::sleep(Duration::from_millis(GLOBAL_SEARCH_DEBOUNCE_MS)).await;

    // Step 2: Get or init the search engine.
    let entry = match crate::search_engine::resolve_engine(
        &ws_name,
        &ws_path,
        "Search engine not ready: ",
        false,
    )
    .await
    {
        Ok(e) => e,
        Err(e) => {
            return EditorMessage::GlobalSearchResults {
                r#gen: gs_gen,
                results: Vec::new(),
                error: Some(e),
            };
        }
    };

    // Step 3: Run grep on the blocking thread pool.
    let entry_for_blocking = Arc::clone(&entry);
    let query_for_blocking = query.clone();
    let base_path = ws_path.clone();

    let result = tokio::task::spawn_blocking(move || {
        let guard = entry_for_blocking.picker.read().unwrap();
        let Some(picker) = guard.as_ref() else {
            return (
                Vec::new(),
                Some("Search engine not initialized.".to_string()),
            );
        };

        let fff_query = parse_grep_query(&query_for_blocking);
        let grep_opts = GrepSearchOptions {
            mode: GrepMode::PlainText,
            smart_case: true,
            max_file_size: MAX_FILE_SIZE,
            max_matches_per_file: GLOBAL_SEARCH_MATCHES_PER_FILE,
            file_offset: 0,
            page_limit: MAX_GLOBAL_SEARCH_RESULTS,
            time_budget_ms: 3_000,
            before_context: 0,
            after_context: 0,
            classify_definitions: false,
            trim_whitespace: true,
            abort_signal: None,
        };

        let grep_result = picker.grep(&fff_query, &grep_opts);

        if grep_result.matches.is_empty() {
            return (Vec::new(), None);
        }

        // Step 4: Extract owned data while holding the picker lock.
        let base = Path::new(&base_path);
        let mut owned: Vec<OwnedGrepMatch> = Vec::with_capacity(grep_result.matches.len());

        for m in &grep_result.matches {
            let file = grep_result.files[m.file_index];
            let rel_path = file.relative_path(picker);
            let abs_path = base.join(&rel_path).to_string_lossy().to_string();
            let offsets: Vec<(u32, u32)> =
                m.match_byte_offsets.iter().map(|&(s, e)| (s, e)).collect();

            owned.push(OwnedGrepMatch {
                abs_path,
                rel_path,
                line_number: m.line_number,
                line_content: m.line_content.clone(),
                match_byte_offsets: offsets,
            });
        }

        (owned, None)
    })
    .await
    .unwrap_or((Vec::new(), Some("spawn_blocking join error".to_string())));

    let (owned_matches, error) = result;

    EditorMessage::GlobalSearchResults {
        r#gen: gs_gen,
        results: owned_matches,
        error,
    }
}

// ── Editor State ──────────────────────────────────────────────────

pub struct EditorState {
    /// Currently selected workspace name (set by the Dashboard sidebar/global
    /// picker).
    selected_workspace_name: Option<String>,
    /// Filesystem path for the currently selected workspace.
    selected_workspace_path: Option<String>,
    /// Monotonically increasing generation counter for stale-result prevention.
    generation: u64,
    /// Monotonically increasing generation counter for saved-tabs restoration,
    /// kept separate from `generation` to avoid collision with file loads and
    /// directory expansions that are dispatched concurrently.
    saved_tabs_gen: u64,
    /// Per-directory generation counters.
    dir_generations: HashMap<String, u64>,
    /// Per-file generation counters (prevents stale FileLoaded results).
    file_generations: HashMap<String, u64>,
    /// Directories currently being loaded.
    loading_dirs: HashSet<String>,
    /// Directory entries loaded from the filesystem (keyed by full path).
    dir_entries: HashMap<String, Vec<FsEntry>>,
    /// Shared file tree state (nodes, expanded dirs, focus, visible nodes, scroll ID).
    file_tree: FileTree,
    /// Currently selected file in the tree (full path).
    selected_file: Option<String>,
    /// Open tabs in order.
    tabs: Vec<Tab>,
    /// Index of the active tab.
    active_tab_index: usize,
    /// Content per tab (keyed by full filesystem path).
    tab_contents: HashMap<String, TabData>,
    /// Scrollable ID for the tab bar.
    tab_scroll_id: Id,
    /// Current horizontal scroll offset of the tab bar (px). Updated via
    /// `on_scroll` on the tab-bar scrollable so scroll-into-view can decide
    /// whether the active tab is visible without waiting for a layout pass.
    tab_scroll_x: f32,
    /// Visible width of the tab-bar viewport (px). `None` until the first
    /// scroll event fires — `on_scroll` only fires while the content
    /// overflows the viewport, so short strips (and the strip before its
    /// first render) leave this unknown. When `None`, tab reveal falls back
    /// to aligning the estimated left edge, which iced ignores visually
    /// while the content fits.
    tab_viewport_w: Option<f32>,
    /// Pending close action to execute after the next successful save.
    pending_close: Option<PendingCloseAction>,
    /// Whether the workspace tabs have been loaded at least once this session.
    session_initialized: bool,
    /// When Enter expands a directory that needs async loading, this holds
    /// the directory path so DirExpanded can advance focus to the first child.
    pending_enter_dir: Option<String>,
    /// Cached git status per file path (relative to workspace root).
    git_status_cache: HashMap<String, GitFileStatus>,
    /// Guard against concurrent git status refresh operations.
    git_status_loading: bool,
    /// Cached gitignored file/directory paths (relative to workspace root).
    git_ignore_cache: HashSet<String>,
    /// Guard against concurrent git ignore refresh operations.
    git_ignore_loading: bool,
    /// Shared atomic counter used by async save tasks for pre-write staleness
    /// checking.  Written to on every save initiation; read by in-flight tasks
    /// to determine if a newer save has superseded them.
    tab_save_counter: Arc<AtomicU64>,
    /// Last-known modification time per open file (keyed by full path).
    /// Used by the auto-refresh poll to detect external file changes.
    file_mtimes: HashMap<String, SystemTime>,
    /// Paths for which a "file deleted" toast has already been shown.
    /// Prevents spamming the toast every 300 ms.
    deleted_file_toasted: HashSet<String>,
    /// Which modal overlay is currently open (None when no overlay is active).
    /// Enforced by the type system to be mutually exclusive — only one overlay
    /// may be open at a time.
    active_modal: Option<ModalKind>,
    /// Cached list of all workspace files for quick-open filtering.
    /// Populated on each quick-open toggle from currently expanded dirs.
    all_workspace_files: Vec<String>,
    /// Generation counter for git status and gitignore stale-result prevention.
    /// Bumped on workspace switch to invalidate in-flight GitStatusLoaded
    /// and GitIgnoredLoaded results. Separate from `generation` to avoid
    /// false-positive discards when `refresh_file_tree` bumps `generation`
    /// for directory refresh tasks.
    git_status_gen: u64,
    /// Generation counter for global search stale-result prevention.
    global_search_gen: u64,
    /// When set, the next file load for this path+generation should jump to this line.
    /// The tuple is (abs_path, 1-based line_number, expected_file_gen). Consumed by the
    /// `FileLoaded` handler only when both path and generation match.
    pending_goto: Option<(String, usize, u64)>,
}

/// Identifies which modal overlay is currently open, in Escape-dismissal
/// priority order (GlobalSearch highest, CloseOthers lowest).
///
/// Each variant carries the state data for that overlay.
#[derive(Debug, Clone)]
enum ModalKind {
    GlobalSearch(GlobalSearchState),
    GotoLine(String),
    QuickOpen(QuickOpenState),
    Rename(RenameTarget),
    NewItem(NewItemTarget),
    DeleteConfirm(DeleteConfirmTarget),
    CloseDialog(usize),
    CloseOthers(usize),
}

/// State for the quick-open file picker.
#[derive(Debug, Clone)]
struct QuickOpenState {
    /// Current filter text.
    filter: String,
    /// Currently highlighted result index.
    selected_index: usize,
    /// Filtered file list (matching the filter text).
    results: Vec<String>,
}

impl EditorState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            selected_workspace_name: None,
            selected_workspace_path: None,
            generation: 0,
            saved_tabs_gen: 0,
            dir_generations: HashMap::new(),
            file_generations: HashMap::new(),
            loading_dirs: HashSet::new(),
            dir_entries: HashMap::new(),
            file_tree: FileTree::new(Id::new("editor_tree_panel")),
            selected_file: None,
            tabs: Vec::new(),
            active_tab_index: 0,
            tab_contents: HashMap::new(),
            tab_scroll_id: Id::new("editor_tabs_bar"),
            tab_scroll_x: 0.0,
            tab_viewport_w: None,
            pending_close: None,
            session_initialized: false,
            pending_enter_dir: None,
            git_status_cache: HashMap::new(),
            git_status_loading: false,
            git_ignore_cache: HashSet::new(),
            git_ignore_loading: false,
            tab_save_counter: Arc::new(AtomicU64::new(0)),
            file_mtimes: HashMap::new(),
            deleted_file_toasted: HashSet::new(),
            active_modal: None,
            all_workspace_files: Vec::new(),
            global_search_gen: 0,
            git_status_gen: 0,
            pending_goto: None,
        }
    }

    /// The filesystem root of the currently selected workspace, if any.
    /// Always absolute — validated & canonicalized at creation time.
    #[inline]
    fn workspace_root(&self) -> Option<&str> {
        self.selected_workspace_path.as_deref()
    }

    /// Resolve a relative tree path to an absolute filesystem path.
    fn abs_path(&self, rel_path: &str) -> Option<String> {
        self.selected_workspace_path
            .as_ref()
            .map(|ws| Path::new(ws).join(rel_path).to_string_lossy().to_string())
    }

    /// Rebuild both the hierarchical tree and visible node list from `dir_entries`
    /// and `expanded_dirs`.  Callers that also need `tree_focused = true` must set
    /// it separately after this call.
    fn rebuild_tree(&mut self) {
        self.file_tree.nodes =
            build_hierarchical_tree(&self.dir_entries, &self.file_tree.expanded_dirs, "");
        self.file_tree.rebuild_visible();
    }

    /// Forget `dir_path` and all of its descendants from the file-tree
    /// refresh/cache state: expanded dirs, cached listings, in-flight loads
    /// and generations, per-file generation slots, mtimes, toast guards,
    /// quick-open cache, and the current selection. Also drops the stale
    /// [`FsEntry`] for `dir_path` from its parent's cached listing so the node
    /// disappears from the tree immediately instead of lingering until the
    /// parent is next refreshed.
    ///
    /// This is the "forget" counterpart of the state migration directory
    /// renames already perform — call it whenever a directory no longer exists
    /// (deleted externally, by scripts, or via the GUI) so the tree stops
    /// re-reading the path every refresh cycle and quick-open stops offering
    /// its files. The caller is responsible for calling [`Self::rebuild_tree`]
    /// afterwards. Open tabs are intentionally NOT touched: externally deleted
    /// files keep their tabs so unsaved work survives, and GUI deletes close
    /// their own tabs before calling this.
    fn forget_directory(&mut self, dir_path: &str) {
        let is_root = dir_path.is_empty();
        let rel_prefix = format!("{dir_path}/");
        let within_rel = |p: &str| is_root || p == dir_path || p.starts_with(&rel_prefix);

        // Remove the deleted directory's stale node from its parent's cached
        // listing so it disappears from the tree right away.
        if !is_root {
            if let Some(parent) = Path::new(dir_path).parent() {
                let parent = parent.to_string_lossy();
                if let Some(parent_entries) = self.dir_entries.get_mut(parent.as_ref()) {
                    parent_entries.retain(|e| !within_rel(&e.full_path));
                }
            }
        }

        // Relative-path-keyed caches.
        self.file_tree.expanded_dirs.retain(|p| !within_rel(p));
        self.dir_entries.retain(|p, _| !within_rel(p));
        self.loading_dirs.retain(|p| !within_rel(p));
        self.dir_generations.retain(|p, _| !within_rel(p));
        self.all_workspace_files.retain(|p| !within_rel(p));

        // Absolute-path-keyed caches (workspace filesystem paths). For the
        // root case the prefix is the workspace root itself, so every file
        // under the workspace is pruned — consistent with "all descendants".
        // (Path::join("") would append a trailing slash, so build the root
        // prefix directly to avoid a doubled separator.)
        let abs_prefix = if is_root {
            self.selected_workspace_path
                .as_ref()
                .map(|ws| format!("{ws}/"))
        } else {
            self.abs_path(dir_path).map(|p| format!("{p}/"))
        };
        let within_abs = |p: &str| abs_prefix.as_deref().is_some_and(|pfx| p.starts_with(pfx));
        self.file_generations.retain(|p, _| !within_abs(p));
        self.file_mtimes.retain(|p, _| !within_abs(p));
        self.deleted_file_toasted.retain(|p| !within_abs(p));

        // Selection and pending-enter focus.
        if let Some(ref sel) = self.selected_file {
            if within_rel(sel) || within_abs(sel) {
                self.selected_file = None;
            }
        }
        if self.pending_enter_dir.as_deref().is_some_and(within_rel) {
            self.pending_enter_dir = None;
        }
    }

    fn bump_generation(&mut self) -> u64 {
        let g = self.generation.wrapping_add(1);
        self.generation = g;
        g
    }

    /// Start an async load of a directory's entries.
    ///
    /// Returns `Some(Task)` with the async load if a workspace is selected and
    /// the directory needs loading (the caller is responsible for checking
    /// `!self.dir_entries.contains_key(dir_path)` before calling this).
    /// Returns `None` if no workspace is selected (caller should
    /// early-return `Task::none()`).
    ///
    /// After calling this, the caller MUST call [`Self::rebuild_tree`] (or
    /// equivalent) to reflect the expanded state.  If the caller needs focus
    /// advancement after the load completes (Enter/Right navigation), it should
    /// set `self.pending_enter_dir` after this call.
    fn load_dir_async(&mut self, dir_path: &str, label: &str) -> Option<Task<EditorMessage>> {
        debug_assert!(
            !self.dir_entries.contains_key(dir_path),
            "load_dir_async: caller must check !dir_entries.contains_key(dir_path) first"
        );
        let ws_path = if let Some(p) = self.selected_workspace_path.as_ref() {
            p.clone()
        } else {
            tracing::error!("{label} without workspace selected");
            return None;
        };
        let dir_gen = self.bump_generation();
        self.dir_generations.insert(dir_path.to_string(), dir_gen);
        self.loading_dirs.insert(dir_path.to_string());
        let d_path = dir_path.to_string();
        Some(dir_expanded_task(ws_path, d_path, dir_gen, false))
    }

    /// Expand a directory and either start an async load or focus the first child.
    ///
    /// If the directory's entries are not yet cached, starts an async load and
    /// sets [`Self::pending_enter_dir`] so [`Self::dir_expanded`] can advance
    /// focus when data arrives.  If the entries are already cached (sync path),
    /// expands and immediately focuses the first child.
    ///
    /// Returns `Task::none()` if no workspace is selected (caller should
    /// propagate this return).
    fn expand_dir_and_focus(&mut self, path: &str, label: &str) -> Task<EditorMessage> {
        self.selected_file = None;
        self.file_tree.expanded_dirs.insert(path.to_string());

        let needs_async_load = !self.dir_entries.contains_key(path);

        if needs_async_load {
            let Some(task) = self.load_dir_async(path, label) else {
                return Task::none();
            };
            self.pending_enter_dir = Some(path.to_string());
            // Rebuild tree for the expanded-but-still-loading state.
            self.rebuild_tree();
            return task;
        }

        // Sync path — children are already cached.
        self.rebuild_tree();
        self.file_tree
            .expand_dir_and_focus_first_child::<EditorMessage>(path)
    }

    /// Collapse an expanded directory and keep keyboard focus on it.
    ///
    /// Removes `path` from [`expanded_dirs`], rebuilds the tree, and delegates
    /// focus-and-scroll management to [`FileTree::collapse_dir_and_keep_focus`].
    /// The caller is responsible for ensuring `expanded_dirs` contains `path`
    /// before calling.
    ///
    /// Note: [`FileTree::collapse_dir_and_keep_focus`] calls [`rebuild_visible`]
    /// internally, so this helper uses raw [`build_hierarchical_tree`] (not
    /// [`rebuild_tree`]) to avoid rebuilding the visible list twice.
    fn collapse_dir(&mut self, path: &str) -> Task<EditorMessage> {
        self.file_tree.expanded_dirs.remove(path);
        self.file_tree.nodes =
            build_hierarchical_tree(&self.dir_entries, &self.file_tree.expanded_dirs, "");
        self.file_tree
            .collapse_dir_and_keep_focus::<EditorMessage>(path)
    }

    /// Build an inline rename [`TextInput`] element for a tree node that is
    /// currently being renamed.  Returns [`None`] when the node is not the
    /// rename target, so callers can fall through to their normal label rendering.
    fn build_rename_input<'a>(
        &'a self,
        node: &'a widgets::TreeNode,
    ) -> Option<Element<'a, EditorMessage>> {
        let ModalKind::Rename(rt) = self.active_modal.as_ref()? else {
            return None;
        };
        if rt.path != node.full_path {
            return None;
        }
        let input: Element<'a, EditorMessage> = text_input("", &rt.input_text)
            .id(Id::from(format!("rename_input_{}", node.full_path)))
            .on_input(EditorMessage::RenameInput)
            .on_submit(EditorMessage::RenameSubmit)
            .size(12)
            .padding([0, 2])
            .style(rename_input_style)
            .into();
        // Only wrap in a Column when an inline error needs to be shown
        // below the input.  The common (no-error) case returns a bare
        // TextInput to keep widget nesting shallow.
        if let Some(ref err) = rt.error {
            Some(
                column![input, text(err).size(10).color(theme::STATUS_ERROR)]
                    .spacing(0)
                    .into(),
            )
        } else {
            Some(input)
        }
    }

    pub fn subscription(&self) -> Subscription<EditorMessage> {
        let mut subs: Vec<Subscription<EditorMessage>> = Vec::new();
        if self.selected_workspace_name.is_some() {
            subs.push(
                iced::time::every(Duration::from_secs(TICK_INTERVAL_SECS))
                    .map(|_| EditorMessage::Tick),
            );
            // Periodic directory refresh — re-reads all expanded directories
            // to pick up external filesystem changes (git checkout, build
            // scripts, other editors).
            subs.push(
                iced::time::every(Duration::from_secs(DIR_REFRESH_INTERVAL_SECS))
                    .map(|_| EditorMessage::RefreshFileTree),
            );
            // Auto-refresh tick for detecting external file changes on the
            // active tab.  Only the active (visible) tab is polled; dirty
            // tabs (unsaved edits) are never auto-reloaded.
            subs.push(
                iced::time::every(Duration::from_millis(300))
                    .map(|_| EditorMessage::CheckFileChanges),
            );
        }
        // Always listen for keyboard events — tree navigation may be active.
        subs.push(keyboard::listen().filter_map(map_editor_shortcut));
        Subscription::batch(subs)
    }

    /// Returns the active tab index, or `None` if there are no tabs open.
    const fn active_tab_idx(&self) -> Option<usize> {
        let idx = self.active_tab_index;
        if idx >= self.tabs.len() {
            None
        } else {
            Some(idx)
        }
    }

    /// Returns the `(index, path)` of the active tab, or `None` if no tab is open.
    fn active_tab(&self) -> Option<(usize, String)> {
        let idx = self.active_tab_idx()?;
        Some((idx, self.tabs[idx].path.clone()))
    }

    /// Returns `true` when the find/replace bar is open on the active tab.
    fn is_find_bar_open(&self) -> bool {
        self.active_tab_idx()
            .and_then(|idx| self.tabs.get(idx))
            .and_then(|tab| self.tab_contents.get(&tab.path))
            .and_then(|data| data.find_replace_state.as_ref())
            .is_some()
    }

    /// Save editor tabs to the database for the currently selected workspace.
    ///
    /// Returns a task that performs the async DB write, or [`None`] if:
    /// - Tabs haven't been initialized yet this session
    /// - No workspace is selected
    ///
    /// Uses the shared atomic counter for stale-result prevention: the pre-write
    /// guard inside the async task checks whether a newer save has superseded
    /// this one before writing.
    pub(crate) fn try_save_current_tabs(&self) -> Option<Task<EditorMessage>> {
        if !self.session_initialized {
            return None;
        }
        let workspace_name = self.selected_workspace_name.as_ref()?;

        // Increment shared counter to invalidate any in-flight stale saves.
        let save_gen = self
            .tab_save_counter
            .fetch_add(1, Ordering::AcqRel)
            .wrapping_add(1);

        let records = build_tab_records(&self.tabs, self.active_tab_index, &self.tab_contents);
        Some(save_tabs_to_db(
            workspace_name.clone(),
            records,
            save_gen,
            self.tab_save_counter.clone(),
        ))
    }

    /// Save editor tabs to the database, returning a fallback [`Task::none`] if
    /// the session isn't initialized or no workspace is selected.
    ///
    /// Most callers should use this wrapper; only use
    /// [`try_save_current_tabs`](Self::try_save_current_tabs) directly when you
    /// need to inspect whether a save was actually dispatched.
    pub(crate) fn save_current_tabs(&mut self) -> Task<EditorMessage> {
        self.try_save_current_tabs().unwrap_or(Task::none())
    }

    /// Scroll the tab bar to keep the active tab visible.
    ///
    /// Reveal semantics (deliberately stricter than the file tree's
    /// [`ScrollMode::ScrollIntoView`], which tolerates partial visibility at
    /// an edge to avoid micro-jumps during wheel scrolling): a tab counts as
    /// visible only when both estimated edges are inside the viewport, so
    /// selecting an already-visible tab never scrolls. A clipped tab is
    /// scrolled by exactly the overflow — the strip never overshoots past
    /// the selected tab or lands arbitrarily at the right edge:
    ///
    /// * left-clipped tabs are brought flush with the viewport's left edge;
    /// * right-clipped tabs advance by the exact overflow via `scroll_by`,
    ///   which iced clamps to the maximum scroll offset (the old absolute
    ///   `index × width` target was only clamped at draw time and could
    ///   land at the far right edge);
    /// * when the viewport width is unknown (`on_scroll` has not fired yet —
    ///   it only fires while content overflows), fall back to aligning the
    ///   estimated left edge. Iced ignores scroll offsets entirely while the
    ///   content fits the viewport, so this is a visual no-op for short
    ///   strips and a genuine reveal for overflowing ones (session restore,
    ///   first selection).
    ///
    /// `tab_scroll_x` is updated synchronously so consecutive selections
    /// within the same frame (e.g. held Ctrl+Tab) judge visibility against
    /// the offset this call produced, before `on_scroll` fires.
    fn scroll_to_active_tab(&mut self) -> Task<EditorMessage> {
        if self.tabs.is_empty() {
            return Task::none();
        }
        let idx = self.active_tab_index.min(self.tabs.len() - 1);

        let left = estimated_tab_left(&self.tabs, idx);
        let Some(viewport_w) = self.tab_viewport_w else {
            // Viewport width unknown — align the estimated left edge.
            self.tab_scroll_x = left;
            return iced::widget::operation::scroll_to(
                self.tab_scroll_id.clone(),
                iced::widget::operation::AbsoluteOffset { x: left, y: 0.0 },
            );
        };

        // The whole (estimated) strip fits — every tab is fully visible
        // regardless of any stale scroll offset.
        if estimated_content_width(&self.tabs) <= viewport_w {
            return Task::none();
        }

        let right = left + estimate_tab_width(&self.tabs[idx]);
        let viewport_right = self.tab_scroll_x + viewport_w;

        if left < self.tab_scroll_x {
            // Left edge is clipped (scrolled past) — bring it flush with the
            // viewport's left edge.
            let delta = self.tab_scroll_x - left;
            self.tab_scroll_x = left;
            iced::widget::operation::scroll_by(
                self.tab_scroll_id.clone(),
                iced::widget::operation::AbsoluteOffset { x: -delta, y: 0.0 },
            )
        } else if right > viewport_right {
            // Right edge is clipped — advance by exactly the overflow.
            // `scroll_by` clamps the result to the max scroll offset, so the
            // strip can never be pushed past the right end.
            let delta = right - viewport_right;
            let max_scroll = (estimated_content_width(&self.tabs) - viewport_w).max(0.0);
            self.tab_scroll_x = (self.tab_scroll_x + delta).clamp(0.0, max_scroll);
            iced::widget::operation::scroll_by(
                self.tab_scroll_id.clone(),
                iced::widget::operation::AbsoluteOffset { x: delta, y: 0.0 },
            )
        } else {
            // Both estimated edges are inside the viewport — already fully
            // visible, so the strip must not move.
            Task::none()
        }
    }

    /// Scroll to the tab at `new_idx` without saving tabs.
    /// Sets the active index and scrolls the tab bar, but does not persist.
    fn scroll_to_tab(&mut self, new_idx: usize) -> Task<EditorMessage> {
        if new_idx >= self.tabs.len() {
            return Task::none();
        }
        self.active_tab_index = new_idx;
        self.scroll_to_active_tab()
    }

    /// Switch to the tab at `idx`, updating active index, scrolling, and
    /// persisting the tab list to the database.
    fn switch_to_tab(&mut self, idx: usize) -> Task<EditorMessage> {
        if idx >= self.tabs.len() {
            return Task::none();
        }
        self.active_tab_index = idx;
        Task::batch(vec![self.scroll_to_active_tab(), self.save_current_tabs()])
    }

    /// Switch to the tab one step in the given direction, wrapping around.
    /// Returns `Task::none()` if a modal overlay is active or if there is
    /// only one tab.
    fn switch_tab_relative(&mut self, direction: TabDirection) -> Task<EditorMessage> {
        if self.active_modal.is_some() || self.tabs.len() <= 1 {
            return Task::none();
        }
        let len = self.tabs.len();
        let new_idx = match direction {
            TabDirection::Next => (self.active_tab_index + 1) % len,
            TabDirection::Prev => (self.active_tab_index + len - 1) % len,
        };
        self.scroll_to_tab(new_idx)
    }

    /// Collect all file paths from the workspace's directory entries for
    /// quick-open filtering. Walks all expanded and known directories.
    /// Called each time QuickOpen is opened to pick up newly expanded dirs.
    fn scan_all_workspace_files(&mut self) {
        self.all_workspace_files.clear();
        let mut paths: Vec<String> = Vec::new();
        for entries in self.dir_entries.values() {
            for entry in entries {
                if !entry.is_dir {
                    paths.push(entry.full_path.clone());
                }
            }
        }
        paths.sort();
        self.all_workspace_files = paths;
    }

    /// Filter workspace file paths by a fuzzy query string.
    /// Returns paths that contain the filter text (case-insensitive).
    fn filter_workspace_files(&self, filter: &str) -> Vec<String> {
        if filter.is_empty() {
            return self.all_workspace_files.iter().take(200).cloned().collect();
        }
        let lower_filter = filter.to_ascii_lowercase();
        let mut scored: Vec<(usize, &String)> = self
            .all_workspace_files
            .iter()
            .filter(|path| path.to_ascii_lowercase().contains(&lower_filter))
            .map(|path| {
                // Score: prefer matches on file name (after last /).
                let name = path.rsplit('/').next().unwrap_or(path);
                let name_lower = name.to_ascii_lowercase();
                let name_score = if name_lower.starts_with(&lower_filter) {
                    0 // highest priority: file name starts with query
                } else if name_lower.contains(&lower_filter) {
                    1 // file name contains query
                } else {
                    2 // path segment match only
                };
                (name_score, path)
            })
            .collect();
        scored.sort_by_key(|(score, _)| *score);
        scored
            .into_iter()
            .take(200)
            .map(|(_, p)| p.clone())
            .collect()
    }

    /// Open a file by its workspace-relative path.
    /// If the file is already open in a tab, switches to that tab.
    /// Otherwise loads the file and adds a new tab.
    fn open_file_in_editor(&mut self, path: &str) -> Task<EditorMessage> {
        let Some(ws) = self.workspace_root() else {
            return Task::none();
        };
        let abs_path = if path.starts_with('/') {
            path.to_string()
        } else {
            std::path::Path::new(&ws)
                .join(path)
                .to_string_lossy()
                .to_string()
        };

        // If already open, just switch to that tab.
        if let Some(existing_idx) = self.tabs.iter().position(|t| t.path == abs_path) {
            return self.scroll_to_tab(existing_idx);
        }

        // Mark tree as not focused when a file is opened.
        self.file_tree.tree_focused = false;
        self.pending_enter_dir = None;

        let file_path = abs_path;
        let file_gen = self.bump_generation();
        self.file_generations.insert(file_path.clone(), file_gen);
        self.selected_file = Some(file_path.clone());

        spawn_file_load(file_path, file_gen)
    }

    /// Remove the tab at `idx`, cleaning up `tab_contents` and adjusting
    /// `active_tab_index`.
    fn remove_tab_at(&mut self, idx: usize) {
        let closed_path = self.tabs[idx].path.clone();
        self.tab_contents.remove(&closed_path);
        self.tabs.remove(idx);
        let len = self.tabs.len();
        if len == 0 {
            self.active_tab_index = 0;
        } else if idx < self.active_tab_index {
            self.active_tab_index = self.active_tab_index.saturating_sub(1);
        } else {
            self.active_tab_index = self.active_tab_index.min(len.saturating_sub(1));
        }
    }

    /// Close all tabs except `keep_idx`, discarding changes.
    ///
    /// Does not update `active_tab_index` — callers that need scroll handling
    /// should do so after the call.
    fn remove_all_tabs_except(&mut self, keep_idx: usize) {
        let mut to_remove: Vec<usize> = (0..self.tabs.len()).collect();
        to_remove.retain(|&i| i != keep_idx);
        to_remove.sort_unstable_by(|a, b| b.cmp(a));
        for i in to_remove {
            self.remove_tab_at(i);
        }
    }

    /// Close the tab at `idx`. If the tab is dirty, shows the close dialog.
    /// If clean, immediately removes the tab and persists.
    /// Returns the task for saving to DB.
    fn close_tab_at(&mut self, idx: usize) -> Task<EditorMessage> {
        if idx >= self.tabs.len() {
            return Task::none();
        }
        if self.tabs[idx].is_dirty {
            self.active_modal = Some(ModalKind::CloseDialog(idx));
            return Task::none();
        }
        self.active_modal = None;
        self.remove_tab_at(idx);
        self.save_current_tabs()
    }

    /// Apply an undo or redo snapshot to the tab at `idx`.
    ///
    /// The snapshot is an owned value so there is no borrow entanglement
    /// with the undo stack.  The helper does a fresh (O(1)) lookup of
    /// `tab_contents` by path — the caller must have already resolved
    /// the path from `self.tabs[idx]`.
    ///
    /// # Panics
    /// Panics if `idx` is out of bounds for `self.tabs`.
    fn apply_undo_snapshot(&mut self, idx: usize, snapshot: Option<UndoSnapshot>) {
        let Some(snapshot) = snapshot else {
            return;
        };
        let path = self.tabs[idx].path.clone();
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            // Clear find/replace state — match byte ranges are now stale.
            tab_data.find_replace_state = None;
            tab_data.content = EditorBuffer::from_file(&snapshot.text, &path);
            tab_data.content.move_to(
                snapshot.cursor.position.line,
                snapshot.cursor.position.column,
            );
        }
        update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
    }

    /// Apply an undo or redo operation to the active tab.
    ///
    /// `is_redo` selects which operation: `false` for undo,
    /// `true` for redo.
    fn apply_undo_or_redo(&mut self, is_redo: bool) -> Task<EditorMessage> {
        let Some((idx, path)) = self.active_tab() else {
            return Task::none();
        };
        let snapshot = self.tab_contents.get_mut(&path).and_then(|tab_data| {
            let mut stack = tab_data.undo_stack.borrow_mut();
            if is_redo {
                stack.redo(&tab_data.content)
            } else {
                stack.undo(&tab_data.content)
            }
        });
        self.apply_undo_snapshot(idx, snapshot);
        Task::none()
    }

    /// Handle Undo or Redo after checking that the find bar or modal overlay
    /// won't intercept the keyboard shortcut.
    ///
    /// When the find bar is open, Cmd+Z / Cmd+Shift+Z should undo/redo within
    /// the find bar's text input (handled natively by Iced's text widget), not
    /// undo the editor content. Bail out early so the text input handles the
    /// shortcut internally.
    fn handle_undo_or_redo(&mut self, is_redo: bool) -> Task<EditorMessage> {
        if self.is_find_bar_open() || self.active_modal.is_some() {
            Task::none()
        } else {
            self.apply_undo_or_redo(is_redo)
        }
    }

    /// Clear all workspace-scoped editor state when switching workspaces.
    /// Does not touch `selected_workspace_name`, `selected_workspace_path`,
    /// `generation`, `saved_tabs_gen`, or `git_status_gen` — those are
    /// managed at the call site.
    fn clear_workspace_editor_state(&mut self) {
        self.file_tree.nodes.clear();
        self.file_tree.expanded_dirs.clear();
        self.selected_file = None;
        self.tabs.clear();
        self.tab_contents.clear();
        self.active_tab_index = 0;
        self.dir_entries.clear();
        self.loading_dirs.clear();
        self.dir_generations.clear();
        self.file_generations.clear();
        self.git_status_cache.clear();
        self.git_status_loading = false;
        self.git_ignore_cache.clear();
        self.git_ignore_loading = false;
        self.session_initialized = false;
        self.active_modal = None;
        self.pending_close = None;
        self.file_tree.visible_tree_nodes.clear();
        self.file_tree.tree_focused = false;
        self.file_tree.tree_focus_index = 0;
        self.pending_enter_dir = None;
        self.tab_save_counter.store(0, Ordering::Release);
        self.file_mtimes.clear();
        self.deleted_file_toasted.clear();
        self.all_workspace_files.clear();
        self.global_search_gen = 0;
        self.pending_goto = None;
        // Tab-bar scroll state is per-workspace; reset so the next selection
        // re-learns the viewport instead of judging visibility against the
        // previous workspace's stale offset/width.
        self.tab_scroll_x = 0.0;
        self.tab_viewport_w = None;
    }

    /// Start creating a new item (file or directory) in the given parent directory.
    ///
    /// Resolves the absolute parent path and sets up the `new_item_input` state
    /// so the user can type a name.  Any previously active modal is implicitly
    /// replaced since `active_modal` enforces mutual exclusion.
    fn start_new_item_creation(&mut self, parent_dir: String, is_dir: bool) -> Task<EditorMessage> {
        let Some(ref ws) = self.selected_workspace_path else {
            return Task::none();
        };
        let abs_parent = if parent_dir.is_empty() {
            ws.clone()
        } else {
            Path::new(ws)
                .join(&parent_dir)
                .to_string_lossy()
                .to_string()
        };
        self.active_modal = Some(ModalKind::NewItem(NewItemTarget {
            parent_dir,
            is_dir,
            abs_parent,
            ws_root: ws.clone(),
            input_text: String::new(),
        }));
        iced::widget::operation::focus::<EditorMessage>(Id::new(NEW_ITEM_INPUT_ID))
    }

    #[expect(clippy::too_many_lines)]
    pub fn update(&mut self, msg: EditorMessage) -> Task<EditorMessage> {
        match msg {
            EditorMessage::WorkspaceSelected(ref name, ref path) => {
                self.workspace_selected(name, path.as_deref())
            }

            EditorMessage::SavedTabsLoaded { tabs_data, r#gen } => {
                self.saved_tabs_loaded(tabs_data, r#gen)
            }

            EditorMessage::DirExpanded {
                dir_path,
                r#gen,
                entries,
                quiet,
            } => self.dir_expanded(&dir_path, r#gen, entries, quiet),

            EditorMessage::DirDeleted {
                dir_path,
                workspace_path,
            } => self.dir_deleted(&dir_path, &workspace_path),

            EditorMessage::ToggleDir(dir_path) => self.toggle_dir(&dir_path),

            EditorMessage::SelectFile(path) => self.select_file(&path),

            EditorMessage::FileLoaded {
                path,
                r#gen,
                result,
            } => self.file_loaded(&path, r#gen, result),

            EditorMessage::TabSelected(idx) => self.switch_to_tab(idx),

            EditorMessage::TabClosed(idx) => self.close_tab_at(idx),

            EditorMessage::EditorAction(action) => self.editor_action(action),

            EditorMessage::SaveActiveTab => self.save_active_tab(),

            EditorMessage::SaveResult {
                path,
                result,
                saved_hash,
            } => self.save_result(&path, result, saved_hash),

            EditorMessage::CloseDialog { tab_index, action } => {
                self.close_dialog(tab_index, action)
            }

            EditorMessage::CloseOthersDialog { keep_idx, action } => {
                self.close_others_dialog(keep_idx, action)
            }

            EditorMessage::CloseOtherTabs(idx) => self.close_other_tabs(idx),

            EditorMessage::Escape => self.escape(),

            // ── Go-to-line ────────────────────────────────────────────
            EditorMessage::GoToLineToggle => self.go_to_line_toggle(),

            EditorMessage::GoToLineInput(input) => self.go_to_line_input(&input),

            EditorMessage::GoToLineGo => self.go_to_line_go(),

            // ── Global search (find-in-files) ──────────────────────────
            EditorMessage::GlobalSearchToggle => self.global_search_toggle(),

            EditorMessage::GlobalSearchInput(query) => self.global_search_input(query),

            EditorMessage::GlobalSearchResults {
                r#gen,
                results,
                error,
            } => self.global_search_results(r#gen, results, error),

            EditorMessage::GlobalSearchSelect(idx) => self.global_search_select(idx),

            // ── Context menu actions ─────────────────────────────────
            EditorMessage::DeleteFileRequested(path) => self.delete_file_requested(path),

            EditorMessage::DeleteDirectoryRequested(path) => self.delete_directory_requested(path),

            EditorMessage::NewFileRequested(parent_dir) => {
                self.start_new_item_creation(parent_dir, false)
            }

            EditorMessage::NewDirectoryRequested(parent_dir) => {
                self.start_new_item_creation(parent_dir, true)
            }

            EditorMessage::RevealInFinder(path) => Self::perform_reveal_in_finder(path),

            EditorMessage::CopyRelativePath(path) | EditorMessage::CopyAbsolutePath(path) => {
                iced::clipboard::write(path)
            }

            EditorMessage::ConfirmDelete => self.confirm_delete(),

            EditorMessage::CancelDelete => {
                self.active_modal = None;
                Task::none()
            }

            EditorMessage::NewItemSubmit(name) => self.new_item_submit(&name),

            EditorMessage::NewItemInput(new_text) => self.new_item_input(new_text),

            // ── Inline rename ────────────────────────────────────────────
            EditorMessage::RenameRequested(path) => self.rename_requested(&path),

            EditorMessage::RenameInput(new_text) => self.rename_input(new_text),

            EditorMessage::RenameSubmit => self.rename_submit(),

            EditorMessage::RenameCancel => self.rename_cancel(),

            EditorMessage::RenameCompleted {
                old_path,
                new_path,
                is_dir,
                result,
                dir_entries,
                rename_gen,
            } => self.rename_completed(
                &old_path,
                &new_path,
                is_dir,
                result,
                dir_entries,
                rename_gen,
            ),

            // ── Quick-open file picker ────────────────────────────────
            EditorMessage::QuickOpenToggle => self.quick_open_toggle(),

            EditorMessage::QuickOpenInput(filter) => self.quick_open_input(filter),

            EditorMessage::QuickOpenSelect(idx) => self.quick_open_select(idx),

            // ── Tab switching ─────────────────────────────────────────
            EditorMessage::TabSwitchNext => self.switch_tab_relative(TabDirection::Next),
            EditorMessage::TabSwitchPrev => self.switch_tab_relative(TabDirection::Prev),

            EditorMessage::CloseActiveTab => self.close_active_tab(),

            // ── Tree keyboard navigation ─────────────────────────────
            EditorMessage::TreeFocusToggled => self.tree_focus_toggled(),

            EditorMessage::TreeScrolled(scroll_y, viewport_h) => {
                self.tree_scrolled(scroll_y, viewport_h)
            }

            EditorMessage::TabBarScrolled(scroll_x, viewport_w) => {
                self.tab_bar_scrolled(scroll_x, viewport_w)
            }

            EditorMessage::TreeNavUp => self.navigate_tree_vertical(TreeNavDirection::Up),

            EditorMessage::TreeNavDown => self.navigate_tree_vertical(TreeNavDirection::Down),

            EditorMessage::TreeNavEnter => self.tree_nav_enter(),

            EditorMessage::TreeNavLeft => self.tree_nav_left(),

            EditorMessage::TreeNavRight => self.tree_nav_right(),

            EditorMessage::Undo => self.handle_undo_or_redo(false),

            EditorMessage::Redo => self.handle_undo_or_redo(true),

            EditorMessage::FindToggle => self.find_toggle(),

            EditorMessage::FindQueryInput(query) => self.find_query_input(query),

            EditorMessage::FindReplaceInput(replace) => self.find_replace_input(replace),

            EditorMessage::FindNext => self.navigate_find_match(FindDirection::Next),

            EditorMessage::FindPrev => self.navigate_find_match(FindDirection::Prev),

            EditorMessage::FindReplace => self.find_replace(),

            EditorMessage::FindReplaceAll => self.find_replace_all(),

            EditorMessage::FindToggleCaseSensitivity => self.find_toggle_case_sensitivity(),

            EditorMessage::RefreshFileTree => self.refresh_file_tree(),

            EditorMessage::Tick => self.tick(),

            EditorMessage::Toast(_) => Task::none(),

            EditorMessage::GitStatusLoaded { r#gen, result } => finish_git_load(
                &mut self.git_status_loading,
                self.git_status_gen,
                r#gen,
                result,
                &mut self.git_status_cache,
                "git status",
            ),

            EditorMessage::GitIgnoredLoaded { r#gen, result } => finish_git_load(
                &mut self.git_ignore_loading,
                self.git_status_gen,
                r#gen,
                result,
                &mut self.git_ignore_cache,
                "git ignore status",
            ),

            EditorMessage::CheckFileChanges => self.check_file_changes(),

            EditorMessage::FileReloaded {
                path,
                result,
                cursor_line,
                cursor_col,
            } => self.file_reloaded(path, result, cursor_line, cursor_col),
        }
    }

    // ── Extracted handler methods ────────────────────────────────────

    /// Handle workspace selection — initializes file tree, loads tabs, sets up workspace.
    fn workspace_selected(&mut self, name: &str, path: Option<&str>) -> Task<EditorMessage> {
        // Accept personal workspaces when a path is provided.
        if name.is_empty() && path.is_none() {
            self.selected_workspace_name = None;
            self.selected_workspace_path = None;
            self.clear_workspace_editor_state();
            return Task::none();
        }

        let mut tasks: Vec<Task<EditorMessage>> = Vec::new();

        self.selected_workspace_name = Some(name.to_string());
        self.selected_workspace_path = path.map(std::string::ToString::to_string);

        // Clear previous state and bump generation counters.
        let r#gen = self.bump_generation();
        let saved_gen = self.saved_tabs_gen.wrapping_add(1);
        self.saved_tabs_gen = saved_gen;
        let git_gen = self.git_status_gen.wrapping_add(1);
        self.git_status_gen = git_gen;
        self.clear_workspace_editor_state();

        // Register the root generation so DirExpanded can validate it.
        self.dir_generations.insert(String::new(), r#gen);

        // ── Task 1: read root directory ───────────────────────
        tasks.push(dir_expanded_task(
            path.unwrap_or_default().to_string(),
            String::new(),
            r#gen,
            false,
        ));

        // ── Task 2: load tabs from DB + file contents ────────
        let tab_ws = name.to_string();
        let tab_path = path.unwrap_or_default().to_string();
        let tab_gen = saved_gen;
        let load_tabs_task = Task::perform(
            async move {
                let store = crate::workspace::store();
                let records = store.load_editor_tabs(&tab_ws).await.unwrap_or_else(|e| {
                    tracing::warn!(?e, workspace = %tab_ws, "Failed to load editor tabs");
                    Vec::new()
                });
                let ws_path = tab_path;

                let mut loaded: Vec<SavedTabData> = Vec::new();
                for record in &records {
                    // Belt-and-suspenders: skip tabs with empty file_path —
                    // load_editor_tabs already filters these, but guard anyway.
                    if record.file_path.is_empty() || record.file_path.trim().is_empty() {
                        tracing::warn!(
                            workspace = %tab_ws,
                            tab_order = record.tab_order,
                            "Skipping editor tab with empty file_path in GUI loader"
                        );
                        continue;
                    }
                    let file_path = if ws_path.is_empty() {
                        record.file_path.clone()
                    } else {
                        Path::new(&ws_path)
                            .join(&record.file_path)
                            .to_string_lossy()
                            .to_string()
                    };

                    let loaded_text = if let Some(dirty) = record.dirty_content.clone() {
                        Some(dirty)
                    } else if let Ok(bytes) = tokio::fs::read(&file_path).await {
                        if validate_file_content(&bytes).is_ok() {
                            String::from_utf8(bytes).ok()
                        } else {
                            None
                        }
                    } else {
                        None
                    };

                    if let Some(text) = loaded_text {
                        let line_ending = detect_line_ending(&text);
                        loaded.push(SavedTabData {
                            file_path,
                            text,
                            was_dirty: record.is_dirty,
                            line_ending,
                            is_active: record.is_active,
                        });
                    }
                }
                EditorMessage::SavedTabsLoaded {
                    tabs_data: loaded,
                    r#gen: tab_gen,
                }
            },
            |msg| msg,
        );
        tasks.push(load_tabs_task);

        // ── Task 3: refresh git status for file tree coloring ──
        self.git_status_loading = true;
        let git_path = path.unwrap_or_default().to_string();
        let git_task = Task::perform(
            async move { load_git_status(git_path).await },
            move |result| EditorMessage::GitStatusLoaded {
                r#gen: git_gen,
                result,
            },
        );
        tasks.push(git_task);

        Task::batch(tasks)
    }

    /// Insert a newly created tab into the editor state: push the tab,
    /// store its content, and record the file mtime (if available).
    fn insert_tab(&mut self, path: String, tab: Tab, tab_data: TabData, mtime: Option<SystemTime>) {
        self.tabs.push(tab);
        self.tab_contents.insert(path.clone(), tab_data);
        if let Some(mtime) = mtime {
            self.file_mtimes.insert(path, mtime);
        }
    }

    /// Handle saved tabs loaded from the database — deserializes tab data,
    /// builds Tab/TabData structures.
    fn saved_tabs_loaded(
        &mut self,
        tabs_data: Vec<SavedTabData>,
        r#gen: u64,
    ) -> Task<EditorMessage> {
        if r#gen != self.saved_tabs_gen {
            return Task::none();
        }

        // Track which tab was active when persisted.
        let mut active_idx = 0;

        for (i, saved) in tabs_data.into_iter().enumerate() {
            if saved.is_active {
                active_idx = i;
            }

            let saved_hash = if saved.was_dirty {
                // Tab was dirty when persisted — the text in DB
                // differs from what's on disk.  Try to read the
                // on-disk version for an accurate saved hash;
                // fall back to the in-memory text if the file
                // is gone or unreadable.
                std::fs::read_to_string(&saved.file_path)
                    .as_ref()
                    .map_or_else(|_| hash_text(&saved.text), |disk| hash_text(disk))
            } else {
                hash_text(&saved.text)
            };

            let (tab, td, mtime) = make_tab_and_data(
                &saved.file_path,
                &saved.text,
                saved.line_ending,
                saved.was_dirty,
                saved_hash,
            );
            self.insert_tab(saved.file_path, tab, td, mtime);
        }

        if !self.tabs.is_empty() {
            self.active_tab_index = active_idx.min(self.tabs.len().saturating_sub(1));
        }
        self.session_initialized = true;

        if !self.tabs.is_empty() {
            self.scroll_to_active_tab()
        } else {
            Task::none()
        }
    }

    /// Handle directory expansion — populates dir_entries, rebuilds tree,
    /// advances focus to first child if requested.
    fn dir_expanded(
        &mut self,
        dir_path: &str,
        r#gen: u64,
        entries: Result<Vec<FsEntry>, ReadDirError>,
        quiet: bool,
    ) -> Task<EditorMessage> {
        if self.dir_generations.get(dir_path) != Some(&r#gen) {
            return Task::none();
        }
        // Consume the generation slot (mirroring the pattern in rename_completed).
        // The entry is no longer needed once the matching result has been accepted.
        self.dir_generations.remove(dir_path);

        self.loading_dirs.remove(dir_path);

        match entries {
            Ok(entries) => {
                self.dir_entries.insert(dir_path.to_string(), entries);
                self.rebuild_tree();
                // If this was triggered by Enter-on-directory, advance
                // focus to the first child now that children are loaded.
                if self.pending_enter_dir.as_deref() == Some(dir_path) {
                    self.pending_enter_dir = None;
                    return self
                        .file_tree
                        .expand_dir_and_focus_first_child::<EditorMessage>(dir_path);
                }
            }
            Err(ReadDirError::NotFound) => {
                // The directory no longer exists (deleted externally, by a
                // script, or via the GUI). Forget it silently — this is a
                // normal scenario, not an error: no toast, and at most one
                // low-level log per path (the path is pruned from the
                // refresh state, so it cannot re-warn every cycle).
                self.forget_directory(dir_path);
                self.rebuild_tree();
                if !dir_path.is_empty() {
                    tracing::debug!(
                        "File tree: forgotten directory that no longer exists: {dir_path}"
                    );
                }
            }
            Err(ReadDirError::Other(err)) => {
                // The directory still exists but cannot be read — a real
                // problem that must keep producing warnings.
                if quiet {
                    tracing::warn!("Failed to read directory '{dir_path}' (refresh): {err}");
                    return Task::none();
                }
                return Task::done(EditorMessage::Toast(super::ToastMessage::Warning(format!(
                    "Failed to read directory '{dir_path}': {err}"
                ))));
            }
        }
        Task::none()
    }

    /// Handle dir-deleted — a GUI directory deletion succeeded. Prune the
    /// deleted path and all descendants from the tree refresh/cache state,
    /// then re-read the parent directory so the tree reflects the deletion
    /// immediately (and picks up any unrelated external changes there).
    ///
    /// The prune is deferred to this success path so a failed delete (e.g.
    /// permission denied) leaves a still-existing directory untouched in the
    /// tree.
    fn dir_deleted(&mut self, dir_path: &str, workspace_path: &str) -> Task<EditorMessage> {
        // Staleness guard: the delete was started in `workspace_path`. If the
        // user switched workspaces while the async delete was in flight, this
        // completion belongs to the old workspace and must not prune the
        // currently selected workspace's state at the same relative path.
        if self.selected_workspace_path.as_deref() != Some(workspace_path) {
            return Task::none();
        }
        self.forget_directory(dir_path);
        self.rebuild_tree();

        // Re-read the parent directory (mirrors perform_delete_with_refresh):
        // register a fresh generation slot and spawn the async read.
        let Some(ws_path) = self.selected_workspace_path.clone() else {
            return Task::none();
        };
        let parent_dir = Path::new(dir_path)
            .parent()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let r#gen = self.bump_generation();
        self.dir_generations.insert(parent_dir.clone(), r#gen);
        dir_expanded_task(ws_path, parent_dir, r#gen, false)
    }

    /// Handle a file being loaded from disk — opens a tab, initializes
    /// EditorBuffer, sets hash/mtime, and handles pending goto from
    /// global search.
    fn file_loaded(
        &mut self,
        path: &str,
        r#gen: u64,
        result: Result<FileLoadData, String>,
    ) -> Task<EditorMessage> {
        // Check per-file generation to prevent stale loads.
        if self.file_generations.get(path).copied() != Some(r#gen) {
            return Task::none();
        }
        // Consume the generation slot — it has served its purpose.
        // This prevents unbounded accumulation in the map without
        // requiring removal code at every close/delete/rename path.
        self.file_generations.remove(path);

        match result {
            Ok(data) => {
                let saved_hash = hash_text(&data.text);
                let (tab, tab_data, mtime) =
                    make_tab_and_data(&data.path, &data.text, data.line_ending, false, saved_hash);
                self.insert_tab(data.path, tab, tab_data, mtime);
                self.active_tab_index = self.tabs.len().saturating_sub(1);
                self.session_initialized = true;

                // ── Pending goto from global search ────────────
                // If this file was loaded for a global-search result click,
                // jump to the matching line. Only consume when both path and
                // generation match to avoid stealing from a different file load.
                if self
                    .pending_goto
                    .as_ref()
                    .is_some_and(|(gp, _, gg)| *gp == path && *gg == r#gen)
                {
                    if let Some((_, goto_line_1based, _)) = self.pending_goto.take() {
                        let cursor_line = goto_line_1based.saturating_sub(1);
                        let tab_path = self.tabs[self.active_tab_index].path.clone();
                        if let Some(tab_data) = self.tab_contents.get_mut(&tab_path) {
                            tab_data.content.move_to(cursor_line, 0);
                        }
                    }
                }

                let tasks = vec![self.scroll_to_active_tab(), self.save_current_tabs()];
                Task::batch(tasks)
            }
            Err(e) => {
                let toast =
                    if e.starts_with("File too large") || e.starts_with("Binary file detected") {
                        super::ToastMessage::Warning(e)
                    } else {
                        super::ToastMessage::Error(e)
                    };
                Task::done(EditorMessage::Toast(toast))
            }
        }
    }

    /// Handle the result of a save operation — updates dirty flags,
    /// handles CloseDialog→close-tab and CloseOthers→save-queue flows.
    fn save_result(
        &mut self,
        path: &str,
        result: Result<(), String>,
        saved_hash: u64,
    ) -> Task<EditorMessage> {
        match result {
            Ok(()) => {
                let still_matches_saved = self
                    .tab_contents
                    .get(path)
                    .is_some_and(|tab_data| hash_text(&tab_data.content.text()) == saved_hash);
                if !still_matches_saved {
                    // A newer edit arrived while the save was in flight — keep dirty state.
                    return Task::none();
                }
                if let Some(tab) = self.tabs.iter_mut().find(|t| t.path == path) {
                    tab.is_dirty = false;
                }
                if let Some(tab_data) = self.tab_contents.get_mut(path) {
                    tab_data.saved_text_hash = saved_hash;
                }
                // Update stored mtime so the next auto-refresh tick won't
                // detect the save-time mtime change as an external edit
                // and re-read the file, destroying the undo stack.
                if let Ok(meta) = std::fs::metadata(path) {
                    if let Ok(mtime) = meta.modified() {
                        self.file_mtimes.insert(path.to_string(), mtime);
                    }
                }

                // If this save is part of a pending close action, handle it now.
                match self.pending_close.take() {
                    Some(PendingCloseAction::CloseTab(close_idx)) => {
                        if close_idx < self.tabs.len() {
                            self.remove_tab_at(close_idx);
                            // Save after removal + scroll.
                            let mut tasks: Vec<Task<EditorMessage>> = Vec::new();
                            if !self.tabs.is_empty() {
                                tasks.push(self.scroll_to_active_tab());
                            }
                            tasks.push(self.save_current_tabs());
                            return Task::batch(tasks);
                        }
                    }
                    Some(PendingCloseAction::CloseOthers {
                        keep_idx,
                        remaining_dirty: mut remaining,
                    }) => {
                        return if remaining.is_empty() {
                            // All dirty tabs saved — close everything except keep_idx.
                            self.remove_all_tabs_except(keep_idx);
                            // Save after removal.
                            self.try_save_current_tabs().map_or_else(Task::none, |t| {
                                Task::batch([
                                    t,
                                    Task::done(EditorMessage::Toast(super::ToastMessage::Saved)),
                                ])
                            })
                        } else {
                            // Save the next dirty tab.
                            let next = remaining.remove(0);
                            self.pending_close = Some(PendingCloseAction::CloseOthers {
                                keep_idx,
                                remaining_dirty: remaining,
                            });
                            build_save_task(&self.tabs, &self.tab_contents, next)
                        };
                    }
                    None => {}
                }

                // Regular save (not from close dialog) — persist clean state.
                if let Some(save_task) = self.try_save_current_tabs() {
                    save_task
                } else {
                    Task::done(EditorMessage::Toast(super::ToastMessage::Saved))
                }
            }
            Err(e) => {
                self.pending_close = None;
                let toast = super::ToastMessage::Error(e);
                Task::done(EditorMessage::Toast(toast))
            }
        }
    }

    /// Handle Escape key — dismisses modal overlays, find bar, tree focus,
    /// and residual close-dialog auxiliary state in priority order.
    ///
    /// Priority:
    /// 1. Active modal overlay (closed via [`ModalKind`] match on
    ///    [`active_modal`] — clears auxiliary state for `CloseDialog`
    ///    and `CloseOthers`).
    /// 2. Find/replace bar on the active tab.
    /// 3. File-tree focus.
    /// 4. Residual [`pending_close`] state.
    fn escape(&mut self) -> Task<EditorMessage> {
        // Close modal overlays first.
        if let Some(modal) = self.active_modal.take() {
            match modal {
                ModalKind::CloseDialog(..) | ModalKind::CloseOthers(..) => {
                    self.pending_close = None;
                }
                _ => {}
            }
            return Task::none();
        }

        // Close find bar on active tab next, if open.
        if let Some((_, path)) = self.active_tab() {
            if let Some(tab_data) = self.tab_contents.get_mut(&path) {
                if tab_data.find_replace_state.is_some() {
                    tab_data.find_replace_state = None;
                    return Task::none();
                }
            }
        }

        // Unfocus the file tree, or clear residual close-dialog state.
        if self.file_tree.tree_focused {
            self.file_tree.tree_focused = false;
            self.pending_enter_dir = None;
            return Task::none();
        }
        self.pending_close = None;
        Task::none()
    }

    /// Handle global search toggle — opens/closes the search overlay,
    /// spawns search engine initialization.
    fn global_search_toggle(&mut self) -> Task<EditorMessage> {
        if matches!(self.active_modal, Some(ModalKind::GlobalSearch(_))) {
            // Close if already open.
            self.active_modal = None;
            return Task::none();
        }
        if self.active_modal.is_some() {
            return Task::none();
        }
        // Close find bar when opening global search.
        if let Some((_, path)) = self.active_tab() {
            if let Some(tab_data) = self.tab_contents.get_mut(&path) {
                tab_data.find_replace_state = None;
            }
        }

        let ws_path = match self.selected_workspace_path.as_ref() {
            Some(p) => p.clone(),
            None => return Task::none(),
        };
        let ws_name = match self.selected_workspace_name.as_ref() {
            Some(n) => n.clone(),
            None => return Task::none(),
        };

        self.global_search_gen = self.global_search_gen.wrapping_add(1);
        let gs_gen = self.global_search_gen;

        self.active_modal = Some(ModalKind::GlobalSearch(GlobalSearchState {
            query: String::new(),
            results: Vec::new(),
            selected_index: 0,
            status: GlobalSearchStatus::Idle,
        }));

        // Start scanning the search engine and show readiness status.
        let engine_task = Task::perform(
            async move {
                match crate::search_engine::resolve_engine(&ws_name, &ws_path, "", false).await {
                    Ok(_) => EditorMessage::GlobalSearchResults {
                        r#gen: gs_gen,
                        results: Vec::new(),
                        error: None,
                    },
                    Err(e) => EditorMessage::GlobalSearchResults {
                        r#gen: gs_gen,
                        results: Vec::new(),
                        error: Some(e),
                    },
                }
            },
            |msg| msg,
        );

        // Auto-focus the search input when the panel opens.
        let focus_task =
            iced::widget::operation::focus::<EditorMessage>(Id::new(GLOBAL_SEARCH_INPUT_ID));

        Task::batch([engine_task, focus_task])
    }

    /// Handle global search results — populates search results, handles
    /// stale results, error states, and empty results.
    fn global_search_results(
        &mut self,
        r#gen: u64,
        results: Vec<OwnedGrepMatch>,
        error: Option<String>,
    ) -> Task<EditorMessage> {
        // Stale result? Discard (r#gen is never 0 from the async helper).
        if r#gen != self.global_search_gen {
            return Task::none();
        }

        let Some(ModalKind::GlobalSearch(state)) = &mut self.active_modal else {
            return Task::none();
        };

        if let Some(err) = error {
            state.status = GlobalSearchStatus::Error(err);
            state.results.clear();
            return Task::none();
        }

        if results.is_empty() && state.query.is_empty() {
            state.status = GlobalSearchStatus::Idle;
            return Task::none();
        }

        if results.is_empty() {
            state.status = GlobalSearchStatus::NoResults;
            state.results.clear();
            state.selected_index = 0;
            return Task::none();
        }

        state.results = results;
        state.selected_index = 0;
        state.status = GlobalSearchStatus::Done;
        Task::none()
    }

    /// Handle FindReplaceAll — replaces all matches in the active buffer.
    fn find_replace_all(&mut self) -> Task<EditorMessage> {
        let Some((idx, path)) = self.active_tab() else {
            return Task::none();
        };
        let mut toast = None;
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            if let Some(ref state) = tab_data.find_replace_state {
                if !state.matches.is_empty() {
                    // Take undo snapshot.
                    tab_data
                        .undo_stack
                        .borrow_mut()
                        .snap_before_edit(&tab_data.content);
                    let cursor_before = tab_data.content.cursor();
                    let text = tab_data.content.text();
                    let replace = &state.replace;
                    // Replace all in reverse order to preserve positions.
                    let mut new_text = text;
                    for range in state.matches.iter().rev() {
                        new_text.replace_range(range.start..range.end, replace);
                    }
                    tab_data.content = EditorBuffer::from_file(&new_text, &path);
                    tab_data
                        .content
                        .move_to(cursor_before.line, cursor_before.column);
                    // Clear matches since they're all replaced.
                    if let Some(ref mut state) = tab_data.find_replace_state {
                        state.matches.clear();
                        state.current_match_idx = 0;
                    }
                    toast = Some(EditorMessage::Toast(super::ToastMessage::SuccessMsg(
                        "All matches replaced".to_string(),
                    )));
                }
            }
        }
        update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
        if let Some(t) = toast {
            Task::done(t)
        } else {
            Task::none()
        }
    }

    /// Toggle directory expansion in the file tree — collapses if already expanded,
    /// otherwise loads and expands.
    fn toggle_dir(&mut self, dir_path: &str) -> Task<EditorMessage> {
        // Clicking a tree row while renaming means the user is dismissing the rename.
        self.dismiss_rename();
        // Clear any previously-selected file highlight — navigating
        // to a directory should visually show the directory as focused,
        // not the previously-selected file.
        self.selected_file = None;
        if self.file_tree.expanded_dirs.contains(dir_path) {
            self.file_tree.tree_focused = true;
            return self.collapse_dir(dir_path);
        }
        self.file_tree.expanded_dirs.insert(dir_path.to_string());

        let read_task = if !self.dir_entries.contains_key(dir_path) {
            match self.load_dir_async(dir_path, "ToggleDir") {
                Some(t) => t,
                None => return Task::none(),
            }
        } else {
            Task::none()
        };

        self.rebuild_tree();
        self.file_tree.tree_focused = true;
        // Place focus on the expanding directory.
        self.file_tree.focus_path(dir_path);
        read_task
    }

    /// Handle file selection in the tree — opens or switches to the selected file.
    fn select_file(&mut self, path: &str) -> Task<EditorMessage> {
        // Clicking a file tree row transfers keyboard focus to the tree
        // so that arrow keys navigate the tree instead of the editor.
        self.file_tree.tree_focused = true;
        // Clicking a tree row while renaming means the user is dismissing the rename.
        self.dismiss_rename();
        self.pending_enter_dir = None;
        // Remember the clicked file's position for Ctrl+B re-focus.
        self.file_tree.focus_path(path);
        self.selected_file = Some(path.to_string());

        // Resolve tree-relative path against workspace root so that
        // file operations and tab paths are absolute (matching restored
        // tabs) and work regardless of MahBot's CWD.
        let Some(abs_path) = self.abs_path(path) else {
            return Task::none();
        };

        if let Some(pos) = self.tabs.iter().position(|t| t.path == abs_path) {
            return self.switch_to_tab(pos);
        }

        // Per-file generation: keyed by absolute path.
        let file_gen = self
            .file_generations
            .get(&abs_path)
            .copied()
            .unwrap_or(0)
            .wrapping_add(1);
        self.file_generations.insert(abs_path.clone(), file_gen);
        spawn_file_load(abs_path, file_gen)
    }

    /// Handle an editor action — performs the action, tracks undo state.
    fn editor_action(&mut self, action: super::editor_widget::EditorAction) -> Task<EditorMessage> {
        // Clicking in the editor content transfers focus from the file
        // tree to the editor, matching Escape handler behavior.
        self.file_tree.tree_focused = false;
        self.pending_enter_dir = None;
        self.dismiss_rename();

        let Some((idx, path)) = self.active_tab() else {
            return Task::none();
        };
        let is_edit = action.is_edit_action();
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            if is_edit {
                tab_data
                    .undo_stack
                    .borrow_mut()
                    .snap_before_edit(&tab_data.content);
            }
            tab_data.content.perform_action(action);
        }
        if is_edit {
            update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
        }
        Task::none()
    }

    /// Handle save-active-tab — builds a save task for the active tab.
    fn save_active_tab(&self) -> Task<EditorMessage> {
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some(idx) = self.active_tab_idx() else {
            return Task::none();
        };
        build_save_task(&self.tabs, &self.tab_contents, idx)
    }

    /// Handle close-dialog actions (Save, Discard, Cancel) for a single tab.
    fn close_dialog(&mut self, tab_index: usize, action: CloseAction) -> Task<EditorMessage> {
        match action {
            CloseAction::Save => {
                if tab_index < self.tabs.len() {
                    // Clear dialog immediately; close tab after save completes.
                    self.active_modal = None;
                    self.pending_close = Some(PendingCloseAction::CloseTab(tab_index));

                    build_save_task(&self.tabs, &self.tab_contents, tab_index)
                } else {
                    self.active_modal = None;
                    Task::none()
                }
            }
            CloseAction::Discard => {
                self.active_modal = None;
                self.pending_close = None;
                if tab_index < self.tabs.len() {
                    self.remove_tab_at(tab_index);
                }
                self.save_current_tabs()
            }
            CloseAction::Cancel => {
                self.active_modal = None;
                self.pending_close = None;
                Task::none()
            }
        }
    }

    /// Handle close-others-dialog — saves dirty tabs then closes all but keep_idx.
    fn close_others_dialog(&mut self, keep_idx: usize, action: CloseAction) -> Task<EditorMessage> {
        match action {
            CloseAction::Save => {
                self.active_modal = None;
                // Collect all dirty tabs (excluding keep_idx) to save sequentially.
                let mut dirty: Vec<usize> = (0..self.tabs.len())
                    .filter(|&i| i != keep_idx && self.tabs[i].is_dirty)
                    .collect();
                if dirty.is_empty() {
                    // Nothing to save — just close the rest and persist.
                    self.remove_all_tabs_except(keep_idx);
                    return self.save_current_tabs();
                }
                // Start saving the first dirty tab in the queue.
                let first = dirty.remove(0);
                self.pending_close = Some(PendingCloseAction::CloseOthers {
                    keep_idx,
                    remaining_dirty: dirty,
                });
                build_save_task(&self.tabs, &self.tab_contents, first)
            }
            CloseAction::Discard => {
                self.active_modal = None;
                self.pending_close = None;
                // Close all tabs except keep_idx, discarding unsaved changes.
                self.remove_all_tabs_except(keep_idx);
                self.save_current_tabs()
            }
            CloseAction::Cancel => {
                self.active_modal = None;
                self.pending_close = None;
                Task::none()
            }
        }
    }

    /// Handle close-other-tabs — shows a dialog if there are dirty tabs.
    fn close_other_tabs(&mut self, idx: usize) -> Task<EditorMessage> {
        if idx >= self.tabs.len() {
            return Task::none();
        }
        // Collect indices of dirty tabs (excluding the kept tab).
        let dirty: Vec<usize> = (0..self.tabs.len())
            .filter(|&i| i != idx && self.tabs[i].is_dirty)
            .collect();
        if dirty.is_empty() {
            // No unsaved changes — close immediately and persist.
            self.remove_all_tabs_except(idx);
            return self.save_current_tabs();
        }
        self.active_modal = Some(ModalKind::CloseOthers(idx));
        Task::none()
    }

    /// Handle go-to-line toggle — opens/closes the go-to-line input bar.
    fn go_to_line_toggle(&mut self) -> Task<EditorMessage> {
        // Allow toggle-to-close when GotoLine is already open, but
        // block if any other modal is active.
        if let Some(modal) = &self.active_modal {
            if !matches!(modal, ModalKind::GotoLine(_)) {
                return Task::none();
            }
        }
        if let Some((_, path)) = self.active_tab() {
            if matches!(self.active_modal, Some(ModalKind::GotoLine(_))) {
                self.active_modal = None;
                return Task::none();
            }
            // Close find bar when opening go-to-line.
            if let Some(tab_data) = self.tab_contents.get_mut(&path) {
                tab_data.find_replace_state = None;
            }
            self.active_modal = Some(ModalKind::GotoLine(String::new()));
            return iced::widget::operation::focus::<EditorMessage>(Id::new(GOTO_LINE_INPUT_ID));
        }
        Task::none()
    }

    /// Handle go-to-line input — filters to digits only.
    fn go_to_line_input(&mut self, input: &str) -> Task<EditorMessage> {
        // Only keep digits in the input.
        let digits: String = input.chars().filter(char::is_ascii_digit).collect();
        if matches!(self.active_modal, Some(ModalKind::GotoLine(_))) {
            self.active_modal = Some(ModalKind::GotoLine(digits));
        }
        Task::none()
    }

    /// Handle go-to-line go — jumps to the entered line number.
    fn go_to_line_go(&mut self) -> Task<EditorMessage> {
        let input = match &self.active_modal {
            Some(ModalKind::GotoLine(v)) => v.clone(),
            _ => return Task::none(),
        };
        let line_num: usize = match input.parse::<usize>() {
            Ok(n) if n > 0 => n.saturating_sub(1), // convert 1-based to 0-based
            _ => return Task::none(),
        };
        let Some((_, path)) = self.active_tab() else {
            return Task::none();
        };
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            tab_data.content.move_to(line_num, 0);
        }
        self.active_modal = None;
        Task::none()
    }

    /// Handle global search input — updates query and triggers async search.
    fn global_search_input(&mut self, query: String) -> Task<EditorMessage> {
        let Some(ModalKind::GlobalSearch(state)) = &mut self.active_modal else {
            return Task::none();
        };
        state.query.clone_from(&query);

        if query.is_empty() {
            state.status = GlobalSearchStatus::Idle;
            state.results.clear();
            state.selected_index = 0;
            // Increment generation to cancel any in-flight searches.
            self.global_search_gen = self.global_search_gen.wrapping_add(1);
            return Task::none();
        }

        state.status = GlobalSearchStatus::Searching;

        let ws_path = match self.selected_workspace_path.as_ref() {
            Some(p) => p.clone(),
            None => return Task::none(),
        };
        let ws_name = match self.selected_workspace_name.as_ref() {
            Some(n) => n.clone(),
            None => return Task::none(),
        };

        self.global_search_gen = self.global_search_gen.wrapping_add(1);
        let gs_gen = self.global_search_gen;

        Task::perform(run_global_search(ws_path, ws_name, query, gs_gen), |msg| {
            msg
        })
    }

    /// Handle global search select — opens the selected file at the matching line.
    fn global_search_select(&mut self, idx: usize) -> Task<EditorMessage> {
        let Some(ModalKind::GlobalSearch(state)) = &self.active_modal else {
            return Task::none();
        };
        let Some(match_result) = state.results.get(idx) else {
            return Task::none();
        };
        let abs_path = match_result.abs_path.clone();
        #[expect(clippy::cast_possible_truncation)]
        let line_number = match_result.line_number as usize;

        // Close the search panel.
        self.active_modal = None;

        // Open the file and move to the matching line.
        // Convert from 1-based (grep) to 0-based (editor).
        let cursor_line = line_number.saturating_sub(1);

        // Check if already open in a tab.
        if let Some(existing_idx) = self.tabs.iter().position(|t| t.path == abs_path) {
            self.active_tab_index = existing_idx;
            if let Some(tab_data) = self.tab_contents.get_mut(&abs_path) {
                tab_data.content.move_to(cursor_line, 0);
            }
            return self.scroll_to_active_tab();
        }

        // File not open — load it, then jump after loading.
        // Set pending_goto so FileLoaded handler moves the cursor.
        // Use self.generation.wrapping_add(1) to predict the generation
        // that open_file_in_editor will produce (it calls bump_generation).
        let file_gen = self.generation.wrapping_add(1);
        self.pending_goto = Some((abs_path.clone(), line_number, file_gen));
        self.open_file_in_editor(&abs_path)
    }

    /// Handle delete-file-requested — shows the delete confirmation dialog.
    fn delete_file_requested(&mut self, path: String) -> Task<EditorMessage> {
        let Some(abs_path) = self.abs_path(&path) else {
            return Task::none();
        };
        self.active_modal = Some(ModalKind::DeleteConfirm(DeleteConfirmTarget {
            path,
            is_dir: false,
            dirty_tab_count: 0,
            abs_path,
        }));
        Task::none()
    }

    /// Handle delete-directory-requested — shows the delete confirmation dialog.
    fn delete_directory_requested(&mut self, path: String) -> Task<EditorMessage> {
        // Guard: don't allow deleting the root directory.
        if path.is_empty() {
            return Task::done(EditorMessage::Toast(super::ToastMessage::Warning(
                "Cannot delete root directory".into(),
            )));
        }
        let Some(abs_path) = self.abs_path(&path) else {
            return Task::none();
        };
        let abs_prefix = format!("{abs_path}/");

        // Count open tabs that are inside this directory.
        let mut dirty_count = 0;
        for tab in &self.tabs {
            if tab.path.starts_with(&abs_prefix) {
                if tab.is_dirty {
                    dirty_count += 1;
                }
            }
        }

        self.active_modal = Some(ModalKind::DeleteConfirm(DeleteConfirmTarget {
            path,
            is_dir: true,
            dirty_tab_count: dirty_count,
            abs_path,
        }));
        Task::none()
    }

    /// Handle confirm-delete — performs the actual file/directory deletion.
    fn confirm_delete(&mut self) -> Task<EditorMessage> {
        let Some(ModalKind::DeleteConfirm(target)) = self.active_modal.clone() else {
            return Task::none();
        };
        self.active_modal = None;
        if target.is_dir {
            self.perform_dir_delete(&target)
        } else {
            self.perform_file_delete(&target)
        }
    }

    /// Handle new-item-submit — validates and creates the new file/directory.
    fn new_item_submit(&mut self, name: &str) -> Task<EditorMessage> {
        let Some(ModalKind::NewItem(target)) = self.active_modal.clone() else {
            return Task::none();
        };
        let trimmed = name.trim();
        if let Some(msg) = validate_item_name(trimmed) {
            return Task::done(EditorMessage::Toast(super::ToastMessage::Warning(
                msg.into(),
            )));
        }
        self.active_modal = None;
        self.perform_create_item(&target, trimmed)
    }

    /// Handle new-item-input — updates the input text as the user types.
    fn new_item_input(&mut self, new_text: String) -> Task<EditorMessage> {
        if let Some(ModalKind::NewItem(ref mut target)) = self.active_modal {
            target.input_text = new_text;
        }
        Task::none()
    }

    /// Handle rename-requested — starts the inline rename modal.
    fn rename_requested(&mut self, path: &str) -> Task<EditorMessage> {
        let Some(ref ws) = self.selected_workspace_path else {
            return Task::none();
        };
        // Guard: don't allow renaming root directory.
        if path.is_empty() {
            return Task::done(EditorMessage::Toast(super::ToastMessage::Warning(
                "Cannot rename root directory".into(),
            )));
        }
        let abs_path = self
            .abs_path(path)
            .expect("RenameRequested: selected_workspace_path already guarded above");
        let file_name = Path::new(&abs_path)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        // Determine if it's a directory by checking the actual filesystem.
        let is_dir = Path::new(&abs_path).is_dir();

        self.active_modal = Some(ModalKind::Rename(RenameTarget {
            abs_path,
            ws_root: ws.clone(),
            path: path.to_string(),
            is_dir,
            input_text: file_name,
            error: None,
        }));
        iced::widget::operation::focus::<EditorMessage>(Id::from(format!("rename_input_{path}")))
    }

    /// Handle rename-input — updates the inline rename text as the user types.
    fn rename_input(&mut self, new_text: String) -> Task<EditorMessage> {
        if let Some(ModalKind::Rename(ref mut target)) = self.active_modal {
            target.input_text = new_text;
            // Clear error when user starts typing again.
            if target.error.is_some() {
                target.error = None;
            }
        }
        Task::none()
    }

    /// Handle rename-submit — validates and performs the async rename operation.
    fn rename_submit(&mut self) -> Task<EditorMessage> {
        let Some(ModalKind::Rename(target)) = self.active_modal.clone() else {
            return Task::none();
        };
        // All-space names fall through to the empty-name check below.
        let trimmed = target.input_text.trim().to_string();

        // ── Validation ────────────────────────────────────────
        // validate_item_name covers empty name, path separators,
        // dot/dotdot, and OS-reserved names.
        let error_msg = validate_item_name(&trimmed);
        if let Some(msg) = error_msg {
            if let Some(ModalKind::Rename(ref mut rt)) = self.active_modal {
                rt.error = Some(msg.into());
            }
            return Task::none();
        }

        // Compute the new absolute and relative paths.
        let parent_dir = Path::new(&target.path)
            .parent()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        let new_rel_path = if parent_dir.is_empty() {
            trimmed.clone()
        } else {
            format!("{parent_dir}/{trimmed}")
        };
        let new_abs_path = Path::new(&target.ws_root)
            .join(&new_rel_path)
            .to_string_lossy()
            .to_string();

        // Check if target already exists.
        if Path::new(&new_abs_path).exists() {
            if let Some(ModalKind::Rename(ref mut rt)) = self.active_modal {
                rt.error = Some("A file or directory with that name already exists".into());
            }
            return Task::none();
        }

        // All validations passed — clear the inline rename state
        // and fire the async rename task.
        self.active_modal = None;

        let old_abs = target.abs_path.clone();
        let old_rel = target.path.clone();
        let is_dir = target.is_dir;
        let parent_dir_clone = parent_dir;
        let ws_root = target.ws_root;
        // Follow the same generation-based invalidation protocol as
        // every other async directory operation (ToggleDir, TreeNavEnter,
        // perform_create_item, etc.): bump self.generation and register
        // it in dir_generations so that any in-flight DirExpanded for
        // this directory is invalidated (its generation won't match).
        let dir_gen = self.bump_generation();
        self.dir_generations
            .insert(parent_dir_clone.clone(), dir_gen);

        Task::perform(
            async move {
                // Handle case-only rename on case-insensitive filesystems
                // via a two-step rename through a temporary name.
                let old_lower = old_rel.to_lowercase();
                let new_lower = new_rel_path.to_lowercase();
                let result = if old_lower == new_lower && old_rel != new_rel_path {
                    // Case-only rename: rename to a temp name first, then to the target.
                    let temp_name = format!(
                        "{}_{}",
                        trimmed,
                        std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .map_or(0, |d| d.as_nanos())
                    );
                    let temp_abs = Path::new(&ws_root)
                        .join(&parent_dir_clone)
                        .join(&temp_name)
                        .to_string_lossy()
                        .to_string();
                    if let Err(e) = tokio::fs::rename(&old_abs, &temp_abs).await {
                        Err(format!("Rename failed: {e}"))
                    } else {
                        tokio::fs::rename(&temp_abs, &new_abs_path)
                            .await
                            .map_err(|e| format!("Rename failed: {e}"))
                    }
                } else {
                    tokio::fs::rename(&old_abs, &new_abs_path)
                        .await
                        .map_err(|e| format!("Rename failed: {e}"))
                };

                // Re-read parent directory regardless of success/failure
                // so the tree reflects the current filesystem state.
                let entries = read_directory_entries(&ws_root, &parent_dir_clone).await;

                EditorMessage::RenameCompleted {
                    old_path: old_rel,
                    new_path: new_rel_path,
                    is_dir,
                    result,
                    dir_entries: entries,
                    rename_gen: dir_gen,
                }
            },
            |msg| msg,
        )
    }

    /// Cancel inline rename — clicking any other UI element while a rename
    /// input is active dismisses the rename.
    fn dismiss_rename(&mut self) {
        if matches!(self.active_modal, Some(ModalKind::Rename(_))) {
            self.active_modal = None;
        }
    }

    /// Handle rename-cancel — dismisses the inline rename modal.
    fn rename_cancel(&mut self) -> Task<EditorMessage> {
        self.active_modal = None;
        Task::none()
    }

    /// Handle rename-completed — updates paths, tab data, tree, and filesystem
    /// state after an async rename operation.
    #[expect(clippy::too_many_lines)]
    fn rename_completed(
        &mut self,
        old_path: &str,
        new_path: &str,
        is_dir: bool,
        result: Result<(), String>,
        dir_entries: Result<Vec<FsEntry>, ReadDirError>,
        rename_gen: u64,
    ) -> Task<EditorMessage> {
        // Workspace could have been cleared mid-rename.  abs_path()
        // returns None when workspace_root() returns None, so we
        // handle both cases in the Ok arm below.

        // Stale-result prevention via the standard dir_generations
        // protocol (same as dir_expanded).  Compute the parent dir
        // and check if we still own the generation slot.
        let re_path = Path::new(old_path)
            .parent()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default();
        if self.dir_generations.get(&re_path) != Some(&rename_gen) {
            return Task::none();
        }
        // Own the generation — consume it so a future operation can
        // take the slot.
        self.dir_generations.remove(&re_path);

        match result {
            Ok(()) => {
                // ── Update selected_file if it matches ────
                if self.selected_file.as_deref() == Some(old_path) {
                    self.selected_file = Some(new_path.to_string());
                }

                // ── Update open tab paths ────────────────
                let Some(old_abs) = self.abs_path(old_path) else {
                    return Task::none();
                };
                let Some(new_abs) = self.abs_path(new_path) else {
                    return Task::none();
                };

                // Build a prefix-based replacement for directory renames.
                if is_dir {
                    let old_prefix = format!("{old_abs}/");
                    for tab in &mut self.tabs {
                        if tab.path.starts_with(&old_prefix) {
                            let rest = tab.path.strip_prefix(&old_prefix).unwrap();

                            tab.path = format!("{new_abs}/{rest}");
                            tab.file_name = Path::new(&tab.path)
                                .file_name()
                                .map(|n| n.to_string_lossy().to_string())
                                .unwrap_or_default();
                        }
                    }
                    // Re-key tab_contents for affected files.
                    rekey_map_prefix(
                        &mut self.tab_contents,
                        &format!("{old_abs}/"),
                        &new_abs,
                        |_| {},
                    );

                    // Update expanded_dirs to replace old_path with new_path.
                    if self.file_tree.expanded_dirs.remove(old_path) {
                        self.file_tree.expanded_dirs.insert(new_path.to_string());
                    }
                    // Also update any child expanded dirs (e.g., dir/subdir → newdir/subdir).
                    rekey_set_prefix(
                        &mut self.file_tree.expanded_dirs,
                        &format!("{old_path}/"),
                        new_path,
                    );

                    // Migrate dir_entries for child paths so expanded children
                    // don't vanish on rebuild.  build_hierarchical_tree looks up
                    // each expanded directory in dir_entries by full_path, so we
                    // must re-key those entries under the new prefix and update
                    // each entry's full_path to reflect the new path.
                    let old_entries_prefix = format!("{old_path}/");
                    let new_path_clone = new_path.to_string();
                    rekey_map_prefix(
                        &mut self.dir_entries,
                        &old_entries_prefix,
                        new_path,
                        |entries: &mut Vec<FsEntry>| {
                            for entry in entries.iter_mut() {
                                update_entry_path(entry, &old_entries_prefix, &new_path_clone);
                            }
                        },
                    );

                    // Also migrate the renamed directory's own dir_entries entry
                    // so it doesn't vanish from the tree on rebuild.
                    // Must update the child entries' full_path to reflect the
                    // new path prefix (same as the child-entries loop above).
                    if let Some(mut own_entries) = self.dir_entries.remove(old_path) {
                        for entry in &mut own_entries {
                            update_entry_path(entry, &old_entries_prefix, new_path);
                        }
                        self.dir_entries.insert(new_path.to_string(), own_entries);
                    }
                } else {
                    // File rename: update single tab.
                    for tab in &mut self.tabs {
                        if tab.path == old_abs {
                            tab.path.clone_from(&new_abs);
                            tab.file_name = Path::new(&new_abs)
                                .file_name()
                                .map(|n| n.to_string_lossy().to_string())
                                .unwrap_or_default();
                            break;
                        }
                    }
                    if let Some(data) = self.tab_contents.remove(&old_abs) {
                        self.tab_contents.insert(new_abs.clone(), data);
                    }
                }

                // ── Migrate file_mtimes, deleted_file_toasted, and file_generations ──
                // Re-key entries from old absolute path to new absolute
                // path so auto-refresh doesn't spuriously stat the old path
                // and in-flight FileLoaded results are properly validated.
                if is_dir {
                    let old_abs_prefix = format!("{old_abs}/");
                    rekey_map_prefix(&mut self.file_mtimes, &old_abs_prefix, &new_abs, |_| {});
                    rekey_set_prefix(&mut self.deleted_file_toasted, &old_abs_prefix, &new_abs);
                    rekey_map_prefix(
                        &mut self.file_generations,
                        &old_abs_prefix,
                        &new_abs,
                        |_| {},
                    );
                } else {
                    // File rename — migrate single entry.
                    if let Some(mtime) = self.file_mtimes.remove(&old_abs) {
                        self.file_mtimes.insert(new_abs.clone(), mtime);
                    }
                    if self.deleted_file_toasted.remove(&old_abs) {
                        self.deleted_file_toasted.insert(new_abs.clone());
                    }
                    if let Some(file_gen) = self.file_generations.remove(&old_abs) {
                        self.file_generations.insert(new_abs.clone(), file_gen);
                    }
                }

                // ── Update dir entries and rebuild tree ───
                match dir_entries {
                    Ok(entries) => {
                        // re_path was computed at the top of the
                        // handler for the staleness check; we own
                        // the generation slot, so insert unconditionally.
                        self.dir_entries.insert(re_path, entries);
                        self.rebuild_tree();
                        // Focus on the renamed entry.
                        self.file_tree.focus_path(new_path);
                    }
                    Err(ReadDirError::NotFound) => {
                        // Parent directory vanished mid-rename — forget it
                        // silently like any other missing directory.
                        self.forget_directory(&re_path);
                        self.rebuild_tree();
                    }
                    Err(ReadDirError::Other(err)) => {
                        self.rebuild_tree();
                        return Task::done(EditorMessage::Toast(super::ToastMessage::Error(
                            format!(
                                "Rename succeeded but failed to refresh tree '{re_path}': {err}"
                            ),
                        )));
                    }
                }

                Task::batch([
                    self.save_current_tabs(),
                    Task::done(EditorMessage::Toast(super::ToastMessage::SuccessMsg(
                        format!("Renamed \"{old_path}\"\"{new_path}\""),
                    ))),
                ])
            }
            Err(e) => {
                // re_path is already computed at the top of the
                // handler; we own the generation slot.
                match dir_entries {
                    Ok(entries) => {
                        self.dir_entries.insert(re_path, entries);
                        self.rebuild_tree();
                    }
                    Err(ReadDirError::NotFound) => {
                        // Parent directory vanished — forget it silently.
                        self.forget_directory(&re_path);
                        self.rebuild_tree();
                    }
                    Err(ReadDirError::Other(_)) => {
                        self.rebuild_tree();
                    }
                }
                Task::done(EditorMessage::Toast(super::ToastMessage::Error(e)))
            }
        }
    }

    /// Handle quick-open toggle — opens/closes the quick-open file picker.
    fn quick_open_toggle(&mut self) -> Task<EditorMessage> {
        if matches!(self.active_modal, Some(ModalKind::QuickOpen(_))) {
            self.active_modal = None;
            return Task::none();
        }
        if self.active_modal.is_some() {
            return Task::none();
        }

        // Refresh file list from all currently expanded directories.
        self.scan_all_workspace_files();

        self.active_modal = Some(ModalKind::QuickOpen(QuickOpenState {
            filter: String::new(),
            selected_index: 0,
            results: Vec::new(),
        }));
        iced::widget::operation::focus::<EditorMessage>(Id::new(QUICK_OPEN_INPUT_ID))
    }

    /// Handle quick-open input — filters the file list.
    fn quick_open_input(&mut self, filter: String) -> Task<EditorMessage> {
        let results = self.filter_workspace_files(&filter);
        if let Some(ModalKind::QuickOpen(ref mut qo)) = self.active_modal {
            qo.filter = filter;
            qo.results = results;
            qo.selected_index = 0;
        }
        Task::none()
    }

    /// Handle quick-open select — opens the selected file.
    fn quick_open_select(&mut self, idx: usize) -> Task<EditorMessage> {
        let result_path = match &self.active_modal {
            Some(ModalKind::QuickOpen(qo)) => qo.results.get(idx).cloned(),
            _ => None,
        };
        self.active_modal = None;
        if let Some(path) = result_path {
            return self.open_file_in_editor(&path);
        }
        Task::none()
    }

    /// Handle close-active-tab — closes the currently active tab.
    fn close_active_tab(&mut self) -> Task<EditorMessage> {
        if self.active_modal.is_some() {
            return Task::none();
        }
        let idx = self.active_tab_index;
        if idx < self.tabs.len() {
            return self.close_tab_at(idx);
        }
        Task::none()
    }

    /// Handle tree-focus-toggled — toggles keyboard focus between tree and editor.
    fn tree_focus_toggled(&mut self) -> Task<EditorMessage> {
        // Suppress during any modal overlay (QuickOpen, GlobalSearch,
        // GotoLine, Rename, etc.) — the overlay owns keyboard focus
        // and the single-field `active_modal` covers all variants.
        if self.active_modal.is_some() {
            return Task::none();
        }
        self.file_tree.tree_focused = !self.file_tree.tree_focused;
        if self.file_tree.tree_focused && self.file_tree.visible_tree_nodes.is_empty() {
            self.file_tree.rebuild_visible();
        }
        if !self.file_tree.tree_focused || self.file_tree.visible_tree_nodes.is_empty() {
            self.file_tree.tree_focused = false;
            self.pending_enter_dir = None;
        }
        Task::none()
    }

    /// Handle tree-scrolled — updates scroll state of the file tree.
    fn tree_scrolled(&mut self, scroll_y: f32, viewport_h: f32) -> Task<EditorMessage> {
        self.file_tree.scroll_y = scroll_y;
        self.file_tree.viewport_h = Some(viewport_h);
        Task::none()
    }

    /// Handle tab-bar-scrolled — updates scroll state of the tab bar.
    fn tab_bar_scrolled(&mut self, scroll_x: f32, viewport_w: f32) -> Task<EditorMessage> {
        self.tab_scroll_x = scroll_x;
        self.tab_viewport_w = Some(viewport_w);
        Task::none()
    }

    /// Handle tree-nav-enter — opens file or expands/collapses directory.
    fn tree_nav_enter(&mut self) -> Task<EditorMessage> {
        // When global search or quick-open is active, Enter selects the
        // highlighted result / file.  Borrow to extract the index without
        // cloning the entire state.
        match &self.active_modal {
            Some(ModalKind::GlobalSearch(gs)) => {
                let idx = gs.selected_index.min(gs.results.len().saturating_sub(1));
                return Task::done(EditorMessage::GlobalSearchSelect(idx));
            }
            Some(ModalKind::QuickOpen(qo)) => {
                let idx = qo.selected_index.min(qo.results.len().saturating_sub(1));
                return Task::done(EditorMessage::QuickOpenSelect(idx));
            }
            _ => {}
        }
        // When any modal overlay (Rename, GotoLine, NewItem, DeleteConfirm,
        // CloseDialog, etc.) is active, suppress tree navigation — the
        // overlay handles its own Enter key handling.  Must be placed
        // AFTER the search redirects above so Enter-to-select still works
        // in GlobalSearch and QuickOpen.
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some((_idx, path, is_dir)) = self.file_tree.focused_tree_node() else {
            return Task::none();
        };
        if self.file_tree.focused_is_expanded_dir() {
            // Collapse: rebuild and keep focus on the collapsed directory.
            return self.collapse_dir(&path);
        }
        if is_dir {
            // Expand: insert, rebuild, jump to first child.
            return self.expand_dir_and_focus(&path, "TreeNavEnter");
        }
        // Open file.
        Task::done(EditorMessage::SelectFile(path))
    }

    /// Handle tree-nav-left — collapses expanded directory or navigates to parent.
    fn tree_nav_left(&mut self) -> Task<EditorMessage> {
        // Suppress during active modal overlays — the overlay handles
        // its own keyboard navigation (covers Rename, GotoLine, etc.).
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some((_idx, path, _)) = self.file_tree.focused_tree_node() else {
            return Task::none();
        };

        if self.file_tree.focused_is_expanded_dir() {
            // Collapse expanded directory and keep focus on it.
            return self.collapse_dir(&path);
        }

        // ArrowLeft on collapsed directory or file — navigate to parent.
        self.file_tree.focus_parent::<EditorMessage>()
    }

    /// Handle tree-nav-right — expands directory or navigates to first child.
    fn tree_nav_right(&mut self) -> Task<EditorMessage> {
        // Suppress during active modal overlays — the overlay handles
        // its own keyboard navigation (covers Rename, GotoLine, etc.).
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some((idx, path, is_dir)) = self.file_tree.focused_tree_node() else {
            return Task::none();
        };

        if !is_dir {
            // ArrowRight on a file does nothing.
            return Task::none();
        }

        if !self.file_tree.expanded_dirs.contains(&path) {
            // Expand directory and move focus to first child.
            return self.expand_dir_and_focus(&path, "TreeNavRight");
        }

        // Already expanded directory — move focus to first child (if any).
        self.file_tree.focus_next_row::<EditorMessage>(idx)
    }

    /// Handle find-toggle — opens/closes the find/replace bar.
    fn find_toggle(&mut self) -> Task<EditorMessage> {
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some((_, path)) = self.active_tab() else {
            return Task::none();
        };
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            if tab_data.find_replace_state.is_none() {
                // Open find bar with current selection as default query.
                let default_query = tab_data.content.selection().unwrap_or_default();
                let mut state = FindReplaceState {
                    query: default_query,
                    replace: String::new(),
                    matches: Vec::new(),
                    current_match_idx: 0,
                    case_sensitive: false,
                };
                state.recompute(&tab_data.content);
                tab_data.find_replace_state = Some(state);
            }
            // Already open — re-focus the search input (no state change needed).
        }
        // Always focus the search input when FindToggle is pressed.
        iced::widget::operation::focus::<EditorMessage>(Id::new(FIND_SEARCH_ID))
    }

    /// Run a mutation against the active tab's find state, if any.
    fn with_active_find_state(
        &mut self,
        f: impl FnOnce(&mut FindReplaceState, &EditorBuffer),
    ) -> Task<EditorMessage> {
        let Some((_, path)) = self.active_tab() else {
            return Task::none();
        };
        if let Some(tab_data) = self.tab_contents.get_mut(&path)
            && let Some(state) = tab_data.find_replace_state.as_mut()
        {
            f(state, &tab_data.content);
        }
        Task::none()
    }

    /// Handle find-query-input — updates the search query and recomputes matches.
    fn find_query_input(&mut self, query: String) -> Task<EditorMessage> {
        self.with_active_find_state(|state, content| {
            state.query = query;
            state.recompute(content);
        })
    }

    /// Handle find-replace-input — updates the replace text.
    fn find_replace_input(&mut self, replace: String) -> Task<EditorMessage> {
        self.with_active_find_state(|state, _| {
            state.replace = replace;
        })
    }

    /// Handle find-replace — replaces the current match and advances to the next.
    fn find_replace(&mut self) -> Task<EditorMessage> {
        let Some((idx, path)) = self.active_tab() else {
            return Task::none();
        };

        // ── Phase 1 (read-only): extract owned values upfront ────────────
        // Cloning range/replace/query here avoids interleaving immutable
        // borrows (to read state) with mutable borrows (to mutate content
        // and update state) in the same scope.
        let Some((range, replace_text, case_sensitive, query)) = self
            .tab_contents
            .get(&path)
            .and_then(|tab_data| tab_data.find_replace_state.as_ref())
            .and_then(|state| {
                let range = state.matches.get(state.current_match_idx)?;
                Some((
                    range.clone(),
                    state.replace.clone(),
                    state.case_sensitive,
                    state.query.clone(),
                ))
            })
        else {
            update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
            return Task::none();
        };

        let replace_end = range.start + replace_text.len();

        // Guard: no-op replacement (empty text on zero-width range).
        if replace_text.is_empty() && range.start >= range.end {
            update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
            return Task::none();
        }

        // ── Phase 2 (mutation): perform the replacement ──────────────────
        if let Some(tab_data) = self.tab_contents.get_mut(&path) {
            tab_data
                .undo_stack
                .borrow_mut()
                .snap_before_edit(&tab_data.content);

            let text = tab_data.content.text();
            let new_text = format!(
                "{}{}{}",
                &text[..range.start],
                replace_text,
                &text[range.end..]
            );
            tab_data.content = EditorBuffer::from_file(&new_text, &path);

            // Recompute matches and auto-advance to next match.
            if let Some(ref mut state) = tab_data.find_replace_state {
                state.matches = compute_text_matches(&new_text, &query, case_sensitive);

                if !state.matches.is_empty() {
                    // Advance to the next match starting at or after the
                    // end of the replacement in the new text
                    // (position = range.start + len(replace_text)).
                    // Using a position in the old text (range.end) would
                    // be wrong when replacement length differs from the
                    // original match length.
                    let next_idx = state
                        .matches
                        .iter()
                        .position(|m| m.start >= replace_end)
                        .unwrap_or(0)
                        .min(state.matches.len() - 1);
                    state.current_match_idx = next_idx;
                    // Position cursor at the new match.
                    if let Some(r) = state.matches.get(next_idx) {
                        let (line, col) = byte_offset_to_line_col(&new_text, r.start);
                        tab_data.content.move_to(line, col);
                    }
                } else {
                    state.current_match_idx = 0;
                    // No remaining matches — place cursor at end of
                    // the replacement, not at buffer start.
                    let (line, col) = byte_offset_to_line_col(&new_text, replace_end);
                    tab_data.content.move_to(line, col);
                }
            }
        }

        update_dirty_flag(&mut self.tabs, &self.tab_contents, idx, &path);
        Task::none()
    }

    /// Handle find-toggle-case-sensitivity — toggles case-sensitive search.
    fn find_toggle_case_sensitivity(&mut self) -> Task<EditorMessage> {
        self.with_active_find_state(|state, content| {
            state.case_sensitive = !state.case_sensitive;
            state.recompute(content);
        })
    }

    /// Handle refresh-file-tree — re-reads all expanded directories from disk.
    fn refresh_file_tree(&mut self) -> Task<EditorMessage> {
        // Suppress during active modal overlays — the file tree should
        // not refresh behind an active overlay.  This covers both the
        // Cmd+R / Ctrl+R keyboard shortcut AND the periodic 30-second
        // timer subscription.
        if self.active_modal.is_some() {
            return Task::none();
        }
        let Some(ref ws_path) = self.selected_workspace_path else {
            return Task::none();
        };

        // Collect directories to refresh: root + all expanded dirs.
        let mut dirs_to_refresh: Vec<String> = Vec::new();

        // Root directory (empty string) is always included — it's
        // implicitly expanded and not tracked in expanded_dirs.
        dirs_to_refresh.push(String::new());

        // All manually expanded directories.
        dirs_to_refresh.extend(self.file_tree.expanded_dirs.iter().cloned());

        // Filter out directories currently being loaded by the user
        // (e.g., from a ToggleDir or TreeNavEnter action). This avoids
        // racing user-initiated async loads. Generation counters also
        // protect against races, but skipping in-flight dirs avoids
        // wasted I/O.
        dirs_to_refresh.retain(|d| !self.loading_dirs.contains(d));

        if dirs_to_refresh.is_empty() {
            return Task::none();
        }

        let mut tasks: Vec<Task<EditorMessage>> = Vec::new();
        let root_path = ws_path.clone();

        for dir_path in dirs_to_refresh {
            let dir_gen = self.bump_generation();
            self.dir_generations.insert(dir_path.clone(), dir_gen);
            // NOTE: deliberately NOT adding to `loading_dirs` — this
            // avoids a "Loading…" flicker for every expanded directory
            // on every background refresh. The tree silently updates
            // when results arrive via DirExpanded.

            tasks.push(dir_expanded_task(
                root_path.clone(),
                dir_path.clone(),
                dir_gen,
                true,
            ));
        }

        // Kick off a git status refresh so newly discovered files
        // get their git status colors without waiting for the next Tick.
        if !self.git_status_loading {
            self.git_status_loading = true;
            let path = root_path;
            let r#gen = self.git_status_gen;
            tasks.push(Task::perform(
                async move { load_git_status(path).await },
                move |result| EditorMessage::GitStatusLoaded { r#gen, result },
            ));
        }

        Task::batch(tasks)
    }

    /// Handle tick — refreshes git status and gitignore for file tree coloring.
    fn tick(&mut self) -> Task<EditorMessage> {
        if let Some(ref ws_path) = self.selected_workspace_path {
            let mut tasks: Vec<Task<EditorMessage>> = Vec::new();

            if !self.git_status_loading {
                self.git_status_loading = true;
                let path = ws_path.clone();
                let r#gen = self.git_status_gen;
                tasks.push(Task::perform(
                    async move { load_git_status(path).await },
                    move |result| EditorMessage::GitStatusLoaded { r#gen, result },
                ));
            }

            if !self.git_ignore_loading {
                self.git_ignore_loading = true;
                let path = ws_path.clone();
                let tree_paths = collect_tree_paths(&self.file_tree.nodes);
                let r#gen = self.git_status_gen;
                tasks.push(Task::perform(
                    async move { load_git_ignore(path, tree_paths).await },
                    move |result| EditorMessage::GitIgnoredLoaded { r#gen, result },
                ));
            }

            Task::batch(tasks)
        } else {
            Task::none()
        }
    }

    /// Handle check-file-changes — detects external file modifications and reloads.
    fn check_file_changes(&mut self) -> Task<EditorMessage> {
        let Some((idx, path)) = self.active_tab() else {
            return Task::none();
        };
        // Only auto-refresh tabs that are not dirty.
        if self.tabs[idx].is_dirty {
            return Task::none();
        }

        let current_mtime = if let Ok(meta) = std::fs::metadata(&path) {
            meta.modified().ok()
        } else {
            // File doesn't exist (deleted or moved).
            if !self.deleted_file_toasted.contains(&path) {
                self.deleted_file_toasted.insert(path);
                return Task::done(EditorMessage::Toast(super::ToastMessage::Warning(format!(
                    "File was deleted: {}",
                    self.tabs[idx].file_name
                ))));
            }
            return Task::none();
        };

        // File exists — if it was previously reported as deleted,
        // clear that flag (file has been recreated).
        self.deleted_file_toasted.remove(&path);

        let Some(current_mtime) = current_mtime else {
            // Cannot determine mtime on this platform — skip.
            return Task::none();
        };

        let stored_mtime = if let Some(m) = self.file_mtimes.get(&path) {
            *m
        } else {
            // No stored mtime yet — record it now and skip.
            self.file_mtimes.insert(path, current_mtime);
            return Task::none();
        };

        // Only re-read if mtime actually changed.
        if current_mtime == stored_mtime {
            return Task::none();
        }

        // Mtime changed — capture cursor position and reload async.
        let cursor = if let Some(tab_data) = self.tab_contents.get(&path) {
            tab_data.content.cursor()
        } else {
            return Task::none();
        };

        // Start the async read.
        Task::perform(
            async move {
                let result = match tokio::fs::read_to_string(&path).await {
                    Ok(text) => validate_file_content(text.as_bytes()).map(|()| text),
                    Err(e) => Err(format!("Cannot read file: {e}")),
                };
                EditorMessage::FileReloaded {
                    path,
                    result,
                    cursor_line: cursor.line,
                    cursor_col: cursor.column,
                }
            },
            |msg| msg,
        )
    }

    /// Handle file-reloaded — replaces tab content with the reloaded file data.
    fn file_reloaded(
        &mut self,
        path: String,
        result: Result<String, String>,
        cursor_line: usize,
        cursor_col: usize,
    ) -> Task<EditorMessage> {
        // Guard: the tab must still be the active one and not dirty.
        let Some(idx) = self.active_tab_idx() else {
            return Task::none();
        };
        if self.tabs[idx].path != path || self.tabs[idx].is_dirty {
            return Task::none();
        }

        let task = match result {
            Ok(text) => {
                let line_ending = detect_line_ending(&text);

                // Update tab metadata.
                if let Some(tab) = self.tabs.get_mut(idx) {
                    tab.is_dirty = false;
                    tab.line_ending = line_ending;
                }

                // Replace content, preserving cursor position (clamped).
                if let Some(tab_data) = self.tab_contents.get_mut(&path) {
                    // Clear find/replace state — match byte ranges are now stale.
                    tab_data.find_replace_state = None;
                    tab_data.content = EditorBuffer::from_file(&text, &path);
                    // Restore cursor, clamped to new file bounds.
                    tab_data.content.move_to(cursor_line, cursor_col);
                    // Clear undo stack — new content didn't come from user edits.
                    *tab_data.undo_stack.borrow_mut() = UndoStack::new();
                    tab_data.saved_text_hash = hash_text(&text);
                }

                Task::none()
            }
            Err(e) => Task::done(EditorMessage::Toast(super::ToastMessage::Warning(e))),
        };

        // Update the stored mtime so the next tick matches
        // and won't retry every 300 ms — even on failure,
        // this prevents repeated read attempts.
        if let Ok(meta) = std::fs::metadata(&path) {
            if let Ok(mtime) = meta.modified() {
                self.file_mtimes.insert(path, mtime);
            }
        }

        task
    }

    /// Navigate to the next or previous find match in the active tab.
    /// Returns silently if there is no active tab, no find state, or no matches.
    fn navigate_find_match(&mut self, direction: FindDirection) -> Task<EditorMessage> {
        self.with_active_find_state(|state, content| {
            if !state.matches.is_empty() {
                let new_idx = match direction {
                    FindDirection::Next => (state.current_match_idx + 1) % state.matches.len(),
                    FindDirection::Prev => {
                        if state.current_match_idx == 0 {
                            state.matches.len().saturating_sub(1)
                        } else {
                            state.current_match_idx - 1
                        }
                    }
                };
                state.current_match_idx = new_idx;
                if let Some(range) = state.matches.get(new_idx) {
                    let (line, col) = byte_offset_to_line_col(&content.text(), range.start);
                    content.move_to(line, col);
                }
            }
        })
    }

    /// Shared helper for navigating search results — adjusts the selected index
    /// based on the direction, staying within bounds.
    fn navigate_search_results(
        selected_index: &mut usize,
        results_len: usize,
        direction: TreeNavDirection,
    ) {
        match direction {
            TreeNavDirection::Up if *selected_index > 0 => *selected_index -= 1,
            TreeNavDirection::Down if *selected_index + 1 < results_len => *selected_index += 1,
            _ => {}
        }
    }

    /// Navigate vertically in the active overlay or file tree.
    ///
    /// Handles global-search results, quick-open results, and file-tree focus
    /// in priority order. Only the file-tree path returns a scroll-to-focus
    /// task; the overlay paths return `Task::none()`.
    fn navigate_tree_vertical(&mut self, direction: TreeNavDirection) -> Task<EditorMessage> {
        // When global search is active, navigate the results list.
        if let Some(ModalKind::GlobalSearch(ref mut gs)) = self.active_modal {
            Self::navigate_search_results(&mut gs.selected_index, gs.results.len(), direction);
            return Task::none();
        }
        // When quick-open is active, navigate the results list.
        if let Some(ModalKind::QuickOpen(ref mut qo)) = self.active_modal {
            Self::navigate_search_results(&mut qo.selected_index, qo.results.len(), direction);
            return Task::none();
        }
        // When another modal overlay (GotoLine, NewItem, DeleteConfirm,
        // CloseDialog, etc.) is active, suppress tree navigation.  The search
        // overlay redirects above have already returned, so only non-search
        // overlays reach this guard.
        if self.active_modal.is_some() {
            return Task::none();
        }
        // Navigate the file tree focus index.
        self.file_tree.nav_and_scroll::<EditorMessage>(direction)
    }

    #[must_use]
    pub fn view(&self) -> Element<'_, EditorMessage> {
        // ── No workspace selected — placeholder ──────────────────────
        if self.selected_workspace_name.is_none() {
            return empty_placeholder(
                text("No workspace selected")
                    .size(24)
                    .color(theme::TEXT_MUTED)
                    .font(theme::FONT_BOLD),
            );
        }

        // ── Split layout ─────────────────────────────────────────────
        let tree_panel = self.build_tree_panel();
        let editor_panel = self.build_editor_panel();

        let split = row![tree_panel, editor_panel]
            .spacing(0)
            .width(Length::Fill)
            .height(Length::Fill);

        // ── Overlay (single match on active_modal) ────────────────────
        let body = column([split.into()])
            .spacing(0)
            .width(Length::Fill)
            .height(Length::Fill);

        // Keep Stack widget type stable — a Column→Stack type change between frames
        // destroys widget state (scroll positions, ContextMenu overlay states),
        // causing stale overlay-to-tab associations. Always return a Stack
        // with a zero-size placeholder when no overlay is present.
        let placeholder: Element<'_, EditorMessage> = widget_helpers::empty_stack_placeholder();

        let overlay: Element<'_, EditorMessage> = match &self.active_modal {
            Some(ModalKind::CloseDialog(tab_idx)) => editor_dialog::build_close_dialog(
                EditorMessage::CloseDialog {
                    tab_index: *tab_idx,
                    action: CloseAction::Save,
                },
                EditorMessage::CloseDialog {
                    tab_index: *tab_idx,
                    action: CloseAction::Discard,
                },
                EditorMessage::CloseDialog {
                    tab_index: *tab_idx,
                    action: CloseAction::Cancel,
                },
                "This file has unsaved changes. What would you like to do?".to_string(),
            ),
            Some(ModalKind::CloseOthers(keep_idx)) => {
                let dirty_count = self
                    .tabs
                    .iter()
                    .enumerate()
                    .filter(|(i, t)| *i != *keep_idx && t.is_dirty)
                    .count();
                let desc = if dirty_count == 1 {
                    "1 file has unsaved changes. What would you like to do?".to_string()
                } else {
                    format!("{dirty_count} files have unsaved changes. What would you like to do?")
                };
                editor_dialog::build_close_dialog(
                    EditorMessage::CloseOthersDialog {
                        keep_idx: *keep_idx,
                        action: CloseAction::Save,
                    },
                    EditorMessage::CloseOthersDialog {
                        keep_idx: *keep_idx,
                        action: CloseAction::Discard,
                    },
                    EditorMessage::CloseOthersDialog {
                        keep_idx: *keep_idx,
                        action: CloseAction::Cancel,
                    },
                    desc,
                )
            }
            Some(ModalKind::GlobalSearch(gs)) => editor_dialog::build_global_search_overlay(gs),
            Some(ModalKind::QuickOpen(qo)) => editor_dialog::build_quick_open_overlay(qo),
            Some(ModalKind::NewItem(target)) => editor_dialog::build_new_item_input(target),
            Some(ModalKind::DeleteConfirm(target)) => {
                editor_dialog::build_delete_confirm_dialog(target)
            }
            // GotoLine and Rename are rendered inline (not as stack overlays).
            Some(ModalKind::GotoLine(_) | ModalKind::Rename(_)) | None => placeholder,
        };

        iced::widget::stack([body.into(), overlay]).into()
    }

    // ── Tree panel ────────────────────────────────────────────────

    fn build_tree_panel(&self) -> Element<'_, EditorMessage> {
        let elements: Vec<Element<'_, EditorMessage>> = self
            .file_tree
            .nodes
            .iter()
            .enumerate()
            .map(|(i, n)| self.render_tree_node(n, 0, 0, i == self.file_tree.nodes.len() - 1))
            .collect();
        // Natural width of every rendered row, in render order, for the
        // auto-sizing tree panel. Replicates the exact row composition:
        // guide (depth*2 box-drawing chars at 14px) + lucide icon
        // (15px dirs / 14px files) + 4px gap + name label at 14px, with the
        // loading/error suffixes and `[⚠]` error marker. The rename
        // text-input mode measures the would-be label so the tree does not
        // snap to its cap while renaming.
        let row_widths = widgets::collect_tree_row_widths(
            &self.file_tree.nodes,
            &self.file_tree.expanded_dirs,
            |node, depth| {
                let guide_chars = depth * 2;
                if node.is_dir {
                    let label: std::borrow::Cow<'_, str> =
                        if self.loading_dirs.contains(&node.full_path) {
                            std::borrow::Cow::Owned(format!("{}  Loading…", node.name))
                        } else if let Some(ref err) = node.error {
                            std::borrow::Cow::Owned(format!("{} [⚠ {err}]", node.name))
                        } else {
                            std::borrow::Cow::Borrowed(&node.name)
                        };
                    widgets::tree_row_natural_width(
                        guide_chars,
                        widgets::TREE_ICON_SIZE,
                        &label,
                        widgets::TREE_FONT_SIZE,
                        None,
                        None,
                    )
                } else {
                    let suffix = node.error.as_ref().map(|_| ("[⚠]", 11.0));
                    widgets::tree_row_natural_width(
                        guide_chars,
                        widgets::TREE_FONT_SIZE,
                        &node.name,
                        widgets::TREE_FONT_SIZE,
                        suffix,
                        None,
                    )
                }
            },
        );
        let panel = widgets::build_tree_panel(&self.file_tree, elements, &row_widths, |viewport| {
            EditorMessage::TreeScrolled(viewport.absolute_offset().y, viewport.bounds().height)
        });

        // Wrap the tree panel with a context menu that fires on empty-space
        // right-clicks. When the user right-clicks on a tree node, the inner
        // node-level ContextMenu captures the event, so this outer fallback
        // does not fire. When right-clicking on empty space below the nodes,
        // no inner ContextMenu captures it, so this one shows the menu.
        ContextMenu::new(
            panel,
            vec![
                MenuItem::new(
                    "New File".into(),
                    EditorMessage::NewFileRequested(String::new()),
                ),
                MenuItem::new(
                    "New Directory".into(),
                    EditorMessage::NewDirectoryRequested(String::new()),
                ),
            ],
        )
        .into()
    }

    /// Check if any child (file or expanded dir) in the node has a git status.
    /// Returns the most "interesting" status: Modified > Added. Only meaningful
    /// for expanded directories (which have children populated).
    fn dir_git_status(&self, node: &widgets::TreeNode) -> Option<GitFileStatus> {
        let mut best: Option<GitFileStatus> = None;
        for child in &node.children {
            if child.is_dir {
                // For expanded subdirectories, recurse into their children.
                if let Some(status) = self.dir_git_status(child) {
                    if best != Some(GitFileStatus::Modified) {
                        best = Some(status);
                    }
                }
            } else {
                match self.git_status_cache.get(&child.full_path) {
                    Some(&GitFileStatus::Modified) => return Some(GitFileStatus::Modified),
                    Some(&GitFileStatus::Added) => {
                        best = Some(GitFileStatus::Added);
                    }
                    None => {}
                }
            }
        }
        best
    }

    /// Check whether a path is gitignored, either directly or because an
    /// ancestor directory is in the gitignore cache (directory inheritance).
    #[must_use]
    fn is_path_ignored(&self, full_path: &str) -> bool {
        if self.git_ignore_cache.is_empty() {
            return false;
        }
        if self.git_ignore_cache.contains(full_path) {
            return true;
        }
        // Walk up the path tree: if any parent directory is ignored,
        // the child inherits that status.
        let mut path = full_path;
        while let Some(pos) = path.rfind('/') {
            path = &path[..pos];
            if self.git_ignore_cache.contains(path) {
                return true;
            }
        }
        false
    }

    /// Shared tree-node row helper.  Builds the guide-lines + icon + name row,
    /// wraps it in a `tree_node_button`, then wraps that in a `ContextMenu`
    /// with caller-specific items prepended before the common items
    /// (Copy Relative Path, Copy Absolute Path, Reveal in Finder).
    ///
    /// # Parameters
    ///
    /// * `guide` — pre-computed tree guide-line prefix string (empty for root-level
    ///   nodes, otherwise contains box-drawing characters for hierarchy lines).
    /// * `icon` — pre-built icon element (size and colour already set).
    /// * `name` — pre-built name element (text content and style already set).
    /// * `highlight` — whether the row should show the highlight style.
    /// * `message` — message to fire when the row is clicked.
    /// * `extra_context_items` — caller-specific context menu items; they are
    ///   placed *before* the three shared items listed above.
    /// * `full_path` — workspace-relative path used to compute absolute/relative
    ///   paths for the shared context menu items.
    #[expect(clippy::too_many_arguments)]
    fn render_tree_node_row<'a>(
        &'a self,
        guide: String,
        icon: Element<'a, EditorMessage>,
        name: Element<'a, EditorMessage>,
        highlight: bool,
        message: EditorMessage,
        extra_context_items: Vec<MenuItem<EditorMessage>>,
        full_path: &str,
    ) -> Element<'a, EditorMessage> {
        let guide_text: Element<'a, EditorMessage> = text(guide)
            .size(widgets::TREE_FONT_SIZE)
            .color(theme::TEXT_MUTED)
            .into();

        let row = row![
            guide_text,
            icon,
            Space::new().width(4),
            name,
            Space::new().width(Length::Fill),
        ]
        .align_y(Alignment::Center)
        .padding([0, 8]);

        let btn = widgets::tree_node_button(row, highlight, Some(message));

        let rel_path = full_path.to_string();

        let mut menu_items: Vec<MenuItem<EditorMessage>> = extra_context_items;
        menu_items.push(MenuItem::new(
            "Copy Relative Path".into(),
            EditorMessage::CopyRelativePath(rel_path),
        ));

        if let Some(abs_path) = self.abs_path(full_path) {
            menu_items.push(MenuItem::new(
                "Copy Absolute Path".into(),
                EditorMessage::CopyAbsolutePath(abs_path.clone()),
            ));
            menu_items.push(MenuItem::new(
                "Reveal in Finder".into(),
                EditorMessage::RevealInFinder(abs_path),
            ));
        }

        ContextMenu::new(btn, menu_items).into()
    }

    fn render_tree_node<'a>(
        &'a self,
        node: &'a widgets::TreeNode,
        depth: usize,
        ancestor_mask: u64,
        is_last: bool,
    ) -> Element<'a, EditorMessage> {
        widgets::render_tree_node(
            node.is_dir,
            || self.render_dir_node(node, depth, ancestor_mask, is_last),
            || self.render_file_node(node, depth, ancestor_mask, is_last),
        )
    }

    fn render_dir_node<'a>(
        &'a self,
        node: &'a widgets::TreeNode,
        depth: usize,
        ancestor_mask: u64,
        is_last: bool,
    ) -> Element<'a, EditorMessage> {
        let is_expanded = self.file_tree.expanded_dirs.contains(&node.full_path);
        let is_loading = self.loading_dirs.contains(&node.full_path);
        let is_ignored = self.is_path_ignored(&node.full_path);
        let icon = if is_expanded {
            lucide::folder_open()
        } else {
            lucide::folder()
        };
        let dir_status = if is_expanded && !is_loading {
            self.dir_git_status(node)
        } else {
            None
        };
        let icon_color = if is_ignored {
            theme::TEXT_MUTED
        } else if is_expanded && dir_status.is_some() {
            match dir_status {
                Some(GitFileStatus::Modified) => theme::STATUS_WARNING,
                Some(GitFileStatus::Added) => theme::STATUS_SUCCESS,
                _ => theme::ACCENT_LIGHT,
            }
        } else if is_expanded {
            theme::ACCENT_LIGHT
        } else {
            theme::TEXT_MUTED
        };

        let (label_text, label_color) = if is_loading {
            (format!("{}  Loading…", node.name), theme::TEXT_MUTED)
        } else if let Some(ref err) = node.error {
            (format!("{} [⚠ {err}]", node.name), theme::STATUS_ERROR)
        } else if is_ignored {
            (node.name.clone(), theme::TEXT_MUTED)
        } else if dir_status.is_some() {
            let color = match dir_status {
                Some(GitFileStatus::Modified) => theme::STATUS_WARNING,
                Some(GitFileStatus::Added) => theme::STATUS_SUCCESS,
                _ => theme::TEXT_SECONDARY,
            };
            (node.name.clone(), color)
        } else {
            (node.name.clone(), theme::TEXT_SECONDARY)
        };

        let is_focused = widgets::tree_node_focused(&self.file_tree, &node.full_path);

        let icon_element: Element<'_, EditorMessage> =
            icon.size(widgets::TREE_ICON_SIZE).color(icon_color).into();
        let name_element: Element<'_, EditorMessage> =
            self.build_rename_input(node).unwrap_or_else(|| {
                text(label_text)
                    .size(widgets::TREE_FONT_SIZE)
                    .color(label_color)
                    .into()
            });

        let guide = widgets::tree_guide_prefix(ancestor_mask, depth, is_last);
        let ctx_menu = self.render_tree_node_row(
            guide,
            icon_element,
            name_element,
            is_focused,
            EditorMessage::ToggleDir(node.full_path.clone()),
            vec![
                MenuItem::new(
                    "New File".into(),
                    EditorMessage::NewFileRequested(node.full_path.clone()),
                ),
                MenuItem::new(
                    "New Directory".into(),
                    EditorMessage::NewDirectoryRequested(node.full_path.clone()),
                ),
                MenuItem::new(
                    "Rename".into(),
                    EditorMessage::RenameRequested(node.full_path.clone()),
                ),
                MenuItem::new(
                    "Delete".into(),
                    EditorMessage::DeleteDirectoryRequested(node.full_path.clone()),
                ),
            ],
            &node.full_path,
        );

        let mut col = column![ctx_menu].spacing(0);
        if is_expanded {
            for elem in widgets::render_tree_children(
                &node.children,
                depth,
                ancestor_mask,
                is_last,
                |child, d, mask, last| self.render_tree_node(child, d, mask, last),
            ) {
                col = col.push(elem);
            }
        }
        col.into()
    }

    fn render_file_node<'a>(
        &'a self,
        node: &'a widgets::TreeNode,
        depth: usize,
        ancestor_mask: u64,
        is_last: bool,
    ) -> Element<'a, EditorMessage> {
        let is_selected = self.selected_file.as_deref() == Some(&node.full_path);

        let guide = widgets::tree_guide_prefix(ancestor_mask, depth, is_last);

        let icon = lucide::file::<iced::Theme, iced::Renderer>();
        let is_ignored = self.is_path_ignored(&node.full_path);
        let icon_color = if is_selected {
            theme::ACCENT
        } else if is_ignored {
            theme::TEXT_FAINT
        } else {
            theme::TEXT_MUTED
        };

        let git_status = self.git_status_cache.get(&node.full_path);
        let name_color = if is_selected {
            theme::TEXT_PRIMARY
        } else if node.error.is_some() {
            theme::STATUS_ERROR
        } else if is_ignored {
            theme::TEXT_MUTED
        } else if git_status == Some(&GitFileStatus::Modified) {
            theme::STATUS_WARNING
        } else if git_status == Some(&GitFileStatus::Added) {
            theme::STATUS_SUCCESS
        } else {
            theme::TEXT_SECONDARY
        };
        let name_weight = if is_selected {
            iced::font::Weight::Bold
        } else {
            iced::font::Weight::Normal
        };

        let name_text: Element<'a, EditorMessage> =
            self.build_rename_input(node).unwrap_or_else(|| {
                if node.error.is_some() {
                    row![
                        text(&node.name)
                            .size(widgets::TREE_FONT_SIZE)
                            .color(name_color)
                            .font(iced::Font {
                                weight: name_weight,
                                ..theme::FONT_REGULAR
                            }),
                        Space::new().width(4),
                        text("[⚠]").size(11).color(theme::STATUS_ERROR),
                    ]
                    .align_y(Alignment::Center)
                    .into()
                } else {
                    text(&node.name)
                        .size(widgets::TREE_FONT_SIZE)
                        .color(name_color)
                        .font(iced::Font {
                            weight: name_weight,
                            ..theme::FONT_REGULAR
                        })
                        .into()
                }
            });

        let is_focused = widgets::tree_node_focused(&self.file_tree, &node.full_path);

        let icon_element: Element<'_, EditorMessage> =
            icon.size(widgets::TREE_FONT_SIZE).color(icon_color).into();

        self.render_tree_node_row(
            guide,
            icon_element,
            name_text,
            is_selected || is_focused,
            EditorMessage::SelectFile(node.full_path.clone()),
            vec![
                MenuItem::new(
                    "Rename".into(),
                    EditorMessage::RenameRequested(node.full_path.clone()),
                ),
                MenuItem::new(
                    "Delete".into(),
                    EditorMessage::DeleteFileRequested(node.full_path.clone()),
                ),
            ],
            &node.full_path,
        )
    }

    // ── Editor panel ──────────────────────────────────────────────

    fn build_editor_panel(&self) -> Element<'_, EditorMessage> {
        if self.tabs.is_empty() {
            return empty_placeholder(
                text("Select a file to edit")
                    .size(18)
                    .color(theme::TEXT_MUTED),
            );
        }

        let tab_bar = self.build_tab_bar();
        let find_bar = self.build_find_replace_bar();
        let go_to_line = self.build_go_to_line_bar();
        let editor_widget = self.build_editor_widget();

        let mut col = column![tab_bar].spacing(0).width(Length::Fill);
        if let Some(bar) = find_bar {
            col = col.push(bar);
        } else if let Some(bar) = go_to_line {
            // Go-to-line uses the same UI slot; only one bar visible at a time.
            col = col.push(bar);
        }
        col = col.push(editor_widget);

        col.height(Length::Fill).into()
    }

    fn build_tab_bar(&self) -> Element<'_, EditorMessage> {
        let mut tab_buttons: Vec<Element<'_, EditorMessage>> = Vec::new();

        for (i, tab) in self.tabs.iter().enumerate() {
            let is_active = i == self.active_tab_index;

            // Dirty indicator dot.
            let dirty_dot: Option<Element<'_, EditorMessage>> = if tab.is_dirty {
                Some(
                    lucide::circle::<iced::Theme, iced::Renderer>()
                        .size(8)
                        .color(theme::STATUS_WARNING)
                        .into(),
                )
            } else {
                None
            };

            let name_color = if is_active {
                theme::ACCENT
            } else {
                theme::TEXT_MUTED
            };
            let name_text = text(&tab.file_name).size(12).color(name_color);

            let mut tab_row = row![].spacing(2).align_y(Alignment::Center);
            if let Some(dot) = dirty_dot {
                tab_row = tab_row.push(dot);
            }
            tab_row = tab_row.push(name_text).push(widgets::tab_close_button(
                is_active,
                EditorMessage::TabClosed(i),
            ));

            let tab_btn = button(tab_row.padding([8, 8]))
                .on_press(EditorMessage::TabSelected(i))
                .style(theme::tab_button_style(is_active))
                .padding(0);

            let tab_abs_path = tab.path.clone();
            let tab_rel_path = self
                .selected_workspace_path
                .as_ref()
                .and_then(|ws| {
                    Path::new(&tab_abs_path)
                        .strip_prefix(ws)
                        .ok()
                        .map(|p| p.to_string_lossy().to_string())
                })
                .unwrap_or_else(|| tab_abs_path.clone());

            let ctx_menu = ContextMenu::new(
                tab_btn,
                vec![
                    MenuItem::new("Close".into(), EditorMessage::TabClosed(i)),
                    MenuItem::new("Close Others".into(), EditorMessage::CloseOtherTabs(i)),
                    MenuItem::new(
                        "Copy Relative Path".into(),
                        EditorMessage::CopyRelativePath(tab_rel_path),
                    ),
                    MenuItem::new(
                        "Copy Absolute Path".into(),
                        EditorMessage::CopyAbsolutePath(tab_abs_path),
                    ),
                ],
            );

            tab_buttons.push(ctx_menu.into());
        }

        widgets::tab_scrollable(
            tab_buttons,
            Some(self.tab_scroll_id.clone()),
            Some(|viewport: scrollable::Viewport| {
                EditorMessage::TabBarScrolled(viewport.absolute_offset().x, viewport.bounds().width)
            }),
        )
    }

    fn build_find_replace_bar(&self) -> Option<Element<'_, EditorMessage>> {
        let idx = self.active_tab_idx()?;
        let path = &self.tabs[idx].path;
        let state = self.tab_contents.get(path)?.find_replace_state.as_ref()?;

        let search_input = text_input("Find…", &state.query)
            .on_input(EditorMessage::FindQueryInput)
            .on_submit(EditorMessage::FindNext)
            .id(Id::new(FIND_SEARCH_ID))
            .style(widgets::text_input_style)
            .width(Length::Fixed(200.0))
            .size(13);

        let replace_input = text_input("Replace…", &state.replace)
            .on_input(EditorMessage::FindReplaceInput)
            .on_submit(EditorMessage::FindNext)
            .id(Id::new(FIND_REPLACE_ID))
            .style(widgets::text_input_style)
            .width(Length::Fixed(160.0))
            .size(13);

        let total = state.matches.len();
        let match_label = if !state.query.is_empty() && state.query.len() < 2 {
            "Min 2 chars".to_string()
        } else if !state.query.is_empty() && total > 0 {
            format!("{}/{}", state.current_match_idx.saturating_add(1), total)
        } else if !state.query.is_empty() {
            "0/0".to_string()
        } else {
            String::new()
        };

        let prev_btn = button(text("").size(14).color(theme::TEXT_SECONDARY))
            .on_press(EditorMessage::FindPrev)
            .style(theme::button_transparent)
            .padding([2, 8]);

        let next_btn = button(text("").size(14).color(theme::TEXT_SECONDARY))
            .on_press(EditorMessage::FindNext)
            .style(theme::button_transparent)
            .padding([2, 8]);

        let replace_btn = button(text("Replace").size(11).color(theme::TEXT_SECONDARY))
            .on_press(EditorMessage::FindReplace)
            .style(theme::button_transparent)
            .padding([2, 6]);

        let replace_all_btn = button(text("All").size(11).color(theme::TEXT_SECONDARY))
            .on_press(EditorMessage::FindReplaceAll)
            .style(theme::button_transparent)
            .padding([2, 6]);

        // Case sensitivity toggle: "Aa" label, highlighted when active.
        let case_label_color = if state.case_sensitive {
            theme::ACCENT_LIGHT
        } else {
            theme::TEXT_SECONDARY
        };
        let case_btn = button(text("Aa").size(11).color(case_label_color))
            .on_press(EditorMessage::FindToggleCaseSensitivity)
            .style(theme::button_transparent)
            .padding([2, 6]);

        let bar = row![
            search_input,
            replace_input,
            prev_btn,
            text(match_label).size(12).color(theme::TEXT_MUTED),
            next_btn,
            Space::new().width(Length::Fixed(4.0)),
            case_btn,
            replace_btn,
            replace_all_btn,
        ]
        .spacing(4)
        .align_y(Alignment::Center)
        .padding([4, 8]);

        Some(
            container(bar)
                .style(theme::container_bar)
                .width(Length::Fill)
                .into(),
        )
    }

    /// Build the go-to-line input bar. Appears in the same slot as the find
    /// bar (below the tab bar) and is mutually exclusive with it.
    fn build_go_to_line_bar(&self) -> Option<Element<'_, EditorMessage>> {
        let ModalKind::GotoLine(input_text) = self.active_modal.as_ref()? else {
            return None;
        };

        let line_input = text_input("Line #", input_text)
            .on_input(EditorMessage::GoToLineInput)
            .on_submit(EditorMessage::GoToLineGo)
            .id(Id::new(GOTO_LINE_INPUT_ID))
            .style(widgets::text_input_style)
            .width(Length::Fixed(120.0))
            .size(13);

        let go_btn = button(text("Go").size(12).color(theme::TEXT_SECONDARY))
            .on_press(EditorMessage::GoToLineGo)
            .style(theme::button_transparent)
            .padding([2, 8]);

        let bar = row![
            text("Go to line:").size(12).color(theme::TEXT_MUTED),
            Space::new().width(4),
            line_input,
            go_btn,
        ]
        .spacing(4)
        .align_y(Alignment::Center)
        .padding([4, 8]);

        Some(
            container(bar)
                .style(theme::container_bar)
                .width(Length::Fill)
                .into(),
        )
    }

    fn build_editor_widget(&self) -> Element<'_, EditorMessage> {
        let Some(idx) = self.active_tab_idx() else {
            return empty_placeholder(
                text("No file selected")
                    .size(EDITOR_FONT_SIZE)
                    .color(theme::TEXT_MUTED),
            );
        };

        let path = &self.tabs[idx].path;
        let Some(tab_data) = self.tab_contents.get(path) else {
            return empty_placeholder(
                text("Error: tab content missing")
                    .size(EDITOR_FONT_SIZE)
                    .color(theme::STATUS_ERROR),
            );
        };

        // ── Build editor widget ────────────────────────────────────────
        let content = &tab_data.content;
        let tree_focused = self.file_tree.tree_focused;
        let find_bar_open = tab_data.find_replace_state.is_some();
        // Modal overlays own keyboard input entirely — block all editor keys.
        let modal_overlay_open = self.active_modal.is_some();
        // Find/replace allows cursor navigation while its text inputs are focused.
        let ignore_keyboard = tree_focused || modal_overlay_open || find_bar_open;

        // Compute match highlight tuples from find/replace state.
        // Each tuple is (line, byte_col_start, byte_col_end) for
        // cosmic_text::Cursor-based highlight rendering.
        let (match_tuples, match_current_idx) = tab_data
            .find_replace_state
            .as_ref()
            .map(|state| {
                let text = tab_data.content.text();
                let tuples: Vec<(usize, usize, usize)> = state
                    .matches
                    .iter()
                    .filter_map(|range| {
                        let (line, byte_col_start, line_start) =
                            byte_offset_to_line_byte_col(&text, range.start)?;
                        let byte_col_end = range.end.saturating_sub(line_start);
                        Some((line, byte_col_start, byte_col_end))
                    })
                    .collect();
                (tuples, state.current_match_idx)
            })
            .unwrap_or_default();

        // ── Bracket matching ───────────────────────────────────────────
        // Compute matching bracket pair from cursor position (if any).
        let cursor = content.cursor();
        let bracket_pair = if !ignore_keyboard && cursor.selection.is_none() {
            let text = content.text();
            super::editor_widget::find_matching_bracket(&text, cursor.line, cursor.column)
        } else {
            None
        };

        Self::build_highlighted_editor(
            content,
            Some(path.as_str()),
            ignore_keyboard,
            match_tuples,
            match_current_idx,
            bracket_pair,
        )
    }

    /// Build an [`Element`] from an editor content reference.
    fn build_highlighted_editor<'a>(
        content: &'a super::editor_widget::EditorBuffer,
        buffer_key: Option<&'a str>,
        ignore_keyboard: bool,
        matches: Vec<(usize, usize, usize)>,
        match_current_idx: usize,
        bracket_pair: Option<super::editor_widget::BracketPair>,
    ) -> Element<'a, EditorMessage> {
        let editor = super::editor_widget::EditorWidget::new(content)
            .padding(8.0)
            .ignore_keyboard(ignore_keyboard)
            .matches(matches, match_current_idx)
            .bracket_pair(bracket_pair)
            .buffer_key(buffer_key);
        let element = iced::Element::new(editor);
        let mapped = element.map(EditorMessage::EditorAction);

        container(mapped)
            .width(Length::Fill)
            .height(Length::Fill)
            .style(theme::base_container_style)
            .into()
    }

    // ── Context menu action handlers ───────────────────────────────

    /// Perform file deletion: close tab, delete file, re-read parent directory.
    fn perform_file_delete(&mut self, target: &DeleteConfirmTarget) -> Task<EditorMessage> {
        // Close tab if open.
        if let Some(tab_idx) = self.tabs.iter().position(|t| t.path == target.abs_path) {
            self.remove_tab_at(tab_idx);
        }
        // Clear selection if it matches the deleted file.
        // selected_file stores relative paths (set by SelectFile handler).
        if self.selected_file.as_deref() == Some(&target.path) {
            self.selected_file = None;
        }
        // Clean up mtime and toast guard.
        self.file_mtimes.remove(&target.abs_path);
        self.deleted_file_toasted.remove(&target.abs_path);

        self.perform_delete_with_refresh(
            target.abs_path.clone(),
            &target.path,
            "file",
            None,
            |abs_path| async move {
                tokio::fs::remove_file(&abs_path)
                    .await
                    .map_err(|e| e.to_string())
            },
        )
    }

    /// Perform directory deletion: remove dir, close affected tabs.
    ///
    /// The tree/cache prune is deferred to the delete-success path (via
    /// [`EditorMessage::DirDeleted`]) so a failed delete — e.g. permission
    /// denied — leaves a still-existing directory fully intact in the tree.
    fn perform_dir_delete(&mut self, target: &DeleteConfirmTarget) -> Task<EditorMessage> {
        let abs_prefix = format!("{}/", target.abs_path);

        // Collect open tabs inside this directory (close in reverse order).
        let mut affected_indices: Vec<usize> = self
            .tabs
            .iter()
            .enumerate()
            .filter(|(_, t)| t.path.starts_with(&abs_prefix))
            .map(|(i, _)| i)
            .collect();
        affected_indices.sort_unstable_by(|a, b| b.cmp(a));

        for &idx in &affected_indices {
            self.remove_tab_at(idx);
        }

        self.perform_delete_with_refresh(
            target.abs_path.clone(),
            &target.path,
            "directory",
            Some(EditorMessage::DirDeleted {
                dir_path: target.path.clone(),
                workspace_path: self.selected_workspace_path.clone().unwrap_or_default(),
            }),
            |abs_path| async move {
                tokio::fs::remove_dir_all(&abs_path)
                    .await
                    .map_err(|e| e.to_string())
            },
        )
    }

    /// Shared preamble for deleting a file or directory: bump a generation,
    /// run the async delete operation, then on success either emit
    /// `success_msg` (when provided — e.g. a directory delete that must
    /// prune tree state) or re-read the parent directory and emit a
    /// [`DirExpanded`] message.
    ///
    /// `delete_op` receives the absolute path and returns `Result<(), String>`.
    /// `error_label` is used in the toast message on failure (e.g. "file" or
    /// "directory").
    fn perform_delete_with_refresh<D, F>(
        &mut self,
        abs_path: String,
        rel_path: &str,
        error_label: &'static str,
        success_msg: Option<EditorMessage>,
        delete_op: D,
    ) -> Task<EditorMessage>
    where
        D: FnOnce(String) -> F + 'static + Send,
        F: Future<Output = Result<(), String>> + 'static + Send,
    {
        let parent_dir = {
            let path = Path::new(rel_path);
            path.parent()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default()
        };
        let ws_path = self.selected_workspace_path.clone().unwrap_or_default();
        // Only the file-delete path re-reads the parent via a DirExpanded
        // message and thus needs a registered generation slot. The
        // directory-delete path emits DirDeleted, which prunes state and
        // re-reads the parent with a fresh generation of its own —
        // registering a slot here would leave an orphaned (never consumed)
        // generation entry.
        let r#gen = if success_msg.is_none() {
            let r#gen = self.bump_generation();
            // Register the generation so DirExpanded handler accepts the result.
            self.dir_generations.insert(parent_dir.clone(), r#gen);
            Some(r#gen)
        } else {
            None
        };

        Task::perform(
            async move {
                if let Err(e) = delete_op(abs_path).await {
                    return EditorMessage::Toast(super::ToastMessage::Error(format!(
                        "Failed to delete {error_label}: {e}"
                    )));
                }
                if let Some(msg) = success_msg {
                    return msg;
                }
                // Re-read parent directory (the file-delete path registered
                // the generation slot above).
                let r#gen = r#gen.expect("file-delete path always registers a generation");
                dir_expanded_msg(ws_path, parent_dir, r#gen, false).await
            },
            |msg| msg,
        )
    }

    /// Perform new file/directory creation, then re-read parent directory.
    fn perform_create_item(&mut self, target: &NewItemTarget, name: &str) -> Task<EditorMessage> {
        let abs_parent = target.abs_parent.clone();
        let parent_dir = target.parent_dir.clone();
        let is_dir = target.is_dir;
        let ws_root = target.ws_root.clone();

        let abs_new_path_str = Path::new(&abs_parent)
            .join(name)
            .to_string_lossy()
            .to_string();
        let r#gen = self.bump_generation();
        // Register the generation so DirExpanded handler accepts the result.
        self.dir_generations.insert(parent_dir.clone(), r#gen);

        Task::perform(
            async move {
                if is_dir {
                    if let Err(e) = tokio::fs::create_dir(&abs_new_path_str).await {
                        return EditorMessage::Toast(super::ToastMessage::Error(format!(
                            "Failed to create directory: {e}"
                        )));
                    }
                } else if let Err(e) = tokio::fs::write(&abs_new_path_str, "").await {
                    return EditorMessage::Toast(super::ToastMessage::Error(format!(
                        "Failed to create file: {e}"
                    )));
                }
                dir_expanded_msg(ws_root, parent_dir, r#gen, false).await
            },
            |msg| msg,
        )
    }

    /// Fire-and-forget reveal in system file manager.
    fn perform_reveal_in_finder(path: String) -> Task<EditorMessage> {
        Task::perform(
            async move {
                #[cfg(target_os = "macos")]
                {
                    if let Err(e) = std::process::Command::new("open")
                        .arg("-R")
                        .arg(&path)
                        .spawn()
                    {
                        tracing::warn!("Failed to open Finder for {path}: {e}");
                    }
                }
                #[cfg(target_os = "windows")]
                {
                    if let Err(e) = std::process::Command::new("explorer")
                        .arg("/select,")
                        .arg(&path)
                        .spawn()
                    {
                        tracing::warn!("Failed to open Explorer for {path}: {e}");
                    }
                }
                #[cfg(not(any(target_os = "macos", target_os = "windows")))]
                {
                    if let Some(parent) = std::path::Path::new(&path).parent() {
                        if let Err(e) = std::process::Command::new("xdg-open").arg(parent).spawn() {
                            tracing::warn!("Failed to open file manager for {path}: {e}");
                        }
                    }
                }
            },
            |()| (),
        )
        .discard::<EditorMessage>()
    }
}

// ── Keyboard shortcut mapping ──────────────────────────────────────

/// Map a keyboard event to an [`EditorMessage`] action, or `None` if unhandled.
///
/// This function is the `filter_map` predicate used by `subscription()` to
/// translate keyboard events into editor actions.  It is extracted to a
/// standalone function so that `subscription()` focuses on timer setup and
/// the shortcut logic is independently readable (and potentially testable).
fn map_editor_shortcut(event: keyboard::Event) -> Option<EditorMessage> {
    use keyboard::Key;
    let (key, modifiers, physical_key) = super::parse_key_press(event)?;
    let km = super::detect_keyboard_mods(modifiers);

    // Helper: match a Character key by its Latin equivalent.
    let latin = |target: char| -> bool { key.to_latin(physical_key) == Some(target) };

    // Ctrl+B / Cmd+B → toggle tree focus.
    if km.is_shortcut_platform_mod() && latin('b') {
        return Some(EditorMessage::TreeFocusToggled);
    }
    // Cmd+Shift+F / Ctrl+Shift+F → global search (find-in-files).
    // Must appear BEFORE the Cmd+F / Ctrl+F check so Cmd+Shift+F
    // doesn't also trigger FindToggle.
    if km.is_platform_mod && !km.altgr_active && modifiers.shift() && latin('f') {
        return Some(EditorMessage::GlobalSearchToggle);
    }
    // Cmd+F / Ctrl+F → toggle find/replace bar.
    // Guard: Cmd+Shift+F handled above, so !modifiers.shift() prevents
    // Cmd+Shift+F from also triggering FindToggle.
    if km.is_shortcut_platform_mod() && !modifiers.shift() && latin('f') {
        return Some(EditorMessage::FindToggle);
    }
    // Cmd+Z / Ctrl+Z → undo.  Check shift first so Cmd+Shift+Z / Ctrl+Shift+Z → redo.
    if km.is_shortcut_platform_mod() && latin('z') {
        if modifiers.shift() {
            return Some(EditorMessage::Redo);
        }
        return Some(EditorMessage::Undo);
    }
    // Cmd+S / Ctrl+S → save.
    if km.is_shortcut_platform_mod() && latin('s') {
        return Some(EditorMessage::SaveActiveTab);
    }
    // Ctrl+Tab / Ctrl+Shift+Tab → switch tabs.
    // On macOS, modifiers.control() is used directly (not is_platform_mod)
    // since Cmd+Tab is captured by the OS for app switching.
    if modifiers.control() && matches!(key, Key::Named(keyboard::key::Named::Tab)) {
        return if modifiers.shift() {
            Some(EditorMessage::TabSwitchPrev)
        } else {
            Some(EditorMessage::TabSwitchNext)
        };
    }
    // Ctrl+W → close tab (all platforms). Cmd+W on macOS is typically
    // captured by the window manager to close the window, so we use
    // Ctrl+W consistently.
    if !km.altgr_active && modifiers.control() && latin('w') {
        return Some(EditorMessage::CloseActiveTab);
    }
    // Go-to-line: Cmd+L on macOS, Ctrl+G on other platforms.
    #[cfg(target_os = "macos")]
    {
        if modifiers.command() && !modifiers.control() && latin('l') {
            return Some(EditorMessage::GoToLineToggle);
        }
    }
    #[cfg(not(target_os = "macos"))]
    {
        if !km.altgr_active && modifiers.control() && latin('g') {
            return Some(EditorMessage::GoToLineToggle);
        }
    }
    // Quick open: Cmd+P / Ctrl+P
    if km.is_shortcut_platform_mod() && latin('p') {
        return Some(EditorMessage::QuickOpenToggle);
    }
    // Refresh file tree: Cmd+R / Ctrl+R
    if km.is_shortcut_platform_mod() && latin('r') {
        return Some(EditorMessage::RefreshFileTree);
    }
    // Find next/prev: Cmd+G / F3 → FindNext, Cmd+Shift+G / Shift+F3 → FindPrev
    // macOS uses Cmd+G; non-macOS uses Ctrl+G for go-to-line (already mapped),
    // so F3 and Shift+F3 serve as the cross-platform find shortcuts.
    #[cfg(target_os = "macos")]
    if modifiers.command() && !modifiers.control() && latin('g') {
        return if modifiers.shift() {
            Some(EditorMessage::FindPrev)
        } else {
            Some(EditorMessage::FindNext)
        };
    }
    // F3 / Shift+F3 (all platforms)
    if matches!(key, Key::Named(keyboard::key::Named::F3)) {
        return if modifiers.shift() {
            Some(EditorMessage::FindPrev)
        } else {
            Some(EditorMessage::FindNext)
        };
    }
    // Shift+Enter → previous match (for use in the find/replace bar;
    // no-op when find bar is closed — handler checks state).
    if modifiers.shift() && matches!(key, Key::Named(keyboard::key::Named::Enter)) {
        return Some(EditorMessage::FindPrev);
    }
    // Arrow key navigation: when quick-open is active, arrow keys
    // navigate the results list (handled in the update method by
    // checking quick_open state before tree focus).
    match &key {
        Key::Named(named) => match named {
            keyboard::key::Named::ArrowUp => Some(EditorMessage::TreeNavUp),
            keyboard::key::Named::ArrowDown => Some(EditorMessage::TreeNavDown),
            keyboard::key::Named::ArrowLeft => Some(EditorMessage::TreeNavLeft),
            keyboard::key::Named::ArrowRight => Some(EditorMessage::TreeNavRight),
            keyboard::key::Named::Enter => Some(EditorMessage::TreeNavEnter),
            _ => None,
        },
        _ => None,
    }
}

// ── Find/Replace helpers ───────────────────────────────────────────

impl FindReplaceState {
    /// Recompute matches against the current text and jump to the first match (or reset the index).
    fn recompute(&mut self, content: &EditorBuffer) {
        let text = content.text();
        self.matches = compute_text_matches(&text, &self.query, self.case_sensitive);
        auto_jump_to_first_match(&text, content, self);
    }
}

/// Convert a byte offset to (line, byte column within line, line byte start).
#[must_use]
fn byte_offset_to_line_byte_col(text: &str, offset: usize) -> Option<(usize, usize, usize)> {
    if offset > text.len() {
        return None;
    }
    let (line, line_start) = super::text_rendering::byte_line_and_start(text, offset);
    Some((line, offset - line_start, line_start))
}

/// Auto-jump the cursor to the first find match and reset the match index to 0.
fn auto_jump_to_first_match(
    text: &str,
    content: &super::editor_widget::EditorBuffer,
    state: &mut FindReplaceState,
) {
    state.current_match_idx = 0;
    if let Some(range) = state.matches.first() {
        let (line, col) = byte_offset_to_line_col(text, range.start);
        content.move_to(line, col);
    }
}

#[cfg(test)]
#[path = "editor_tests.rs"]
mod tests;