uzor 1.5.39

Core UI engine — geometry, interaction, input state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
//! DockState — Generic panel orchestration layer
//!
//! This module provides the orchestration layer for the docking panel system.
//! It bridges the panel tree data structures with layout computation, separator
//! generation, drag-and-drop, and floating windows.
//!
//! # Architecture
//!
//! DockState wraps:
//! - **DockingTree<P>**: Generic N-ary panel tree
//! - **Separators**: Generated from tree branches
//! - **Floating Windows**: Panels extracted from tree
//! - **Drag State**: Panel/tab/floating window drag operations
//!
//! # Type Parameter
//!
//! - `P: DockPanel` — The panel type stored in leaves (generic over domain-specific panels)
//!
//! # Usage
//!
//! ```rust,ignore
//! use uzor_panels::{DockState, DockPanel, LeafId, PanelRect};
//!
//! #[derive(Clone)]
//! struct MyPanel { title: String }
//!
//! impl DockPanel for MyPanel {
//!     fn title(&self) -> &str { &self.title }
//!     fn type_id(&self) -> &'static str { "my_panel" }
//! }
//!
//! let mut manager = DockState::<MyPanel>::new();
//! manager.add_leaf(MyPanel { title: "Chart".to_string() });
//! manager.layout(PanelRect::new(0.0, 0.0, 1920.0, 1080.0));
//!
//! // Hit test
//! match manager.hit_test(100.0, 200.0) {
//!     HitResult::Panel(id) => println!("Hit panel {:?}", id),
//!     HitResult::Separator(idx) => println!("Hit separator {}", idx),
//!     _ => {}
//! }
//! ```

use crate::layout::docking::{
    DockPanel, DockingTree, Leaf, Branch, PanelNode, LeafId, BranchId, PanelRect,
    Separator, SeparatorOrientation, SeparatorState, SeparatorLevel,
    SnapBackAnimation, TabBarInfo, TabItem, TabReorderState,
    FloatingWindow, FloatingWindowId, FloatingDragState,
    HitResult, CornerHandle, DropZone, PanelDragState, DragPayload,
    WindowLayout, SplitterPolicy, GridAxis, GridLine, GridSpec,
};
use std::collections::HashMap;

// =============================================================================
// DockState
// =============================================================================

/// Generic panel manager for docking system
///
/// Orchestrates:
/// - Panel tree layout (DockingTree)
/// - Separator generation and interaction
/// - Floating windows
/// - Drag-and-drop operations
/// - Tab management
///
/// Type parameter `P` is the panel type (must implement `DockPanel` trait).
pub struct DockState<P: DockPanel> {
    /// Docking tree (N-ary panel tree with tabs, splits, grids)
    tree: DockingTree<P>,
    /// Computed separators (after layout)
    separators: Vec<Separator>,
    /// Computed panel rects (after layout) — keyed by LeafId
    panel_rects: HashMap<LeafId, PanelRect>,
    /// Computed panel header rects (after layout) — for drag detection
    panel_headers: HashMap<LeafId, PanelRect>,
    /// Tab bars (for Tabs containers with multiple panels)
    tab_bars: Vec<TabBarInfo>,
    /// Corner handles (separator intersections for bidirectional resize)
    corners: Vec<CornerHandle>,
    /// Layout area (full manager dimensions) — for window-edge drop detection
    layout_area: PanelRect,
    /// Window edge indicator rects (for window-level drop zones)
    /// [top, bottom, left, right]
    window_edge_rects: Option<[PanelRect; 4]>,
    /// Panel drag state (for header drag-and-drop)
    panel_drag: Option<PanelDragState>,
    /// Tab reorder state (for dragging tabs within a container)
    tab_reorder: Option<TabReorderState>,
    /// Snap-back animations for separators (when constraints violated)
    snap_animations: Vec<SnapBackAnimation>,
    /// Floating windows (extracted from tree, hovering above layout)
    floating_windows: Vec<FloatingWindow<P>>,
    /// Drag state for floating window repositioning
    floating_drag: Option<FloatingDragState>,
    /// Next floating window ID counter
    next_floating_id: u64,
    /// Hovered header (for transparent overlay headers)
    hovered_header: Option<LeafId>,
    /// Active panel (focused leaf)
    active_leaf: Option<LeafId>,
    /// Panel header height (default 24px)
    header_height: f32,
    /// Per-leaf minimum size overrides in pixels (width, height).
    /// Falls back to `panel.min_size()` when not set.
    leaf_min_sizes: HashMap<LeafId, (f32, f32)>,
    /// Whether a drop on a panel BODY may resolve to `DropZone::Center`
    /// (tabify). When disabled the body is classified sides-only — the four
    /// diagonal quadrants each map to a side split, so no cursor position is
    /// a dead drop. Consumers without tab UI disable this.
    body_center_drop: bool,
    /// Consumer veto/override for drop targeting (panel-type constraints —
    /// e.g. one-row strips only dock Up/Down). Applied to every candidate
    /// `(dragged, target, zone)` while a drag is live.
    drop_policy: Option<DropPolicyFn<P>>,
    /// How separator drags treat minimum sizes. Default
    /// [`SplitterPolicy::Cascade`] (today's behaviour).
    splitter_policy: SplitterPolicy,
    /// Pixels kept free at the right end of every multi-tab chip bar
    /// (room for a trailing "+" button the consumer draws). Default `0.0`:
    /// chips share the full leaf width, as before.
    tab_strip_reserve: f32,
}

/// Consumer drop-targeting policy. Arguments: the dragged panel, the
/// target leaf's ACTIVE panel (`None` only for the window-edge fallback
/// target), the detected [`DropZone`], `is_window_edge`, and the cursor
/// position inside the target rect normalized to 0..1 (`(0.5, 0.5)` when
/// no target rect applies). Returns the zone to use, or `None` to reject
/// this target entirely.
pub type DropPolicyFn<P> =
    Box<dyn Fn(&P, Option<&P>, DropZone, bool, (f32, f32)) -> Option<DropZone> + Send + Sync>;

impl<P: DockPanel> DockState<P> {
    /// Create new docking manager with empty tree
    pub fn new() -> Self {
        Self {
            tree: DockingTree::new(),
            separators: Vec::new(),
            panel_rects: HashMap::new(),
            panel_headers: HashMap::new(),
            tab_bars: Vec::new(),
            corners: Vec::new(),
            layout_area: PanelRect::ZERO,
            window_edge_rects: None,
            panel_drag: None,
            tab_reorder: None,
            snap_animations: Vec::new(),
            floating_windows: Vec::new(),
            floating_drag: None,
            next_floating_id: 1,
            hovered_header: None,
            active_leaf: None,
            header_height: 24.0,
            leaf_min_sizes: HashMap::new(),
            body_center_drop: true,
            drop_policy: None,
            splitter_policy: SplitterPolicy::Cascade,
            tab_strip_reserve: 0.0,
        }
    }

    /// Create manager from an existing `DockingTree`.
    ///
    /// All derived state (separators, rects, drag state, etc.) is reset to
    /// empty. Call [`layout`](Self::layout) after construction to recompute
    /// geometry.
    ///
    /// This is the primary entry-point for restoring a layout from a
    /// [`LayoutSnapshot`]:
    ///
    /// ```rust,ignore
    /// let tree = snapshot.restore_tree(|type_id| create_panel(type_id))?;
    /// let manager = DockingManager::from_tree(tree);
    /// ```
    pub fn from_tree(tree: DockingTree<P>) -> Self {
        let active_leaf = tree.active_leaf_id();
        Self {
            tree,
            separators: Vec::new(),
            panel_rects: HashMap::new(),
            panel_headers: HashMap::new(),
            tab_bars: Vec::new(),
            corners: Vec::new(),
            layout_area: PanelRect::ZERO,
            window_edge_rects: None,
            panel_drag: None,
            tab_reorder: None,
            snap_animations: Vec::new(),
            floating_windows: Vec::new(),
            floating_drag: None,
            next_floating_id: 1,
            hovered_header: None,
            active_leaf,
            header_height: 24.0,
            leaf_min_sizes: HashMap::new(),
            body_center_drop: true,
            drop_policy: None,
            splitter_policy: SplitterPolicy::Cascade,
            tab_strip_reserve: 0.0,
        }
    }

    /// Create manager with single panel
    pub fn with_panel(panel: P) -> Self {
        let tree = DockingTree::with_single_leaf(panel);
        let active_leaf = tree.active_leaf_id();
        Self {
            tree,
            separators: Vec::new(),
            panel_rects: HashMap::new(),
            panel_headers: HashMap::new(),
            tab_bars: Vec::new(),
            corners: Vec::new(),
            layout_area: PanelRect::ZERO,
            window_edge_rects: None,
            panel_drag: None,
            tab_reorder: None,
            snap_animations: Vec::new(),
            floating_windows: Vec::new(),
            floating_drag: None,
            next_floating_id: 1,
            hovered_header: None,
            active_leaf,
            header_height: 24.0,
            leaf_min_sizes: HashMap::new(),
            body_center_drop: true,
            drop_policy: None,
            splitter_policy: SplitterPolicy::Cascade,
            tab_strip_reserve: 0.0,
        }
    }

    // =============================================================================
    // Tree Access
    // =============================================================================

    /// Get reference to docking tree
    pub fn tree(&self) -> &DockingTree<P> {
        &self.tree
    }

    /// Get mutable reference to docking tree
    pub fn tree_mut(&mut self) -> &mut DockingTree<P> {
        &mut self.tree
    }

    // =============================================================================
    // Layout
    // =============================================================================

    /// Compute layout for all panels
    ///
    /// This walks the tree recursively and computes PanelRect for each panel.
    /// Results are stored in `panel_rects`, `panel_headers`, `separators`, and `tab_bars`.
    pub fn layout(&mut self, area: PanelRect) {
        self.layout_area = area;

        // Water-fill normalization: enforce per-child min sizes before computing rects.
        // Idempotent — only mutates proportions when they violate minimums.
        self.normalize_proportions(area.width, area.height);

        self.panel_rects.clear();
        self.panel_headers.clear();
        self.separators.clear();
        self.tab_bars.clear();

        // Layout tree (compute rects for all leaves)
        let rects = self.compute_leaf_rects(area);

        for (leaf_id, rect) in rects {
            let leaf = match self.tree.leaf(leaf_id) {
                Some(l) => l,
                None => continue,
            };

            // Store panel rect
            self.panel_rects.insert(leaf_id, rect);

            // Panel header (for single-tab panels only)
            if rect.width >= 1.0 && rect.height >= 1.0 && leaf.tab_count() <= 1
                && leaf.active_panel().map_or(true, |p| p.shows_header())
            {
                self.panel_headers.insert(leaf_id, PanelRect::new(
                    rect.x, rect.y, rect.width, self.header_height,
                ));
            }

            // Tab bar (for multi-tab panels)
            if leaf.tab_count() > 1 && rect.width >= 1.0 && rect.height >= 1.0 {
                let tab_bar = self.create_tab_bar(leaf_id, leaf, rect);
                self.tab_bars.push(tab_bar);
            }
        }

        // Generate separators recursively (clone root to avoid borrow conflict)
        let root = self.tree.root().clone();
        self.generate_separators_recursive(&root, area);

        // Detect corners at separator intersections
        self.detect_corners();
    }

    /// Set a single leaf as occupying the entire area (used by expand).
    pub fn set_single_panel_rect(&mut self, leaf_id: LeafId, area: PanelRect) {
        self.layout_area = area;
        self.panel_rects.clear();
        self.panel_headers.clear();
        self.separators.clear();
        self.tab_bars.clear();
        self.panel_rects.insert(leaf_id, area);
        if let Some(leaf) = self.tree.leaf(leaf_id) {
            if area.width >= 1.0 && area.height >= 1.0 && leaf.tab_count() <= 1
                && leaf.active_panel().map_or(true, |p| p.shows_header())
            {
                self.panel_headers.insert(leaf_id, PanelRect::new(
                    area.x, area.y, area.width, self.header_height,
                ));
            }
            if leaf.tab_count() > 1 && area.width >= 1.0 && area.height >= 1.0 {
                let tab_bar = self.create_tab_bar(leaf_id, leaf, area);
                self.tab_bars.push(tab_bar);
            }
        }
    }

    /// Compute leaf rects from tree layout (delegates to the pure-fn lib).
    fn compute_leaf_rects(&self, area: PanelRect) -> HashMap<LeafId, PanelRect> {
        crate::layout::docking::lib::compute_leaf_rects(&self.tree, area)
    }


    /// Create tab bar for multi-tab leaf — chips share the leaf's FULL
    /// width evenly (VSCode-style stretch, owner spec 2026-07-29), not
    /// text-sized left-packed islands.
    fn create_tab_bar(&self, leaf_id: LeafId, leaf: &Leaf<P>, rect: PanelRect) -> TabBarInfo {
        let tab_bar_height = self.header_height;
        let mut tab_items = Vec::new();
        let mut tab_x_offset = 0.0_f32;
        let even_w = (rect.width - self.tab_strip_reserve).max(0.0) / leaf.panels.len().max(1) as f32;

        for (i, panel) in leaf.panels.iter().enumerate() {
            let title = panel.title();
            let tab_w = even_w.max(0.0);

            let tab_rect = PanelRect::new(
                rect.x + tab_x_offset,
                rect.y,
                tab_w,
                tab_bar_height,
            );

            let close_size = 14.0;
            let close_rect = PanelRect::new(
                tab_rect.x + tab_rect.width - close_size - 4.0,
                tab_rect.y + (tab_bar_height - close_size) / 2.0,
                close_size,
                close_size,
            );

            tab_items.push(TabItem {
                panel_id: LeafId(leaf_id.0 * 100 + i as u64), // unique id per tab
                title: title.to_string(),
                rect: tab_rect,
                is_active: i == leaf.active_tab,
                close_rect,
            });

            tab_x_offset += tab_w;
        }

        let tab_bar_rect = PanelRect::new(rect.x, rect.y, tab_x_offset, tab_bar_height);

        TabBarInfo {
            container_id: leaf_id,
            rect: tab_bar_rect,
            tabs: tab_items,
        }
    }

    /// Generate separators recursively through the tree (delegates to lib).
    ///
    /// Field-level split borrow: separate `&self.tree` (shared) from
    /// `&mut self.separators` (exclusive) so the free fn can read tree
    /// while writing the separator list.
    fn generate_separators_recursive(&mut self, branch: &Branch<P>, branch_rect: PanelRect) {
        crate::layout::docking::lib::generate_separators(branch, branch_rect, &mut self.separators);
    }

    /// Detect corners at separator intersections.
    fn detect_corners(&mut self) {
        self.corners = crate::layout::docking::lib::detect_corners(&self.separators);
    }

