uzor 1.2.0

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
//! PanelDockingManager — 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
//!
//! PanelDockingManager 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::{PanelDockingManager, 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 = PanelDockingManager::<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 super::{
    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;

// =============================================================================
// PanelDockingManager
// =============================================================================

/// 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 PanelDockingManager<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> PanelDockingManager<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
    fn compute_leaf_rects(&self, area: PanelRect) -> HashMap<LeafId, PanelRect> {
        let mut rects = HashMap::new();
        self.collect_leaf_rects_from_branch(self.tree.root(), area, &mut rects);
        rects
    }

    /// Recursively collect leaf rects from branch
    fn collect_leaf_rects_from_branch(
        &self,
        branch: &Branch<P>,
        branch_rect: PanelRect,
        out: &mut HashMap<LeafId, PanelRect>,
    ) {
        let child_rects = self.compute_child_rects(branch, branch_rect);

        for (child, rect) in branch.children.iter().zip(child_rects.iter()) {
            match child {
                PanelNode::Leaf(leaf) => {
                    if !leaf.hidden {
                        out.insert(leaf.id, *rect);
                    }
                }
                PanelNode::Branch(b) => {
                    self.collect_leaf_rects_from_branch(b, *rect, out);
                }
            }
        }
    }

    /// Compute child rects for a branch (layout algorithm)
    fn compute_child_rects(&self, branch: &Branch<P>, area: PanelRect) -> Vec<PanelRect> {
        DockingTree::<P>::compute_child_rects(branch, 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
    fn generate_separators_recursive(&mut self, branch: &Branch<P>, branch_rect: PanelRect) {
        let child_rects = self.compute_child_rects(branch, branch_rect);

        if child_rects.len() < 2 {
            // Single or no children — no separators at this level
            // But still recurse into child branches
            for (child, rect) in branch.children.iter().zip(child_rects.iter()) {
                if let PanelNode::Branch(b) = child {
                    self.generate_separators_recursive(b, *rect);
                }
            }
            return;
        }

        // Convert to rects for adjacency detection (include both leaves and branches)
        let child_panel_rects: Vec<(u64, PanelRect)> = branch.children.iter()
            .zip(child_rects.iter())
            .filter(|(node, _)| !node.is_hidden())
            .map(|(node, wr)| (node.raw_id(), *wr))
            .collect();

        // Generate separators between adjacent children
        for i in 0..child_panel_rects.len() {
            for j in (i + 1)..child_panel_rects.len() {
                let (_, r1) = child_panel_rects[i];
                let (_, r2) = child_panel_rects[j];

                let h_overlap = r1.y.max(r2.y) < (r1.y + r1.height).min(r2.y + r2.height) - 1.0;
                let v_overlap = r1.x.max(r2.x) < (r1.x + r1.width).min(r2.x + r2.width) - 1.0;

                if h_overlap {
                    // Horizontal overlap — vertical separator
                    let left = if r1.x < r2.x { r1 } else { r2 };
                    let right = if r1.x < r2.x { r2 } else { r1 };
                    let gap = right.x - (left.x + left.width);

                    if gap <= 15.0 {
                        let sep_x = left.x + left.width + gap / 2.0;
                        let sep_y = r1.y.max(r2.y);
                        let sep_h = (r1.y + r1.height).min(r2.y + r2.height) - sep_y;
                        let (ca, cb) = if child_panel_rects[i].1.x < child_panel_rects[j].1.x {
                            (child_panel_rects[i].0, child_panel_rects[j].0)
                        } else {
                            (child_panel_rects[j].0, child_panel_rects[i].0)
                        };

                        self.separators.push(Separator::new(
                            SeparatorOrientation::Vertical,
                            sep_x, sep_y, sep_h,
                            SeparatorLevel::Node { parent_id: branch.id, child_a: ca, child_b: cb },
                        ));
                    }
                } else if v_overlap {
                    // Vertical overlap — horizontal separator
                    let top = if r1.y < r2.y { r1 } else { r2 };
                    let bottom = if r1.y < r2.y { r2 } else { r1 };
                    let gap = bottom.y - (top.y + top.height);

                    if gap <= 15.0 {
                        let sep_y = top.y + top.height + gap / 2.0;
                        let sep_x = r1.x.max(r2.x);
                        let sep_w = (r1.x + r1.width).min(r2.x + r2.width) - sep_x;
                        let (ca, cb) = if child_panel_rects[i].1.y < child_panel_rects[j].1.y {
                            (child_panel_rects[i].0, child_panel_rects[j].0)
                        } else {
                            (child_panel_rects[j].0, child_panel_rects[i].0)
                        };

                        self.separators.push(Separator::new(
                            SeparatorOrientation::Horizontal,
                            sep_y, sep_x, sep_w,
                            SeparatorLevel::Node { parent_id: branch.id, child_a: ca, child_b: cb },
                        ));
                    }
                }
            }
        }

        // Recurse into child branches
        for (child, rect) in branch.children.iter().zip(child_rects.iter()) {
            if let PanelNode::Branch(b) = child {
                self.generate_separators_recursive(b, *rect);
            }
        }
    }

    /// Detect corners at separator intersections
    fn detect_corners(&mut self) {
        self.corners.clear();
        for (vi, v_sep) in self.separators.iter().enumerate() {
            if v_sep.orientation != SeparatorOrientation::Vertical {
                continue;
            }
            for (hi, h_sep) in self.separators.iter().enumerate() {
                if h_sep.orientation != SeparatorOrientation::Horizontal {
                    continue;
                }
                self.corners.push(CornerHandle {
                    v_separator_idx: vi,
                    h_separator_idx: hi,
                    x: v_sep.position,
                    y: h_sep.position,
                });
            }
        }
    }

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

        // 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: &PanelDockingManager<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 = PanelDockingManager::<P>::layout_is_horizontal(branch.layout);
            let vertical = PanelDockingManager::<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 {
        let center_margin = 0.20;
        let cx = width * center_margin;
        let cy = height * center_margin;

        // Center zone — only if clearly in the middle
        if x > cx && x < width - cx && y > cy && y < height - cy {
            return DropZone::Center;
        }

        // Determine direction based on which edge is closest
        let dist_left = x;
        let dist_right = width - x;
        let dist_top = y;
        let dist_bottom = height - y;

        let min_dist = dist_left.min(dist_right).min(dist_top).min(dist_bottom);

        if min_dist == dist_left {
            DropZone::Left
        } else if min_dist == dist_right {
            DropZone::Right
        } else if min_dist == dist_top {
            DropZone::Up
        } else {
            DropZone::Down
        }
    }

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

    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 PanelDockingManager<P> {
    fn default() -> Self {
        Self::new()
    }
}