tear-types 0.1.3

Pure types for the tear multiplexer — TearSession/Window/Pane/Layout/KeyTable/Hook/StatusBar, the MultiplexerControl trait, no I/O. Consumed by tear-core, tear-client, mado, and any third-party driver.
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
//! Binary-tree layout for a window's panes.
//!
//! Every [`crate::TearWindow`] holds exactly one [`LayoutNode`] —
//! either a leaf (a single pane) or an internal node that splits the
//! window into two children with a given orientation. The recursive
//! structure mirrors how operators reason about tmux/screen panes:
//! "split this pane to my right, then split the bottom-half down".
//!
//! mado's existing pane.rs/tab.rs uses a flat Vec<PaneRect>; the
//! eventual M5 rebase swaps that for [`LayoutNode`] so a single
//! algorithm computes pixel rects for both apps.

use serde::{Deserialize, Serialize};

use crate::{
    direction::{Direction, SplitOrientation},
    geometry::Rect,
    id::PaneId,
};

/// Minimum fraction a side of a split may hold — keeps a resize from
/// collapsing a pane to nothing while still letting the *cell*
/// arithmetic squeeze it (a 2-cell window splits 1/1 regardless).
pub const MIN_RATIO: f32 = 0.05;

/// Outcome of [`LayoutNode::remove_leaf`]. Removing a pane either
/// collapses its parent split into the surviving sibling, removes the
/// only pane (leaving nothing the tree can represent — the caller must
/// close the window), or finds no such pane.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LeafRemoval {
    /// The leaf was removed and its parent split collapsed into the
    /// sibling subtree. The tree still holds ≥1 pane.
    Removed,
    /// The leaf was the *root* — the tree is a single pane and cannot
    /// represent emptiness. The caller closes the window/pane instead.
    WasRoot,
    /// No leaf with that id exists in the tree.
    NotFound,
}

/// Why a [`LayoutNode`] failed [`LayoutNode::validate`]. Every variant
/// names a structurally-illegal tree so the invariant violation is a
/// typed value, not a silent mis-render (UNREPRESENTABILITY: a tree
/// that fails to validate never reaches the renderer).
// No `Eq` — `BadRatio(f32)` carries a float (NaN breaks total equality);
// `PartialEq` is enough for tests and consumers.
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutError {
    /// A leaf carries [`PaneId::NULL`] — a dangling reference left by a
    /// botched removal. The renderer would draw a blank hole.
    NullLeaf,
    /// The same [`PaneId`] appears in two leaves. A pane belongs to
    /// exactly one slot; aliasing means two views fight over one PTY.
    DuplicatePane(PaneId),
    /// A split's ratio is not in the open interval `(0.0, 1.0)` — a 0 or
    /// 1 (or NaN/out-of-range) ratio means one side is unrepresentable.
    BadRatio(f32),
}

/// One node in a window's layout tree.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum LayoutNode {
    /// A single pane filling its bounding box.
    Leaf {
        pane: PaneId,
    },
    /// A split that divides its area between [`LayoutNode::Split::a`]
    /// (top/left) and [`LayoutNode::Split::b`] (bottom/right). `ratio`
    /// is a in 0.0..=1.0 — the fraction of the parent area allotted
    /// to side `a`.
    Split {
        orientation: SplitOrientation,
        ratio: f32,
        a: Box<LayoutNode>,
        b: Box<LayoutNode>,
    },
}

impl LayoutNode {
    /// Convenience constructor for a leaf.
    #[must_use]
    pub fn leaf(pane: PaneId) -> Self {
        Self::Leaf { pane }
    }

    /// Convenience constructor for a balanced (`ratio = 0.5`) split.
    #[must_use]
    pub fn split(orientation: SplitOrientation, a: LayoutNode, b: LayoutNode) -> Self {
        Self::Split {
            orientation,
            ratio: 0.5,
            a: Box::new(a),
            b: Box::new(b),
        }
    }

    /// Collect every pane id reachable from this node, in left-to-
    /// right (then top-to-bottom) traversal order. Useful for
    /// rendering a status bar that wants "the active window's panes
    /// in display order".
    #[must_use]
    pub fn panes(&self) -> Vec<PaneId> {
        let mut out = Vec::new();
        self.collect(&mut out);
        out
    }

    fn collect(&self, out: &mut Vec<PaneId>) {
        match self {
            Self::Leaf { pane } => out.push(*pane),
            Self::Split { a, b, .. } => {
                a.collect(out);
                b.collect(out);
            }
        }
    }

    /// Number of leaves in the tree (= number of panes).
    #[must_use]
    pub fn pane_count(&self) -> usize {
        match self {
            Self::Leaf { .. } => 1,
            Self::Split { a, b, .. } => a.pane_count() + b.pane_count(),
        }
    }

    /// True when this node is exactly a leaf holding `pane`.
    #[must_use]
    fn is_leaf_of(&self, pane: PaneId) -> bool {
        matches!(self, Self::Leaf { pane: p } if *p == pane)
    }

    /// True when `pane` is one of this subtree's leaves.
    #[must_use]
    pub fn contains_pane(&self, pane: PaneId) -> bool {
        match self {
            Self::Leaf { pane: p } => *p == pane,
            Self::Split { a, b, .. } => a.contains_pane(pane) || b.contains_pane(pane),
        }
    }