    // =============================================================================
    // Hit Testing
    // =============================================================================

    /// Hit test at given point
    ///
    /// Returns what's at this point (priority: corners > separators > panels > none)
    pub fn hit_test(&self, x: f32, y: f32) -> HitResult {
        // Check corners first (highest priority)
        let corner_hit_radius = 10.0_f32;
        for (i, corner) in self.corners.iter().enumerate() {
            if corner.hit_test(x, y, corner_hit_radius) {
                return HitResult::Corner(i);
            }
        }

        // Check separators
        for (idx, sep) in self.separators.iter().enumerate() {
            if sep.hit_test(x, y) {
                return HitResult::Separator(idx);
            }
        }

        // Check panels
        for (&id, rect) in &self.panel_rects {
            if rect.contains(x, y) {
                return HitResult::Panel(id);
            }
        }

        HitResult::None
    }

    // =============================================================================
    // Separator Hover + Resize
    // =============================================================================

    /// Move a separator by a pixel delta along its axis.
    ///
    /// Uses cascading resize: when dragging, the delta is taken from siblings
    /// on one side in order, never going below each child's minimum size.
    /// This allows multi-panel resize without rejecting moves.
    ///
    /// That is the default [`SplitterPolicy::Cascade`] behaviour for preset
    /// layouts; [`SplitterPolicy::Clamp`] moves only the two neighbours and
    /// stops at the limit; [`SplitterPolicy::RejectSnapBack`] moves only the
    /// two neighbours and refuses (with a snap-back) a move past a minimum. A `rows × cols` grid line moves
    /// only its two adjacent row / column ratios (see [`SplitterPolicy`] for
    /// how each policy treats minimums there).
    ///
    /// Per-leaf minimum sizes are read from [`set_leaf_min_size`] overrides,
    /// falling back to `panel.min_size()`. Branch minimums are derived
    /// recursively via [`min_for_node`].
    ///
    /// # Arguments
    /// - `sep_idx`: Index into the `separators()` slice.
    /// - `delta`: Pixel movement along the separator's axis (positive = right/down).
    /// - `content_width`: Full content area width (for `rect_for_branch`).
    /// - `content_height`: Full content area height (for `rect_for_branch`).
    ///
    /// # Returns
    /// `true` if the proportions were updated, `false` if the separator was not
    /// found or the branch has fewer than 2 children.
    pub fn drag_separator(
        &mut self,
        sep_idx: usize,
        delta: f32,
        content_width: f32,
        content_height: f32,
    ) -> bool {
        // Snapshot separator info to avoid borrow conflicts.
        let (parent_id, child_a_raw, child_b_raw, orientation, grid_line) = {
            let sep = match self.separators.get(sep_idx) {
                Some(s) => s,
                None => return false,
            };
            let (parent_id, child_a, child_b) = match &sep.level {
                SeparatorLevel::Node { parent_id, child_a, child_b } => {
                    (*parent_id, *child_a, *child_b)
                }
            };
            (parent_id, child_a, child_b, sep.orientation, sep.grid_line)
        };

        // Rows × cols grid line: moves only the two adjacent row / column
        // ratios of the grid branch.
        if let Some(line) = grid_line {
            return self.drag_grid_line(sep_idx, parent_id, line, delta, content_width, content_height);
        }

        // Use the actual pixel size of the parent branch (not the full content area).
        // This ensures nested branches are correctly constrained.
        let branch_rect = self.tree.rect_for_branch(parent_id, content_width, content_height);
        let branch_size = match branch_rect {
            Some(r) => match orientation {
                SeparatorOrientation::Horizontal => r.height,
                SeparatorOrientation::Vertical => r.width,
            },
            None => match orientation {
                SeparatorOrientation::Horizontal => content_height,
                SeparatorOrientation::Vertical => content_width,
            },
        };

        if branch_size <= 0.0 {
            return false;
        }

        // Retrieve proportions, child positions, and per-child minimums.
        let (n, raw_props, children_min_px, pos_a, pos_b) = {
            let branch = match self.tree.find_branch(parent_id) {
                Some(b) => b,
                None => return false,
            };

            let n = branch.children.len();
            if n < 2 {
                return false;
            }

            let raw_props: Vec<f64> = if branch.proportions.len() == n {
                branch.proportions.clone()
            } else {
                vec![1.0_f64 / n as f64; n]
            };

            // Per-child minimum in pixels along the drag axis.
            let children_min_px: Vec<f32> = if orientation == SeparatorOrientation::Vertical {
                branch.children.iter()
                    .map(|c| self.min_width_for_node(c))
                    .collect()
            } else {
                branch.children.iter()
                    .map(|c| self.min_height_for_node(c))
                    .collect()
            };

            let pos_a = branch.children.iter().position(|c| c.raw_id() == child_a_raw);
            let pos_b = branch.children.iter().position(|c| c.raw_id() == child_b_raw);
            let (pos_a, pos_b) = match (pos_a, pos_b) {
                (Some(a), Some(b)) => (a, b),
                _ => return false,
            };

            (n, raw_props, children_min_px, pos_a, pos_b)
        };

        // --- Multi-axis fast path: route separator drags to cross_ratio ---
        //
        // Grid2x2 and the four L-shaped layouts (OneLeftTwoRight, TwoLeftOneRight,
        // OneTopTwoBottom, TwoTopOneBottom) are controlled by cross_ratio rather
        // than proportions.  Writing proportions on them is wrong — the Part A
        // guard in compute_child_rects prevents the layout collapse, but we still
        // need a functional drag.  Convert the pixel delta into a ratio delta and
        // commit via set_branch_cross_ratio.
        //
        // Default cross_ratio when None (matches presets.rs fixed-shape defaults):
        //   Grid2x2          : (0.5, 0.5)
        //   OneLeftTwoRight  : (0.6, 0.5)   xr=left fraction, yr=right-column split
        //   TwoLeftOneRight  : (0.4, 0.5)   xr=left fraction, yr=left-column split
        //   OneTopTwoBottom  : (0.5, 0.6)   yr=top fraction,  xr=bottom-row split
        //   TwoTopOneBottom  : (0.5, 0.4)   yr=top fraction,  xr=top-row split
        {
            let layout_opt = self.tree.find_branch(parent_id).map(|b| b.layout);
            let default_cross_ratio = match layout_opt {
                Some(WindowLayout::Grid2x2)         => Some((0.5, 0.5)),
                Some(WindowLayout::OneLeftTwoRight)  => Some((0.6, 0.5)),
                Some(WindowLayout::TwoLeftOneRight)  => Some((0.4, 0.5)),
                Some(WindowLayout::OneTopTwoBottom)  => Some((0.5, 0.6)),
                Some(WindowLayout::TwoTopOneBottom)  => Some((0.5, 0.4)),
                _                                    => None,
            };

            if let Some(default_cr) = default_cross_ratio {
                let (full_w, full_h) = match branch_rect {
                    Some(r) => (r.width, r.height),
                    None => (content_width, content_height),
                };
                // Read current cross_ratio, falling back to the layout default.
                let (cur_xr, cur_yr) = self.tree.find_branch(parent_id)
                    .and_then(|b| b.cross_ratio)
                    .unwrap_or(default_cr);

                // Ratio bounds: 0.05..=0.95 as always; `Clamp` may tighten them.
                let (lo, hi) = match self.splitter_policy {
                    SplitterPolicy::Cascade | SplitterPolicy::RejectSnapBack => (0.05, 0.95),
                    SplitterPolicy::Clamp { min_frac } => {
                        let m = sanitize_min_frac(min_frac).max(0.05);
                        (m, 1.0 - m)
                    }
                };
                let reject = self.splitter_policy == SplitterPolicy::RejectSnapBack;
                // Account for the separator gap so the ratio tracks the visible line.
                let gap = super::docking::presets::PANEL_GAP;
                let new_xr;
                let new_yr;
                match orientation {
                    SeparatorOrientation::Vertical => {
                        // Vertical bar → moves left/right → affects x ratio.
                        let available_w = (full_w - gap).max(1.0);
                        let raw = cur_xr + delta as f64 / available_w as f64;
                        if reject && (raw < lo || raw > hi) {
                            let overshoot = (raw - raw.max(lo).min(hi)) * available_w as f64;
                            self.snap_animations.push(SnapBackAnimation::new(sep_idx, overshoot as f32));
                            return false;
                        }
                        new_xr = raw.max(lo).min(hi);
                        new_yr = cur_yr;
                    }
                    SeparatorOrientation::Horizontal => {
                        // Horizontal bar → moves up/down → affects y ratio.
                        let available_h = (full_h - gap).max(1.0);
                        let raw = cur_yr + delta as f64 / available_h as f64;
                        if reject && (raw < lo || raw > hi) {
                            let overshoot = (raw - raw.max(lo).min(hi)) * available_h as f64;
                            self.snap_animations.push(SnapBackAnimation::new(sep_idx, overshoot as f32));
                            return false;
                        }
                        new_xr = cur_xr;
                        new_yr = raw.max(lo).min(hi);
                    }
                }
                self.tree.set_branch_cross_ratio(parent_id, new_xr, new_yr);
                return true;
            }
        }

        // Convert pixel delta to share-space delta relative to total share sum.
        let total_share: f64 = raw_props.iter().sum();
        let delta_share = (delta as f64 / branch_size as f64) * total_share;

        // Per-child minimum in share space.
        let min_shares: Vec<f64> = children_min_px.iter()
            .map(|&px| (px as f64 / branch_size as f64) * total_share)
            .collect();

        // --- Clamp policy: only the two neighbours move, the shrinking one
        // stops at max(min_frac, its pixel minimum). Never rejects. ---
        if let SplitterPolicy::Clamp { min_frac } = self.splitter_policy {
            let m = sanitize_min_frac(min_frac) * total_share;
            let (a, b) = clamp_pair(
                raw_props[pos_a],
                raw_props[pos_b],
                delta_share,
                min_shares[pos_a].max(m),
                min_shares[pos_b].max(m),
            );
            let mut new_props = raw_props;
            new_props[pos_a] = a;
            new_props[pos_b] = b;
            self.tree.set_branch_proportions(parent_id, new_props);
            return true;
        }

        // --- Reject policy: only the two neighbours move; a move past
        // either minimum is refused with a snap-back. ---
        if self.splitter_policy == SplitterPolicy::RejectSnapBack {
            let (a, b) = (raw_props[pos_a], raw_props[pos_b]);
            let (na, nb) = (a + delta_share, b - delta_share);
            let a_bad = na < min_shares[pos_a] && na < a;
            let b_bad = nb < min_shares[pos_b] && nb < b;
            if a_bad || b_bad {
                let limit_a = if a_bad { min_shares[pos_a] } else { a + b - min_shares[pos_b] };
                let overshoot_px = ((na - limit_a) / total_share * branch_size as f64) as f32;
                self.snap_animations.push(SnapBackAnimation::new(sep_idx, overshoot_px));
                return false;
            }
            let mut new_props = raw_props;
            new_props[pos_a] = na;
            new_props[pos_b] = nb;
            self.tree.set_branch_proportions(parent_id, new_props);
            return true;
        }

        // --- Cascading resize in share space ---
        //
        // When delta >= 0 (pos_a grows, pos_b shrinks):
        //   Walk from pos_b rightward, take (share - min) from each sibling.
        //   Give the accumulated shrinkage to pos_a.
        //
        // When delta < 0 (pos_a shrinks, pos_b grows):
        //   Walk from pos_a leftward, take (share - min) from each sibling.
        //   Give the accumulated shrinkage to pos_b.

        let mut new_props = raw_props.clone();

        if delta_share >= 0.0 {
            let mut remaining = delta_share;
            for i in pos_b..n {
                if new_props[i] <= 0.0 { continue; }
                let available = (new_props[i] - min_shares[i]).max(0.0);
                let take = remaining.min(available);
                new_props[i] -= take;
                remaining -= take;
                if remaining <= 0.0 { break; }
            }
            new_props[pos_a] += delta_share - remaining;
        } else {
            let mut remaining = (-delta_share).abs();
            for i in (0..=pos_a).rev() {
                if new_props[i] <= 0.0 { continue; }
                let available = (new_props[i] - min_shares[i]).max(0.0);
                let take = remaining.min(available);
                new_props[i] -= take;
                remaining -= take;
                if remaining <= 0.0 { break; }
            }
            new_props[pos_b] += (-delta_share) - remaining;
        }

        // Commit new proportions.
        self.tree.set_branch_proportions(parent_id, new_props);
        true
    }

    /// Keep `px` free at the right end of every multi-tab chip bar (the
    /// chips share the rest evenly); `0.0` (default) = full width. Takes
    /// effect on the next [`layout`](Self::layout).
    pub fn set_tab_strip_reserve(&mut self, px: f32) {
        self.tab_strip_reserve = if px.is_finite() { px.max(0.0) } else { 0.0 };
    }

    /// Pixels kept free at the right end of multi-tab chip bars.
    pub fn tab_strip_reserve(&self) -> f32 {
        self.tab_strip_reserve
    }

    /// Current separator-drag policy.
    pub fn splitter_policy(&self) -> SplitterPolicy {
        self.splitter_policy
    }

    /// Choose how separator drags treat minimum sizes (see
    /// [`SplitterPolicy`]). Takes effect on the next `drag_separator`.
    pub fn set_splitter_policy(&mut self, policy: SplitterPolicy) {
        self.splitter_policy = policy;
    }

