term39 1.5.1

A modern, retro-styled terminal multiplexer with a classic MS-DOS aesthetic
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
use super::base::ResizeEdge;
use super::terminal_window::{MouseContentPosition, TerminalWindow};
use crate::app::app_state::AutoScrollDirection;
use crate::app::session::{self, SessionState, WindowSnapshot};
use crate::rendering::{Charset, Theme, VideoBuffer};
use crate::term_emu::ShellConfig;
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use std::collections::HashMap;
use std::io;
use std::time::Instant;

/// Focus state - desktop, a specific window, or the topbar
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FocusState {
    Desktop,
    Window(u32),
    Topbar,
}

/// Events from the persist daemon that the event loop needs to handle
#[cfg(unix)]
#[derive(Debug)]
#[allow(dead_code)]
pub enum PersistEvent {
    /// A window's shell exited on the daemon side
    WindowClosed(u32),
    /// A window was created on the daemon side
    WindowCreated(u32),
    /// An error occurred
    Error(String),
    /// The daemon connection was lost
    DaemonDied,
}

/// Window manager handles z-order, focus, and interactions
pub struct WindowManager {
    windows: Vec<TerminalWindow>,
    next_id: u32,
    focus: FocusState,

    // Window ID to Vec index cache for O(1) lookups
    window_index_cache: HashMap<u32, usize>,

    // Interaction state
    dragging: Option<DragState>,
    resizing: Option<ResizeState>,
    scrollbar_dragging: Option<ScrollbarDragState>,
    last_click: Option<LastClick>,
    current_snap_zone: Option<SnapZone>,

    // Cascading window position tracking
    last_window_x: Option<u16>,
    last_window_y: Option<u16>,

    // Shell configuration for new terminal windows
    shell_config: ShellConfig,

    // Pivot state for tiled window resizing
    pivot_dragging: Option<PivotDragState>,
    /// Current split ratio for horizontal division (left column width / total)
    h_split_ratio: f32,
    /// Current split ratio for vertical division (top row height / total)
    v_split_ratio: f32,
    /// Last pivot click for double-click detection
    last_pivot_click: Option<Instant>,

    /// Persist mode client connection (Unix only)
    #[cfg(unix)]
    persist_client: Option<crate::persist::client::PersistClient>,
}

/// Snap zones for window positioning
#[derive(Clone, Copy, Debug, PartialEq)]
enum SnapZone {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
    FullLeft,
    FullRight,
}

/// Snap threshold in pixels
const SNAP_THRESHOLD: u16 = 25;

#[derive(Clone, Copy, Debug)]
struct DragState {
    window_id: u32,
    offset_x: i16,
    offset_y: i16,
}

#[derive(Clone, Copy, Debug)]
struct ResizeState {
    window_id: u32,
    edge: ResizeEdge,
    start_x: u16,
    start_y: u16,
    start_width: u16,
    start_height: u16,
    start_window_x: u16,
    start_window_y: u16,
}

#[derive(Clone, Copy, Debug)]
struct ScrollbarDragState {
    window_id: u32,
    #[allow(dead_code)]
    start_offset: usize,
}

#[derive(Clone, Debug)]
struct LastClick {
    window_id: u32,
    x: u16,
    y: u16,
    time: Instant,
}

/// State for tracking pivot dragging
#[derive(Clone, Copy, Debug)]
struct PivotDragState {
    /// Initial mouse X position when drag started
    start_x: u16,
    /// Initial mouse Y position when drag started
    start_y: u16,
    /// Initial split ratio for horizontal division (0.0-1.0)
    start_h_ratio: f32,
    /// Initial split ratio for vertical division (0.0-1.0)
    start_v_ratio: f32,
}

impl WindowManager {
    pub fn new() -> Self {
        Self {
            windows: Vec::new(),
            next_id: 1,
            focus: FocusState::Desktop,
            window_index_cache: HashMap::new(),
            dragging: None,
            resizing: None,
            scrollbar_dragging: None,
            last_click: None,
            current_snap_zone: None,
            last_window_x: None,
            last_window_y: None,
            shell_config: ShellConfig::default(),
            pivot_dragging: None,
            h_split_ratio: 0.5,
            v_split_ratio: 0.5,
            last_pivot_click: None,
            #[cfg(unix)]
            persist_client: None,
        }
    }

    // =========================================================================
    // Window Index Cache Management (O(1) lookups)
    // =========================================================================

    /// Rebuild the entire window index cache
    /// Called after operations that may invalidate multiple indices
    #[inline]
    fn rebuild_cache(&mut self) {
        self.window_index_cache.clear();
        for (idx, window) in self.windows.iter().enumerate() {
            self.window_index_cache.insert(window.id(), idx);
        }
    }

    /// Get window index by ID (O(1) lookup)
    #[inline]
    fn get_window_index(&self, id: u32) -> Option<usize> {
        self.window_index_cache.get(&id).copied()
    }

    /// Get immutable reference to window by ID (O(1) lookup)
    #[inline]
    fn get_window_by_id(&self, id: u32) -> Option<&TerminalWindow> {
        self.get_window_index(id)
            .and_then(|idx| self.windows.get(idx))
    }

    /// Get mutable reference to window by ID (O(1) lookup)
    #[inline]
    fn get_window_by_id_mut(&mut self, id: u32) -> Option<&mut TerminalWindow> {
        self.get_window_index(id)
            .and_then(|idx| self.windows.get_mut(idx))
    }

    /// Create a new WindowManager with a custom shell configuration
    pub fn with_shell_config(shell_config: ShellConfig) -> Self {
        let mut manager = Self::new();
        manager.shell_config = shell_config;
        manager
    }

    /// Set the shell configuration
    #[allow(dead_code)]
    pub fn set_shell_config(&mut self, shell_config: ShellConfig) {
        self.shell_config = shell_config;
    }

    /// Get the current shell configuration
    #[allow(dead_code)]
    pub fn shell_config(&self) -> &ShellConfig {
        &self.shell_config
    }

    /// Calculate dynamic window size based on screen dimensions
    /// Returns (width, height) sized to ~2/3 of usable screen area
    /// with minimum constraints for usability
    pub fn calculate_window_size(buffer_width: u16, buffer_height: u16) -> (u16, u16) {
        // Usable height excludes topbar (1) and bottom bar (1)
        let usable_height = buffer_height.saturating_sub(2);

        // Target ~2/3 of screen size, with min/max constraints
        let width = ((buffer_width * 2) / 3).clamp(40, 200);
        let height = ((usable_height * 2) / 3).clamp(10, 60);

        (width, height)
    }

    /// Calculate next cascading window position
    /// Returns (x, y) for the next window, offsetting by 2 from the last position
    /// Resets to centered position if it would go off-screen
    pub fn get_cascade_position(
        &self,
        width: u16,
        height: u16,
        buffer_width: u16,
        buffer_height: u16,
    ) -> (u16, u16) {
        // Minimum y position (below topbar at y=0)
        const MIN_Y: u16 = 1;

        // Default centered position (ensuring y is below topbar)
        let default_x = (buffer_width.saturating_sub(width)) / 2;
        let default_y = ((buffer_height.saturating_sub(height)) / 2).max(MIN_Y);

        // If we have a last position, cascade from it
        if let (Some(last_x), Some(last_y)) = (self.last_window_x, self.last_window_y) {
            let new_x = last_x.saturating_add(2);
            let new_y = last_y.saturating_add(2).max(MIN_Y); // Ensure y is below topbar

            // Check if the new position would go off-screen
            // Window needs to have at least some visible area (not completely off-screen)
            let max_x = buffer_width.saturating_sub(width);
            let max_y = buffer_height.saturating_sub(height);

            if new_x <= max_x && new_y <= max_y && new_y >= MIN_Y {
                (new_x, new_y)
            } else {
                // Reset to centered position if we'd go off-screen or above topbar
                (default_x, default_y)
            }
        } else {
            // First window, use centered position
            (default_x, default_y)
        }
    }

    /// Create and add a new terminal window (returns window ID or error message)
    pub fn create_window(
        &mut self,
        x: u16,
        y: u16,
        width: u16,
        height: u16,
        title: String,
        initial_command: Option<String>,
    ) -> Result<u32, String> {
        // In persist mode, route through daemon so PTYs survive client exit
        #[cfg(unix)]
        if self.persist_client.is_some() {
            return self.create_window_via_daemon(x, y, width, height, title, initial_command);
        }

        let id = self.next_id;
        self.next_id += 1;

        // Unfocus all windows
        for w in &mut self.windows {
            w.set_focused(false);
        }

        // Track this position for cascading
        self.last_window_x = Some(x);
        self.last_window_y = Some(y);

        // Create terminal window
        match TerminalWindow::new(
            id,
            x,
            y,
            width,
            height,
            title.clone(),
            initial_command.clone(),
            &self.shell_config,
        ) {
            Ok(mut terminal_window) => {
                terminal_window.set_focused(true);
                let idx = self.windows.len();
                self.windows.push(terminal_window);
                self.window_index_cache.insert(id, idx);
                self.focus = FocusState::Window(id);
                Ok(id)
            }
            Err(e) => {
                // Format error message for user
                if let Some(cmd) = initial_command {
                    Err(format!("Failed to launch '{}': {}", cmd, e))
                } else {
                    Err(format!("Failed to create terminal: {}", e))
                }
            }
        }
    }

    /// Automatically position windows based on count (snap corners pattern)
    /// Called when buffer size is known
    /// If `gaps` is true, adds spacing between windows and screen edges
    /// For 2-4 windows with gaps, uses current split ratios (for pivot support)
    pub fn auto_position_windows(&mut self, buffer_width: u16, buffer_height: u16, gaps: bool) {
        let visible_count = self
            .windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .count();

        if visible_count == 0 {
            return;
        }

        // For 2-4 windows with gaps, use split ratios (pivot-aware positioning)
        if gaps && (2..=4).contains(&visible_count) {
            self.apply_split_ratios(buffer_width, buffer_height);
            // Resize PTYs after applying ratios
            for window in &mut self.windows {
                if !window.window.is_minimized {
                    let _ = window.resize(window.window.width, window.window.height);
                }
            }
            #[cfg(unix)]
            self.send_persist_geometry_all();
            return;
        }

        // Get visible windows sorted by ID (creation order)
        let mut visible_ids: Vec<u32> = self
            .windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .map(|w| w.id())
            .collect();
        visible_ids.sort();

        // Calculate positions based on pattern
        let positions =
            self.calculate_auto_positions(visible_count, buffer_width, buffer_height, gaps);

        // Apply positions to windows
        for (idx, &window_id) in visible_ids.iter().enumerate() {
            if idx >= positions.len() {
                continue;
            }
            if let Some(win) = self.get_window_by_id_mut(window_id) {
                let (x, y, width, height) = positions[idx];
                win.window.x = x;
                win.window.y = y;
                win.window.width = width;
                win.window.height = height;
                // Resize the terminal to match new window size
                let _ = win.resize(width, height);
            }
        }

        // Notify daemon of all geometry changes
        #[cfg(unix)]
        self.send_persist_geometry_all();
    }