    /// Arrange an ordered slice of panes into a named [`LayoutKind`]
    /// preset — the live-tree twin of [`crate::LayoutPlan::realize`]. The
    /// result always [`validate`](Self::validate)s and (by the shipped
    /// tiling property) `compute_rects` tiles its bounds exactly. `Even*`
    /// arrangements give every pane a `1/n` share (ratio `1/(n-k)` per
    /// split level), so an even-3 row is three equal thirds, not a
    /// balanced binary `0.5` split.
    ///
    /// Returns `None` for an empty slice and for [`LayoutKind::Custom`]
    /// (whose tree is its own source of truth — there is no canonical
    /// arrangement to build). A single pane yields a leaf for any kind.
    #[must_use]
    pub fn from_kind(kind: LayoutKind, panes: &[PaneId]) -> Option<Self> {
        match panes {
            [] => None,
            [only] => Some(Self::leaf(*only)),
            [main, rest @ ..] => match kind {
                // A horizontal ROW = panes side by side = Vertical splits.
                LayoutKind::EvenHorizontal => {
                    even_chain(SplitOrientation::Vertical, &leaves(panes))
                }
                // A vertical COLUMN = panes stacked = Horizontal splits.
                LayoutKind::EvenVertical => {
                    even_chain(SplitOrientation::Horizontal, &leaves(panes))
                }
                // One big pane on top; the rest share the bottom row.
                LayoutKind::MainHorizontal => {
                    let bottom = even_chain(SplitOrientation::Vertical, &leaves(rest))?;
                    Some(Self::Split {
                        orientation: SplitOrientation::Horizontal,
                        ratio: 0.5,
                        a: Box::new(Self::leaf(*main)),
                        b: Box::new(bottom),
                    })
                }
                // One big pane on the left; the rest stack on the right.
                LayoutKind::MainVertical => {
                    let right = even_chain(SplitOrientation::Horizontal, &leaves(rest))?;
                    Some(Self::Split {
                        orientation: SplitOrientation::Vertical,
                        ratio: 0.5,
                        a: Box::new(Self::leaf(*main)),
                        b: Box::new(right),
                    })
                }
                LayoutKind::Tiled => tiled(panes),
                // No canonical arrangement — the operator's manual tree wins.
                LayoutKind::Custom => None,
            },
        }
    }

    /// Replace the leaf holding `target` with a split whose two children
    /// are the original pane and a fresh `new_pane`, ordered by
    /// `direction`. This is the *correct* split — it replaces only the
    /// matched leaf, leaving every other pane's position untouched
    /// (unlike a whole-window re-wrap). `origin_ratio` is the fraction
    /// the *target* keeps (clamped to `[MIN_RATIO, 1 - MIN_RATIO]`);
    /// pass `0.5` for a balanced split.
    ///
    /// Returns `true` if `target` was found and split. A `Right`/`Below`
    /// split puts the new pane after the target (right/below); a
    /// `Left`/`Above` split puts it before.
    pub fn split_leaf(
        &mut self,
        target: PaneId,
        new_pane: PaneId,
        direction: Direction,
        origin_ratio: f32,
    ) -> bool {
        match self {
            Self::Leaf { pane } if *pane == target => {
                let origin = Self::leaf(*pane);
                let fresh = Self::leaf(new_pane);
                // A non-finite ratio survives `clamp` (NaN compares false
                // both ways), producing a tree `validate` rejects — coerce
                // it to a balanced split before clamping.
                let sane = if origin_ratio.is_finite() {
                    origin_ratio
                } else {
                    0.5
                };
                let keep = sane.clamp(MIN_RATIO, 1.0 - MIN_RATIO);
                let orientation = direction.orientation();
                // The new pane lands after the origin for Right/Below,
                // before it for Left/Above. `ratio` is always the
                // fraction held by side `a` (top/left), so it flips
                // depending on which side the origin ends up on.
                let (a, b, ratio) = match direction {
                    Direction::Right | Direction::Below => (origin, fresh, keep),
                    Direction::Left | Direction::Above => (fresh, origin, 1.0 - keep),
                };
                *self = Self::Split {
                    orientation,
                    ratio,
                    a: Box::new(a),
                    b: Box::new(b),
                };
                true
            }
            Self::Leaf { .. } => false,
            Self::Split { a, b, .. } => {
                a.split_leaf(target, new_pane, direction, origin_ratio)
                    || b.split_leaf(target, new_pane, direction, origin_ratio)
            }
        }
    }

    /// Remove the leaf holding `target` and collapse its parent split
    /// into the surviving sibling — no dangling `NULL` leaf, no blank
    /// hole. See [`LeafRemoval`] for the three outcomes.
    pub fn remove_leaf(&mut self, target: PaneId) -> LeafRemoval {
        match self {
            Self::Leaf { pane } if *pane == target => LeafRemoval::WasRoot,
            Self::Leaf { .. } => LeafRemoval::NotFound,
            Self::Split { a, b, .. } => {
                // A direct child that *is* the target leaf collapses this
                // split into the other child.
                if a.is_leaf_of(target) {
                    *self = std::mem::replace(b.as_mut(), Self::leaf(PaneId::NULL));
                    return LeafRemoval::Removed;
                }
                if b.is_leaf_of(target) {
                    *self = std::mem::replace(a.as_mut(), Self::leaf(PaneId::NULL));
                    return LeafRemoval::Removed;
                }
                // Otherwise recurse — a deeper split collapses in place.
                match a.remove_leaf(target) {
                    LeafRemoval::NotFound => b.remove_leaf(target),
                    other => other,
                }
            }
        }
    }

    /// Move the divider of the split governing `target` along `direction`
    /// by `delta_frac` (a fraction of that split). Finds the deepest
    /// ancestor split whose orientation matches the direction's axis and
    /// contains `target`, then slides its divider: Right/Below raise the
    /// ratio (the upper/left side grows), Left/Above lower it. Returns
    /// `true` if such a divider was found.
    ///
    /// For the natural gesture — grow a left pane Right, a right pane
    /// Left, a top pane Below, a bottom pane Above — this enlarges the
    /// focused pane, because `direction` then points across the shared
    /// divider toward `target`'s neighbour. The ratio is clamped to
    /// `[MIN_RATIO, 1 - MIN_RATIO]`, so a divider never pins a pane to
    /// zero (cell rounding may still squeeze a too-small window).
    pub fn resize_leaf(&mut self, target: PaneId, direction: Direction, delta_frac: f32) -> bool {
        let want = direction.orientation();
        // We enlarge `target` toward `direction`, so we want the divider
        // it shares with its neighbour ON THAT SIDE. The neighbour lives
        // on side `b` for Right/Below and side `a` for Left/Above — so we
        // need the deepest matching-orientation split where `target`
        // descends into the OPPOSITE (its own) side: `a` when growing
        // toward b, `b` when growing toward a. If no such split exists,
        // `target` is at the window edge that way — a no-op (false).
        let toward_b = matches!(direction, Direction::Right | Direction::Below);
        // Two-pass to satisfy the borrow checker: locate the path (shared
        // borrow), then mutate the ratio (exclusive borrow).
        let Some(path) = self.governing_split_path(target, want, toward_b) else {
            return false;
        };
        let Some(Self::Split { ratio, .. }) = self.split_at_path(&path) else {
            return false;
        };
        // Growing toward b raises the ratio (side `a` = target grows);
        // toward a lowers it (side `b` = target grows). A non-finite delta
        // leaves the ratio untouched (NaN must never reach the tree).
        let sign = if toward_b { 1.0 } else { -1.0 };
        let next = *ratio + sign * delta_frac;
        *ratio = (if next.is_finite() { next } else { *ratio }).clamp(MIN_RATIO, 1.0 - MIN_RATIO);
        true
    }