    /// Drag grid line `line` of grid branch `branch_id` by `delta` px:
    /// only the two tracks next to the line change, their sum is kept.
    fn drag_grid_line(
        &mut self,
        sep_idx: usize,
        branch_id: BranchId,
        line: GridLine,
        delta: f32,
        content_width: f32,
        content_height: f32,
    ) -> bool {
        let rect = self.tree.rect_for_branch(branch_id, content_width, content_height)
            .unwrap_or(PanelRect::new(0.0, 0.0, content_width, content_height));
        let Some(branch) = self.tree.find_branch(branch_id) else { return false };
        let Some(grid) = Self::fitting_grid(branch) else { return false };

        let (n_tracks, extent) = match line.axis {
            GridAxis::Row => (grid.rows, rect.height),
            GridAxis::Col => (grid.cols, rect.width),
        };
        let (i, j) = (line.index, line.index + 1);
        if j >= n_tracks {
            return false;
        }
        let gap = super::docking::presets::PANEL_GAP;
        let available = extent - gap * (n_tracks - 1) as f32;
        if available <= 0.0 {
            return false;
        }

        // Stored weights (equal if unset/invalid) — only [i] and [j] change.
        let stored = match line.axis {
            GridAxis::Row => &grid.row_ratios,
            GridAxis::Col => &grid.col_ratios,
        };
        let mut weights: Vec<f64> = if stored.len() == n_tracks && GridSpec::valid_block(stored) {
            stored.clone()
        } else {
            vec![1.0 / n_tracks as f64; n_tracks]
        };
        let total_w: f64 = weights.iter().sum();
        let px_to_w = total_w / available as f64;

        // A track's minimum is the largest minimum of the cells in it.
        let track_min_px = |t: usize| -> f32 {
            match line.axis {
                GridAxis::Row => (0..grid.cols)
                    .map(|c| self.min_height_for_node(&branch.children[grid.cell_index(t, c)]))
                    .fold(0.0, f32::max),
                GridAxis::Col => (0..grid.rows)
                    .map(|r| self.min_width_for_node(&branch.children[grid.cell_index(r, t)]))
                    .fold(0.0, f32::max),
            }
        };
        // Tracks never reach zero (a zero weight would invalidate the block).
        let floor = total_w * 1e-4;
        let min_a = (track_min_px(i) as f64 * px_to_w).max(floor);
        let min_b = (track_min_px(j) as f64 * px_to_w).max(floor);
        let delta_w = delta as f64 * px_to_w;
        let (a, b) = (weights[i], weights[j]);

        let (new_a, new_b) = match self.splitter_policy {
            SplitterPolicy::Cascade => clamp_pair(a, b, delta_w, min_a, min_b),
            SplitterPolicy::Clamp { min_frac } => {
                let m = sanitize_min_frac(min_frac) * total_w;
                clamp_pair(a, b, delta_w, min_a.max(m), min_b.max(m))
            }
            SplitterPolicy::RejectSnapBack => {
                let (na, nb) = (a + delta_w, b - delta_w);
                // Reject a move that takes a track below its minimum (a move
                // that only improves an already-violated track is allowed).
                let a_bad = na < min_a && na < a;
                let b_bad = nb < min_b && nb < b;
                if a_bad || b_bad {
                    let limit_a = if a_bad { min_a } else { a + b - min_b };
                    let overshoot_px = ((na - limit_a) / px_to_w) as f32;
                    self.snap_animations.push(SnapBackAnimation::new(sep_idx, overshoot_px));
                    return false;
                }
                (na, nb)
            }
        };

        weights[i] = new_a;
        weights[j] = new_b;
        match line.axis {
            GridAxis::Row => self.tree.set_grid_row_ratios(branch_id, weights),
            GridAxis::Col => self.tree.set_grid_col_ratios(branch_id, weights),
        }
    }

    // =============================================================================
    // Minimum-size helpers
    // =============================================================================

    /// Recursively compute the minimum width for a node.
    ///
    /// - Leaf: returns the per-leaf override from `leaf_min_sizes`, or the panel's
    ///   `min_size().0`, whichever is larger.
    /// - Branch with horizontal split (children side-by-side): **sum** of children minimums.
    /// - Branch with vertical split (children stacked): **max** of children minimums.
    fn min_width_for_node(&self, node: &PanelNode<P>) -> f32 {
        match node {
            PanelNode::Leaf(leaf) => {
                let panel_min = leaf.active_panel()
                    .map(|p| p.min_size().0)
                    .unwrap_or(0.0);
                let override_min = self.leaf_min_sizes
                    .get(&leaf.id)
                    .map(|&(w, _)| w)
                    .unwrap_or(0.0);
                panel_min.max(override_min)
            }
            PanelNode::Branch(branch) => {
                if let Some(g) = Self::fitting_grid(branch) {
                    // Sum over columns of each column's widest minimum.
                    return (0..g.cols)
                        .map(|c| (0..g.rows)
                            .map(|r| self.min_width_for_node(&branch.children[g.cell_index(r, c)]))
                            .fold(0.0_f32, f32::max))
                        .sum();
                }
                let children_mins = branch.children.iter().map(|c| self.min_width_for_node(c));
                if Self::layout_is_horizontal(branch.layout) {
                    children_mins.sum()
                } else {
                    children_mins.fold(0.0_f32, f32::max)
                }
            }
        }
    }

    /// Recursively compute the minimum height for a node.
    ///
    /// - Leaf: returns the per-leaf override from `leaf_min_sizes`, or the panel's
    ///   `min_size().1`, whichever is larger.
    /// - Branch with vertical split (children stacked): **sum** of children minimums.
    /// - Branch with horizontal split (children side-by-side): **max** of children minimums.
    fn min_height_for_node(&self, node: &PanelNode<P>) -> f32 {
        match node {
            PanelNode::Leaf(leaf) => {
                let panel_min = leaf.active_panel()
                    .map(|p| p.min_size().1)
                    .unwrap_or(0.0);
                let override_min = self.leaf_min_sizes
                    .get(&leaf.id)
                    .map(|&(_, h)| h)
                    .unwrap_or(0.0);
                panel_min.max(override_min)
            }
            PanelNode::Branch(branch) => {
                if let Some(g) = Self::fitting_grid(branch) {
                    // Sum over rows of each row's tallest minimum.
                    return (0..g.rows)
                        .map(|r| (0..g.cols)
                            .map(|c| self.min_height_for_node(&branch.children[g.cell_index(r, c)]))
                            .fold(0.0_f32, f32::max))
                        .sum();
                }
                let children_mins = branch.children.iter().map(|c| self.min_height_for_node(c));
                if Self::layout_is_vertical(branch.layout) {
                    children_mins.sum()
                } else {
                    children_mins.fold(0.0_f32, f32::max)
                }
            }
        }
    }

    /// The branch's grid, if it has one that fits its child count.
    fn fitting_grid(branch: &Branch<P>) -> Option<&GridSpec> {
        branch.grid.as_ref().filter(|g| g.cell_count() == branch.children.len())
    }

    /// Returns `true` when the layout places children side-by-side horizontally.
    fn layout_is_horizontal(layout: WindowLayout) -> bool {
        matches!(
            layout,
            WindowLayout::SplitHorizontal
                | WindowLayout::ThreeColumns
                | WindowLayout::OneLeftTwoRight
                | WindowLayout::TwoLeftOneRight
        )
    }

    /// Returns `true` when the layout stacks children vertically.
    fn layout_is_vertical(layout: WindowLayout) -> bool {
        matches!(layout, WindowLayout::SplitVertical | WindowLayout::ThreeRows)
    }

    // =============================================================================
    // Per-leaf minimum size overrides
    // =============================================================================

    /// Override the minimum size for a specific leaf.
    ///
    /// The docking engine takes `max(panel.min_size(), override)` per axis,
    /// so this can only tighten the constraint, never loosen it below the
    /// panel's own declared minimum.
    pub fn set_leaf_min_size(&mut self, leaf_id: LeafId, min_w: f32, min_h: f32) {
        self.leaf_min_sizes.insert(leaf_id, (min_w, min_h));
    }

    /// Return the effective minimum size for a leaf.
    ///
    /// Combines the override (if any) with the panel's declared `min_size()`.
    pub fn leaf_min_size(&self, leaf_id: LeafId) -> (f32, f32) {
        let panel_min = self.tree.leaf(leaf_id)
            .and_then(|l| l.active_panel())
            .map(|p| p.min_size())
            .unwrap_or((0.0, 0.0));
        let override_min = self.leaf_min_sizes.get(&leaf_id).copied().unwrap_or((0.0, 0.0));
        (panel_min.0.max(override_min.0), panel_min.1.max(override_min.1))
    }

    // =============================================================================
    // Water-fill proportion normalization
    // =============================================================================

    /// Enforce per-child minimum sizes across the whole tree by water-filling.
    ///
    /// For each branch in the tree, if any child proportion would place it below
    /// its minimum pixel size, the child is frozen at its minimum and the remaining
    /// share is redistributed proportionally among the free children. This repeats
    /// until stable (classic water-filling). Idempotent: returns without mutation
    /// when all children already satisfy their minimums, so drag is not fought.
    fn normalize_proportions(&mut self, content_width: f32, content_height: f32) {
        struct Pending {
            id: BranchId,
            props: Vec<f64>,
        }

        /// Classic water-fill over free (non-fixed) children — returns the
        /// children's shares of `available` (summing to 1).
        fn water_fill_free(available: f32, norm: &[f64], mins: &[f32]) -> Vec<f64> {
            let n = norm.len();
            let avail_f = (available as f64).max(f64::EPSILON);

            let total_min: f32 = mins.iter().sum();
            if total_min >= available {
                let sum_min = (total_min as f64).max(f64::EPSILON);
                return mins.iter().map(|&m| m as f64 / sum_min).collect();
            }

            let mut frozen = vec![false; n];
            let mut out = norm.to_vec();

            loop {
                let frozen_min: f64 = (0..n)
                    .filter(|&i| frozen[i])
                    .map(|i| mins[i] as f64 / avail_f)
                    .sum();

                let free_indices: Vec<usize> = (0..n).filter(|&i| !frozen[i]).collect();
                if free_indices.is_empty() { break; }

                let free_pool = (1.0 - frozen_min).max(0.0);
                let free_w_sum: f64 = free_indices.iter()
                    .map(|&i| norm[i])
                    .sum::<f64>()
                    .max(f64::EPSILON);

                let mut newly_frozen = false;
                for &i in &free_indices {
                    let share = free_pool * norm[i] / free_w_sum;
                    let min_share = mins[i] as f64 / avail_f;
                    if share + 1e-9 < min_share {
                        frozen[i] = true;
                        out[i] = min_share;
                        newly_frozen = true;
                    } else {
                        out[i] = share;
                    }
                }
                for i in 0..n {
                    if frozen[i] && out[i] == 0.0 {
                        out[i] = mins[i] as f64 / avail_f;
                    }
                }
                if !newly_frozen { break; }
            }

            let s: f64 = out.iter().sum();
            if s > f64::EPSILON {
                for v in &mut out { *v /= s; }
            }
            out
        }

        /// Fixed-point water-fill for one branch.
        /// `fixed[i] = Some(px)` pins child `i` at EXACTLY that many pixels
        /// (one-row strips must never stretch when the tree restructures);
        /// the rest water-fill over the remaining pool by their minimums.
        /// Returns `Some(new_props)` only when current proportions violate
        /// a minimum or a fixed extent.
        fn water_fill(
            available: f32,
            weights: &[f64],
            mins: &[f32],
            fixed: &[Option<f32>],
        ) -> Option<Vec<f64>> {
            let n = weights.len();
            if n == 0 || available <= 0.0 {
                return None;
            }

            let w_sum: f64 = weights.iter().sum::<f64>().max(f64::EPSILON);
            let norm: Vec<f64> = weights.iter().map(|w| w / w_sum).collect();

            let avail_f = available as f64;
            let all_ok = (0..n).all(|i| match fixed[i] {
                Some(f) => (norm[i] * avail_f - f as f64).abs() <= 0.75,
                None => norm[i] * avail_f + 1e-6 >= mins[i] as f64,
            });
            if all_ok {
                return None;
            }

            if fixed.iter().all(|f| f.is_none()) {
                return Some(water_fill_free(available, &norm, mins));
            }

            // Pin fixed children at exactly their pixels, water-fill the
            // rest over what remains.
            let fixed_total: f64 = (0..n).filter_map(|i| fixed[i].map(|v| v as f64)).sum();
            let rest_pool = (avail_f - fixed_total).max(0.0);
            let rest: Vec<usize> = (0..n).filter(|&i| fixed[i].is_none()).collect();

            let mut out = vec![0.0f64; n];
            for i in 0..n {
                if let Some(f) = fixed[i] {
                    out[i] = (f as f64 / avail_f).min(1.0);
                }
            }
            if !rest.is_empty() && rest_pool > 0.0 {
                let rest_w_sum: f64 = rest.iter().map(|&i| norm[i]).sum::<f64>().max(f64::EPSILON);
                let rest_norm: Vec<f64> = rest.iter().map(|&i| norm[i] / rest_w_sum).collect();
                let rest_mins: Vec<f32> = rest.iter().map(|&i| mins[i]).collect();
                let shares = water_fill_free(rest_pool as f32, &rest_norm, &rest_mins);
                for (k, &i) in rest.iter().enumerate() {
                    out[i] = shares[k] * rest_pool / avail_f;
                }
            }

            let s: f64 = out.iter().sum();
            if s > f64::EPSILON {
                for v in &mut out { *v /= s; }
            }
            Some(out)
        }

        // Collect updates without mutating during traversal.
        let mut pending: Vec<Pending> = Vec::new();

        // Clone root to avoid borrow conflict during recursive walk.
        let root = self.tree.root().clone();

        fn walk<P: DockPanel>(
            node: &PanelNode<P>,
            rect_w: f32,
            rect_h: f32,
            pending: &mut Vec<Pending>,
            mgr: &DockState<P>,
        ) {
            let branch = match node {
                PanelNode::Branch(b) => b,
                _ => return,
            };
            let n = branch.children.len();
            if n < 2 {
                for c in &branch.children { walk(c, rect_w, rect_h, pending, mgr); }
                return;
            }

            // Grid: recurse into each cell with the cell's own size. The
            // grid's ratios themselves are not water-filled.
            if let Some(g) = DockState::<P>::fitting_grid(branch) {
                let rows = g.normalized_rows();
                let cols = g.normalized_cols();
                for r in 0..g.rows {
                    for c in 0..g.cols {
                        walk(
                            &branch.children[g.cell_index(r, c)],
                            rect_w * cols[c] as f32,
                            rect_h * rows[r] as f32,
                            pending,
                            mgr,
                        );
                    }
                }
                return;
            }

            let horizontal = DockState::<P>::layout_is_horizontal(branch.layout);
            let vertical = DockState::<P>::layout_is_vertical(branch.layout);

            if horizontal || vertical {
                let available = if horizontal { rect_w } else { rect_h };
                let mins: Vec<f32> = if horizontal {
                    branch.children.iter().map(|c| mgr.min_width_for_node(c)).collect()
                } else {
                    branch.children.iter().map(|c| mgr.min_height_for_node(c)).collect()
                };
                // Fixed-extent children: a direct LEAF whose active panel
                // declares a strip height is pinned at exactly that many
                // pixels in a VERTICAL branch — strips never stretch, no
                // matter how the tree restructures around them.
                let fixed: Vec<Option<f32>> = if vertical {
                    branch.children.iter().map(|c| match c {
                        PanelNode::Leaf(l) => l
                            .active_panel()
                            .and_then(|p| p.preferred_strip_height()),
                        _ => None,
                    }).collect()
                } else {
                    vec![None; n]
                };
                let weights: Vec<f64> = if branch.proportions.len() == n {
                    branch.proportions.clone()
                } else {
                    vec![1.0; n]
                };

                let effective_props: Vec<f64> = match water_fill(available, &weights, &mins, &fixed) {
                    Some(new_props) => {
                        pending.push(Pending { id: branch.id, props: new_props.clone() });
                        new_props
                    }
                    None => {
                        let s: f64 = weights.iter().sum::<f64>().max(f64::EPSILON);
                        weights.iter().map(|w| w / s).collect()
                    }
                };

                for (i, child) in branch.children.iter().enumerate() {
                    let frac = effective_props[i] as f32;
                    let (cw, ch) = if horizontal {
                        (rect_w * frac, rect_h)
                    } else {
                        (rect_w, rect_h * frac)
                    };
                    walk(child, cw, ch, pending, mgr);
                }
            } else {
                for c in &branch.children { walk(c, rect_w, rect_h, pending, mgr); }
            }
        }

        walk(&PanelNode::Branch(root), content_width, content_height, &mut pending, self);

        for upd in pending {
            self.tree.set_branch_proportions(upd.id, upd.props);
        }
    }

