uzor 1.4.13

Core UI engine — geometry, interaction, input state
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
//! 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,
    WindowLayout,
};
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)>,
}

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(),
        }
    }

    /// 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(),
        }
    }

    /// 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(),
        }
    }

    // =============================================================================
    // 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 {
                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 {
                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
    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;

        for (i, panel) in leaf.panels.iter().enumerate() {
            let title = panel.title();
            let estimated_text_w = title.len() as f32 * 7.0; // ~7px per char
            let tab_w: f32 = (8.0 + estimated_text_w + 24.0 + 8.0).clamp(80.0, 200.0);

            let remaining = rect.width - tab_x_offset;
            let tab_w = tab_w.min(remaining).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.
    ///
    /// 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) = {
            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)
        };

        // 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);

                // 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);
                        new_xr = (cur_xr + delta as f64 / available_w as f64)
                            .clamp(0.05, 0.95);
                        new_yr = cur_yr;
                    }
                    SeparatorOrientation::Horizontal => {
                        // Horizontal bar → moves up/down → affects y ratio.
                        let available_h = (full_h - gap).max(1.0);
                        new_xr = cur_xr;
                        new_yr = (cur_yr + delta as f64 / available_h as f64)
                            .clamp(0.05, 0.95);
                    }
                }
                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();

        // --- 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
    }

    // =============================================================================
    // 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) => {
                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) => {
                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)
                }
            }
        }
    }

    /// 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>,
        }

        /// Fixed-point water-fill for one branch.
        /// Returns `Some(new_props)` only when current proportions violate minimums.
        fn water_fill(available: f32, weights: &[f64], mins: &[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 = norm.iter().zip(mins.iter())
                .all(|(p, m)| p * avail_f + 1e-6 >= *m as f64);
            if all_ok {
                return None;
            }

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

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

            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; }
            }
            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;
            }

            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()
                };
                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) {
                    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)
    pub fn start_panel_drag(&mut self, leaf_id: LeafId, x: f32, y: f32) {
        self.panel_drag = Some(PanelDragState {
            dragged_leaf_id: leaf_id,
            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;

            // Check headers first — dropping on a header always creates tabs
            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;
                        }
                }
            }

            // Check window-level edges (before panel body detection)
            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()
                                .find(|&&id| 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;
                            }
                        }
                    }
                }
            }

            // Fall back to panel body detection with drop zone algorithm
            if target.is_none() {
                for (&id, &rect) in &self.panel_rects {
                    if 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;
                        zone = Some(Self::detect_drop_zone(local_x, local_y, rect.width, rect.height));
                        break;
                    }
                }
            }

            drag.target_leaf_id = target;
            drag.drop_zone = 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()?;

        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 => {
                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);
                }
            }
        }
    }

    // =============================================================================
    // 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.clamp(0.0, (area_width - 300.0).max(0.0)),
            y: y.clamp(0.0, (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);
    }

    /// 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).clamp(0.0, (area_width - fw.width).max(0.0));
                fw.y = (cursor_y - oy).clamp(0.0, (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),
        ]);
    }

    // =============================================================================
    // 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; }
            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
    }

    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()
    }
}

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");
    }
}