    /// Path to the deepest split of orientation `want` that contains
    /// `target` on the required side (`need_side_a` ⇒ `target` in side
    /// `a`, else side `b`). That is the divider `target` shares with its
    /// neighbour on the opposite side. `true` in a path step means "into
    /// side a". `None` when no such split exists (window edge that way).
    fn governing_split_path(
        &self,
        target: PaneId,
        want: SplitOrientation,
        need_side_a: bool,
    ) -> Option<Vec<bool>> {
        let mut best: Option<Vec<bool>> = None;
        let mut path: Vec<bool> = Vec::new();
        self.walk_governing(target, want, need_side_a, &mut path, &mut best);
        best
    }

    fn walk_governing(
        &self,
        target: PaneId,
        want: SplitOrientation,
        need_side_a: bool,
        path: &mut Vec<bool>,
        best: &mut Option<Vec<bool>>,
    ) {
        if let Self::Split {
            orientation, a, b, ..
        } = self
        {
            let in_a = a.contains_pane(target);
            let in_b = b.contains_pane(target);
            // Record only a split of the wanted orientation where target
            // is on the required side — that's the divider toward the
            // neighbour we grow into. Deeper (closer) overwrites shallower.
            if *orientation == want && ((in_a && need_side_a) || (in_b && !need_side_a)) {
                *best = Some(path.clone());
            }
            if in_a {
                path.push(true);
                a.walk_governing(target, want, need_side_a, path, best);
                path.pop();
            } else if in_b {
                path.push(false);
                b.walk_governing(target, want, need_side_a, path, best);
                path.pop();
            }
        }
    }

    fn split_at_path(&mut self, path: &[bool]) -> Option<&mut Self> {
        let mut node = self;
        for &into_a in path {
            match node {
                Self::Split { a, b, .. } => {
                    node = if into_a { a.as_mut() } else { b.as_mut() };
                }
                Self::Leaf { .. } => return None,
            }
        }
        Some(node)
    }

    /// Compute the pixel/cell rectangle of every pane, laying the tree
    /// out within `bounds`. This is *the* layout renderer — mado draws
    /// from it, tear-core sizes PTYs from it. Division is gap-free and
    /// overlap-free: side `b` gets exactly the remainder side `a` left.
    #[must_use]
    pub fn compute_rects(&self, bounds: Rect) -> Vec<(PaneId, Rect)> {
        let mut out = Vec::with_capacity(self.pane_count());
        self.lay_out(bounds, &mut out);
        out
    }

    fn lay_out(&self, bounds: Rect, out: &mut Vec<(PaneId, Rect)>) {
        match self {
            Self::Leaf { pane } => out.push((*pane, bounds)),
            Self::Split {
                orientation,
                ratio,
                a,
                b,
            } => {
                let (ra, rb) = split_rect(bounds, *orientation, *ratio);
                a.lay_out(ra, out);
                b.lay_out(rb, out);
            }
        }
    }

    /// The pane the operator would land on by moving `direction` from
    /// `target`, laid out within `bounds` (tmux `select-pane -L/-R/-U/-D`).
    /// Among every pane on that side that shares perpendicular edge with
    /// `target`, picks the **nearest** (smallest gap along the axis of
    /// motion), tie-broken by the **largest** shared edge. The result is
    /// independent of tree shape and traversal order. Returns `None` at
    /// the window edge or for an unknown `target`.
    #[must_use]
    pub fn neighbor(&self, target: PaneId, direction: Direction, bounds: Rect) -> Option<PaneId> {
        let rects = self.compute_rects(bounds);
        let me = rects.iter().find(|(p, _)| *p == target).map(|(_, r)| *r)?;
        // Score each candidate as (gap, overlap): a candidate is better
        // when it is closer (smaller gap) or — at equal gap — shares more
        // edge (larger overlap). `best` holds the winning (gap, overlap).
        let mut best: Option<(PaneId, u32, u32)> = None;
        for (pane, r) in &rects {
            if *pane == target {
                continue;
            }
            // (on the correct side, gap along the axis, perpendicular
            // overlap). `gap` is the clearance between the two edges
            // facing each other; the immediate neighbour of a gap-free
            // tiling has gap 0.
            let (on_side, gap, overlap) = match direction {
                Direction::Left => (
                    r.right() <= u32::from(me.x),
                    u32::from(me.x).saturating_sub(r.right()),
                    Rect::span_overlap(u32::from(r.y), r.bottom(), u32::from(me.y), me.bottom()),
                ),
                Direction::Right => (
                    u32::from(r.x) >= me.right(),
                    u32::from(r.x).saturating_sub(me.right()),
                    Rect::span_overlap(u32::from(r.y), r.bottom(), u32::from(me.y), me.bottom()),
                ),
                Direction::Above => (
                    r.bottom() <= u32::from(me.y),
                    u32::from(me.y).saturating_sub(r.bottom()),
                    Rect::span_overlap(u32::from(r.x), r.right(), u32::from(me.x), me.right()),
                ),
                Direction::Below => (
                    u32::from(r.y) >= me.bottom(),
                    u32::from(r.y).saturating_sub(me.bottom()),
                    Rect::span_overlap(u32::from(r.x), r.right(), u32::from(me.x), me.right()),
                ),
            };
            if on_side && overlap > 0 {
                let better = match best {
                    None => true,
                    Some((_, best_gap, best_overlap)) => {
                        gap < best_gap || (gap == best_gap && overlap > best_overlap)
                    }
                };
                if better {
                    best = Some((*pane, gap, overlap));
                }
            }
        }
        best.map(|(p, _, _)| p)
    }