    /// Update separator hover state based on mouse position
    /// Returns true if any separator is hovered (for cursor change)
    pub fn update_separator_hover(&mut self, x: f32, y: f32) -> bool {
        let mut any_hovered = false;
        for sep in &mut self.separators {
            if sep.hit_test(x, y) {
                sep.state = SeparatorState::Hover;
                any_hovered = true;
            } else {
                sep.state = SeparatorState::Idle;
            }
        }
        any_hovered
    }

    /// Get the orientation of the hovered separator (for cursor style)
    pub fn hovered_separator_orientation(&self) -> Option<SeparatorOrientation> {
        self.separators.iter()
            .find(|s| s.state == SeparatorState::Hover)
            .map(|s| s.orientation)
    }

    // =============================================================================
    // Panel Drag-and-Drop
    // =============================================================================

    /// Start panel drag (called when mouse down on panel header). The leaf
    /// travels with all its tabs, so a drag never arms while any of them
    /// is pinned ([`crate::layout::docking::Pin::locks_tear_off`]).
    pub fn start_panel_drag(&mut self, leaf_id: LeafId, x: f32, y: f32) {
        let pinned = self
            .tree
            .leaf(leaf_id)
            .map(|l| l.panels.iter().any(|p| p.pin().locks_tear_off()))
            .unwrap_or(false);
        if pinned {
            return;
        }
        self.panel_drag = Some(PanelDragState {
            dragged_leaf_id: leaf_id,
            payload: DragPayload::Leaf,
            current_x: x,
            current_y: y,
            target_leaf_id: None,
            drop_zone: None,
            is_window_edge: false,
        });
    }

    /// Start a TAB drag — tear `tab_idx` out of `leaf_id`'s stack by its
    /// chip. Targeting runs exactly like a leaf drag; on drop the single
    /// panel leaves the stack (Center → joins the target's stack, side →
    /// a fresh leaf splits the target, edge → root split); cancelling
    /// leaves the stack untouched.
    pub fn start_tab_drag(&mut self, leaf_id: LeafId, tab_idx: usize, x: f32, y: f32) {
        // Only real multi-tab stacks tear by chip — a single-panel leaf
        // travels whole via the leaf drag (and `apply_tab_drop` relies on
        // the source leaf surviving `remove_tab`).
        let valid = self
            .tree
            .leaf(leaf_id)
            .map(|l| {
                l.panels.len() > 1
                    && tab_idx < l.panels.len()
                    && !l.panels[tab_idx].pin().locks_tear_off()
            })
            .unwrap_or(false);
        if !valid {
            return;
        }
        self.panel_drag = Some(PanelDragState {
            dragged_leaf_id: leaf_id,
            payload: DragPayload::Tab { tab_idx },
            current_x: x,
            current_y: y,
            target_leaf_id: None,
            drop_zone: None,
            is_window_edge: false,
        });
    }

    /// Update panel drag (called on mouse move during drag)
    pub fn update_panel_drag(&mut self, x: f32, y: f32) {
        if let Some(ref mut drag) = self.panel_drag {
            drag.current_x = x;
            drag.current_y = y;
            drag.is_window_edge = false;

            let mut target = None;
            let mut zone = None;

            // A torn-out TAB may target its own source leaf (dropping on
            // the source leaf's compass edges splits that very leaf); a
            // whole-leaf drag never targets itself.
            let skip_self = matches!(drag.payload, DragPayload::Leaf);

            // Window-level edges FIRST — when the global edge band overlaps
            // a local target (a panel header hugging the window top), the
            // GLOBAL drop must win, otherwise no cursor position can reach
            // it at all.
            if let Some(edge_rects) = &self.window_edge_rects {
                let zones = [DropZone::Up, DropZone::Down, DropZone::Left, DropZone::Right];
                for (i, rect) in edge_rects.iter().enumerate() {
                    if rect.contains(x, y) {
                        let fallback_target = self.panel_rects.keys()
                            .find(|&&id| !skip_self || id != drag.dragged_leaf_id)
                            .copied();
                        if let Some(ft) = fallback_target {
                            target = Some(ft);
                            zone = Some(zones[i]);
                            drag.is_window_edge = true;
                            break;
                        }
                    }
                }
            }

            // Headers — dropping on a header always creates tabs
            if target.is_none() {
                for (&id, &header_rect) in &self.panel_headers {
                    if id == drag.dragged_leaf_id {
                        continue; // Skip the panel being dragged
                    }
                    if header_rect.contains(x, y) {
                        target = Some(id);
                        zone = Some(DropZone::Center);
                        break;
                    }
                }
            }

            // Check tab bars
            if target.is_none() {
                for bar in &self.tab_bars {
                    if bar.rect.contains(x, y)
                        && bar.container_id != drag.dragged_leaf_id {
                            target = Some(bar.container_id);
                            zone = Some(DropZone::Center);
                            break;
                        }
                }
            }

            // Fall back to panel body detection with drop zone algorithm
            let mut target_frac = (0.5_f32, 0.5_f32);
            if target.is_none() {
                for (&id, &rect) in &self.panel_rects {
                    if skip_self && id == drag.dragged_leaf_id {
                        continue;
                    }
                    if rect.contains(x, y) {
                        target = Some(id);
                        let local_x = x - rect.x;
                        let local_y = y - rect.y;
                        target_frac = (
                            (local_x / rect.width.max(1.0)).clamp(0.0, 1.0),
                            (local_y / rect.height.max(1.0)).clamp(0.0, 1.0),
                        );
                        let mut z = Self::detect_drop_zone(local_x, local_y, rect.width, rect.height);
                        if !self.body_center_drop && z == DropZone::Center {
                            z = crate::layout::docking::lib::detect_drop_zone_sides_only(
                                local_x, local_y, rect.width, rect.height,
                            );
                        }
                        zone = Some(z);
                        break;
                    }
                }
            }

            // Consumer drop policy — veto or override the candidate.
            if let (Some(t), Some(z), Some(policy)) = (target, zone, self.drop_policy.as_ref()) {
                let dragged_panel = self.tree.leaf(drag.dragged_leaf_id).and_then(|l| match drag.payload {
                    DragPayload::Leaf => l.active_panel(),
                    DragPayload::Tab { tab_idx } => l.panels.get(tab_idx),
                });
                if let Some(dp) = dragged_panel {
                    let target_panel = self.tree.leaf(t).and_then(|l| l.active_panel());
                    match policy(dp, target_panel, z, drag.is_window_edge, target_frac) {
                        Some(nz) => zone = Some(nz),
                        None => {
                            target = None;
                            zone = None;
                            drag.is_window_edge = false;
                        }
                    }
                }
            }

            drag.target_leaf_id = target;
            drag.drop_zone = zone;
        }
    }

    /// Install a consumer drop-targeting policy (see [`DropPolicyFn`]).
    pub fn set_drop_policy(&mut self, policy: DropPolicyFn<P>) {
        self.drop_policy = Some(policy);
    }

    /// Run the installed drop policy for one candidate — the renderer's
    /// door to "which zones are even available for this drag" (drop-zone
    /// affordances must not advertise placements the policy would veto).
    /// No policy installed → every zone passes through.
    pub fn drop_policy_check(
        &self,
        dragged: &P,
        target: Option<&P>,
        zone: DropZone,
        is_window_edge: bool,
        frac: (f32, f32),
    ) -> Option<DropZone> {
        match &self.drop_policy {
            Some(p) => p(dragged, target, zone, is_window_edge, frac),
            None => Some(zone),
        }
    }

    /// End panel drag - perform the drop action, or float the leaf if no target
    pub fn end_panel_drag(&mut self, area_width: f32, area_height: f32) -> Option<FloatingWindowId> {
        let drag = self.panel_drag.take()?;

        // Torn-out tab payload: the panel leaves its stack only on a valid
        // drop; a miss cancels (no floating for single tabs).
        if let DragPayload::Tab { tab_idx } = drag.payload {
            if let (Some(target_id), Some(zone)) = (drag.target_leaf_id, drag.drop_zone) {
                self.apply_tab_drop(drag.dragged_leaf_id, tab_idx, target_id, zone, drag.is_window_edge);
            }
            return None;
        }

        let target_id = match drag.target_leaf_id {
            Some(id) => id,
            None => {
                // No valid target → float the leaf
                return self.float_leaf(
                    drag.dragged_leaf_id,
                    drag.current_x - 150.0,
                    drag.current_y - 150.0,
                    area_width,
                    area_height,
                );
            }
        };

        let zone = drag.drop_zone?;

        // Perform the tree restructuring based on drop zone
        self.apply_panel_drop(drag.dragged_leaf_id, target_id, zone, drag.is_window_edge);
        None
    }

    /// Cancel panel drag without dropping
    pub fn cancel_panel_drag(&mut self) {
        self.panel_drag = None;
    }

    /// Get current panel drag state (for rendering)
    pub fn panel_drag_state(&self) -> Option<&PanelDragState> {
        self.panel_drag.as_ref()
    }

    /// Detect drop zone using improved algorithm with smaller center zone
    fn detect_drop_zone(x: f32, y: f32, width: f32, height: f32) -> DropZone {
        crate::layout::docking::lib::detect_drop_zone(x, y, width, height)
    }

    /// Apply panel drop - restructure the tree based on drop zone
    fn apply_panel_drop(&mut self, dragged_id: LeafId, target_id: LeafId, zone: DropZone, is_window_edge: bool) {
        match zone {
            DropZone::Center => {
                // Move all panels from dragged leaf as tabs into target leaf
                let panels = match self.tree.leaf(dragged_id) {
                    Some(leaf) => leaf.panels.clone(),
                    None => return,
                };

                for panel in panels {
                    self.tree.add_tab(target_id, panel);
                }

                self.tree.remove_leaf(dragged_id);
            }
            DropZone::Left | DropZone::Right | DropZone::Up | DropZone::Down => {
                // Divided space along the zone axis — for the fixed-strip
                // proportion rewrite below. Captured BEFORE the move
                // (rects are stale after tree surgery until re-layout).
                let space_px = if is_window_edge {
                    self.strip_space_px(self.layout_area, zone)
                } else {
                    self.panel_rects
                        .get(&target_id)
                        .map(|r| self.strip_space_px(*r, zone))
                        .unwrap_or(0.0)
                };
                if is_window_edge {
                    self.tree.move_leaf_to_root_split(dragged_id, zone);
                } else {
                    self.tree.move_leaf_to_branch(dragged_id, target_id, zone);
                }
                self.fix_strip_proportions(dragged_id, zone, space_px);
            }
        }
    }

    /// Torn-out tab drop: extract `tab_idx` from `source_id`'s stack and
    /// place it — Center joins the target's stack; a side splits the
    /// target with a fresh leaf; a window edge root-splits the tree.
    fn apply_tab_drop(
        &mut self,
        source_id: LeafId,
        tab_idx: usize,
        target_id: LeafId,
        zone: DropZone,
        is_window_edge: bool,
    ) {
        let panel = match self.tree.leaf(source_id).and_then(|l| l.panels.get(tab_idx)) {
            Some(p) => p.clone(),
            None => return,
        };
        match zone {
            DropZone::Center => {
                if target_id == source_id {
                    return; // rejoining its own stack is a no-op
                }
                self.tree.remove_tab(source_id, tab_idx);
                self.tree.add_tab(target_id, panel);
            }
            DropZone::Left | DropZone::Right | DropZone::Up | DropZone::Down => {
                let space_px = if is_window_edge {
                    self.strip_space_px(self.layout_area, zone)
                } else {
                    self.panel_rects
                        .get(&target_id)
                        .map(|r| self.strip_space_px(*r, zone))
                        .unwrap_or(0.0)
                };
                self.tree.remove_tab(source_id, tab_idx);
                // NB: the source leaf survives remove_tab (a chip drag
                // only exists on multi-tab stacks), so `target_id` stays
                // valid even when target == source.
                let new_id = if is_window_edge {
                    self.tree.add_leaf_root_split(panel, zone)
                } else {
                    self.tree.split_leaf_zone(target_id, zone, panel)
                };
                if let Some(id) = new_id {
                    self.fix_strip_proportions(id, zone, space_px);
                }
            }
        }
    }

    /// Extent of `rect` along the axis an Up/Down|Left/Right split divides.
    fn strip_space_px(&self, rect: PanelRect, zone: DropZone) -> f32 {
        match zone {
            DropZone::Up | DropZone::Down => rect.height,
            DropZone::Left | DropZone::Right => rect.width,
            DropZone::Center => 0.0,
        }
    }

    /// After a side drop created a fresh binary branch holding `leaf_id`,
    /// rewrite that branch's proportions when the docked panel declares a
    /// fixed strip height ([`DockPanel::preferred_strip_height`]) — the
    /// strip gets exactly its pixels of `space_px`, the neighbour the
    /// rest. Only vertical (Up/Down) splits qualify; equal split
    /// otherwise.
    fn fix_strip_proportions(&mut self, leaf_id: LeafId, zone: DropZone, space_px: f32) {
        if !matches!(zone, DropZone::Up | DropZone::Down) {
            return;
        }
        let strip_px = match self
            .tree
            .leaf(leaf_id)
            .and_then(|l| l.active_panel())
            .and_then(|p| p.preferred_strip_height())
        {
            Some(px) => px,
            None => return,
        };
        if space_px <= strip_px + 1.0 {
            return;
        }
        let rest = (space_px - strip_px) as f64;
        let strip = strip_px as f64;
        let parent_id = match self.tree.find_parent_of_leaf(leaf_id).map(|b| b.id) {
            Some(id) => id,
            None => return,
        };
        if let Some(branch) = self.tree.find_branch_mut(parent_id) {
            if branch.children.len() == 2 {
                let strip_first = branch
                    .children
                    .first()
                    .and_then(|c| c.leaf_id())
                    .map(|id| id == leaf_id)
                    .unwrap_or(false);
                branch.proportions = if strip_first {
                    vec![strip, rest]
                } else {
                    vec![rest, strip]
                };
            }
        }
    }