    /// Calculate positions for all windows based on the snap pattern
    /// If `gaps` is true, adds spacing between windows and screen edges
    fn calculate_auto_positions(
        &self,
        count: usize,
        buffer_width: u16,
        buffer_height: u16,
        gaps: bool,
    ) -> Vec<(u16, u16, u16, u16)> {
        // Gap constants (only used when gaps is true)
        const EDGE_GAP: u16 = 1; // Gap from screen edges
        const INTER_GAP: u16 = 1; // Gap between windows (after shadow)
        const SHADOW_SIZE: u16 = 2; // Shadow width/height

        let usable_height = buffer_height.saturating_sub(2); // -1 for top bar, -1 for button bar

        if gaps {
            // With gaps: calculate dimensions accounting for shadows and gaps
            // Horizontal: left_gap + w + shadow + inter_gap + w + shadow + right_gap = buffer_width
            // So: 2w = buffer_width - 2*EDGE_GAP - 2*SHADOW_SIZE - INTER_GAP
            let total_h_overhead = 2 * EDGE_GAP + 2 * SHADOW_SIZE + INTER_GAP;
            let window_width = buffer_width.saturating_sub(total_h_overhead) / 2;

            // Vertical: top_bar(1) + top_gap + h + shadow + h + shadow + bottom_gap = buffer_height
            // No inter-gap vertically - shadow provides enough separation
            // So: 2h = buffer_height - 1 - 2*EDGE_GAP - 2*SHADOW_SIZE
            let total_v_overhead = 1 + 2 * EDGE_GAP + 2 * SHADOW_SIZE;
            let window_height = buffer_height.saturating_sub(total_v_overhead) / 2;

            // Positions with gaps
            let left_x = EDGE_GAP;
            let right_x = EDGE_GAP + window_width + SHADOW_SIZE + INTER_GAP;
            let top_y = 1 + EDGE_GAP; // 1 for top bar + gap
            let bottom_y = 1 + EDGE_GAP + window_height + SHADOW_SIZE; // No inter-gap vertically

            match count {
                1 => {
                    // Single window fills the screen with gaps (like maximized)
                    let full_width = buffer_width.saturating_sub(2 * EDGE_GAP + SHADOW_SIZE);
                    let full_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + SHADOW_SIZE);
                    vec![(left_x, top_y, full_width, full_height)]
                }
                2 => {
                    // Two windows: left and right with full height
                    let full_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + SHADOW_SIZE);
                    vec![
                        (left_x, top_y, window_width, full_height), // Window 1: Left
                        (right_x, top_y, window_width, full_height), // Window 2: Right
                    ]
                }
                3 => {
                    // Three windows: top-left, bottom-left, full-right
                    let full_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + SHADOW_SIZE);
                    // Calculate bottom window height to fill remaining space
                    // bottom_y + bottom_height + SHADOW_SIZE + EDGE_GAP = buffer_height
                    // So: bottom_height = buffer_height - bottom_y - SHADOW_SIZE - EDGE_GAP
                    let bottom_height =
                        buffer_height.saturating_sub(bottom_y + SHADOW_SIZE + EDGE_GAP);
                    vec![
                        (left_x, top_y, window_width, window_height), // Window 1: Top-left
                        (left_x, bottom_y, window_width, bottom_height), // Window 2: Bottom-left
                        (right_x, top_y, window_width, full_height),  // Window 3: Full-right
                    ]
                }
                4 => {
                    // Four equal windows in 2x2 grid
                    // Calculate bottom window height to fill remaining space
                    let bottom_height =
                        buffer_height.saturating_sub(bottom_y + SHADOW_SIZE + EDGE_GAP);
                    vec![
                        (left_x, top_y, window_width, window_height), // Window 1: Top-left
                        (left_x, bottom_y, window_width, bottom_height), // Window 2: Bottom-left
                        (right_x, top_y, window_width, window_height), // Window 3: Top-right
                        (right_x, bottom_y, window_width, bottom_height), // Window 4: Bottom-right
                    ]
                }
                _ => {
                    // 5+ windows: first 4 in quarters with gaps, rest centered
                    // Calculate bottom window height to fill remaining space
                    let bottom_height =
                        buffer_height.saturating_sub(bottom_y + SHADOW_SIZE + EDGE_GAP);
                    let mut positions = vec![
                        (left_x, top_y, window_width, window_height), // Window 1: Top-left
                        (left_x, bottom_y, window_width, bottom_height), // Window 2: Bottom-left
                        (right_x, top_y, window_width, window_height), // Window 3: Top-right
                        (right_x, bottom_y, window_width, bottom_height), // Window 4: Bottom-right
                    ];

                    // Add center positions for remaining windows (with slight offset)
                    for i in 4..count {
                        let (width, height) =
                            Self::calculate_window_size(buffer_width, buffer_height);
                        let offset = ((i - 4) * 2) as u16;
                        let x = ((buffer_width.saturating_sub(width)) / 2).saturating_add(offset);
                        let y =
                            1 + ((usable_height.saturating_sub(height)) / 2).saturating_add(offset);
                        positions.push((x, y, width, height));
                    }

                    positions
                }
            }
        } else {
            // Without gaps: original behavior
            let half_width = buffer_width / 2;
            let half_height = usable_height / 2;

            match count {
                1 => {
                    // Center position with dynamic size
                    let (width, height) = Self::calculate_window_size(buffer_width, buffer_height);
                    let x = (buffer_width.saturating_sub(width)) / 2;
                    let y = 1 + (usable_height.saturating_sub(height)) / 2;
                    vec![(x, y, width, height)]
                }
                2 => {
                    // Split screen: full left, full right
                    vec![
                        (0, 1, half_width, usable_height),          // Window 1: Full left
                        (half_width, 1, half_width, usable_height), // Window 2: Full right
                    ]
                }
                3 => {
                    // Split left, full right
                    vec![
                        (0, 1, half_width, half_height),               // Window 1: Top-left
                        (0, 1 + half_height, half_width, half_height), // Window 2: Bottom-left
                        (half_width, 1, half_width, usable_height),    // Window 3: Full right
                    ]
                }
                4 => {
                    // All four quarters
                    vec![
                        (0, 1, half_width, half_height),               // Window 1: Top-left
                        (0, 1 + half_height, half_width, half_height), // Window 2: Bottom-left
                        (half_width, 1, half_width, half_height),      // Window 3: Top-right
                        (half_width, 1 + half_height, half_width, half_height), // Window 4: Bottom-right
                    ]
                }
                _ => {
                    // 5+ windows: first 4 in quarters, rest centered
                    let mut positions = vec![
                        (0, 1, half_width, half_height),               // Window 1: Top-left
                        (0, 1 + half_height, half_width, half_height), // Window 2: Bottom-left
                        (half_width, 1, half_width, half_height),      // Window 3: Top-right
                        (half_width, 1 + half_height, half_width, half_height), // Window 4: Bottom-right
                    ];

                    // Add center positions for remaining windows (with slight offset)
                    for i in 4..count {
                        let (width, height) =
                            Self::calculate_window_size(buffer_width, buffer_height);
                        let offset = ((i - 4) * 2) as u16;
                        let x = ((buffer_width.saturating_sub(width)) / 2).saturating_add(offset);
                        let y =
                            1 + ((usable_height.saturating_sub(height)) / 2).saturating_add(offset);
                        positions.push((x, y, width, height));
                    }

                    positions
                }
            }
        }
    }

    /// Clamp all windows to fit within the new screen bounds
    /// This is used when the terminal is resized and auto-tiling is disabled
    pub fn clamp_windows_to_bounds(&mut self, buffer_width: u16, buffer_height: u16) {
        let usable_height = buffer_height.saturating_sub(2); // -1 for top bar, -1 for button bar
        let min_visible_width = 10u16; // Minimum visible portion of window

        for win in &mut self.windows {
            // Skip minimized windows
            if win.window.is_minimized {
                continue;
            }

            // Clamp width and height to fit screen
            let max_width = buffer_width;
            let max_height = usable_height;
            if win.window.width > max_width {
                win.window.width = max_width;
            }
            if win.window.height > max_height {
                win.window.height = max_height;
            }

            // Clamp x position to keep window partially visible
            if win.window.x + min_visible_width > buffer_width {
                win.window.x = buffer_width.saturating_sub(min_visible_width);
            }

            // Clamp y position to keep window partially visible (min y=1 for topbar)
            if win.window.y < 1 {
                win.window.y = 1;
            }
            if win.window.y + 3 > buffer_height.saturating_sub(1) {
                // Keep at least title bar visible (3 rows: border + title + border)
                win.window.y = buffer_height.saturating_sub(4).max(1);
            }

            // Resize the terminal PTY to match new window dimensions
            let _ = win.resize(win.window.width, win.window.height);
        }

        // Notify daemon of all geometry changes
        #[cfg(unix)]
        self.send_persist_geometry_all();
    }

    /// Bring window to front and focus it
    pub fn focus_window(&mut self, id: u32) {
        // Find window using cache
        if let Some(pos) = self.get_window_index(id) {
            // Move to end (top of z-order)
            let mut window = self.windows.remove(pos);

            // Unfocus all windows
            for w in &mut self.windows {
                w.set_focused(false);
            }

            // Focus this window
            window.set_focused(true);
            self.windows.push(window);
            self.focus = FocusState::Window(id);

            // Rebuild cache since indices changed
            self.rebuild_cache();
        }
    }

    /// Focus the desktop (unfocus all windows)
    pub fn focus_desktop(&mut self) {
        for w in &mut self.windows {
            w.set_focused(false);
        }
        self.focus = FocusState::Desktop;
    }

    /// Focus the topbar (unfocus all windows)
    pub fn focus_topbar(&mut self) {
        for w in &mut self.windows {
            w.set_focused(false);
        }
        self.focus = FocusState::Topbar;
    }

    /// Get the current focus state
    pub fn get_focus(&self) -> FocusState {
        self.focus
    }

    /// Find top-most window at coordinates
    pub fn window_at(&self, x: u16, y: u16) -> Option<u32> {
        // Iterate backwards (top to bottom)
        for window in self.windows.iter().rev() {
            if window.contains_point(x, y) {
                return Some(window.id());
            }
        }
        None
    }

    /// Calculate target rectangle (x, y, width, height) for a given snap zone
    fn calculate_snap_rect(
        &self,
        zone: SnapZone,
        buffer_width: u16,
        buffer_height: u16,
    ) -> (u16, u16, u16, u16) {
        // Account for top bar (y starts at 1) and button bar (height - 1)
        let usable_height = buffer_height.saturating_sub(2); // -1 for top bar, -1 for button bar
        let half_width = buffer_width / 2;
        let half_height = usable_height / 2;

        match zone {
            SnapZone::TopLeft => (0, 1, half_width, half_height),
            SnapZone::TopRight => (half_width, 1, half_width, half_height),
            SnapZone::BottomLeft => (0, 1 + half_height, half_width, half_height),
            SnapZone::BottomRight => (half_width, 1 + half_height, half_width, half_height),
            SnapZone::FullLeft => (0, 1, half_width, usable_height),
            SnapZone::FullRight => (half_width, 1, half_width, usable_height),
        }
    }

    /// Detect snap zone based on mouse position
    /// Checks corners first, then edges
    fn detect_snap_zone(
        &self,
        x: u16,
        y: u16,
        buffer_width: u16,
        buffer_height: u16,
    ) -> Option<SnapZone> {
        let threshold = SNAP_THRESHOLD;

        // Define corner regions (top-left, top-right, bottom-left, bottom-right)
        // Corners are checked first for priority

        // Top-left corner
        if x <= threshold && y <= threshold + 1 {
            return Some(SnapZone::TopLeft);
        }

        // Top-right corner
        if x >= buffer_width.saturating_sub(threshold) && y <= threshold + 1 {
            return Some(SnapZone::TopRight);
        }

        // Bottom-left corner
        if x <= threshold && y >= buffer_height.saturating_sub(threshold + 1) {
            return Some(SnapZone::BottomLeft);
        }

        // Bottom-right corner
        if x >= buffer_width.saturating_sub(threshold)
            && y >= buffer_height.saturating_sub(threshold + 1)
        {
            return Some(SnapZone::BottomRight);
        }

        // Check edges (full-height snaps on left/right)

        // Left edge (not corner)
        if x <= threshold {
            return Some(SnapZone::FullLeft);
        }

        // Right edge (not corner)
        if x >= buffer_width.saturating_sub(threshold) {
            return Some(SnapZone::FullRight);
        }

        None
    }

    /// Handle mouse event
    /// Returns true if a window was closed (so caller can reposition)
    /// If `gaps` is true, maximize operations will respect gap settings
    pub fn handle_mouse_event(
        &mut self,
        buffer: &mut VideoBuffer,
        event: MouseEvent,
        charset: &Charset,
        gaps: bool,
        auto_tiling: bool,
    ) -> bool {
        // Validate mouse coordinates are within buffer bounds
        let (buffer_width, buffer_height) = buffer.dimensions();
        let x = event.column;
        let y = event.row;

        // Bounds check: ignore events outside the valid screen area
        if x >= buffer_width || y >= buffer_height {
            return false;
        }

        // Check if the clicked window has a close confirmation dialog
        // If so, handle confirmation clicks; otherwise allow normal interaction
        if let Some(clicked_window_id) = self.window_at(x, y) {
            // Check if this specific clicked window has a confirmation dialog
            let clicked_window_has_confirmation = self
                .get_window_by_id(clicked_window_id)
                .map(|w| w.has_close_confirmation())
                .unwrap_or(false);

            if clicked_window_has_confirmation {
                if let MouseEventKind::Down(MouseButton::Left) = event.kind {
                    // Handle confirmation dialog click
                    if let Some(window) = self.get_window_by_id_mut(clicked_window_id) {
                        if let Some(should_close) =
                            window.handle_close_confirmation_click(event.column, event.row, charset)
                        {
                            if should_close {
                                return self.close_window(clicked_window_id);
                            }
                        }
                    }
                }
                // Block all other events on windows with confirmation dialogs
                return false;
            }
        }

        // Handle pivot interactions first (highest priority when visible)
        // Pivot is only available when auto-tiling is enabled with gaps
        if auto_tiling && gaps {
            match event.kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    if self.is_point_on_pivot(x, y, buffer_width, buffer_height, gaps) {
                        let now = Instant::now();
                        // Check for double-click on pivot
                        if let Some(last_time) = self.last_pivot_click {
                            if now.duration_since(last_time).as_millis() < 500 {
                                // Double-click detected - swap windows
                                self.swap_windows_horizontal(buffer_width, buffer_height);
                                self.last_pivot_click = None;
                                return false;
                            }
                        }
                        // Record click time and start drag
                        self.last_pivot_click = Some(now);
                        self.start_pivot_drag(x, y);
                        return false;
                    }
                }
                MouseEventKind::Drag(MouseButton::Left) => {
                    if self.pivot_dragging.is_some() {
                        self.handle_pivot_drag(x, y, buffer_width, buffer_height);
                        return false;
                    }
                }
                MouseEventKind::Up(MouseButton::Left) => {
                    if self.pivot_dragging.is_some() {
                        self.end_pivot_drag();
                        return false;
                    }
                }
                _ => {}
            }
        }

        match event.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                self.handle_mouse_down(buffer, x, y, gaps, auto_tiling)
            }
            MouseEventKind::Drag(MouseButton::Left) => {
                // Pass modifiers to check if Control is pressed (to disable snap)
                self.handle_mouse_drag(buffer, x, y, event.modifiers);
                false
            }
            MouseEventKind::Up(MouseButton::Left) => {
                self.handle_mouse_up(buffer, gaps);
                false
            }
            MouseEventKind::ScrollUp => {
                self.handle_scroll_up(x, y);
                false
            }
            MouseEventKind::ScrollDown => {
                self.handle_scroll_down(x, y);
                false
            }
            _ => false,
        }
    }

    fn handle_mouse_down(
        &mut self,
        buffer: &mut VideoBuffer,
        x: u16,
        y: u16,
        gaps: bool,
        auto_tiling: bool,
    ) -> bool {
        // Find window at click position
        if let Some(window_id) = self.window_at(x, y) {
            // Extract all needed data from window before any mutable operations
            // This avoids borrow checker issues with self.last_click, self.dragging, etc.
            let window_data = self.get_window_by_id(window_id).map(|tw| {
                let w = &tw.window;
                (
                    tw.is_in_close_button(x, y),
                    tw.is_dirty(),
                    w.is_in_maximize_button(x, y),
                    w.is_in_minimize_button(x, y),
                    w.is_maximized,
                    w.get_resize_edge(x, y),
                    w.width,
                    w.height,
                    w.x,
                    w.y,
                    tw.is_point_on_scrollbar(x, y),
                    tw.is_point_on_scrollbar_thumb(x, y),
                    tw.get_scroll_offset(),
                    tw.is_in_title_bar(x, y),
                )
            });

            if let Some((
                is_close_button,
                is_dirty,
                is_maximize_button,
                is_minimize_button,
                is_maximized,
                resize_edge,
                win_width,
                win_height,
                win_x,
                win_y,
                is_on_scrollbar,
                is_on_thumb,
                scroll_offset,
                is_title_bar,
            )) = window_data
            {
                // Check if clicking close button
                if is_close_button {
                    if is_dirty {
                        // Show confirmation dialog
                        if let Some(window) = self.get_window_by_id_mut(window_id) {
                            window.show_close_confirmation();
                        }
                        return false; // Don't close yet
                    } else {
                        // Clean window - close immediately
                        let closed = self.close_window(window_id);
                        return closed;
                    }
                }

                // Check if clicking maximize button
                if is_maximize_button {
                    let (buffer_width, buffer_height) = buffer.dimensions();

                    // Find the window mutably and toggle maximize
                    if let Some(win) = self.get_window_by_id_mut(window_id) {
                        win.window
                            .toggle_maximize(buffer_width, buffer_height, gaps);
                        // Resize the terminal to match new window size
                        let _ = win.resize(win.window.width, win.window.height);
                    }
                    #[cfg(unix)]
                    self.send_persist_geometry_for_window(window_id);
                    return false;
                }

                // Check if clicking minimize button
                if is_minimize_button {
                    // Find the window mutably and minimize it
                    if let Some(win) = self.get_window_by_id_mut(window_id) {
                        win.window.minimize();
                    }

                    // Find the next non-minimized window to focus (from top of z-order)
                    let next_window_id = self
                        .windows
                        .iter()
                        .rev()
                        .find(|w| !w.window.is_minimized && w.id() != window_id)
                        .map(|w| w.id());

                    if let Some(next_id) = next_window_id {
                        // Focus the next available window
                        self.focus_window(next_id);
                    } else {
                        // No other windows available, focus desktop
                        self.focus_desktop();
                    }
                    return false;
                }

                // Check if clicking on a resizable border (only if not maximized)
                if !is_maximized {
                    if let Some(edge) = resize_edge {
                        // Don't allow resize if window is locked (auto-tiled first 4)
                        if self.is_window_tiled_locked(window_id, auto_tiling) {
                            self.focus_window(window_id);
                            return false;
                        }
                        // Focus the window when clicking on resize border
                        self.focus_window(window_id);
                        self.resizing = Some(ResizeState {
                            window_id,
                            edge,
                            start_x: x,
                            start_y: y,
                            start_width: win_width,
                            start_height: win_height,
                            start_window_x: win_x,
                            start_window_y: win_y,
                        });
                        return false;
                    }
                }

                // Check if clicking scrollbar
                if is_on_scrollbar {
                    // Focus the window when clicking on scrollbar
                    self.focus_window(window_id);
                    if is_on_thumb {
                        // Start dragging scrollbar thumb
                        self.scrollbar_dragging = Some(ScrollbarDragState {
                            window_id,
                            start_offset: scroll_offset,
                        });
                    } else {
                        // Click on track - jump to position or page up/down
                        // For simplicity, jump to clicked position
                        if let Some(win) = self.get_window_by_id_mut(window_id) {
                            win.scroll_to_position(y);
                        }
                    }
                    return false;
                }

                // Check if clicking title bar (for dragging or double-click maximize)
                if is_title_bar {
                    let now = Instant::now();

                    // Check for double-click (within 500ms, same window and position)
                    let is_double_click = if let Some(ref last) = self.last_click {
                        last.window_id == window_id
                            && last.x == x
                            && last.y == y
                            && now.duration_since(last.time).as_millis() < 500
                    } else {
                        false
                    };

                    if is_double_click {
                        // Double-click detected - toggle maximize
                        let (buffer_width, buffer_height) = buffer.dimensions();
                        if let Some(win) = self.get_window_by_id_mut(window_id) {
                            win.window
                                .toggle_maximize(buffer_width, buffer_height, gaps);
                            // Resize the terminal to match new window size
                            let _ = win.resize(win.window.width, win.window.height);
                        }
                        #[cfg(unix)]
                        self.send_persist_geometry_for_window(window_id);
                        // Clear last click so we don't trigger triple-click
                        self.last_click = None;
                    } else {
                        // Single click - record it and start dragging if not maximized
                        self.last_click = Some(LastClick {
                            window_id,
                            x,
                            y,
                            time: now,
                        });

                        // Only start dragging if not maximized and not locked
                        if !is_maximized && !self.is_window_tiled_locked(window_id, auto_tiling) {
                            let offset_x = x as i16 - win_x as i16;
                            let offset_y = y as i16 - win_y as i16;

                            self.dragging = Some(DragState {
                                window_id,
                                offset_x,
                                offset_y,
                            });
                        }
                    }

                    // Don't bring to front yet for title bar clicks
                    // to avoid interfering with double-click detection
                }
            }

            // Bring window to front and focus it
            self.focus_window(window_id);
        } else {
            // Clicked on desktop - focus it
            self.focus_desktop();
        }
        false
    }

    #[allow(clippy::collapsible_if)]
    fn handle_mouse_drag(
        &mut self,
        buffer: &mut VideoBuffer,
        x: u16,
        y: u16,
        modifiers: KeyModifiers,
    ) {
        // Handle window dragging
        if let Some(drag) = self.dragging {
            let (buffer_width, buffer_height) = buffer.dimensions();

            // Detect snap zone for preview (don't apply position yet)
            // Disable snap if Control key is pressed
            if modifiers.contains(KeyModifiers::CONTROL) {
                self.current_snap_zone = None;
            } else {
                self.current_snap_zone = self.detect_snap_zone(x, y, buffer_width, buffer_height);
            }

            if let Some(terminal_window) = self.get_window_by_id_mut(drag.window_id) {
                // Calculate desired position
                let desired_x = x as i16 - drag.offset_x;
                let desired_y = y as i16 - drag.offset_y;

                // Constrain x: keep entire window visible horizontally
                let max_x = buffer_width.saturating_sub(terminal_window.window.width);
                let new_x = (desired_x.max(0) as u16).min(max_x);

                // Constrain y: keep below top bar and entire window visible vertically
                let max_y = buffer_height
                    .saturating_sub(terminal_window.window.height)
                    .saturating_sub(1); // -1 for button bar
                let new_y = (desired_y.max(1) as u16).min(max_y);

                terminal_window.window.x = new_x;
                terminal_window.window.y = new_y;
            }
        }

        // Handle window resizing
        if let Some(resize) = self.resizing {
            if let Some(terminal_window) = self.get_window_by_id_mut(resize.window_id) {
                // Calculate deltas from start position
                let delta_x = x as i16 - resize.start_x as i16;
                let delta_y = y as i16 - resize.start_y as i16;

                // Apply resize based on which edge is being dragged
                match resize.edge {
                    ResizeEdge::Left => {
                        // Left edge: move window left and increase width
                        // delta_x > 0 means moving right (decrease width)
                        // delta_x < 0 means moving left (increase width)
                        let new_width = (resize.start_width as i16 - delta_x).max(24) as u16;
                        let new_x = (resize.start_window_x as i16 + delta_x).max(0) as u16;

                        terminal_window.window.x = new_x;
                        terminal_window.window.width = new_width;
                    }
                    ResizeEdge::Right => {
                        // Right edge: just adjust width
                        let new_width = (resize.start_width as i16 + delta_x).max(24) as u16;
                        terminal_window.window.width = new_width;
                    }
                    ResizeEdge::Bottom => {
                        // Bottom edge: just adjust height
                        let new_height = (resize.start_height as i16 + delta_y).max(5) as u16;
                        terminal_window.window.height = new_height;
                    }
                    ResizeEdge::BottomLeft => {
                        // Bottom-left corner: adjust x position and width (like Left) AND height (like Bottom)
                        let new_width = (resize.start_width as i16 - delta_x).max(24) as u16;
                        let new_x = (resize.start_window_x as i16 + delta_x).max(0) as u16;
                        let new_height = (resize.start_height as i16 + delta_y).max(5) as u16;

                        terminal_window.window.x = new_x;
                        terminal_window.window.width = new_width;
                        terminal_window.window.height = new_height;
                    }
                    ResizeEdge::BottomRight => {
                        // Bottom-right corner: adjust width (like Right) AND height (like Bottom)
                        let new_width = (resize.start_width as i16 + delta_x).max(24) as u16;
                        let new_height = (resize.start_height as i16 + delta_y).max(5) as u16;

                        terminal_window.window.width = new_width;
                        terminal_window.window.height = new_height;
                    }
                    ResizeEdge::TopLeft => {
                        // Top-left corner: adjust x and y position while changing width and height
                        // delta_x > 0 (right) = decrease width, move right
                        // delta_y > 0 (down) = decrease height, move down
                        let new_width = (resize.start_width as i16 - delta_x).max(24) as u16;
                        let new_height = (resize.start_height as i16 - delta_y).max(5) as u16;
                        let new_x = (resize.start_window_x as i16 + delta_x).max(0) as u16;
                        let new_y = (resize.start_window_y as i16 + delta_y).max(1) as u16; // min y=1 (below top bar)

                        terminal_window.window.x = new_x;
                        terminal_window.window.y = new_y;
                        terminal_window.window.width = new_width;
                        terminal_window.window.height = new_height;
                    }
                    ResizeEdge::TopRight => {
                        // Top-right corner: adjust y position and width/height
                        // delta_x > 0 (right) = increase width
                        // delta_y > 0 (down) = decrease height, move down
                        let new_width = (resize.start_width as i16 + delta_x).max(24) as u16;
                        let new_height = (resize.start_height as i16 - delta_y).max(5) as u16;
                        let new_y = (resize.start_window_y as i16 + delta_y).max(1) as u16; // min y=1 (below top bar)

                        terminal_window.window.y = new_y;
                        terminal_window.window.width = new_width;
                        terminal_window.window.height = new_height;
                    }
                }

                // DON'T resize the terminal PTY during drag - it causes artifacts
                // The PTY will be resized on mouse up
            }
        }

        // Handle scrollbar dragging
        if let Some(_scrollbar) = self.scrollbar_dragging {
            if let Some(terminal_window) = self.get_window_by_id_mut(_scrollbar.window_id) {
                // Update scroll position based on mouse Y position
                terminal_window.scroll_to_position(y);
            }
        }
    }

    fn handle_mouse_up(&mut self, buffer: &mut VideoBuffer, _gaps: bool) {
        // Track which window changed geometry for persist notification
        #[cfg(unix)]
        let mut geometry_changed_id: Option<u32> = None;

        // Apply snap positioning if a snap zone is active
        if let (Some(snap_zone), Some(drag)) = (self.current_snap_zone, self.dragging) {
            let (buffer_width, buffer_height) = buffer.dimensions();
            let (snap_x, snap_y, snap_width, snap_height) =
                self.calculate_snap_rect(snap_zone, buffer_width, buffer_height);

            // Find the dragged window and apply snap position
            if let Some(terminal_window) = self.get_window_by_id_mut(drag.window_id) {
                terminal_window.window.x = snap_x;
                terminal_window.window.y = snap_y;
                terminal_window.window.width = snap_width;
                terminal_window.window.height = snap_height;

                // Resize the terminal to match new window size
                let _ = terminal_window.resize(snap_width, snap_height);
                #[cfg(unix)]
                {
                    geometry_changed_id = Some(drag.window_id);
                }
            }
        } else if self.dragging.is_some() {
            // Normal drag (no snap) — position changed
            #[cfg(unix)]
            if let Some(drag) = self.dragging {
                geometry_changed_id = Some(drag.window_id);
            }
        }

        // Finalize resize - update PTY terminal size
        if let Some(resize) = self.resizing {
            let window_id = resize.window_id;
            if let Some(terminal_window) = self.get_window_by_id_mut(window_id) {
                // Resize the terminal PTY to match final window size
                let _ = terminal_window
                    .resize(terminal_window.window.width, terminal_window.window.height);
            }
            #[cfg(unix)]
            {
                geometry_changed_id = Some(window_id);
            }
        }

        // Notify daemon of updated window geometry (persist mode)
        #[cfg(unix)]
        if let Some(wid) = geometry_changed_id {
            if let Some(tw) = self.get_window_by_id(wid) {
                let (x, y, w, h) = (tw.window.x, tw.window.y, tw.window.width, tw.window.height);
                self.send_persist_geometry(wid, x, y, w, h);
            }
        }

        self.dragging = None;
        self.resizing = None;
        self.scrollbar_dragging = None;
        self.current_snap_zone = None;
    }

    #[allow(clippy::collapsible_if)]
    fn handle_scroll_up(&mut self, x: u16, y: u16) {
        // Find window at position
        if let Some(window_id) = self.window_at(x, y) {
            if let Some(terminal_window) = self.get_window_by_id_mut(window_id) {
                // Scroll up 3 lines
                terminal_window.scroll_up(3);
            }
        }
    }

    #[allow(clippy::collapsible_if)]
    fn handle_scroll_down(&mut self, x: u16, y: u16) {
        // Find window at position
        if let Some(window_id) = self.window_at(x, y) {
            if let Some(terminal_window) = self.get_window_by_id_mut(window_id) {
                // Scroll down 3 lines
                terminal_window.scroll_down(3);
            }
        }
    }

    /// Render all windows in z-order (bottom to top)
    /// Returns true if any windows were closed (so caller can reposition)
    /// If keyboard_mode_active is true, focused window uses keyboard mode colors
    pub fn render_all(
        &mut self,
        buffer: &mut VideoBuffer,
        charset: &Charset,
        theme: &Theme,
        tint_terminal: bool,
        keyboard_mode_active: bool,
    ) -> bool {
        let mut windows_to_close = Vec::new();

        for i in 0..self.windows.len() {
            // Process terminal output before rendering
            if let Ok(false) = self.windows[i].process_output() {
                // Shell process has exited, mark for closure
                windows_to_close.push(self.windows[i].id());
            }

            self.windows[i].render(buffer, charset, theme, tint_terminal, keyboard_mode_active);
        }

        // Close windows whose shell processes have exited
        let mut any_closed = false;
        for window_id in windows_to_close {
            if self.close_window(window_id) {
                any_closed = true;
            }
        }

        any_closed
    }

    /// Render snap preview overlay (if dragging and snap zone is active)
    pub fn render_snap_preview(&self, buffer: &mut VideoBuffer, charset: &Charset, theme: &Theme) {
        use crate::rendering::Cell;

        // Only render if dragging and a snap zone is active
        if self.dragging.is_none() || self.current_snap_zone.is_none() {
            return;
        }

        let snap_zone = self.current_snap_zone.unwrap();
        let (buffer_width, buffer_height) = buffer.dimensions();
        let (x, y, width, height) =
            self.calculate_snap_rect(snap_zone, buffer_width, buffer_height);

        // Use bright yellow for the preview border
        let border_color = theme.snap_preview_border;
        let bg_color = theme.snap_preview_bg;

        // Draw top border
        for i in 0..width {
            let ch = if i == 0 {
                charset.border_top_left
            } else if i == width - 1 {
                charset.border_top_right
            } else {
                charset.border_horizontal
            };
            buffer.set(x + i, y, Cell::new_unchecked(ch, border_color, bg_color));
        }

        // Draw bottom border
        let bottom_y = y + height.saturating_sub(1);
        for i in 0..width {
            let ch = if i == 0 {
                charset.border_bottom_left
            } else if i == width - 1 {
                charset.border_bottom_right
            } else {
                charset.border_horizontal
            };
            buffer.set(
                x + i,
                bottom_y,
                Cell::new_unchecked(ch, border_color, bg_color),
            );
        }

        // Draw left and right borders
        for j in 1..height.saturating_sub(1) {
            buffer.set(
                x,
                y + j,
                Cell::new_unchecked(charset.border_vertical, border_color, bg_color),
            );
            buffer.set(
                x + width.saturating_sub(1),
                y + j,
                Cell::new_unchecked(charset.border_vertical, border_color, bg_color),
            );
        }
    }

    /// Get the number of windows
    pub fn window_count(&self) -> usize {
        self.windows.len()
    }

    /// Find window ID by title number (e.g., "Terminal 3" matches number 3)
    /// Returns None if no window with that number exists
    pub fn find_window_by_title_number(&self, target_num: u32) -> Option<u32> {
        for w in &self.windows {
            // Extract number from "Terminal N" or "Terminal N [ > ... ]"
            if let Some(rest) = w.window.title.strip_prefix("Terminal ") {
                let num_str: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
                if let Ok(num) = num_str.parse::<u32>() {
                    if num == target_num {
                        return Some(w.id());
                    }
                }
            }
        }
        None
    }

    /// Get window positions for overlay rendering
    /// Returns: (window_id, x, y, width, height, is_minimized, title)
    pub fn get_window_positions(&self) -> Vec<(u32, u16, u16, u16, u16, bool, String)> {
        self.windows
            .iter()
            .map(|w| {
                (
                    w.id(),
                    w.window.x,
                    w.window.y,
                    w.window.width,
                    w.window.height,
                    w.window.is_minimized,
                    w.window.title.clone(),
                )
            })
            .collect()
    }

    /// Get window info for button bar rendering (id, title, is_focused, is_minimized)
    /// Returns windows sorted by creation order (ID), not z-order
    /// Optimized: uses sort_unstable for better performance on small arrays
    pub fn get_window_list(&self) -> Vec<(u32, &str, bool, bool)> {
        let mut list: Vec<(u32, &str, bool, bool)> = self
            .windows
            .iter()
            .map(|w| {
                (
                    w.id(),
                    w.window.title.as_str(),
                    w.window.is_focused,
                    w.window.is_minimized,
                )
            })
            .collect();

        // Sort by window ID to maintain creation order
        // Use sort_unstable for better performance (stable sort not needed for unique IDs)
        list.sort_unstable_by_key(|(id, _, _, _)| *id);
        list
    }

    /// Get window ID at button bar position (read-only, does not modify state)
    /// offset_x: the starting x position for window buttons (after other UI elements)
    pub fn button_bar_get_window_at(
        &self,
        x: u16,
        bar_y: u16,
        click_y: u16,
        offset_x: u16,
    ) -> Option<u32> {
        // Only process if clicking on the button bar row
        if click_y != bar_y {
            return None;
        }

        // Get windows sorted by creation order (same as display order)
        let mut sorted_windows: Vec<&TerminalWindow> = self.windows.iter().collect();
        sorted_windows.sort_by_key(|w| w.id());

        let mut current_x = offset_x; // Start at the offset position

        for terminal_window in sorted_windows {
            let window = &terminal_window.window;

            // Button format: [ Title ]
            // Max button width is 18 chars (including brackets and spaces)
            let max_title_len = 14; // Leaves room for [ ] and spaces
            let button_title = if window.title.len() > max_title_len {
                &window.title[..max_title_len]
            } else {
                &window.title
            };

            let button_width = button_title.len() as u16 + 4; // "[ " + title + " ]"
            let button_end = current_x + button_width;

            // Check if click is within this button
            if x >= current_x && x < button_end {
                return Some(window.id);
            }

            // Move to next button position (with 1 space gap)
            current_x = button_end + 1;
        }

        None
    }

    /// Handle click on button bar - returns window ID if clicked on a button
    /// offset_x: the starting x position for window buttons (after other UI elements)
    pub fn button_bar_click(
        &mut self,
        x: u16,
        bar_y: u16,
        click_y: u16,
        offset_x: u16,
    ) -> Option<u32> {
        // Use the read-only method to find the window
        let clicked_window_id = self.button_bar_get_window_at(x, bar_y, click_y, offset_x);

        // Focus the clicked window if found
        if let Some(window_id) = clicked_window_id {
            // If the window is minimized, restore it first
            #[allow(clippy::collapsible_if)]
            if let Some(win) = self.get_window_by_id_mut(window_id) {
                if win.window.is_minimized {
                    win.window.restore_from_minimize();
                }
            }

            self.focus_window(window_id);
            return Some(window_id);
        }

        None
    }

    /// Send input to the focused terminal window
    #[allow(clippy::collapsible_if)]
    pub fn send_to_focused(&mut self, s: &str) -> std::io::Result<()> {
        if let FocusState::Window(id) = self.focus {
            // In persist mode, route input through daemon
            #[cfg(unix)]
            if self.persist_client.is_some() {
                self.send_persist_input(id, s.as_bytes());
                return Ok(());
            }

            if let Some(terminal_window) = self.get_window_by_id_mut(id) {
                return terminal_window.send_str(s);
            }
        }
        Ok(())
    }

    /// Send a character to the focused terminal window
    #[allow(clippy::collapsible_if)]
    pub fn send_char_to_focused(&mut self, c: char) -> std::io::Result<()> {
        if let FocusState::Window(id) = self.focus {
            // In persist mode, route input through daemon
            #[cfg(unix)]
            if self.persist_client.is_some() {
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf);
                self.send_persist_input(id, s.as_bytes());
                return Ok(());
            }

            if let Some(terminal_window) = self.get_window_by_id_mut(id) {
                return terminal_window.send_char(c);
            }
        }
        Ok(())
    }

    /// Check if the focused window has mouse tracking enabled
    pub fn focused_has_mouse_tracking(&self) -> bool {
        if let FocusState::Window(id) = self.focus {
            if let Some(terminal_window) = self.get_window_by_id(id) {
                return terminal_window.has_mouse_tracking_enabled();
            }
        }
        false
    }

    /// Check if the focused window has a close confirmation dialog active
    pub fn focused_has_close_confirmation(&self) -> bool {
        if let FocusState::Window(id) = self.focus {
            if let Some(terminal_window) = self.get_window_by_id(id) {
                return terminal_window.has_close_confirmation();
            }
        }
        false
    }

    /// Forward a mouse event to the focused terminal window
    /// Returns true if the event was consumed (forwarded to child process)
    /// button: 0=left, 1=middle, 2=right, 64=scroll up, 65=scroll down
    /// action: 0=press, 1=release, 2=drag/motion
    #[allow(clippy::collapsible_if)]
    pub fn forward_mouse_to_focused(
        &mut self,
        screen_x: u16,
        screen_y: u16,
        button: u8,
        action: u8,
    ) -> bool {
        if let FocusState::Window(id) = self.focus {
            if let Some(terminal_window) = self.get_window_by_id_mut(id) {
                let consumed =
                    terminal_window.handle_mouse_for_terminal(screen_x, screen_y, button, action);
                // Forward any buffered mouse bytes to daemon (Remote mode)
                #[cfg(unix)]
                if consumed {
                    if let Some(bytes) = terminal_window.drain_pending_remote_bytes() {
                        self.send_persist_input(id, &bytes);
                    }
                }
                return consumed;
            }
        }
        false
    }

    /// Flush buffered input for all terminal windows
    /// Call this once after processing a batch of keyboard events
    /// to avoid per-keystroke I/O overhead (especially important on Windows)
    pub fn flush_all_terminal_input(&mut self) {
        // Collect pending resize notifications from remote windows
        #[cfg(unix)]
        let mut resize_notifications: Vec<(u32, u16, u16)> = Vec::new();

        for terminal_window in &mut self.windows {
            let _ = terminal_window.flush_input();

            // Check for pending resize on remote windows
            #[cfg(unix)]
            if terminal_window.is_remote() {
                if let Some((cols, rows)) = terminal_window.take_pending_resize() {
                    if let Some(wid) = terminal_window.remote_window_id() {
                        resize_notifications.push((wid, cols, rows));
                    }
                }
            }
        }

        // Send resize notifications to daemon
        #[cfg(unix)]
        for (wid, cols, rows) in resize_notifications {
            self.send_persist_resize(wid, cols, rows);
        }
    }

    // =========================================================================
    // Persist Mode (Client-Daemon) Support
    // =========================================================================

    /// Set the persist client for daemon communication
    #[cfg(unix)]
    pub fn set_persist_client(&mut self, client: crate::persist::client::PersistClient) {
        self.persist_client = Some(client);
    }

    /// Restore windows from daemon's window list (called on reattach)
    /// Creates local Remote windows for each window the daemon knows about
    #[cfg(unix)]
    pub fn restore_persist_windows(&mut self, windows: Vec<crate::persist::protocol::WindowInfo>) {
        for info in windows {
            let mut terminal_window = TerminalWindow::new_remote(
                info.window_id,
                info.x,
                info.y,
                info.width,
                info.height,
                info.title,
                info.window_id,
            );

            terminal_window.set_focused(false);
            let idx = self.windows.len();
            self.windows.push(terminal_window);
            self.window_index_cache.insert(info.window_id, idx);

            // Keep next_id above daemon's IDs
            if info.window_id >= self.next_id {
                self.next_id = info.window_id + 1;
            }
        }

        // Focus the last (top) window if any
        if let Some(last) = self.windows.last_mut() {
            last.set_focused(true);
            self.focus = FocusState::Window(last.id());
        }
    }

    /// Check if we're in persist client mode
    #[cfg(unix)]
    #[allow(dead_code)]
    pub fn has_persist_client(&self) -> bool {
        self.persist_client.is_some()
    }

    /// Detach from daemon on exit (send Detach message)
    #[cfg(unix)]
    pub fn detach_persist_client(&mut self) {
        if let Some(ref mut client) = self.persist_client {
            let _ = client.detach();
        }
        self.persist_client = None;
    }

    /// Shutdown the daemon on exit (send Shutdown message, kills daemon)
    #[cfg(unix)]
    pub fn shutdown_persist_daemon(&mut self) {
        if let Some(ref mut client) = self.persist_client {
            let _ = client.shutdown();
        }
        self.persist_client = None;
    }

    /// Send PTY input to daemon for the focused window (persist mode)
    #[cfg(unix)]
    fn send_persist_input(&mut self, window_id: u32, data: &[u8]) {
        if let Some(ref mut client) = self.persist_client {
            let _ = client.send_pty_input(window_id, data);
        }
    }

    /// Poll daemon for messages and process them (call from event loop)
    #[cfg(unix)]
    pub fn poll_persist_messages(&mut self) -> Vec<PersistEvent> {
        let mut events = Vec::new();

        if self.persist_client.is_none() {
            return events;
        }

        // Collect all messages first to avoid borrow conflicts
        let mut messages = Vec::new();
        let mut connection_lost = false;

        if let Some(ref mut client) = self.persist_client {
            loop {
                match client.try_recv() {
                    Ok(Some(msg)) => messages.push(msg),
                    Ok(None) => break,
                    Err(e) => {
                        if e.kind() == io::ErrorKind::ConnectionReset
                            || e.kind() == io::ErrorKind::BrokenPipe
                        {
                            connection_lost = true;
                        }
                        break;
                    }
                }
            }
        }

        // Now process collected messages (no borrow on persist_client)
        let mut needs_pong = false;
        for msg in messages {
            match msg {
                crate::persist::protocol::DaemonMsg::PtyOutput { window_id, data } => {
                    if let Some(w) = self.get_window_by_id_mut(window_id) {
                        w.feed_remote_output(&data);
                    }
                }
                crate::persist::protocol::DaemonMsg::WindowClosed { window_id } => {
                    events.push(PersistEvent::WindowClosed(window_id));
                }
                crate::persist::protocol::DaemonMsg::WindowCreated { window_id } => {
                    events.push(PersistEvent::WindowCreated(window_id));
                }
                crate::persist::protocol::DaemonMsg::Error { message } => {
                    events.push(PersistEvent::Error(message));
                }
                crate::persist::protocol::DaemonMsg::Ping => {
                    needs_pong = true;
                }
                _ => {}
            }
        }

        // Respond to heartbeat ping outside the message processing loop
        if needs_pong {
            if let Some(ref mut client) = self.persist_client {
                let _ = client.send(&crate::persist::protocol::ClientMsg::Pong);
            }
        }

        if connection_lost {
            events.push(PersistEvent::DaemonDied);
            self.persist_client = None;
        }

        events
    }

    /// Create a window via the daemon (persist mode)
    /// Sends CreateWindow to daemon, waits for WindowCreated response,
    /// then creates a local Remote window with the daemon's window_id.
    #[cfg(unix)]
    fn create_window_via_daemon(
        &mut self,
        x: u16,
        y: u16,
        width: u16,
        height: u16,
        title: String,
        initial_command: Option<String>,
    ) -> Result<u32, String> {
        let client = match self.persist_client.as_mut() {
            Some(c) => c,
            None => return Err("No persist client".to_string()),
        };

        // Send request to daemon
        client
            .request_create_window(x, y, width, height, title.clone(), initial_command)
            .map_err(|e| format!("Failed to send create request: {}", e))?;

        // Wait for WindowCreated response (daemon processes synchronously)
        // Buffer any PtyOutput messages that arrive in the meantime
        let mut buffered_pty: Vec<(u32, Vec<u8>)> = Vec::new();
        let daemon_window_id;
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);

        loop {
            if std::time::Instant::now() > deadline {
                return Err("Timeout waiting for daemon to create window".to_string());
            }

            match client.try_recv() {
                Ok(Some(crate::persist::protocol::DaemonMsg::WindowCreated { window_id })) => {
                    daemon_window_id = window_id;
                    break;
                }
                Ok(Some(crate::persist::protocol::DaemonMsg::PtyOutput { window_id, data })) => {
                    buffered_pty.push((window_id, data));
                }
                Ok(Some(crate::persist::protocol::DaemonMsg::Error { message })) => {
                    return Err(message);
                }
                Ok(Some(_)) => {} // Ignore other messages
                Ok(None) => {
                    std::thread::sleep(std::time::Duration::from_millis(1));
                }
                Err(e) => {
                    return Err(format!("Daemon error: {}", e));
                }
            }
        }

        // Apply buffered PtyOutput to existing windows
        for (wid, data) in buffered_pty {
            if let Some(w) = self.get_window_by_id_mut(wid) {
                w.feed_remote_output(&data);
            }
        }

        // Use daemon's window_id as local id so IDs stay in sync
        let mut terminal_window = TerminalWindow::new_remote(
            daemon_window_id,
            x,
            y,
            width,
            height,
            title,
            daemon_window_id,
        );

        // Unfocus all windows
        for w in &mut self.windows {
            w.set_focused(false);
        }

        terminal_window.set_focused(true);
        let idx = self.windows.len();
        self.windows.push(terminal_window);
        self.window_index_cache.insert(daemon_window_id, idx);
        self.focus = FocusState::Window(daemon_window_id);

        // Track position for cascading
        self.last_window_x = Some(x);
        self.last_window_y = Some(y);

        // Update next_id to avoid conflicts
        if daemon_window_id >= self.next_id {
            self.next_id = daemon_window_id + 1;
        }

        Ok(daemon_window_id)
    }

    /// Notify daemon of PTY resize (persist mode)
    #[cfg(unix)]
    fn send_persist_resize(&mut self, window_id: u32, cols: u16, rows: u16) {
        if let Some(ref mut client) = self.persist_client {
            let _ = client.send_resize_pty(window_id, cols, rows);
        }
    }

    /// Notify daemon of window geometry change (position and/or size)
    #[cfg(unix)]
    fn send_persist_geometry(&mut self, window_id: u32, x: u16, y: u16, width: u16, height: u16) {
        if let Some(ref mut client) = self.persist_client {
            let _ = client.send_update_geometry(window_id, x, y, width, height);
        }
    }

    /// Notify daemon of geometry change for a window by ID (reads current geometry)
    #[cfg(unix)]
    fn send_persist_geometry_for_window(&mut self, window_id: u32) {
        if self.persist_client.is_some() {
            if let Some(tw) = self.get_window_by_id(window_id) {
                let (x, y, w, h) = (tw.window.x, tw.window.y, tw.window.width, tw.window.height);
                self.send_persist_geometry(window_id, x, y, w, h);
            }
        }
    }

    /// Notify daemon of geometry change for all windows
    #[cfg(unix)]
    fn send_persist_geometry_all(&mut self) {
        if self.persist_client.is_some() {
            let updates: Vec<(u32, u16, u16, u16, u16)> = self
                .windows
                .iter()
                .map(|w| {
                    (
                        w.id(),
                        w.window.x,
                        w.window.y,
                        w.window.width,
                        w.window.height,
                    )
                })
                .collect();
            for (id, x, y, w, h) in updates {
                self.send_persist_geometry(id, x, y, w, h);
            }
        }
    }

    /// Get application cursor keys mode (DECCKM) state for the focused window
    pub fn get_focused_application_cursor_keys(&self) -> bool {
        if let FocusState::Window(id) = self.focus {
            if let Some(terminal_window) = self.get_window_by_id(id) {
                return terminal_window.get_application_cursor_keys();
            }
        }
        false
    }

    /// Close window by ID
    /// Returns true if a window was actually closed
    ///
    /// Uses MRU (Most Recently Used) algorithm for focus selection:
    /// After closing, focuses the top-most non-minimized window in z-order,
    /// which represents the window the user most recently interacted with.
    pub fn close_window(&mut self, id: u32) -> bool {
        if let Some(pos) = self.get_window_index(id) {
            // Notify daemon if this is a remote window being closed by the client
            #[cfg(unix)]
            if self.persist_client.is_some() {
                if let Some(w) = self.windows.get(pos) {
                    if w.is_remote() {
                        if let Some(ref mut client) = self.persist_client {
                            let _ = client.request_close_window(id);
                        }
                    }
                }
            }

            self.windows.remove(pos);
            self.window_index_cache.remove(&id);
            // Rebuild cache since indices after pos have shifted
            self.rebuild_cache();

            // MRU focus selection: find the top-most non-minimized window
            // The windows Vec is ordered by z-order (last = top = most recently used)
            if self.focus == FocusState::Window(id) {
                // Find next window to focus: iterate from top of z-order (end of vec)
                // looking for a non-minimized window
                let next_focus = self
                    .windows
                    .iter()
                    .rev()
                    .find(|w| !w.window.is_minimized)
                    .map(|w| w.id());

                if let Some(next_id) = next_focus {
                    // Focus the MRU non-minimized window
                    self.focus = FocusState::Window(next_id);
                    // Mark it as focused
                    if let Some(win) = self.get_window_by_id_mut(next_id) {
                        win.set_focused(true);
                    }
                } else {
                    // No non-minimized windows left, focus desktop
                    self.focus = FocusState::Desktop;
                }
            }
            true
        } else {
            false
        }
    }

    /// Handle keyboard input for close confirmation on focused window
    /// Returns Some(true) if should close, Some(false) if canceled, None if no confirmation active
    pub fn handle_close_confirmation_key(
        &mut self,
        window_id: u32,
        key: crossterm::event::KeyEvent,
    ) -> Option<bool> {
        self.get_window_by_id_mut(window_id)
            .and_then(|w| w.handle_close_confirmation_key(key))
    }

    /// Maximize window by ID
    pub fn maximize_window(&mut self, id: u32, buffer_width: u16, buffer_height: u16, gaps: bool) {
        if let Some(win) = self.get_window_by_id_mut(id) {
            // Only maximize if not already maximized
            if !win.window.is_maximized {
                win.window
                    .toggle_maximize(buffer_width, buffer_height, gaps);
                // Resize the terminal to match new window size
                let _ = win.resize(win.window.width, win.window.height);
            }
        }
        #[cfg(unix)]
        self.send_persist_geometry_for_window(id);
    }

    /// Cycle to the next window (for ALT+TAB)
    /// Cycle order: Windows → Topbar → Windows
    /// If the next window is minimized, restore it
    pub fn cycle_to_next_window(&mut self) {
        if self.windows.is_empty() {
            // No windows: cycle between Desktop and Topbar
            match self.focus {
                FocusState::Desktop => self.focus_topbar(),
                FocusState::Topbar => self.focus_desktop(),
                FocusState::Window(_) => self.focus_topbar(),
            }
            return;
        }

        // Get sorted list of windows by creation order (ID)
        let mut sorted_windows: Vec<u32> = self.windows.iter().map(|w| w.id()).collect();
        sorted_windows.sort();

        match self.focus {
            FocusState::Desktop | FocusState::Topbar => {
                // From Desktop or Topbar, go to first window
                let next_window_id = sorted_windows[0];
                self.restore_and_focus_window(next_window_id);
            }
            FocusState::Window(id) => {
                // Find current window index
                let current_index = sorted_windows.iter().position(|&w_id| w_id == id);

                match current_index {
                    Some(idx) if idx + 1 < sorted_windows.len() => {
                        // Not at last window: go to next window
                        let next_window_id = sorted_windows[idx + 1];
                        self.restore_and_focus_window(next_window_id);
                    }
                    Some(_) => {
                        // At last window: go to Topbar (unfocus current window)
                        self.focus_topbar();
                    }
                    None => {
                        // Window not found: go to first window
                        let next_window_id = sorted_windows[0];
                        self.restore_and_focus_window(next_window_id);
                    }
                }
            }
        }
    }

    /// Helper to restore minimized window and focus it
    pub fn restore_and_focus_window(&mut self, window_id: u32) {
        if let Some(win) = self.get_window_by_id_mut(window_id) {
            if win.window.is_minimized {
                win.window.restore_from_minimize();
            } else if win.window.is_maximized {
                win.window.restore_from_maximize();
            }
        }
        self.focus_window(window_id);
    }

    /// Cycle to the previous window (for Shift+Tab)
    /// Cycle order: Windows ← Topbar ← Windows
    /// If the previous window is minimized, restore it
    pub fn cycle_to_previous_window(&mut self) {
        if self.windows.is_empty() {
            // No windows: cycle between Desktop and Topbar
            match self.focus {
                FocusState::Desktop => self.focus_topbar(),
                FocusState::Topbar => self.focus_desktop(),
                FocusState::Window(_) => self.focus_topbar(),
            }
            return;
        }

        // Get sorted list of windows by creation order (ID)
        let mut sorted_windows: Vec<u32> = self.windows.iter().map(|w| w.id()).collect();
        sorted_windows.sort();

        match self.focus {
            FocusState::Desktop => {
                // From Desktop, go to Topbar
                self.focus_topbar();
            }
            FocusState::Topbar => {
                // From Topbar, go to last window
                let prev_window_id = sorted_windows[sorted_windows.len() - 1];
                self.restore_and_focus_window(prev_window_id);
            }
            FocusState::Window(id) => {
                // Find current window index
                let current_index = sorted_windows.iter().position(|&w_id| w_id == id);

                match current_index {
                    Some(0) => {
                        // At first window: go to Topbar (unfocus current window)
                        self.focus_topbar();
                    }
                    Some(idx) => {
                        // Not at first window: go to previous window
                        let prev_window_id = sorted_windows[idx - 1];
                        self.restore_and_focus_window(prev_window_id);
                    }
                    None => {
                        // Window not found: go to last window
                        let prev_window_id = sorted_windows[sorted_windows.len() - 1];
                        self.restore_and_focus_window(prev_window_id);
                    }
                }
            }
        }
    }

    /// Get selected text from a window
    pub fn get_selected_text(&self, window_id: u32) -> Option<String> {
        self.get_window_by_id(window_id)?.get_selected_text()
    }

    /// Paste text to a window
    pub fn paste_to_window(&mut self, window_id: u32, text: &str) -> std::io::Result<()> {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.paste_text(text)?;
        }
        Ok(())
    }

    /// Clear selection in a window
    pub fn clear_selection(&mut self, window_id: u32) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.clear_selection();
        }
    }

    /// Start selection in a window
    pub fn start_selection(
        &mut self,
        window_id: u32,
        x: u16,
        y: u16,
        selection_type: crate::term_emu::SelectionType,
    ) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.start_selection(x, y, selection_type);
        }
    }

    /// Update selection in a window
    pub fn update_selection(&mut self, window_id: u32, x: u16, y: u16) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.update_selection(x, y);
        }
    }

    /// Complete selection in a window
    pub fn complete_selection(&mut self, window_id: u32) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.complete_selection();
        }
    }

    /// Expand selection to word in a window
    pub fn expand_selection_to_word(&mut self, window_id: u32) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.expand_selection_to_word();
        }
    }

    /// Expand selection to line in a window
    pub fn expand_selection_to_line(&mut self, window_id: u32) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.expand_selection_to_line();
        }
    }

    /// Select all content in a window
    pub fn select_all(&mut self, window_id: u32) {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            window.select_all();
        }
    }

    /// Get the mouse position relative to a window's content area
    pub fn get_mouse_content_position(
        &self,
        window_id: u32,
        x: u16,
        y: u16,
    ) -> Option<MouseContentPosition> {
        self.get_window_by_id(window_id)
            .map(|w| w.get_mouse_content_position(x, y))
    }

    /// Scroll the window and update selection for auto-scroll during selection
    pub fn auto_scroll_with_selection(
        &mut self,
        window_id: u32,
        direction: AutoScrollDirection,
    ) -> bool {
        if let Some(window) = self.get_window_by_id_mut(window_id) {
            match direction {
                AutoScrollDirection::Up => window.scroll_up(3),
                AutoScrollDirection::Down => window.scroll_down(3),
            }
            window.update_selection_at_edge(direction);
            true
        } else {
            false
        }
    }

    /// Check if a window is currently being dragged or resized (includes pivot dragging)
    pub fn is_dragging_or_resizing(&self) -> bool {
        self.dragging.is_some() || self.resizing.is_some() || self.pivot_dragging.is_some()
    }

    /// Check if a point is on a window's title bar or resize edge
    /// Returns true if clicking here would start a drag or resize operation
    /// Also returns true for buttons (they're UI elements that shouldn't forward to terminal)
    pub fn is_point_on_drag_or_resize_area(&self, x: u16, y: u16) -> bool {
        if let Some(window_id) = self.window_at(x, y) {
            if let Some(terminal_window) = self.get_window_by_id(window_id) {
                let w = &terminal_window.window;

                // ALWAYS check buttons first - they're UI elements regardless of window state
                if terminal_window.is_in_close_button(x, y)
                    || w.is_in_maximize_button(x, y)
                    || w.is_in_minimize_button(x, y)
                {
                    return true;
                }

                // Check drag/resize areas only for non-maximized windows
                // (can't drag/resize maximized windows)
                if !w.is_maximized {
                    if terminal_window.is_in_title_bar(x, y) || w.get_resize_edge(x, y).is_some() {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Check if the focused window has a selection
    #[allow(dead_code)]
    pub fn focused_window_has_selection(&self) -> bool {
        if let FocusState::Window(window_id) = self.focus {
            self.get_window_by_id(window_id)
                .map(|w| w.has_selection())
                .unwrap_or(false)
        } else {
            false
        }
    }

    /// Check if the focused window has a meaningful selection (more than 1 character)
    pub fn focused_window_has_meaningful_selection(&self) -> bool {
        if let FocusState::Window(window_id) = self.focus {
            self.get_window_by_id(window_id)
                .and_then(|w| w.get_selected_text())
                .map(|text| text.len() > 1)
                .unwrap_or(false)
        } else {
            false
        }
    }

    // =========================================================================
    // Keyboard Mode Window Operations
    // =========================================================================

    /// Get immutable reference to the focused window
    pub fn get_focused_window(&self) -> Option<&TerminalWindow> {
        if let FocusState::Window(id) = self.focus {
            self.get_window_by_id(id)
        } else {
            None
        }
    }

    /// Get mutable reference to the focused window
    pub fn get_focused_window_mut(&mut self) -> Option<&mut TerminalWindow> {
        if let FocusState::Window(id) = self.focus {
            self.get_window_by_id_mut(id)
        } else {
            None
        }
    }

    /// Get the focused window ID
    #[allow(dead_code)]
    pub fn get_focused_window_id(&self) -> Option<u32> {
        if let FocusState::Window(id) = self.focus {
            Some(id)
        } else {
            None
        }
    }

    /// Move the focused window by a relative offset with bounds checking
    /// `top_y` is typically 1 (row 0 is the top bar)
    pub fn move_focused_window_by(
        &mut self,
        dx: i16,
        dy: i16,
        buffer_width: u16,
        buffer_height: u16,
        top_y: u16,
    ) {
        let wid = if let Some(win) = self.get_focused_window_mut() {
            // Don't move maximized windows
            if win.window.is_maximized {
                return;
            }

            // Calculate new position
            let new_x = (win.window.x as i16 + dx).max(0) as u16;
            let new_y = (win.window.y as i16 + dy).max(top_y as i16) as u16;

            // Bounds check - keep window within screen
            let max_x = buffer_width.saturating_sub(win.window.width);
            let max_y = buffer_height.saturating_sub(win.window.height);

            win.window.x = new_x.min(max_x);
            win.window.y = new_y.max(top_y).min(max_y);
            Some(win.id())
        } else {
            None
        };
        #[cfg(unix)]
        if let Some(wid) = wid {
            self.send_persist_geometry_for_window(wid);
        }
    }

    /// Resize the focused window by a relative amount
    /// Returns true if resize was successful
    pub fn resize_focused_window_by(&mut self, dw: i16, dh: i16) -> bool {
        let result = if let Some(win) = self.get_focused_window_mut() {
            // Don't resize maximized windows
            if win.window.is_maximized {
                return false;
            }

            // Calculate new dimensions with minimum constraints
            let new_width = (win.window.width as i16 + dw).max(24) as u16;
            let new_height = (win.window.height as i16 + dh).max(5) as u16;

            win.window.width = new_width;
            win.window.height = new_height;
            let _ = win.resize(new_width, new_height);
            Some(win.id())
        } else {
            None
        };
        #[cfg(unix)]
        if let Some(wid) = result {
            self.send_persist_geometry_for_window(wid);
        }
        result.is_some()
    }

    /// Resize from the left edge: positive step grows width and moves window left
    /// Negative step shrinks width and moves window right
    pub fn resize_focused_window_from_left(&mut self, step: i16) -> bool {
        let result = if let Some(win) = self.get_focused_window_mut() {
            // Don't resize maximized windows
            if win.window.is_maximized {
                return false;
            }

            // Calculate new width and x position
            let new_width = (win.window.width as i16 + step).max(24) as u16;
            let width_change = new_width as i16 - win.window.width as i16;

            // Move window left by the amount we grew (or right if we shrunk)
            let new_x = (win.window.x as i16 - width_change).max(0) as u16;

            win.window.x = new_x;
            win.window.width = new_width;
            let _ = win.resize(new_width, win.window.height);
            Some(win.id())
        } else {
            None
        };
        #[cfg(unix)]
        if let Some(wid) = result {
            self.send_persist_geometry_for_window(wid);
        }
        result.is_some()
    }

    /// Resize from the top edge: positive step grows height and moves window up
    /// Negative step shrinks height and moves window down
    pub fn resize_focused_window_from_top(&mut self, step: i16) -> bool {
        let result = if let Some(win) = self.get_focused_window_mut() {
            // Don't resize maximized windows
            if win.window.is_maximized {
                return false;
            }

            // Calculate new height and y position
            let new_height = (win.window.height as i16 + step).max(5) as u16;
            let height_change = new_height as i16 - win.window.height as i16;

            // Move window up by the amount we grew (or down if we shrunk)
            // Keep y >= 1 (top bar is at row 0)
            let new_y = (win.window.y as i16 - height_change).max(1) as u16;

            win.window.y = new_y;
            win.window.height = new_height;
            let _ = win.resize(win.window.width, new_height);
            Some(win.id())
        } else {
            None
        };
        #[cfg(unix)]
        if let Some(wid) = result {
            self.send_persist_geometry_for_window(wid);
        }
        result.is_some()
    }

    /// Snap the focused window to specific position and size
    /// Used for keyboard snap positions (numpad layout, half-screen, etc.)
    pub fn snap_focused_window(&mut self, x: u16, y: u16, width: u16, height: u16) -> bool {
        if let Some(win) = self.get_focused_window_mut() {
            let wid = win.id();
            // If maximized, restore first
            if win.window.is_maximized {
                win.window.is_maximized = false;
            }

            win.window.x = x;
            win.window.y = y;
            win.window.width = width;
            win.window.height = height;
            let _ = win.resize(width, height);
            #[cfg(unix)]
            self.send_persist_geometry_for_window(wid);
            true
        } else {
            false
        }
    }

    /// Get window centers for spatial navigation
    /// Returns Vec of (window_id, center_x, center_y) for all non-minimized windows
    #[allow(dead_code)]
    pub fn get_window_centers(&self) -> Vec<(u32, u16, u16)> {
        self.windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .map(|w| {
                let center_x = w.window.x + w.window.width / 2;
                let center_y = w.window.y + w.window.height / 2;
                (w.id(), center_x, center_y)
            })
            .collect()
    }

    /// Focus the nearest window in the given direction from the current focused window
    /// direction: 0=left, 1=down, 2=up, 3=right
    /// Returns true if focus was changed
    pub fn focus_window_in_direction(&mut self, direction: u8) -> bool {
        let current_id = match self.focus {
            FocusState::Window(id) => id,
            FocusState::Desktop | FocusState::Topbar => return false,
        };

        // Get current window center
        let current_window = self.get_window_by_id(current_id);
        let (cx, cy) = match current_window {
            Some(w) => (
                w.window.x + w.window.width / 2,
                w.window.y + w.window.height / 2,
            ),
            None => return false,
        };

        // Find candidate windows in the specified direction
        let candidates: Vec<_> = self
            .windows
            .iter()
            .filter(|w| w.id() != current_id && !w.window.is_minimized)
            .filter_map(|w| {
                let wx = w.window.x + w.window.width / 2;
                let wy = w.window.y + w.window.height / 2;

                // Check if window is in the right direction
                let in_direction = match direction {
                    0 => wx < cx, // left
                    1 => wy > cy, // down
                    2 => wy < cy, // up
                    3 => wx > cx, // right
                    _ => false,
                };

                if in_direction {
                    // Calculate weighted distance (favor windows more aligned with direction)
                    let dx = (wx as i32 - cx as i32).unsigned_abs();
                    let dy = (wy as i32 - cy as i32).unsigned_abs();
                    let distance = match direction {
                        0 | 3 => dx + dy / 2, // horizontal: weight x more
                        1 | 2 => dy + dx / 2, // vertical: weight y more
                        _ => dx + dy,
                    };
                    Some((w.id(), distance))
                } else {
                    None
                }
            })
            .collect();

        // Find the nearest candidate
        if let Some((nearest_id, _)) = candidates.into_iter().min_by_key(|(_, dist)| *dist) {
            self.focus_window(nearest_id);
            return true;
        }

        false
    }

    /// Request to close the focused window, checking dirty state first
    /// Returns true if a window was closed, false if confirmation dialog was shown or no window focused
    pub fn request_close_focused_window(&mut self) -> bool {
        if let Some(window) = self.get_focused_window_mut() {
            if window.is_dirty() {
                // Show confirmation dialog
                window.show_close_confirmation();
                false
            } else {
                // Clean window - close immediately
                if let FocusState::Window(id) = self.focus {
                    self.close_window(id)
                } else {
                    false
                }
            }
        } else {
            false
        }
    }

    /// Toggle maximize on the focused window
    /// Returns true if the operation was performed
    pub fn toggle_focused_window_maximize(
        &mut self,
        buffer_width: u16,
        buffer_height: u16,
        gaps: bool,
    ) -> bool {
        if let Some(win) = self.get_focused_window_mut() {
            let wid = win.id();
            win.window
                .toggle_maximize(buffer_width, buffer_height, gaps);
            let _ = win.resize(win.window.width, win.window.height);
            #[cfg(unix)]
            self.send_persist_geometry_for_window(wid);
            true
        } else {
            false
        }
    }

    /// Toggle minimize on the focused window
    /// Returns true if the operation was performed
    pub fn toggle_focused_window_minimize(&mut self) -> bool {
        if let Some(win) = self.get_focused_window_mut() {
            win.window.toggle_minimize();
            true
        } else {
            false
        }
    }

    /// Save current session to file
    pub fn save_session_to_file(&self) -> io::Result<()> {
        let path = session::get_session_path()?;
        let state = self.create_session_state();
        session::save_session(&state, &path)?;
        Ok(())
    }

    /// Clear/delete session file
    pub fn clear_session_file() -> io::Result<()> {
        session::clear_session()
    }

    /// Create a session state from current windows
    fn create_session_state(&self) -> SessionState {
        let mut state = SessionState::new();
        state.next_id = self.next_id;

        // Extract focused window ID (Topbar focus treated as no window focused)
        state.focused_window_id = match self.focus {
            FocusState::Window(id) => Some(id),
            FocusState::Desktop | FocusState::Topbar => None,
        };

        // Extract window snapshots (in z-order)
        for terminal_window in &self.windows {
            let window = &terminal_window.window;
            let (terminal_lines, cursor) = terminal_window.get_terminal_content();
            let (pre_max_x, pre_max_y, pre_max_w, pre_max_h) = window.get_pre_maximize_geometry();

            let snapshot = WindowSnapshot {
                id: window.id,
                title: window.title.clone(),
                x: window.x,
                y: window.y,
                width: window.width,
                height: window.height,
                is_focused: window.is_focused,
                is_minimized: window.is_minimized,
                is_maximized: window.is_maximized,
                pre_maximize_x: pre_max_x,
                pre_maximize_y: pre_max_y,
                pre_maximize_width: pre_max_w,
                pre_maximize_height: pre_max_h,
                scroll_offset: terminal_window.get_scroll_offset(),
                cursor,
                terminal_lines,
            };

            state.windows.push(snapshot);
        }

        state
    }

    /// Restore session from file
    pub fn restore_session_from_file(shell_config: ShellConfig) -> io::Result<Self> {
        let path = session::get_session_path()?;

        // Try to load session
        let state = match session::load_session(&path)? {
            Some(s) => s,
            None => {
                // No session file found, return default with shell config
                return Ok(Self::with_shell_config(shell_config));
            }
        };

        let mut manager = Self::with_shell_config(shell_config);
        manager.next_id = state.next_id;

        // Restore windows
        for snapshot in state.windows {
            // Create new terminal window with same geometry
            if let Ok(mut terminal_window) = TerminalWindow::new(
                snapshot.id,
                snapshot.x,
                snapshot.y,
                snapshot.width,
                snapshot.height,
                snapshot.title.clone(),
                None, // No initial command for restored windows
                &manager.shell_config,
            ) {
                // Restore window state
                terminal_window.set_focused(snapshot.is_focused);
                terminal_window.window.is_minimized = snapshot.is_minimized;
                terminal_window.window.is_maximized = snapshot.is_maximized;
                terminal_window.window.set_pre_maximize_geometry(
                    snapshot.pre_maximize_x,
                    snapshot.pre_maximize_y,
                    snapshot.pre_maximize_width,
                    snapshot.pre_maximize_height,
                );

                // Restore scroll offset
                terminal_window.set_scroll_offset(snapshot.scroll_offset);

                // Restore terminal content
                terminal_window.restore_terminal_content(snapshot.terminal_lines, &snapshot.cursor);

                manager.windows.push(terminal_window);
            }
        }

        // Rebuild cache after restoring all windows
        manager.rebuild_cache();

        // Restore focus state
        manager.focus = match state.focused_window_id {
            Some(id) => FocusState::Window(id),
            None => FocusState::Desktop,
        };

        Ok(manager)
    }

    // =========================================================================
    // Pivot Operations for Tiled Window Resizing
    // =========================================================================

    /// Get visible (non-minimized) window count
    fn visible_window_count(&self) -> usize {
        self.windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .count()
    }

    /// Check if a window is in the locked tiled set (first 4 visible windows when auto-tiling)
    /// Locked windows cannot be moved or resized manually (but pivot still works)
    pub fn is_window_tiled_locked(&self, window_id: u32, auto_tiling_enabled: bool) -> bool {
        if !auto_tiling_enabled {
            return false;
        }

        // Get visible windows sorted by ID (creation order)
        let mut visible_ids: Vec<u32> = self
            .windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .map(|w| w.id())
            .collect();
        visible_ids.sort();

        // Check if this window is in the first 4
        visible_ids.iter().take(4).any(|&id| id == window_id)
    }

    /// Check if pivot should be visible
    pub fn should_show_pivot(&self, gaps: bool) -> bool {
        let visible_count = self.visible_window_count();
        gaps && (2..=4).contains(&visible_count)
    }

    /// Calculate the pivot position based on current split ratios
    /// Returns (x, y) position of pivot center, or None if pivot shouldn't be shown
    pub fn calculate_pivot_position(
        &self,
        buffer_width: u16,
        buffer_height: u16,
        gaps: bool,
    ) -> Option<(u16, u16)> {
        let visible_count = self.visible_window_count();

        // Pivot only shown for 2-4 windows with gaps enabled
        if !gaps || !(2..=4).contains(&visible_count) {
            return None;
        }

        const EDGE_GAP: u16 = 1;
        const SHADOW_SIZE: u16 = 2;
        const INTER_GAP: u16 = 1;

        // Calculate usable dimensions (matching apply_split_ratios)
        let usable_width = buffer_width.saturating_sub(2 * EDGE_GAP + 2 * SHADOW_SIZE + INTER_GAP);
        let usable_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + 2 * SHADOW_SIZE);

        // Horizontal position: at the inter-gap between left/right columns
        let left_col_width = (usable_width as f32 * self.h_split_ratio) as u16;
        let pivot_x = EDGE_GAP + left_col_width + SHADOW_SIZE;

        // Vertical position depends on window count
        let pivot_y = match visible_count {
            2 => {
                // 2 windows: side by side, pivot at vertical center
                let top_y = 1 + EDGE_GAP;
                let full_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + SHADOW_SIZE);
                top_y + full_height / 2
            }
            3 | 4 => {
                // 3 or 4 windows: use v_split_ratio for vertical position
                let top_height = (usable_height as f32 * self.v_split_ratio) as u16;
                let top_y = 1 + EDGE_GAP;
                top_y + top_height + SHADOW_SIZE / 2
            }
            _ => buffer_height / 2,
        };

        Some((pivot_x, pivot_y))
    }

    /// Check if a point is on the pivot (1-char hit area)
    pub fn is_point_on_pivot(
        &self,
        x: u16,
        y: u16,
        buffer_width: u16,
        buffer_height: u16,
        gaps: bool,
    ) -> bool {
        if let Some((px, py)) = self.calculate_pivot_position(buffer_width, buffer_height, gaps) {
            x == px && y == py
        } else {
            false
        }
    }

    /// Start pivot drag operation
    pub fn start_pivot_drag(&mut self, x: u16, y: u16) {
        self.pivot_dragging = Some(PivotDragState {
            start_x: x,
            start_y: y,
            start_h_ratio: self.h_split_ratio,
            start_v_ratio: self.v_split_ratio,
        });
    }

    /// Handle pivot drag movement
    pub fn handle_pivot_drag(&mut self, x: u16, y: u16, buffer_width: u16, buffer_height: u16) {
        let Some(drag) = self.pivot_dragging else {
            return;
        };

        // Clear double-click tracking when dragging (prevents false double-click after drag)
        self.last_pivot_click = None;

        let visible_count = self.visible_window_count();
        if !(2..=4).contains(&visible_count) {
            return;
        }

        const EDGE_GAP: u16 = 1;
        const SHADOW_SIZE: u16 = 2;
        const INTER_GAP: u16 = 1;
        const MIN_RATIO: f32 = 0.2; // Minimum 20% for any column/row
        const MAX_RATIO: f32 = 0.8; // Maximum 80%

        let usable_width = buffer_width.saturating_sub(2 * EDGE_GAP + 2 * SHADOW_SIZE + INTER_GAP);
        let usable_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + 2 * SHADOW_SIZE);

        // Calculate horizontal ratio change (all 2-4 window layouts)
        let delta_x = x as i32 - drag.start_x as i32;
        let ratio_delta_h = delta_x as f32 / usable_width as f32;
        self.h_split_ratio = (drag.start_h_ratio + ratio_delta_h).clamp(MIN_RATIO, MAX_RATIO);

        // Calculate vertical ratio change (only for 4 windows)
        if visible_count == 4 {
            let delta_y = y as i32 - drag.start_y as i32;
            let ratio_delta_v = delta_y as f32 / usable_height as f32;
            self.v_split_ratio = (drag.start_v_ratio + ratio_delta_v).clamp(MIN_RATIO, MAX_RATIO);
        }

        // Apply new ratios to window positions
        self.apply_split_ratios(buffer_width, buffer_height);
    }

    /// End pivot drag and resize PTYs
    pub fn end_pivot_drag(&mut self) {
        if self.pivot_dragging.is_some() {
            self.pivot_dragging = None;

            // Resize all terminal PTYs to match new window dimensions
            for window in &mut self.windows {
                if !window.window.is_minimized {
                    let _ = window.resize(window.window.width, window.window.height);
                }
            }
        }
    }

    /// Apply current split ratios to window positions
    fn apply_split_ratios(&mut self, buffer_width: u16, buffer_height: u16) {
        const EDGE_GAP: u16 = 1;
        const SHADOW_SIZE: u16 = 2;
        const INTER_GAP: u16 = 1;

        let visible_count = self.visible_window_count();
        if !(2..=4).contains(&visible_count) {
            return;
        }

        // Get visible windows sorted by ID (creation order)
        let mut visible_ids: Vec<u32> = self
            .windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .map(|w| w.id())
            .collect();
        visible_ids.sort();

        // Calculate dimensions based on ratios
        let usable_width = buffer_width.saturating_sub(2 * EDGE_GAP + 2 * SHADOW_SIZE + INTER_GAP);
        let usable_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + 2 * SHADOW_SIZE);

        let left_width = (usable_width as f32 * self.h_split_ratio) as u16;
        let right_width = usable_width.saturating_sub(left_width);
        let top_height = (usable_height as f32 * self.v_split_ratio) as u16;

        let left_x = EDGE_GAP;
        let right_x = EDGE_GAP + left_width + SHADOW_SIZE + INTER_GAP;
        let top_y = 1 + EDGE_GAP;
        let bottom_y = 1 + EDGE_GAP + top_height + SHADOW_SIZE;

        let full_height = buffer_height.saturating_sub(1 + 2 * EDGE_GAP + SHADOW_SIZE);
        let bottom_height = buffer_height.saturating_sub(bottom_y + SHADOW_SIZE + EDGE_GAP);

        // Apply positions based on window count
        match visible_count {
            2 => {
                // Window 1: Left (full height)
                // Window 2: Right (full height)
                if let Some(w) = self.get_window_by_id_mut(visible_ids[0]) {
                    w.window.x = left_x;
                    w.window.y = top_y;
                    w.window.width = left_width;
                    w.window.height = full_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[1]) {
                    w.window.x = right_x;
                    w.window.y = top_y;
                    w.window.width = right_width;
                    w.window.height = full_height;
                }
            }
            3 => {
                // Window 1: Top-left
                // Window 2: Bottom-left
                // Window 3: Full-right
                if let Some(w) = self.get_window_by_id_mut(visible_ids[0]) {
                    w.window.x = left_x;
                    w.window.y = top_y;
                    w.window.width = left_width;
                    w.window.height = top_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[1]) {
                    w.window.x = left_x;
                    w.window.y = bottom_y;
                    w.window.width = left_width;
                    w.window.height = bottom_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[2]) {
                    w.window.x = right_x;
                    w.window.y = top_y;
                    w.window.width = right_width;
                    w.window.height = full_height;
                }
            }
            4 => {
                // 2x2 grid
                if let Some(w) = self.get_window_by_id_mut(visible_ids[0]) {
                    w.window.x = left_x;
                    w.window.y = top_y;
                    w.window.width = left_width;
                    w.window.height = top_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[1]) {
                    w.window.x = left_x;
                    w.window.y = bottom_y;
                    w.window.width = left_width;
                    w.window.height = bottom_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[2]) {
                    w.window.x = right_x;
                    w.window.y = top_y;
                    w.window.width = right_width;
                    w.window.height = top_height;
                }
                if let Some(w) = self.get_window_by_id_mut(visible_ids[3]) {
                    w.window.x = right_x;
                    w.window.y = bottom_y;
                    w.window.width = right_width;
                    w.window.height = bottom_height;
                }
            }
            _ => {}
        }
    }

    /// Reset split ratios to default (50/50)
    #[allow(dead_code)]
    pub fn reset_split_ratios(&mut self) {
        self.h_split_ratio = 0.5;
        self.v_split_ratio = 0.5;
    }

    /// Check if currently dragging pivot
    #[allow(dead_code)]
    pub fn is_dragging_pivot(&self) -> bool {
        self.pivot_dragging.is_some()
    }

    /// Swap windows between left and right columns (double-click pivot action)
    pub fn swap_windows_horizontal(&mut self, buffer_width: u16, buffer_height: u16) {
        let visible_count = self.visible_window_count();
        if !(2..=4).contains(&visible_count) {
            return;
        }

        // Get visible window IDs sorted by creation order
        let mut visible_ids: Vec<u32> = self
            .windows
            .iter()
            .filter(|w| !w.window.is_minimized)
            .map(|w| w.id())
            .collect();
        visible_ids.sort();

        // Swap window IDs between columns by swapping internal IDs
        // This changes which window appears in which sorted position
        match visible_count {
            2 => {
                // Swap IDs of windows 0 and 1
                self.swap_window_ids(visible_ids[0], visible_ids[1]);
            }
            3 => {
                // Treat same as 4-window: swap columns
                // Left column (0,1) <-> Right column (2)
                // After swap: right window becomes top-left, top-left becomes right
                self.swap_window_ids(visible_ids[0], visible_ids[2]);
                // Note: visible_ids[1] (bottom-left) stays in left column
            }
            4 => {
                // Swap columns: [0,1] <-> [2,3]
                self.swap_window_ids(visible_ids[0], visible_ids[2]);
                self.swap_window_ids(visible_ids[1], visible_ids[3]);
            }
            _ => {}
        }

        // Rebuild cache and re-apply positions
        self.rebuild_cache();
        self.apply_split_ratios(buffer_width, buffer_height);

        // Resize PTYs
        for window in &mut self.windows {
            if !window.window.is_minimized {
                let _ = window.resize(window.window.width, window.window.height);
            }
        }
    }

    /// Helper: Swap the IDs of two windows
    fn swap_window_ids(&mut self, id1: u32, id2: u32) {
        let idx1 = self.get_window_index(id1);
        let idx2 = self.get_window_index(id2);

        if let (Some(i1), Some(i2)) = (idx1, idx2) {
            // Swap the IDs in the window structs
            self.windows[i1].window.id = id2;
            self.windows[i2].window.id = id1;
        }
    }

    /// Render the pivot character if conditions are met
    pub fn render_pivot(
        &self,
        buffer: &mut VideoBuffer,
        charset: &Charset,
        _theme: &Theme,
        gaps: bool,
    ) {
        use crate::rendering::Cell;

        if !self.should_show_pivot(gaps) {
            return;
        }

        let (buffer_width, buffer_height) = buffer.dimensions();

        if let Some((x, y)) = self.calculate_pivot_position(buffer_width, buffer_height, gaps) {
            // Get the current cell at this position and invert its colors
            let (pivot_fg, pivot_bg) = if let Some(current_cell) = buffer.get(x, y) {
                // Invert: current fg becomes bg, current bg becomes fg
                (current_cell.fg_color, current_cell.bg_color)
            } else {
                // Fallback if cell doesn't exist
                (
                    crossterm::style::Color::Black,
                    crossterm::style::Color::White,
                )
            };

            buffer.set(x, y, Cell::new(charset.pivot, pivot_fg, pivot_bg));
        }
    }
}

impl Default for WindowManager {
    fn default() -> Self {
        Self::new()
    }
}