    /// Verify the tree's structural invariants. A tree that validates is
    /// safe to render; one that fails carries a typed [`LayoutError`]
    /// naming the illegal shape instead of silently mis-drawing.
    pub fn validate(&self) -> Result<(), LayoutError> {
        let mut seen = Vec::new();
        self.validate_into(&mut seen)
    }

    fn validate_into(&self, seen: &mut Vec<PaneId>) -> Result<(), LayoutError> {
        match self {
            Self::Leaf { pane } => {
                if *pane == PaneId::NULL {
                    return Err(LayoutError::NullLeaf);
                }
                if seen.contains(pane) {
                    return Err(LayoutError::DuplicatePane(*pane));
                }
                seen.push(*pane);
                Ok(())
            }
            Self::Split { ratio, a, b, .. } => {
                if !(*ratio > 0.0 && *ratio < 1.0) {
                    return Err(LayoutError::BadRatio(*ratio));
                }
                a.validate_into(seen)?;
                b.validate_into(seen)
            }
        }
    }
}

/// Divide `bounds` between a split's two children. Horizontal splits
/// stack rows (divide the height); vertical splits sit side by side
/// (divide the width). Side `a` gets a clamped extent, side `b` the
/// exact remainder — so the two rects tile `bounds` with no gap and no
/// overlap.
fn split_rect(bounds: Rect, orientation: SplitOrientation, ratio: f32) -> (Rect, Rect) {
    match orientation {
        SplitOrientation::Horizontal => {
            let a_h = split_extent(bounds.h, ratio);
            let b_h = bounds.h - a_h;
            (
                Rect::new(bounds.x, bounds.y, bounds.w, a_h),
                Rect::new(bounds.x, bounds.y + a_h, bounds.w, b_h),
            )
        }
        SplitOrientation::Vertical => {
            let a_w = split_extent(bounds.w, ratio);
            let b_w = bounds.w - a_w;
            (
                Rect::new(bounds.x, bounds.y, a_w, bounds.h),
                Rect::new(bounds.x + a_w, bounds.y, b_w, bounds.h),
            )
        }
    }
}

/// The number of cells side `a` gets from `total` at `ratio`. Clamped so
/// both sides keep ≥1 cell whenever `total >= 2`; a 1-cell total can't be
/// divided (side `a` takes it, `b` gets 0) and a 0-cell total yields 0.
fn split_extent(total: u16, ratio: f32) -> u16 {
    if total <= 1 {
        return total;
    }
    let raw = (f32::from(total) * ratio).round();
    // round() of a finite product in [0, total] is in range; clamp pins
    // NaN-free bounds and guarantees neither side vanishes.
    let a = raw.clamp(1.0, f32::from(total) - 1.0);
    a as u16
}

/// Wrap each pane id in a leaf node.
fn leaves(panes: &[PaneId]) -> Vec<LayoutNode> {
    panes.iter().map(|p| LayoutNode::leaf(*p)).collect()
}

/// Fold a slice of subtrees into an *even* chain along `orientation`: the
/// first child gets `1/n` of the area and the remainder recurses, so —
/// because each level's `1/(n-k)` is taken of the previous remainder —
/// every leaf ends with exactly `1/n`. `None` for an empty slice.
fn even_chain(orientation: SplitOrientation, nodes: &[LayoutNode]) -> Option<LayoutNode> {
    match nodes {
        [] => None,
        [single] => Some(single.clone()),
        [first, rest @ ..] => {
            let n = nodes.len() as f32;
            let rest_tree = even_chain(orientation, rest)?;
            Some(LayoutNode::Split {
                orientation,
                ratio: 1.0 / n,
                a: Box::new(first.clone()),
                b: Box::new(rest_tree),
            })
        }
    }
}

/// Arrange panes in an approximate square grid: `ceil(sqrt(n))` rows, each
/// an even row (side by side), the rows stacked evenly. `None` for empty.
fn tiled(panes: &[PaneId]) -> Option<LayoutNode> {
    let n = panes.len();
    if n == 0 {
        return None;
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let rows = (n as f64).sqrt().ceil() as usize;
    let per = n / rows;
    let extra = n % rows;
    let mut row_trees = Vec::with_capacity(rows);
    let mut i = 0;
    for r in 0..rows {
        // The first `extra` rows carry one more pane than the rest.
        let cnt = per + usize::from(r < extra);
        let row = even_chain(SplitOrientation::Vertical, &leaves(&panes[i..i + cnt]))?;
        row_trees.push(row);
        i += cnt;
    }
    even_chain(SplitOrientation::Horizontal, &row_trees)
}

/// Named tmux-style layout presets. tmux ships five built-ins; tear
/// supports the same plus a `tatami`-style auto-balance.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LayoutKind {
    /// All panes in one horizontal row.
    EvenHorizontal,
    /// All panes in one vertical column.
    EvenVertical,
    /// One large pane on top, all others on the bottom row.
    MainHorizontal,
    /// One large pane on the left, all others stacked on the right.
    MainVertical,
    /// Tiled: arrange panes in an approximate square grid.
    Tiled,
    /// Custom: the [`LayoutNode`] tree on the [`crate::TearWindow`] is
    /// the source of truth. Operators reach this state after manual
    /// splits / resizes; tear-core serialises the tree as the canonical
    /// shape.
    Custom,
}

/// Size specification for a pane within a layout.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Size {
    /// Fixed number of terminal cells.
    Cells(u16),
    /// Fraction of the parent's available space (`0.0..=1.0`).
    Fraction(f32),
    /// Automatic — the parent layout decides.
    Auto,
}