    /// Spawn a brand-new panel as a root-level split on `zone`'s side
    /// (e.g. a one-row strip docked to the container bottom), honouring
    /// the panel's fixed strip height. Returns the fresh leaf id. Call
    /// [`Self::layout`] afterwards.
    pub fn spawn_leaf_root_split(&mut self, panel: P, zone: DropZone) -> Option<LeafId> {
        let space_px = self.strip_space_px(self.layout_area, zone);
        let id = self.tree.add_leaf_root_split(panel, zone)?;
        self.fix_strip_proportions(id, zone, space_px);
        Some(id)
    }

    /// Re-home an EXISTING leaf as a root-level split on `zone`'s side
    /// (e.g. send an already-hosted strip back to the canonical
    /// container-bottom band), honouring the panel's fixed strip height.
    /// Call [`Self::layout`] afterwards.
    pub fn move_leaf_to_root_split_fixed(&mut self, leaf_id: LeafId, zone: DropZone) {
        let space_px = self.strip_space_px(self.layout_area, zone);
        self.tree.move_leaf_to_root_split(leaf_id, zone);
        self.fix_strip_proportions(leaf_id, zone, space_px);
    }

    // =============================================================================
    // Tab Management
    // =============================================================================

    /// Switch active tab in a leaf
    pub fn set_active_tab(&mut self, container_id: LeafId, tab_id: LeafId) {
        if let Some(leaf) = self.tree.leaf_mut(container_id) {
            let tab_idx = (tab_id.0 % 100) as usize;
            if tab_idx < leaf.panels.len() {
                leaf.active_tab = tab_idx;
            }
        }
        self.tree.set_active_leaf(container_id);
    }

    /// Close a tab (remove panel from leaf)
    pub fn close_tab(&mut self, container_id: LeafId, tab_id: LeafId) {
        let tab_idx = (tab_id.0 % 100) as usize;
        self.tree.remove_tab(container_id, tab_idx);
    }

    /// Start tab reorder drag
    pub fn start_tab_reorder(&mut self, container_id: LeafId, tab_id: LeafId, x: f32) {
        if let Some(leaf) = self.tree.leaf(container_id) {
            let tab_idx = (tab_id.0 % 100) as usize;
            if tab_idx < leaf.panels.len() {
                self.tab_reorder = Some(TabReorderState {
                    container_id,
                    dragged_tab_id: tab_id,
                    original_index: tab_idx,
                    current_x: x,
                    insert_index: tab_idx,
                });
            }
        }
    }

    /// Update tab reorder drag
    pub fn update_tab_reorder(&mut self, x: f32) {
        if let Some(ref mut state) = self.tab_reorder {
            state.current_x = x;

            // Calculate insert index based on mouse position
            if let Some(bar) = self.tab_bars.iter().find(|b| b.container_id == state.container_id) {
                let mut insert_idx = 0;
                for (idx, tab) in bar.tabs.iter().enumerate() {
                    if x > tab.rect.x + tab.rect.width / 2.0 {
                        insert_idx = idx + 1;
                    }
                }
                state.insert_index = insert_idx.min(bar.tabs.len());
            }
        }
    }

    /// End tab reorder drag - reorder tabs in leaf
    pub fn end_tab_reorder(&mut self) {
        if let Some(state) = self.tab_reorder.take() {
            if state.original_index != state.insert_index {
                if let Some(leaf) = self.tree.leaf_mut(state.container_id) {
                    if state.original_index < leaf.panels.len() {
                        let dragged = leaf.panels.remove(state.original_index);
                        let final_idx = if state.insert_index > state.original_index {
                            (state.insert_index - 1).min(leaf.panels.len())
                        } else {
                            state.insert_index.min(leaf.panels.len())
                        };
                        leaf.panels.insert(final_idx, dragged);
                    }
                }
            }
        }
    }

    // =============================================================================
    // Floating Windows
    // =============================================================================

    /// Extract leaf from tree into floating window at given position
    pub fn float_leaf(&mut self, leaf_id: LeafId, x: f32, y: f32, area_width: f32, area_height: f32) -> Option<FloatingWindowId> {
        if self.tree.visible_leaf_count() <= 1 {
            return None;
        }

        let leaf = self.tree.leaf(leaf_id)?.clone();
        self.tree.remove_leaf(leaf_id);

        let id = FloatingWindowId(self.next_floating_id);
        self.next_floating_id += 1;

        let fw = FloatingWindow {
            id,
            panels: leaf.panels,
            active_tab: leaf.active_tab,
            x: x.max(0.0).min((area_width - 300.0).max(0.0)),
            y: y.max(0.0).min((area_height - 300.0).max(0.0)),
            width: 300.0,
            height: 300.0,
        };

        self.floating_windows.push(fw);
        Some(id)
    }

    /// Dock floating window back into tree at target leaf with drop zone
    pub fn dock_floating(&mut self, fw_id: FloatingWindowId, target_id: LeafId, zone: DropZone, is_window_edge: bool) {
        let idx = match self.floating_windows.iter().position(|fw| fw.id == fw_id) {
            Some(i) => i,
            None => return,
        };
        let fw = self.floating_windows.remove(idx);

        if fw.panels.is_empty() {
            return;
        }

        // Re-insert into tree: add first panel, then rest as tabs
        let new_leaf_id = self.tree.add_leaf(fw.panels[0].clone());

        for panel in fw.panels.iter().skip(1) {
            self.tree.add_tab(new_leaf_id, panel.clone());
        }

        // Restore active tab
        if let Some(leaf) = self.tree.leaf_mut(new_leaf_id) {
            leaf.active_tab = fw.active_tab.min(fw.panels.len().saturating_sub(1));
        }

        // Apply drop
        self.apply_panel_drop(new_leaf_id, target_id, zone, is_window_edge);
    }

    /// The id the next floating window created by this state would get.
    pub fn next_floating_id(&self) -> FloatingWindowId {
        FloatingWindowId(self.next_floating_id)
    }

    /// Put a floating window built by the caller (a restored layout, a
    /// panel opened straight into a float) above the layout, keeping its
    /// id. Refused (`None`) when it has no panels or its id is already
    /// used. Later ids are allocated past it; `active_tab` is clamped to
    /// the panel count.
    pub fn insert_floating(&mut self, mut window: FloatingWindow<P>) -> Option<FloatingWindowId> {
        if window.panels.is_empty() || self.floating_windows.iter().any(|fw| fw.id == window.id) {
            return None;
        }
        window.active_tab = window.active_tab.min(window.panels.len() - 1);
        let id = window.id;
        self.next_floating_id = self.next_floating_id.max(id.0.saturating_add(1));
        self.floating_windows.push(window);
        Some(id)
    }

    /// Move / resize a floating window. `false` when no window has this id.
    pub fn set_floating_rect(&mut self, fw_id: FloatingWindowId, rect: PanelRect) -> bool {
        match self.floating_windows.iter_mut().find(|fw| fw.id == fw_id) {
            Some(fw) => {
                fw.x = rect.x;
                fw.y = rect.y;
                fw.width = rect.width;
                fw.height = rect.height;
                true
            }
            None => false,
        }
    }

    /// Close floating window (removes it)
    pub fn close_floating(&mut self, fw_id: FloatingWindowId) {
        if let Some(idx) = self.floating_windows.iter().position(|fw| fw.id == fw_id) {
            self.floating_windows.remove(idx);
        }
    }

    /// Start dragging a floating window (reposition)
    pub fn start_floating_drag(&mut self, fw_id: FloatingWindowId, cursor_x: f32, cursor_y: f32) {
        if let Some(fw) = self.floating_windows.iter().find(|fw| fw.id == fw_id) {
            self.floating_drag = Some(FloatingDragState {
                window_id: fw_id,
                offset_x: cursor_x - fw.x,
                offset_y: cursor_y - fw.y,
                dock_target: None,
            });
        }
    }

    /// Update floating window position during drag
    pub fn update_floating_drag(&mut self, cursor_x: f32, cursor_y: f32, area_width: f32, area_height: f32) {
        if let Some(ref drag) = self.floating_drag {
            let fw_id = drag.window_id;
            let ox = drag.offset_x;
            let oy = drag.offset_y;
            if let Some(fw) = self.floating_windows.iter_mut().find(|fw| fw.id == fw_id) {
                fw.x = (cursor_x - ox).max(0.0).min((area_width - fw.width).max(0.0));
                fw.y = (cursor_y - oy).max(0.0).min((area_height - fw.height).max(0.0));
            }
        }
    }

    /// Update dock target detection during floating window drag
    pub fn update_floating_dock_target(&mut self, x: f32, y: f32) {
        if self.floating_drag.is_none() {
            return;
        }

        let mut target = None;
        let mut zone = None;
        let mut is_window_edge = false;

        // Check headers first
        for (&id, &header_rect) in &self.panel_headers {
            if header_rect.contains(x, y) {
                target = Some(id);
                zone = Some(DropZone::Center);
                break;
            }
        }

        // Check tab bars
        if target.is_none() {
            for bar in &self.tab_bars {
                if bar.rect.contains(x, y) {
                    target = Some(bar.container_id);
                    zone = Some(DropZone::Center);
                    break;
                }
            }
        }

        // Check window edges
        if target.is_none() {
            if let Some(edge_rects) = &self.window_edge_rects {
                let zones = [DropZone::Up, DropZone::Down, DropZone::Left, DropZone::Right];
                for (i, rect) in edge_rects.iter().enumerate() {
                    if rect.contains(x, y) {
                        let fallback_target = self.panel_rects.keys().copied().next();
                        if let Some(ft) = fallback_target {
                            target = Some(ft);
                            zone = Some(zones[i]);
                            is_window_edge = true;
                            break;
                        }
                    }
                }
            }
        }

        // Fall back to panel body
        if target.is_none() {
            for (&id, &rect) in &self.panel_rects {
                if rect.contains(x, y) {
                    target = Some(id);
                    let local_x = x - rect.x;
                    let local_y = y - rect.y;
                    zone = Some(Self::detect_drop_zone(local_x, local_y, rect.width, rect.height));
                    break;
                }
            }
        }

        if let Some(ref mut drag) = self.floating_drag {
            drag.dock_target = match (target, zone) {
                (Some(t), Some(z)) => Some((t, z, is_window_edge)),
                _ => None,
            };
        }
    }

    /// End floating window drag
    pub fn end_floating_drag(&mut self) -> Option<(FloatingWindowId, LeafId, DropZone, bool)> {
        let drag = self.floating_drag.take()?;
        if let Some((target_id, zone, is_edge)) = drag.dock_target {
            Some((drag.window_id, target_id, zone, is_edge))
        } else {
            None
        }
    }

    /// Hit test: is cursor over a floating window header?
    pub fn hit_test_floating_header(&self, x: f32, y: f32) -> Option<FloatingWindowId> {
        for fw in self.floating_windows.iter().rev() {
            let header_h = self.header_height;
            if x >= fw.x && x <= fw.x + fw.width && y >= fw.y && y <= fw.y + header_h {
                return Some(fw.id);
            }
        }
        None
    }

    /// Hit test: is cursor over a floating window body?
    pub fn hit_test_floating_body(&self, x: f32, y: f32) -> Option<FloatingWindowId> {
        for fw in self.floating_windows.iter().rev() {
            if fw.contains(x, y) {
                return Some(fw.id);
            }
        }
        None
    }

    /// Hit test: is cursor over a floating window close button?
    pub fn hit_test_floating_close(&self, x: f32, y: f32) -> Option<FloatingWindowId> {
        for fw in self.floating_windows.iter().rev() {
            let close_size = 20.0_f32;
            let close_x = fw.x + fw.width - close_size - 4.0;
            let close_y = fw.y + 2.0;
            if x >= close_x && x <= close_x + close_size && y >= close_y && y <= close_y + close_size {
                return Some(fw.id);
            }
        }
        None
    }

    // =============================================================================
    // Snap-back Animations
    // =============================================================================

    /// Update snap-back animations
    pub fn update_snap_animations(&mut self, dt: f32) {
        for anim in &mut self.snap_animations {
            anim.update(dt);
        }
        self.snap_animations.retain(|a| !a.done);
    }

    // =============================================================================
    // Window Edge Rects
    // =============================================================================

    /// Compute window edge indicator rects (for window-level drop zones)
    pub fn compute_window_edge_rects(&mut self) {
        let area = self.layout_area;
        let size = 28.0_f32;
        let half = size / 2.0;
        let cx = area.x + area.width / 2.0;
        let cy = area.y + area.height / 2.0;
        let inset = 4.0_f32;

        self.window_edge_rects = Some([
            // Top
            PanelRect::new(cx - half, area.y + inset, size, size),
            // Bottom
            PanelRect::new(cx - half, area.y + area.height - size - inset, size, size),
            // Left
            PanelRect::new(area.x + inset, cy - half, size, size),
            // Right
            PanelRect::new(area.x + area.width - size - inset, cy - half, size, size),
        ]);
    }

    /// Compute window edge drop zones as FULL-LENGTH bands of `thickness`
    /// px hugging each side of the layout area — the coarse "grab the
    /// container edge" variant of [`Self::compute_window_edge_rects`]'s
    /// 28px midpoint squares. A drop in a band root-splits the tree on
    /// that side. Order matches the drag detector: [top, bottom, left,
    /// right]; corners resolve to top/bottom (checked first).
    ///
    /// Call after [`Self::layout`] (bands derive from the layout area).
    pub fn compute_window_edge_bands(&mut self, thickness: f32) {
        let area = self.layout_area;
        let t = thickness
            .min(area.width / 2.0)
            .min(area.height / 2.0)
            .max(0.0);
        self.window_edge_rects = Some([
            // Top
            PanelRect::new(area.x, area.y, area.width, t),
            // Bottom
            PanelRect::new(area.x, area.y + area.height - t, area.width, t),
            // Left
            PanelRect::new(area.x, area.y, t, area.height),
            // Right
            PanelRect::new(area.x + area.width - t, area.y, t, area.height),
        ]);
    }

    /// Enable/disable `DropZone::Center` (tabify) on panel-BODY drops.
    /// Disabled → the body classifies sides-only (diagonal quadrants), so
    /// every position is a live side split. Header/tab-bar drops still
    /// resolve to Center. Default: enabled.
    pub fn set_body_center_drop(&mut self, enabled: bool) {
        self.body_center_drop = enabled;
    }

    // =============================================================================
    // Accessors
    // =============================================================================

    pub fn separators(&self) -> &[Separator] {
        &self.separators
    }

    pub fn panel_rects(&self) -> &HashMap<LeafId, PanelRect> {
        &self.panel_rects
    }

    /// Look up a panel rect by the string representation of its `LeafId`.
    ///
    /// The canonical string form is `"Leaf(<n>)"` (matches `LeafId`'s `Display`
    /// impl), e.g. `"Leaf(42)"`.  Returns `None` if the string cannot be parsed
    /// or the leaf is not in the current layout.
    pub fn rect_for_leaf_str(&self, s: &str) -> Option<PanelRect> {
        // Parse "Leaf(<n>)" → u64.
        let inner = s.strip_prefix("Leaf(")?.strip_suffix(')')?;
        let n: u64 = inner.parse().ok()?;
        self.panel_rects.get(&LeafId(n)).copied()
    }

    /// Look up a leaf rect by the active panel's `type_id()`.  Walks the
    /// dock tree, returns the rect of the first leaf whose first panel's
    /// `type_id()` matches `panel_id`.
    ///
    /// This lets callers address dock leaves by user-meaningful panel
    /// identifiers (e.g. `"paint:r1_30fps"`) instead of opaque
    /// `Leaf(<n>)` strings — useful for `lm::panel(panel_id, ...)`.
    pub fn rect_for_panel_id(&self, panel_id: &str) -> Option<PanelRect> {
        for (leaf_id, rect) in &self.panel_rects {
            if let Some(leaf) = self.tree.leaf(*leaf_id) {
                if let Some(p) = leaf.panels.first() {
                    if p.type_id() == panel_id {
                        return Some(*rect);
                    }
                }
            }
        }
        None
    }

    /// Look up the `LeafId` whose active panel's `type_id()` matches
    /// `panel_id`.  Companion to [`Self::rect_for_panel_id`] used by
    /// resize-handle dispatch — the composite knows the panel by its
    /// builder slot id, the docking math knows it by `LeafId`.
    pub fn leaf_for_panel_id(&self, panel_id: &str) -> Option<LeafId> {
        for leaf_id in self.panel_rects.keys() {
            if let Some(leaf) = self.tree.leaf(*leaf_id) {
                if let Some(p) = leaf.panels.first() {
                    if p.type_id() == panel_id {
                        return Some(*leaf_id);
                    }
                }
            }
        }
        None
    }

    /// Find the index in `separators()` for the separator that should move
    /// when the user drags `edge` on the panel at `leaf`.
    ///
    /// - `E` / `W` map to vertical separators (axis = X).
    /// - `S` / `N` map to horizontal separators (axis = Y).
    /// - For `E` / `S` the leaf is on the **start** side (child_a side); the
    ///   separator that owns the trailing edge has `child_a` containing leaf.
    /// - For `W` / `N` the leaf is on the **end** side (child_b side).
    ///
    /// Returns `None` if no separator on the matching axis lives between the
    /// leaf and a sibling — typically because the panel's edge sits against
    /// the window / a chrome strip rather than a sibling panel.
    pub fn separator_for_edge(
        &self,
        leaf:  LeafId,
        edge:  super::ResizeEdge,
    ) -> Option<usize> {
        use super::ResizeEdge as E;

        let (orientation, leaf_is_a) = match edge {
            E::E => (SeparatorOrientation::Vertical,   true),
            E::W => (SeparatorOrientation::Vertical,   false),
            E::S => (SeparatorOrientation::Horizontal, true),
            E::N => (SeparatorOrientation::Horizontal, false),
            // Corner drags are out of scope for now; ignored.
            _    => return None,
        };

        for (idx, sep) in self.separators.iter().enumerate() {
            if sep.orientation != orientation { continue; }
            if let Some(line) = sep.grid_line {
                // A grid line borders every cell of its two adjacent tracks.
                let SeparatorLevel::Node { parent_id, .. } = sep.level;
                let track = if leaf_is_a { line.index } else { line.index + 1 };
                let hit = self.tree.find_branch(parent_id).is_some_and(|branch| {
                    Self::fitting_grid(branch).is_some_and(|g| {
                        let cells: Vec<usize> = match line.axis {
                            GridAxis::Row => (0..g.cols).map(|c| g.cell_index(track, c)).collect(),
                            GridAxis::Col => (0..g.rows).map(|r| g.cell_index(r, track)).collect(),
                        };
                        cells.into_iter().any(|i| {
                            self.node_contains_target_leaf(branch.children[i].raw_id(), leaf)
                        })
                    })
                });
                if hit {
                    return Some(idx);
                }
                continue;
            }
            let SeparatorLevel::Node { child_a, child_b, .. } = sep.level;
            let target_side = if leaf_is_a { child_a } else { child_b };
            if self.node_contains_target_leaf(target_side, leaf) {
                return Some(idx);
            }
        }
        None
    }

    /// True if the subtree rooted at `node_raw` contains `target`.  Used
    /// by [`Self::separator_for_edge`] to walk through nested branches —
    /// a leaf-targeted edge drag may map to a separator whose child is
    /// an ancestor branch of the leaf.
    fn node_contains_target_leaf(&self, node_raw: u64, target: LeafId) -> bool {
        if node_raw == target.0 { return true; }
        if let Some(branch) = self.tree.find_branch(BranchId(node_raw)) {
            return self.branch_subtree_contains(branch, target);
        }
        false
    }

    fn branch_subtree_contains(
        &self,
        branch: &Branch<P>,
        target: LeafId,
    ) -> bool {
        for child in &branch.children {
            match child {
                PanelNode::Leaf(l) => {
                    if l.id == target { return true; }
                }
                PanelNode::Branch(b) => {
                    if self.branch_subtree_contains(b, target) { return true; }
                }
            }
        }
        false
    }

    pub fn panel_headers(&self) -> &HashMap<LeafId, PanelRect> {
        &self.panel_headers
    }

    pub fn tab_bars(&self) -> &[TabBarInfo] {
        &self.tab_bars
    }

    pub fn corners(&self) -> &[CornerHandle] {
        &self.corners
    }

    pub fn floating_windows(&self) -> &[FloatingWindow<P>] {
        &self.floating_windows
    }

    pub fn snap_animations(&self) -> &[SnapBackAnimation] {
        &self.snap_animations
    }

    pub fn active_leaf(&self) -> Option<LeafId> {
        self.active_leaf
    }

    pub fn set_active_leaf(&mut self, id: LeafId) {
        self.tree.set_active_leaf(id);
        self.active_leaf = Some(id);
    }

    pub fn layout_area(&self) -> PanelRect {
        self.layout_area
    }

    /// Height of a panel header / multi-tab chip bar (the strip
    /// `create_tab_bar` lays chips in). Content under a stacked leaf
    /// starts this many px below the leaf's rect top.
    pub fn tab_bar_height(&self) -> f32 {
        self.header_height
    }

    pub fn window_edge_rects(&self) -> Option<&[PanelRect; 4]> {
        self.window_edge_rects.as_ref()
    }

    pub fn hovered_header(&self) -> Option<LeafId> {
        self.hovered_header
    }

    pub fn set_hovered_header(&mut self, id: Option<LeafId>) {
        self.hovered_header = id;
    }

    pub fn tab_reorder_state(&self) -> Option<&TabReorderState> {
        self.tab_reorder.as_ref()
    }

    pub fn floating_drag_state(&self) -> Option<&FloatingDragState> {
        self.floating_drag.as_ref()
    }
}

/// `min_frac` limited to `0.0..0.5` (NaN → 0), so two neighbours can
/// always both satisfy it.
fn sanitize_min_frac(min_frac: f64) -> f64 {
    if min_frac.is_nan() { 0.0 } else { min_frac.clamp(0.0, 0.49) }
}

/// Move `delta` from `b` to `a`, stopping where either would go below its
/// minimum. The sum `a + b` is kept. A side already below its minimum may
/// grow but never shrink further.
fn clamp_pair(a: f64, b: f64, delta: f64, min_a: f64, min_b: f64) -> (f64, f64) {
    let total = a + b;
    let lo = min_a.min(a);
    let hi = (total - min_b).max(a);
    let new_a = (a + delta).max(lo).min(hi);
    (new_a, total - new_a)
}

impl<P: DockPanel> Default for DockState<P> {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::docking::{DockPanel, DockingTree, SplitKind, PanelNode, BranchId};

    /// Minimal panel for testing.
    #[derive(Clone)]
    struct P;
    impl DockPanel for P {
        fn title(&self)   -> &str { "p" }
        fn type_id(&self) -> &'static str { "p" }
        fn min_size(&self) -> (f32, f32) { (0.0, 0.0) }
    }

    /// Build a `DockState` with a Grid2x2 layout (root→Grid2x2Branch→4 leaves),
    /// call `layout` so separators are populated.  Returns (state, [leaf_ids]).
    fn grid2x2_state(w: f32, h: f32) -> (DockState<P>, Vec<LeafId>) {
        let mut state = DockState::<P>::new();
        let first = state.tree_mut().add_leaf(P);
        let ids = state.tree_mut().split_leaf_with_children(
            first, SplitKind::Grid2x2, w, h
        );
        state.layout(PanelRect::new(0.0, 0.0, w, h));
        (state, ids)
    }

    /// After `add_leaf` + `split_leaf_with_children(Grid2x2)`, root has 1 child
    /// which is the Grid2x2 branch.  Return its BranchId.
    fn grid2x2_branch_id(state: &DockState<P>) -> BranchId {
        match &state.tree().root().children[0] {
            PanelNode::Branch(b) => b.id,
            _ => panic!("expected Grid2x2 branch as first root child"),
        }
    }

    // -------------------------------------------------------------------------
    // Part B — drag_separator routes Grid2x2 to cross_ratio, not proportions
    // -------------------------------------------------------------------------