impl Default for Size {
    fn default() -> Self {
        Self::Auto
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::direction::SplitOrientation;

    #[test]
    fn leaf_has_one_pane() {
        let n = LayoutNode::leaf(PaneId(7));
        assert_eq!(n.pane_count(), 1);
        assert_eq!(n.panes(), vec![PaneId(7)]);
    }

    #[test]
    fn split_aggregates_panes_left_then_right() {
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        assert_eq!(n.pane_count(), 2);
        assert_eq!(n.panes(), vec![PaneId(1), PaneId(2)]);
    }

    #[test]
    fn nested_split_traversal_is_predictable() {
        let n = LayoutNode::split(
            SplitOrientation::Horizontal,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        assert_eq!(n.panes(), vec![PaneId(1), PaneId(2), PaneId(3)]);
        assert_eq!(n.pane_count(), 3);
    }

    // ── split_leaf ───────────────────────────────────────────────

    #[test]
    fn split_leaf_targets_the_matched_leaf_only() {
        // Tree: 1 | (2 / 3). Splitting pane 2 to the right must touch
        // ONLY pane 2's slot — panes 1 and 3 keep their positions. This
        // is the bug the old whole-window re-wrap had.
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        assert!(n.split_leaf(PaneId(2), PaneId(9), Direction::Right, 0.5));
        // Display order: 1, then (2-split-9), then 3.
        assert_eq!(n.panes(), vec![PaneId(1), PaneId(2), PaneId(9), PaneId(3)]);
        assert_eq!(n.pane_count(), 4);
        n.validate().unwrap();
    }

    #[test]
    fn split_leaf_orders_new_pane_by_direction() {
        let mut right = LayoutNode::leaf(PaneId(1));
        right.split_leaf(PaneId(1), PaneId(2), Direction::Right, 0.5);
        assert_eq!(right.panes(), vec![PaneId(1), PaneId(2)]); // origin first

        let mut left = LayoutNode::leaf(PaneId(1));
        left.split_leaf(PaneId(1), PaneId(2), Direction::Left, 0.5);
        assert_eq!(left.panes(), vec![PaneId(2), PaneId(1)]); // new first
    }

    #[test]
    fn split_leaf_unknown_target_is_noop() {
        let mut n = LayoutNode::leaf(PaneId(1));
        assert!(!n.split_leaf(PaneId(99), PaneId(2), Direction::Right, 0.5));
        assert_eq!(n.panes(), vec![PaneId(1)]);
    }

    #[test]
    fn split_leaf_clamps_extreme_ratio() {
        let mut n = LayoutNode::leaf(PaneId(1));
        n.split_leaf(PaneId(1), PaneId(2), Direction::Right, 0.0);
        // 0.0 origin-keep clamps to MIN_RATIO — still a valid split.
        n.validate().unwrap();
        if let LayoutNode::Split { ratio, .. } = n {
            assert!(ratio >= MIN_RATIO && ratio <= 1.0 - MIN_RATIO);
        } else {
            panic!("expected a split");
        }
    }

    // ── remove_leaf ──────────────────────────────────────────────

    #[test]
    fn remove_leaf_collapses_parent_into_sibling() {
        // (1 | 2) → remove 1 → just 2 (no dangling NULL).
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        assert_eq!(n.remove_leaf(PaneId(1)), LeafRemoval::Removed);
        assert_eq!(n, LayoutNode::leaf(PaneId(2)));
        n.validate().unwrap();
    }

    #[test]
    fn remove_leaf_collapses_deep_node() {
        // 1 | (2 / 3) → remove 3 → 1 | 2.
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        assert_eq!(n.remove_leaf(PaneId(3)), LeafRemoval::Removed);
        assert_eq!(n.panes(), vec![PaneId(1), PaneId(2)]);
        assert!(!n.contains_pane(PaneId(3)));
        // No PaneId::NULL leaf left behind.
        n.validate().unwrap();
    }

    #[test]
    fn remove_leaf_root_reports_was_root() {
        let mut n = LayoutNode::leaf(PaneId(1));
        assert_eq!(n.remove_leaf(PaneId(1)), LeafRemoval::WasRoot);
        // Tree untouched — caller closes the window instead.
        assert_eq!(n, LayoutNode::leaf(PaneId(1)));
    }

    #[test]
    fn remove_leaf_unknown_is_not_found() {
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        assert_eq!(n.remove_leaf(PaneId(99)), LeafRemoval::NotFound);
        assert_eq!(n.pane_count(), 2);
    }

    // ── compute_rects ────────────────────────────────────────────

    #[test]
    fn compute_rects_single_pane_fills_bounds() {
        let n = LayoutNode::leaf(PaneId(1));
        let r = n.compute_rects(Rect::sized(80, 24));
        assert_eq!(r, vec![(PaneId(1), Rect::new(0, 0, 80, 24))]);
    }

    #[test]
    fn compute_rects_vertical_split_is_side_by_side_gapless() {
        // Vertical split divides width; a left, b right; no gap/overlap.
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        let r = n.compute_rects(Rect::sized(80, 24));
        let a = r.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1;
        let b = r.iter().find(|(p, _)| *p == PaneId(2)).unwrap().1;
        assert_eq!(a, Rect::new(0, 0, 40, 24));
        assert_eq!(b, Rect::new(40, 0, 40, 24));
        assert_eq!(a.right(), u32::from(b.x)); // gapless
    }

    #[test]
    fn compute_rects_horizontal_split_stacks_rows() {
        let n = LayoutNode::split(
            SplitOrientation::Horizontal,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        let r = n.compute_rects(Rect::sized(80, 24));
        let a = r.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1;
        let b = r.iter().find(|(p, _)| *p == PaneId(2)).unwrap().1;
        assert_eq!(a, Rect::new(0, 0, 80, 12));
        assert_eq!(b, Rect::new(0, 12, 80, 12));
        assert_eq!(a.bottom(), u32::from(b.y));
    }

    #[test]
    fn compute_rects_tiles_bounds_exactly() {
        // The union of all leaf rects must equal bounds.area() with no
        // double-counting — proves gap-free + overlap-free for a nested
        // tree at an odd size (forces rounding).
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        let bounds = Rect::sized(81, 25);
        let rects = n.compute_rects(bounds);
        let total: u32 = rects.iter().map(|(_, r)| r.area()).sum();
        assert_eq!(total, bounds.area());
        // No overlap: every interior cell belongs to exactly one rect.
        for y in 0..bounds.h {
            for x in 0..bounds.w {
                let owners = rects.iter().filter(|(_, r)| r.contains(x, y)).count();
                assert_eq!(owners, 1, "cell ({x},{y}) owned by {owners} panes");
            }
        }
    }

    #[test]
    fn compute_rects_tiny_window_never_panics() {
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        // 1-cell width can't show two panes side-by-side; b is squeezed
        // to 0 but the call is total and gapless.
        let r = n.compute_rects(Rect::sized(1, 5));
        let total: u32 = r.iter().map(|(_, rr)| rr.area()).sum();
        assert_eq!(total, 5);
    }

    // ── neighbor ─────────────────────────────────────────────────

    #[test]
    fn neighbor_walks_left_and_right() {
        // 1 | 2 | 3 (three columns).
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        let b = Rect::sized(90, 24);
        assert_eq!(n.neighbor(PaneId(2), Direction::Left, b), Some(PaneId(1)));
        assert_eq!(n.neighbor(PaneId(2), Direction::Right, b), Some(PaneId(3)));
        assert_eq!(n.neighbor(PaneId(1), Direction::Left, b), None); // window edge
        assert_eq!(n.neighbor(PaneId(3), Direction::Right, b), None);
    }

    #[test]
    fn neighbor_crosses_split_boundary_by_edge_overlap() {
        // Left column = pane 1 (full height). Right column split into
        // 2 (top) / 3 (bottom). From 1 going Right, the neighbour with
        // the most shared edge is whichever covers the focal band; both
        // 2 and 3 are valid candidates — assert it returns one of them.
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        let b = Rect::sized(80, 24);
        let right = n.neighbor(PaneId(1), Direction::Right, b);
        assert!(matches!(right, Some(PaneId(2)) | Some(PaneId(3))));
        // And from 2 going Left lands back on 1.
        assert_eq!(n.neighbor(PaneId(2), Direction::Left, b), Some(PaneId(1)));
    }

    #[test]
    fn neighbor_unknown_target_is_none() {
        let n = LayoutNode::leaf(PaneId(1));
        assert_eq!(n.neighbor(PaneId(99), Direction::Left, Rect::sized(80, 24)), None);
    }

    #[test]
    fn neighbor_prefers_nearest_not_just_max_overlap() {
        // 1 | 2 | 3 — from 1, both 2 and 3 are to the Right with equal
        // (full-height) overlap. The NEAREST (2) must win regardless of
        // how the tree nests 2 and 3 (right-leaning vs left-leaning).
        let right_leaning = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        let left_leaning = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(1)),
                LayoutNode::leaf(PaneId(2)),
            ),
            LayoutNode::leaf(PaneId(3)),
        );
        let b = Rect::sized(90, 24);
        assert_eq!(right_leaning.neighbor(PaneId(1), Direction::Right, b), Some(PaneId(2)));
        assert_eq!(left_leaning.neighbor(PaneId(1), Direction::Right, b), Some(PaneId(2)));
    }

    // ── from_kind ────────────────────────────────────────────────

    #[test]
    fn from_kind_empty_and_custom_are_none() {
        assert_eq!(LayoutNode::from_kind(LayoutKind::Tiled, &[]), None);
        assert_eq!(
            LayoutNode::from_kind(LayoutKind::Custom, &[PaneId(1), PaneId(2)]),
            None
        );
    }

    #[test]
    fn from_kind_single_pane_is_a_leaf_for_every_kind() {
        for kind in [
            LayoutKind::EvenHorizontal,
            LayoutKind::EvenVertical,
            LayoutKind::MainHorizontal,
            LayoutKind::MainVertical,
            LayoutKind::Tiled,
        ] {
            assert_eq!(
                LayoutNode::from_kind(kind, &[PaneId(1)]),
                Some(LayoutNode::leaf(PaneId(1)))
            );
        }
    }

    #[test]
    fn from_kind_even_horizontal_gives_equal_thirds() {
        // The even-ratio refinement: 3 panes in a row are three EQUAL
        // widths, not a 50/25/25 balanced binary split.
        let panes = [PaneId(1), PaneId(2), PaneId(3)];
        let tree = LayoutNode::from_kind(LayoutKind::EvenHorizontal, &panes).unwrap();
        tree.validate().unwrap();
        let rects = tree.compute_rects(Rect::sized(90, 24));
        let mut widths: Vec<u16> = rects.iter().map(|(_, r)| r.w).collect();
        widths.sort_unstable();
        // 90/3 = 30 each (exactly, since 90 is divisible by 3).
        assert_eq!(widths, vec![30, 30, 30]);
    }

    /// The first-brick proof: for EVERY non-Custom kind and pane-count
    /// 1..=7, `from_kind` produces a tree that validates AND whose
    /// `compute_rects` tiles its bounds exactly (the shipped tiling
    /// invariant) — gap-free, overlap-free, every pane present once.
    #[test]
    fn from_kind_every_preset_validates_and_tiles_exactly() {
        let kinds = [
            LayoutKind::EvenHorizontal,
            LayoutKind::EvenVertical,
            LayoutKind::MainHorizontal,
            LayoutKind::MainVertical,
            LayoutKind::Tiled,
        ];
        for kind in kinds {
            for n in 1..=7usize {
                let panes: Vec<PaneId> = (1..=n as u64).map(PaneId).collect();
                let tree = LayoutNode::from_kind(kind, &panes)
                    .unwrap_or_else(|| panic!("{kind:?} n={n} produced None"));
                // Structurally sound + every pane present exactly once.
                tree.validate()
                    .unwrap_or_else(|e| panic!("{kind:?} n={n} invalid: {e:?}"));
                assert_eq!(tree.pane_count(), n, "{kind:?} n={n} pane count");
                assert_eq!(tree.panes().len(), n);
                // Tiles bounds exactly at a rounding-forcing size.
                for &(w, h) in &[(80u16, 24u16), (81, 25), (97, 31)] {
                    let bounds = Rect::sized(w, h);
                    let rects = tree.compute_rects(bounds);
                    let total: u32 = rects.iter().map(|(_, r)| r.area()).sum();
                    assert_eq!(total, bounds.area(), "{kind:?} n={n} at {w}x{h}");
                }
            }
        }
    }