    /// Dragging the vertical separator in a Grid2x2 layout must update
    /// cross_ratio.x on the Grid2x2 branch.  Proportions must stay empty.
    #[test]
    fn grid2x2_drag_vertical_sep_updates_cross_ratio_x() {
        let (mut state, _) = grid2x2_state(1000.0, 800.0);
        let grid_id = grid2x2_branch_id(&state);

        // Find a vertical separator belonging to the Grid2x2 branch.
        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Vertical
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == grid_id)
        });
        let sep_idx = sep_idx.expect("Grid2x2 must have at least one vertical separator");

        // Initial cross_ratio (None = defaults to 0.5/0.5)
        let initial_xr = state.tree().find_branch(grid_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .unwrap_or(0.5);

        // Drag right by +100 px
        let result = state.drag_separator(sep_idx, 100.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for Grid2x2");

        // cross_ratio.x must have moved right (increased)
        let new_xr = state.tree().find_branch(grid_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .expect("cross_ratio must be Some after drag");
        assert!(new_xr > initial_xr,
            "cross_ratio.x must increase after rightward drag: {} -> {}", initial_xr, new_xr);

        // proportions on the Grid2x2 branch must remain empty
        let grid_proportions = state.tree().find_branch(grid_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(grid_proportions, 0,
            "Grid2x2 drag must not write proportions");
    }

    /// Dragging the horizontal separator in a Grid2x2 layout must update
    /// cross_ratio.y on the Grid2x2 branch.
    #[test]
    fn grid2x2_drag_horizontal_sep_updates_cross_ratio_y() {
        let (mut state, _) = grid2x2_state(1000.0, 800.0);
        let grid_id = grid2x2_branch_id(&state);

        // Find a horizontal separator belonging to the Grid2x2 branch.
        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Horizontal
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == grid_id)
        });
        let sep_idx = sep_idx.expect("Grid2x2 must have at least one horizontal separator");

        let initial_yr = state.tree().find_branch(grid_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .unwrap_or(0.5);

        // Drag down by +80 px
        let result = state.drag_separator(sep_idx, 80.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for Grid2x2 horizontal sep");

        let new_yr = state.tree().find_branch(grid_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .expect("cross_ratio must be Some after horizontal drag");
        assert!(new_yr > initial_yr,
            "cross_ratio.y must increase after downward drag: {} -> {}", initial_yr, new_yr);

        let grid_proportions = state.tree().find_branch(grid_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(grid_proportions, 0,
            "Grid2x2 drag must not write proportions");
    }

    /// After a Grid2x2 separator drag, re-running layout must produce four
    /// distinct quadrants (not a single column/row).
    #[test]
    fn grid2x2_drag_then_layout_keeps_2x2_shape() {
        let (mut state, _) = grid2x2_state(1000.0, 800.0);
        let grid_id = grid2x2_branch_id(&state);

        // Drag the vertical separator right by 100px
        if let Some(sep_idx) = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Vertical
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == grid_id)
        }) {
            state.drag_separator(sep_idx, 100.0, 1000.0, 800.0);
        }

        // Re-layout
        state.layout(PanelRect::new(0.0, 0.0, 1000.0, 800.0));

        // Note: empty leaves (slots 1-3 after split_leaf_with_children) may not
        // appear in panel_rects since they have no panels.  What matters is that
        // the ones that DO appear keep the 2x2 quadrant shape, i.e. there are at
        // most 2 distinct x-origins and 2 distinct y-origins.
        // Minimum: the root branch passes through the Grid2x2 branch's cross_ratio.
        // Verify by checking the Grid2x2 branch directly.
        let grid_branch = state.tree().find_branch(grid_id)
            .expect("Grid2x2 branch must still exist after drag+layout");
        let parent = PanelRect::new(0.0, 0.0, 1000.0, 800.0);
        let child_rects = DockingTree::<P>::compute_child_rects(grid_branch, parent);

        assert_eq!(child_rects.len(), 4, "Grid2x2 must have 4 child rects");

        // Two distinct x-origins (left/right columns)
        let mut xs: Vec<i32> = child_rects.iter().map(|r| r.x.round() as i32).collect();
        xs.sort();
        xs.dedup();
        assert_eq!(xs.len(), 2, "must have exactly 2 column x-origins, got {:?}", xs);

        // Two distinct y-origins (top/bottom rows)
        let mut ys: Vec<i32> = child_rects.iter().map(|r| r.y.round() as i32).collect();
        ys.sort();
        ys.dedup();
        assert_eq!(ys.len(), 2, "must have exactly 2 row y-origins, got {:?}", ys);

        // Left column must be wider than default 500 (we dragged +100px right)
        let left_w = child_rects[0].width;
        assert!(left_w > 550.0,
            "left column must be wider than 550 after +100px drag, got {}", left_w);
    }

    // -------------------------------------------------------------------------
    // Regression: single-axis proportions still work via drag_separator
    // -------------------------------------------------------------------------

    /// Dragging a SplitHorizontal separator must still write proportions (not
    /// cross_ratio) and change panel widths accordingly.
    ///
    /// After `add_leaf` + `split_leaf(SplitRight)`, root has 1 child = the
    /// SplitHorizontal branch.
    #[test]
    fn split_horizontal_drag_writes_proportions() {
        let mut state = DockState::<P>::new();
        let first = state.tree_mut().add_leaf(P);
        state.tree_mut().split_leaf(first, SplitKind::SplitRight, P);
        state.layout(PanelRect::new(0.0, 0.0, 1000.0, 600.0));

        // The SplitHorizontal branch is root's first child.
        let split_branch_id = match &state.tree().root().children[0] {
            PanelNode::Branch(b) => b.id,
            _ => panic!("expected SplitHorizontal branch as first root child"),
        };

        // Must have a vertical separator belonging to that branch
        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Vertical
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == split_branch_id)
        }).expect("SplitHorizontal must have a vertical separator");

        let result = state.drag_separator(sep_idx, 100.0, 1000.0, 600.0);
        assert!(result, "drag must succeed for SplitHorizontal");

        // cross_ratio must remain None on the split branch
        let cr = state.tree().find_branch(split_branch_id)
            .and_then(|b| b.cross_ratio);
        assert!(cr.is_none(),
            "SplitHorizontal drag must not set cross_ratio");

        // proportions must now be written on the split branch
        let props_len = state.tree().find_branch(split_branch_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(props_len, 2,
            "SplitHorizontal drag must write 2 proportions, got {}", props_len);
    }

    // -------------------------------------------------------------------------
    // L-shape drag_separator routes to cross_ratio
    // -------------------------------------------------------------------------

    /// Helper: build a DockState with a OneLeftTwoRight layout, call layout().
    /// Returns (state, l_shape_branch_id).
    fn one_left_two_right_state(w: f32, h: f32) -> (DockState<P>, BranchId) {
        let mut state = DockState::<P>::new();
        let first = state.tree_mut().add_leaf(P);
        state.tree_mut().split_leaf_with_children(
            first, SplitKind::OneLeftTwoRight, w, h
        );
        state.layout(PanelRect::new(0.0, 0.0, w, h));
        // The L-shape branch is root's first child.
        let branch_id = match &state.tree().root().children[0] {
            PanelNode::Branch(b) => b.id,
            _ => panic!("expected OneLeftTwoRight branch as first root child"),
        };
        (state, branch_id)
    }

    /// Dragging the vertical separator of a OneLeftTwoRight layout must update
    /// cross_ratio.x (the left/right column split) and leave proportions empty.
    #[test]
    fn one_left_two_right_drag_vertical_sep_updates_cross_ratio_x() {
        let (mut state, branch_id) = one_left_two_right_state(1000.0, 800.0);

        // Find a vertical separator owned by the L-shape branch.
        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Vertical
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == branch_id)
        });
        let sep_idx = sep_idx.expect("OneLeftTwoRight must have a vertical separator");

        // Default xr = 0.6; dragging right (+100px) must increase it.
        let initial_xr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .unwrap_or(0.6);

        let result = state.drag_separator(sep_idx, 100.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for OneLeftTwoRight");

        let new_xr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .expect("cross_ratio must be Some after drag");
        assert!(new_xr > initial_xr,
            "cross_ratio.x must increase after rightward drag: {} -> {}", initial_xr, new_xr);

        // proportions must stay empty
        let props_len = state.tree().find_branch(branch_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(props_len, 0,
            "OneLeftTwoRight drag must not write proportions");
    }

    /// Dragging the horizontal separator of a OneLeftTwoRight layout must update
    /// cross_ratio.y (the right-column row split) and leave proportions empty.
    #[test]
    fn one_left_two_right_drag_horizontal_sep_updates_cross_ratio_y() {
        let (mut state, branch_id) = one_left_two_right_state(1000.0, 800.0);

        // Find a horizontal separator owned by the L-shape branch.
        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Horizontal
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == branch_id)
        });
        let sep_idx = sep_idx.expect("OneLeftTwoRight must have a horizontal separator");

        let initial_yr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .unwrap_or(0.5);

        let result = state.drag_separator(sep_idx, 80.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for OneLeftTwoRight horizontal sep");

        let new_yr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .expect("cross_ratio must be Some after horizontal drag");
        assert!(new_yr > initial_yr,
            "cross_ratio.y must increase after downward drag: {} -> {}", initial_yr, new_yr);

        // proportions must stay empty
        let props_len = state.tree().find_branch(branch_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(props_len, 0,
            "OneLeftTwoRight drag must not write proportions");
    }

    /// Helper: build a DockState with TwoTopOneBottom layout.
    fn two_top_one_bottom_state(w: f32, h: f32) -> (DockState<P>, BranchId) {
        let mut state = DockState::<P>::new();
        let first = state.tree_mut().add_leaf(P);
        state.tree_mut().split_leaf_with_children(
            first, SplitKind::TwoTopOneBottom, w, h
        );
        state.layout(PanelRect::new(0.0, 0.0, w, h));
        let branch_id = match &state.tree().root().children[0] {
            PanelNode::Branch(b) => b.id,
            _ => panic!("expected TwoTopOneBottom branch as first root child"),
        };
        (state, branch_id)
    }

    /// Dragging the horizontal separator of TwoTopOneBottom must increase cross_ratio.y.
    #[test]
    fn two_top_one_bottom_drag_horizontal_sep_updates_cross_ratio_y() {
        let (mut state, branch_id) = two_top_one_bottom_state(1000.0, 800.0);

        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Horizontal
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == branch_id)
        });
        let sep_idx = sep_idx.expect("TwoTopOneBottom must have a horizontal separator");

        let initial_yr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .unwrap_or(0.4);

        let result = state.drag_separator(sep_idx, 60.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for TwoTopOneBottom");

        let new_yr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(_, y)| y)
            .expect("cross_ratio must be Some after drag");
        assert!(new_yr > initial_yr,
            "cross_ratio.y must increase after downward drag: {} -> {}", initial_yr, new_yr);

        let props_len = state.tree().find_branch(branch_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(props_len, 0,
            "TwoTopOneBottom drag must not write proportions");
    }

    /// Dragging the vertical separator of TwoTopOneBottom must increase cross_ratio.x.
    #[test]
    fn two_top_one_bottom_drag_vertical_sep_updates_cross_ratio_x() {
        let (mut state, branch_id) = two_top_one_bottom_state(1000.0, 800.0);

        let sep_idx = state.separators().iter().position(|s| {
            s.orientation == SeparatorOrientation::Vertical
                && matches!(&s.level, SeparatorLevel::Node { parent_id, .. } if *parent_id == branch_id)
        });
        let sep_idx = sep_idx.expect("TwoTopOneBottom must have a vertical separator");

        let initial_xr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .unwrap_or(0.5);

        let result = state.drag_separator(sep_idx, 100.0, 1000.0, 800.0);
        assert!(result, "drag_separator must return true for TwoTopOneBottom vertical sep");

        let new_xr = state.tree().find_branch(branch_id)
            .and_then(|b| b.cross_ratio)
            .map(|(x, _)| x)
            .expect("cross_ratio must be Some after drag");
        assert!(new_xr > initial_xr,
            "cross_ratio.x must increase after rightward drag: {} -> {}", initial_xr, new_xr);

        let props_len = state.tree().find_branch(branch_id)
            .map(|b| b.proportions.len())
            .unwrap_or(0);
        assert_eq!(props_len, 0,
            "TwoTopOneBottom drag must not write proportions");
    }
}

#[cfg(test)]
mod center_drop_tests {
    use super::*;
    use crate::layout::docking::{DockPanel, SplitKind};

    #[derive(Clone, Debug, PartialEq)]
    struct Q(&'static str);
    impl DockPanel for Q {
        fn title(&self) -> &str { self.0 }
        fn type_id(&self) -> &'static str { "q" }
        fn min_size(&self) -> (f32, f32) { (0.0, 0.0) }
    }

    /// A grip drag dropped on another leaf's CENTER must tab-join: the
    /// dragged leaf's panels move into the target leaf, the dragged leaf
    /// is removed.
    #[test]
    fn center_drop_tab_joins() {
        let mut ds = DockState::<Q>::new();
        let a = ds.tree_mut().add_leaf(Q("a"));
        let b = ds.tree_mut().split_leaf(a, SplitKind::SplitRight, Q("b")).unwrap();
        ds.layout(PanelRect::new(0.0, 0.0, 1000.0, 800.0));

        // Drag leaf B by its grip, hover the CENTER of leaf A, drop.
        ds.start_panel_drag(b, 900.0, 400.0);
        ds.update_panel_drag(250.0, 400.0); // center of A (0..500 x 0..800)
        let drag = ds.panel_drag_state().expect("drag alive");
        assert_eq!(drag.target_leaf_id, Some(a), "target must be leaf A");
        assert_eq!(drag.drop_zone, Some(DropZone::Center), "zone must be Center");
        ds.end_panel_drag(1000.0, 800.0);

        let leaf_a = ds.tree().leaf(a).expect("A survives");
        assert_eq!(leaf_a.panels.len(), 2, "A must hold both panels as tabs");
        assert!(ds.tree().leaf(b).is_none(), "B leaf must be gone");
    }

    /// Same drop with a drop policy installed that passes everything
    /// through — the policy must not break Center.
    #[test]
    fn center_drop_with_passthrough_policy() {
        let mut ds = DockState::<Q>::new();
        let a = ds.tree_mut().add_leaf(Q("a"));
        let b = ds.tree_mut().split_leaf(a, SplitKind::SplitRight, Q("b")).unwrap();
        ds.set_drop_policy(Box::new(|_, _, zone, _, _| Some(zone)));
        ds.layout(PanelRect::new(0.0, 0.0, 1000.0, 800.0));

        ds.start_panel_drag(b, 900.0, 400.0);
        ds.update_panel_drag(250.0, 400.0);
        assert_eq!(ds.panel_drag_state().unwrap().drop_zone, Some(DropZone::Center));
        ds.end_panel_drag(1000.0, 800.0);
        assert_eq!(ds.tree().leaf(a).unwrap().panels.len(), 2);
    }

    #[derive(Clone)]
    struct Pinned(crate::layout::docking::Pin);
    impl DockPanel for Pinned {
        fn title(&self) -> &str { "pinned" }
        fn type_id(&self) -> &'static str { "pinned" }
        fn pin(&self) -> crate::layout::docking::Pin { self.0 }
    }

    #[test]
    fn a_system_pinned_panel_never_arms_a_header_or_tab_drag() {
        use crate::layout::docking::Pin;
        let mut state = DockState::<Pinned>::new();
        let leaf = state.tree_mut().add_leaf(Pinned(Pin::System));
        state.start_panel_drag(leaf, 10.0, 10.0);
        assert!(state.panel_drag_state().is_none(), "System pin: header drag must not arm");

        state.tree_mut().add_tab(leaf, Pinned(Pin::Free));
        state.start_panel_drag(leaf, 10.0, 10.0);
        assert!(state.panel_drag_state().is_none(), "a leaf with any pinned tab travels nowhere");
        state.start_tab_drag(leaf, 0, 10.0, 10.0);
        assert!(state.panel_drag_state().is_none(), "the pinned tab itself cannot tear off");
        state.start_tab_drag(leaf, 1, 10.0, 10.0);
        assert!(state.panel_drag_state().is_some(), "a free tab in the same stack still tears off");
    }

    #[test]
    fn free_and_unpinned_panels_arm_as_before() {
        use crate::layout::docking::Pin;
        let mut state = DockState::<Pinned>::new();
        let leaf = state.tree_mut().add_leaf(Pinned(Pin::User { pinned: false }));
        state.start_panel_drag(leaf, 10.0, 10.0);
        assert!(state.panel_drag_state().is_some());
    }
}


// =============================================================================
// Tests — rows × cols grids and SplitterPolicy
// =============================================================================

#[cfg(test)]
mod grid_policy_tests {
    use super::*;
    use crate::layout::docking::{DockPanel, DockingTree, GridAxis, GridLine, SplitterPolicy};

    /// Panel with a configurable minimum size.
    #[derive(Clone)]
    struct M(f32, f32);
    impl DockPanel for M {
        fn title(&self) -> &str { "m" }
        fn type_id(&self) -> &'static str { "m" }
        fn min_size(&self) -> (f32, f32) { (self.0, self.1) }
    }

    fn grid_state(rows: usize, cols: usize, w: f32, h: f32, min: (f32, f32)) -> DockState<M> {
        let tree = DockingTree::with_grid(rows, cols, vec![M(min.0, min.1); rows * cols]).unwrap();
        let mut state = DockState::from_tree(tree);
        state.layout(PanelRect::new(0.0, 0.0, w, h));
        state
    }

    fn line(state: &DockState<M>, axis: GridAxis, index: usize) -> usize {
        state.separators().iter()
            .position(|s| s.grid_line == Some(GridLine { axis, index }))
            .expect("grid line separator")
    }

    fn grid(state: &DockState<M>) -> GridSpec {
        state.tree().root().grid.clone().expect("root is a grid")
    }

    fn near(a: f64, b: f64) -> bool { (a - b).abs() < 1e-9 }

    #[test]
    fn default_policy_is_cascade() {
        assert_eq!(SplitterPolicy::default(), SplitterPolicy::Cascade);
        assert_eq!(DockState::<M>::new().splitter_policy(), SplitterPolicy::Cascade);
        let mut s = DockState::<M>::new();
        s.set_splitter_policy(SplitterPolicy::Clamp { min_frac: 0.1 });
        assert_eq!(s.splitter_policy(), SplitterPolicy::Clamp { min_frac: 0.1 });
    }

    #[test]
    fn row_line_drag_changes_only_the_two_adjacent_rows() {
        // 3 rows × 2 cols, 600 × 600 → rows of 200 px.
        let mut s = grid_state(3, 2, 600.0, 600.0, (0.0, 0.0));
        let before = grid(&s);
        let idx = line(&s, GridAxis::Row, 0);
        assert!(s.drag_separator(idx, 60.0, 600.0, 600.0));
        let after = grid(&s);

        assert_eq!(after.col_ratios, before.col_ratios, "columns untouched");
        assert_eq!(after.row_ratios[2], before.row_ratios[2], "row 2 untouched");
        assert!(near(after.row_ratios[0], before.row_ratios[0] + 0.1));
        assert!(near(after.row_ratios[1], before.row_ratios[1] - 0.1));
        let sum_b: f64 = before.row_ratios.iter().sum();
        let sum_a: f64 = after.row_ratios.iter().sum();
        assert!(near(sum_a, sum_b), "sum preserved");

        s.layout(PanelRect::new(0.0, 0.0, 600.0, 600.0));
        let first = s.tree().root().children[0].leaf_id().unwrap();
        assert!((s.panel_rects()[&first].height - 260.0).abs() < 0.01);
        assert!(s.snap_animations().is_empty());
    }