    #[test]
    fn from_kind_main_vertical_keeps_main_on_the_left() {
        let panes = [PaneId(1), PaneId(2), PaneId(3)];
        let tree = LayoutNode::from_kind(LayoutKind::MainVertical, &panes).unwrap();
        // Outer split is vertical (left|right), side a is the main leaf.
        match &tree {
            LayoutNode::Split { orientation, a, .. } => {
                assert_eq!(*orientation, SplitOrientation::Vertical);
                assert_eq!(a.as_ref(), &LayoutNode::leaf(PaneId(1)));
            }
            LayoutNode::Leaf { .. } => panic!("expected a split"),
        }
        // The main pane is the leftmost on screen.
        let rects = tree.compute_rects(Rect::sized(80, 24));
        let main = rects.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1;
        assert_eq!(main.x, 0);
    }

    /// A pseudo-property test: across a spread of tree shapes and bounds
    /// (including odd sizes that force rounding), `compute_rects` must
    /// tile `bounds` exactly — total area equals `bounds.area()` and no
    /// interior cell is owned by two panes. This is the load-bearing
    /// invariant both apps depend on (no seams, no double-draws).
    #[test]
    fn compute_rects_tiles_exactly_across_shapes_and_sizes() {
        let shapes = [
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(1)),
                LayoutNode::leaf(PaneId(2)),
            ),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::split(
                    SplitOrientation::Vertical,
                    LayoutNode::leaf(PaneId(1)),
                    LayoutNode::leaf(PaneId(2)),
                ),
                LayoutNode::split(
                    SplitOrientation::Vertical,
                    LayoutNode::leaf(PaneId(3)),
                    LayoutNode::split(
                        SplitOrientation::Horizontal,
                        LayoutNode::leaf(PaneId(4)),
                        LayoutNode::leaf(PaneId(5)),
                    ),
                ),
            ),
        ];
        for shape in &shapes {
            for &(w, h) in &[(80u16, 24u16), (81, 25), (1, 1), (3, 200), (200, 3), (2, 2)] {
                let bounds = Rect::sized(w, h);
                let rects = shape.compute_rects(bounds);
                let total: u32 = rects.iter().map(|(_, r)| r.area()).sum();
                assert_eq!(total, bounds.area(), "area mismatch at {w}x{h}");
                // Every leaf appears exactly once.
                assert_eq!(rects.len(), shape.pane_count());
                // No interior cell double-owned (sample the full grid for
                // small bounds; the area equality covers the rest).
                if bounds.area() <= 8192 {
                    for y in 0..h {
                        for x in 0..w {
                            let owners = rects.iter().filter(|(_, r)| r.contains(x, y)).count();
                            assert!(owners <= 1, "cell ({x},{y}) owned by {owners} at {w}x{h}");
                        }
                    }
                }
            }
        }
    }

    // ── resize_leaf ──────────────────────────────────────────────

    #[test]
    fn resize_leaf_grows_focused_pane_rightward() {
        // 1 | 2, vertical. "grow 1 to the Right" enlarges pane 1.
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        let before = n.compute_rects(Rect::sized(80, 24));
        let w1_before = before.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1.w;
        assert!(n.resize_leaf(PaneId(1), Direction::Right, 0.2));
        let after = n.compute_rects(Rect::sized(80, 24));
        let w1_after = after.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1.w;
        assert!(w1_after > w1_before, "{w1_after} !> {w1_before}");
    }

    #[test]
    fn resize_leaf_grows_pane_on_side_b_too() {
        // 1 | 2; "grow 2 to the Left" enlarges pane 2 (side b).
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        let before = n.compute_rects(Rect::sized(80, 24));
        let w2_before = before.iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(n.resize_leaf(PaneId(2), Direction::Left, 0.2));
        let after = n.compute_rects(Rect::sized(80, 24));
        let w2_after = after.iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(w2_after > w2_before, "{w2_after} !> {w2_before}");
    }

    #[test]
    fn resize_leaf_grows_toward_outer_neighbour_across_a_deeper_split() {
        // 1 | (2 | 3): pane 2 is the LEFT child of the inner split, but
        // its on-screen left neighbour is pane 1 across the OUTER split.
        // "grow 2 Left" must enlarge pane 2 (regression: the old sign-only
        // logic slid the inner 2|3 divider and SHRANK pane 2).
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        let b = Rect::sized(90, 24);
        let w2_before = n.compute_rects(b).iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(n.resize_leaf(PaneId(2), Direction::Left, 0.2));
        let w2_after = n.compute_rects(b).iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(w2_after > w2_before, "grow-Left should enlarge pane 2: {w2_before} -> {w2_after}");
    }

    #[test]
    fn resize_leaf_side_b_of_deeper_split_grows_right_toward_outer_neighbour() {
        // (1 | 2) | 3: pane 2 is the RIGHT child of the inner split; its
        // on-screen right neighbour is pane 3 across the OUTER split.
        // "grow 2 Right" must enlarge pane 2 (the symmetric regression).
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(1)),
                LayoutNode::leaf(PaneId(2)),
            ),
            LayoutNode::leaf(PaneId(3)),
        );
        let b = Rect::sized(90, 24);
        let w2_before = n.compute_rects(b).iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(n.resize_leaf(PaneId(2), Direction::Right, 0.2));
        let w2_after = n.compute_rects(b).iter().find(|(p, _)| *p == PaneId(2)).unwrap().1.w;
        assert!(w2_after > w2_before, "grow-Right should enlarge pane 2: {w2_before} -> {w2_after}");
    }

    #[test]
    fn resize_leaf_no_neighbour_that_way_is_noop() {
        // 1 | 2: pane 1 is leftmost — it has no left neighbour, so
        // "grow 1 Left" finds no governing divider and is a no-op.
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        assert!(!n.resize_leaf(PaneId(1), Direction::Left, 0.2));
    }

    #[test]
    fn resize_leaf_grows_focused_pane_in_all_four_directions() {
        // Exhaustive sign coverage. For each direction, build a layout
        // where the focused pane HAS a neighbour that way, and assert the
        // focused pane grows. This pins every (side × direction) sign
        // combination — the bug the original 3 tests missed.
        let cases: &[(SplitOrientation, Direction)] = &[
            (SplitOrientation::Vertical, Direction::Right),
            (SplitOrientation::Vertical, Direction::Left),
            (SplitOrientation::Horizontal, Direction::Below),
            (SplitOrientation::Horizontal, Direction::Above),
        ];
        for &(orient, dir) in cases {
            // Two-pane split on the matching axis; focus the pane that has
            // a neighbour in `dir` (the `a`-side pane for Right/Below, the
            // `b`-side pane for Left/Above).
            let (focus, other) = match dir {
                Direction::Right | Direction::Below => (PaneId(1), PaneId(2)),
                Direction::Left | Direction::Above => (PaneId(2), PaneId(1)),
            };
            let mut n = LayoutNode::split(
                orient,
                LayoutNode::leaf(PaneId(1)),
                LayoutNode::leaf(PaneId(2)),
            );
            let b = Rect::sized(80, 24);
            let axis = |r: Rect| if orient == SplitOrientation::Vertical { r.w } else { r.h };
            let before = axis(n.compute_rects(b).iter().find(|(p, _)| *p == focus).unwrap().1);
            assert!(n.resize_leaf(focus, dir, 0.2), "{dir:?} should find a divider");
            let after = axis(n.compute_rects(b).iter().find(|(p, _)| *p == focus).unwrap().1);
            assert!(after > before, "focus pane should grow {dir:?}: {before} -> {after}");
            let _ = other;
        }
    }

    #[test]
    fn split_leaf_nan_ratio_coerces_to_valid_split() {
        // A NaN ratio survives f32::clamp; split_leaf must coerce it so the
        // resulting tree still validates (its doc promises a clamped ratio).
        let mut n = LayoutNode::leaf(PaneId(1));
        assert!(n.split_leaf(PaneId(1), PaneId(2), Direction::Right, f32::NAN));
        n.validate().unwrap();
    }

    #[test]
    fn resize_leaf_nan_delta_leaves_tree_valid() {
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        // A NaN delta must not poison the ratio.
        n.resize_leaf(PaneId(1), Direction::Right, f32::NAN);
        n.validate().unwrap();
    }

    #[test]
    fn resize_leaf_ignores_wrong_axis() {
        // 1 | 2 vertical; resizing Up/Down finds no horizontal split.
        let mut n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::leaf(PaneId(2)),
        );
        assert!(!n.resize_leaf(PaneId(1), Direction::Below, 0.2));
    }

    #[test]
    fn resize_leaf_picks_deepest_governing_split() {
        // (1 | 2) stacked-over 3 — both a vertical and an enclosing
        // horizontal split exist. Resizing 1 to the Right must adjust
        // the inner VERTICAL split (1|2), not the outer horizontal one.
        let mut n = LayoutNode::split(
            SplitOrientation::Horizontal,
            LayoutNode::split(
                SplitOrientation::Vertical,
                LayoutNode::leaf(PaneId(1)),
                LayoutNode::leaf(PaneId(2)),
            ),
            LayoutNode::leaf(PaneId(3)),
        );
        let bounds = Rect::sized(80, 24);
        let w1_before = n.compute_rects(bounds).iter().find(|(p, _)| *p == PaneId(1)).unwrap().1.w;
        let h3_before = n.compute_rects(bounds).iter().find(|(p, _)| *p == PaneId(3)).unwrap().1.h;
        assert!(n.resize_leaf(PaneId(1), Direction::Right, 0.2));
        let after = n.compute_rects(bounds);
        let w1_after = after.iter().find(|(p, _)| *p == PaneId(1)).unwrap().1.w;
        let h3_after = after.iter().find(|(p, _)| *p == PaneId(3)).unwrap().1.h;
        assert!(w1_after > w1_before); // inner split moved
        assert_eq!(h3_after, h3_before); // outer split untouched
    }

    // ── validate ─────────────────────────────────────────────────

    #[test]
    fn validate_rejects_null_leaf() {
        let n = LayoutNode::leaf(PaneId::NULL);
        assert_eq!(n.validate(), Err(LayoutError::NullLeaf));
    }

    #[test]
    fn validate_rejects_duplicate_pane() {
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(5)),
            LayoutNode::leaf(PaneId(5)),
        );
        assert_eq!(n.validate(), Err(LayoutError::DuplicatePane(PaneId(5))));
    }

    #[test]
    fn validate_rejects_degenerate_ratio() {
        let n = LayoutNode::Split {
            orientation: SplitOrientation::Vertical,
            ratio: 0.0,
            a: Box::new(LayoutNode::leaf(PaneId(1))),
            b: Box::new(LayoutNode::leaf(PaneId(2))),
        };
        assert_eq!(n.validate(), Err(LayoutError::BadRatio(0.0)));
    }

    #[test]
    fn validate_accepts_well_formed_tree() {
        let n = LayoutNode::split(
            SplitOrientation::Vertical,
            LayoutNode::leaf(PaneId(1)),
            LayoutNode::split(
                SplitOrientation::Horizontal,
                LayoutNode::leaf(PaneId(2)),
                LayoutNode::leaf(PaneId(3)),
            ),
        );
        n.validate().unwrap();
    }

    // ── round-trip: split then remove returns to the original ────

    #[test]
    fn split_then_remove_is_identity() {
        let original = LayoutNode::leaf(PaneId(1));
        let mut n = original.clone();
        n.split_leaf(PaneId(1), PaneId(2), Direction::Right, 0.5);
        assert_eq!(n.pane_count(), 2);
        assert_eq!(n.remove_leaf(PaneId(2)), LeafRemoval::Removed);
        assert_eq!(n, original);
    }
}