    #[test]
    fn column_line_drag_changes_only_the_two_adjacent_columns() {
        // 2 rows × 3 cols, 900 × 400 → columns of 300 px.
        let mut s = grid_state(2, 3, 900.0, 400.0, (0.0, 0.0));
        let before = grid(&s);
        let idx = line(&s, GridAxis::Col, 1);
        assert!(s.drag_separator(idx, -90.0, 900.0, 400.0));
        let after = grid(&s);

        assert_eq!(after.row_ratios, before.row_ratios, "rows untouched");
        assert_eq!(after.col_ratios[0], before.col_ratios[0], "column 0 untouched");
        assert!(near(after.col_ratios[1], before.col_ratios[1] - 0.1));
        assert!(near(after.col_ratios[2], before.col_ratios[2] + 0.1));
        let sum_b: f64 = before.col_ratios.iter().sum();
        let sum_a: f64 = after.col_ratios.iter().sum();
        assert!(near(sum_a, sum_b), "sum preserved");
    }

    #[test]
    fn reject_snap_back_on_a_grid_rejects_and_queues_a_snap_back() {
        // 2 × 2, 1000 × 1000, every cell at least 200 × 200.
        let mut s = grid_state(2, 2, 1000.0, 1000.0, (200.0, 200.0));
        s.set_splitter_policy(SplitterPolicy::RejectSnapBack);
        let idx = line(&s, GridAxis::Col, 0);
        // +400 px would leave the right column 100 px < 200 px minimum.
        assert!(!s.drag_separator(idx, 400.0, 1000.0, 1000.0));
        assert_eq!(grid(&s).col_ratios, vec![0.5, 0.5], "ratios unchanged");
        assert_eq!(s.snap_animations().len(), 1);
        assert_eq!(s.snap_animations()[0].separator_idx, idx);
        assert!(!s.snap_animations()[0].done);

        // A move that respects the minimum goes through.
        assert!(s.drag_separator(idx, 250.0, 1000.0, 1000.0));
        let cols = grid(&s).col_ratios;
        assert!(near(cols[0], 0.75) && near(cols[1], 0.25), "{cols:?}");
    }

    #[test]
    fn clamp_on_a_grid_stops_at_min_frac_and_never_rejects() {
        let mut s = grid_state(2, 2, 1000.0, 1000.0, (0.0, 0.0));
        s.set_splitter_policy(SplitterPolicy::Clamp { min_frac: 0.1 });
        let idx = line(&s, GridAxis::Col, 0);
        assert!(s.drag_separator(idx, 10_000.0, 1000.0, 1000.0));
        let cols = grid(&s).col_ratios;
        assert!(near(cols[0], 0.9) && near(cols[1], 0.1), "{cols:?}");
        // Pushing further stays at the limit — still accepted.
        assert!(s.drag_separator(idx, 100.0, 1000.0, 1000.0));
        let cols = grid(&s).col_ratios;
        assert!(near(cols[0], 0.9) && near(cols[1], 0.1), "{cols:?}");
        // Rows are independent.
        let row = line(&s, GridAxis::Row, 0);
        assert!(s.drag_separator(row, -10_000.0, 1000.0, 1000.0));
        let g = grid(&s);
        assert!(near(g.row_ratios[0], 0.1) && near(g.row_ratios[1], 0.9), "{g:?}");
        assert!(near(g.col_ratios[0], 0.9));
        assert!(s.snap_animations().is_empty(), "clamp never snaps back");
    }

    fn two_columns(min_w: f32) -> (DockState<M>, usize, BranchId) {
        let mut tree = DockingTree::with_single_leaf(M(min_w, 0.0));
        tree.add_leaf(M(min_w, 0.0));
        let root = tree.root().id;
        let mut s = DockState::from_tree(tree);
        s.layout(PanelRect::new(0.0, 0.0, 1000.0, 500.0));
        let idx = s.separators().iter()
            .position(|sp| sp.orientation == SeparatorOrientation::Vertical)
            .unwrap();
        (s, idx, root)
    }

    fn fractions(s: &DockState<M>, id: BranchId) -> Vec<f64> {
        let p = &s.tree().find_branch(id).unwrap().proportions;
        let sum: f64 = p.iter().sum();
        p.iter().map(|v| v / sum).collect()
    }

    #[test]
    fn clamp_on_a_single_axis_split_stops_at_the_larger_minimum() {
        // min_frac wins: 0.2 of 1000 px > 0 px panel minimum.
        let (mut s, idx, root) = two_columns(0.0);
        s.set_splitter_policy(SplitterPolicy::Clamp { min_frac: 0.2 });
        assert!(s.drag_separator(idx, -5_000.0, 1000.0, 500.0));
        let f = fractions(&s, root);
        assert!(near(f[0], 0.2) && near(f[1], 0.8), "{f:?}");
        assert!(s.snap_animations().is_empty());

        // Pixel minimum wins: 300 px of 1000 > 0.1.
        let (mut s, idx, root) = two_columns(300.0);
        s.set_splitter_policy(SplitterPolicy::Clamp { min_frac: 0.1 });
        assert!(s.drag_separator(idx, -5_000.0, 1000.0, 500.0));
        let f = fractions(&s, root);
        assert!((f[0] - 0.3).abs() < 1e-6 && (f[1] - 0.7).abs() < 1e-6, "{f:?}");
    }

    #[test]
    fn default_policy_keeps_the_cascading_single_axis_drag_clamp_moves_only_neighbours() {
        // Three 300 px columns, each at least 100 px.
        let build = || {
            let mut tree = DockingTree::with_single_leaf(M(100.0, 0.0));
            tree.add_leaf(M(100.0, 0.0));
            tree.add_leaf(M(100.0, 0.0));
            let root = tree.root().id;
            let mut s = DockState::from_tree(tree);
            s.layout(PanelRect::new(0.0, 0.0, 900.0, 300.0));
            let first = s.tree().root().children[0].raw_id();
            let idx = s.separators().iter()
                .position(|sp| sp.child_a() == Some(first))
                .unwrap();
            (s, idx, root)
        };

        // Default: the delta cascades through column 1 then column 2.
        let (mut s, idx, root) = build();
        assert!(s.drag_separator(idx, 400.0, 900.0, 300.0));
        let f = fractions(&s, root);
        assert!((f[0] - 700.0 / 900.0).abs() < 1e-6, "{f:?}");
        assert!((f[1] - 100.0 / 900.0).abs() < 1e-6 && (f[2] - 100.0 / 900.0).abs() < 1e-6, "{f:?}");

        // Clamp: column 2 is never touched; column 1 stops at its minimum.
        let (mut s, idx, root) = build();
        s.set_splitter_policy(SplitterPolicy::Clamp { min_frac: 0.0 });
        assert!(s.drag_separator(idx, 400.0, 900.0, 300.0));
        let f = fractions(&s, root);
        assert!((f[0] - 500.0 / 900.0).abs() < 1e-6, "{f:?}");
        assert!((f[1] - 100.0 / 900.0).abs() < 1e-6, "{f:?}");
        assert!((f[2] - 300.0 / 900.0).abs() < 1e-6, "{f:?}");
    }

    #[test]
    fn hit_test_finds_grid_cells_and_grid_lines() {
        // 2 × 3 over 600 × 400: columns at x = 200 / 400, row line at y = 200.
        let s = grid_state(2, 3, 600.0, 400.0, (0.0, 0.0));
        let cells: Vec<LeafId> = s.tree().root().children.iter()
            .map(|c| c.leaf_id().unwrap()).collect();
        assert_eq!(s.hit_test(500.0, 300.0).panel_id(), Some(cells[5]));
        assert_eq!(s.hit_test(100.0, 100.0).panel_id(), Some(cells[0]));
        match s.hit_test(50.0, 200.0) {
            HitResult::Separator(i) => assert_eq!(i, line(&s, GridAxis::Row, 0)),
            other => panic!("expected the row line, got {other:?}"),
        }
        match s.hit_test(400.0, 350.0) {
            HitResult::Separator(i) => assert_eq!(i, line(&s, GridAxis::Col, 1)),
            other => panic!("expected column line 1, got {other:?}"),
        }
    }

    #[test]
    fn separator_for_edge_maps_any_grid_cell_to_its_lines() {
        use crate::layout::ResizeEdge;
        let s = grid_state(2, 3, 600.0, 400.0, (0.0, 0.0));
        // Cell (1, 2): bottom-right.
        let leaf = s.tree().root().children[5].leaf_id().unwrap();
        assert_eq!(s.separator_for_edge(leaf, ResizeEdge::N), Some(line(&s, GridAxis::Row, 0)));
        assert_eq!(s.separator_for_edge(leaf, ResizeEdge::W), Some(line(&s, GridAxis::Col, 1)));
        assert_eq!(s.separator_for_edge(leaf, ResizeEdge::E), None);
        assert_eq!(s.separator_for_edge(leaf, ResizeEdge::S), None);
    }

    #[test]
    fn cascade_on_a_grid_stops_at_the_pixel_minimum_and_never_rejects() {
        let mut s = grid_state(2, 2, 1000.0, 1000.0, (200.0, 200.0));
        let idx = line(&s, GridAxis::Col, 0);
        assert!(s.drag_separator(idx, 400.0, 1000.0, 1000.0));
        let cols = grid(&s).col_ratios;
        let total: f64 = cols.iter().sum();
        let right_px = cols[1] / total * (1000.0 - crate::layout::docking::presets::PANEL_GAP as f64);
        assert!((right_px - 200.0).abs() < 0.5, "{cols:?} → right {right_px}px");
        assert!(s.snap_animations().is_empty());
    }

    #[test]
    fn reject_snap_back_on_a_single_axis_split_refuses_past_the_minimum() {
        // Three 300 px columns, each at least 100 px.
        let mut tree = DockingTree::with_single_leaf(M(100.0, 0.0));
        tree.add_leaf(M(100.0, 0.0));
        tree.add_leaf(M(100.0, 0.0));
        let root = tree.root().id;
        let mut s = DockState::from_tree(tree);
        s.layout(PanelRect::new(0.0, 0.0, 900.0, 300.0));
        s.set_splitter_policy(SplitterPolicy::RejectSnapBack);
        let first = s.tree().root().children[0].raw_id();
        let idx = s.separators().iter().position(|sp| sp.child_a() == Some(first)).unwrap();

        // +250 px leaves column 1 at 50 px < 100 px: refused, nothing moves.
        let before = fractions(&s, root);
        assert!(!s.drag_separator(idx, 250.0, 900.0, 300.0));
        assert_eq!(fractions(&s, root), before);
        assert_eq!(s.snap_animations().len(), 1);
        assert!(s.snap_animations()[0].offset() > 0.0);

        // +150 px is allowed and moves only the two neighbours.
        assert!(s.drag_separator(idx, 150.0, 900.0, 300.0));
        let f = fractions(&s, root);
        assert!((f[0] - 450.0 / 900.0).abs() < 1e-6, "{f:?}");
        assert!((f[1] - 150.0 / 900.0).abs() < 1e-6, "{f:?}");
        assert!((f[2] - 300.0 / 900.0).abs() < 1e-6, "{f:?}");
    }
}

#[cfg(test)]
mod floating_and_strip_tests {
    use super::*;
    use crate::layout::docking::DockPanel;

    #[derive(Clone)]
    struct T(&'static str);
    impl DockPanel for T {
        fn title(&self) -> &str { self.0 }
        fn type_id(&self) -> &'static str { self.0 }
        fn min_size(&self) -> (f32, f32) { (0.0, 0.0) }
    }

    fn fw(id: u64, panels: Vec<T>, active_tab: usize) -> FloatingWindow<T> {
        FloatingWindow::new(FloatingWindowId(id), panels, active_tab, 10.0, 20.0, 200.0, 100.0)
    }

    #[test]
    fn insert_floating_keeps_the_id_and_allocates_past_it() {
        let mut s = DockState::<T>::new();
        assert_eq!(s.next_floating_id(), FloatingWindowId(1));
        assert_eq!(s.insert_floating(fw(7, vec![T("a"), T("b")], 9)), Some(FloatingWindowId(7)));
        assert_eq!(s.floating_windows()[0].active_tab, 1, "active tab clamped");
        assert_eq!(s.next_floating_id(), FloatingWindowId(8));
        // Duplicate id and empty windows are refused.
        assert_eq!(s.insert_floating(fw(7, vec![T("c")], 0)), None);
        assert_eq!(s.insert_floating(fw(9, vec![], 0)), None);
        assert_eq!(s.floating_windows().len(), 1);
        // A lower id does not move the counter back.
        assert_eq!(s.insert_floating(fw(2, vec![T("c")], 0)), Some(FloatingWindowId(2)));
        assert_eq!(s.next_floating_id(), FloatingWindowId(8));
    }

    #[test]
    fn set_floating_rect_moves_and_resizes() {
        let mut s = DockState::<T>::new();
        s.insert_floating(fw(1, vec![T("a")], 0));
        assert!(s.set_floating_rect(FloatingWindowId(1), PanelRect::new(1.0, 2.0, 3.0, 4.0)));
        assert_eq!(s.floating_windows()[0].rect(), PanelRect::new(1.0, 2.0, 3.0, 4.0));
        assert!(!s.set_floating_rect(FloatingWindowId(5), PanelRect::ZERO));
    }

    #[test]
    fn tab_strip_reserve_leaves_room_right_of_the_chips() {
        let mut s = DockState::<T>::with_panel(T("a"));
        let leaf = s.tree().leaves()[0].id;
        s.tree_mut().add_tab(leaf, T("b"));
        s.layout(PanelRect::new(0.0, 0.0, 400.0, 300.0));
        assert_eq!(s.tab_strip_reserve(), 0.0);
        let last = &s.tab_bars()[0].tabs[1].rect;
        assert_eq!(last.x + last.width, 400.0);

        s.set_tab_strip_reserve(24.0);
        s.layout(PanelRect::new(0.0, 0.0, 400.0, 300.0));
        let bar = &s.tab_bars()[0];
        assert_eq!(bar.tabs[0].rect.width, 188.0);
        assert_eq!(bar.rect.width, 376.0);
        s.set_tab_strip_reserve(f32::NAN);
        assert_eq!(s.tab_strip_reserve(), 0.0);
    }
}