bettertui_engine 0.1.1

High-performance terminal UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
//! Layout engine: Taffy-based layout computation with tree synchronization and result mapping.
//!
//! This module contains everything related to layout:
//! - Types — Input types: LayoutProps, Sizing, enums (FlexDirection, etc.)
//! - Paint — Paint primitives: PaintBounds, Viewport, ClipBounds, PaintContext, PaintFlags
//! - Culling — Binary search viewport culling for large scrollable lists
//! - Engine — LayoutEngine, LayoutTreeSync, LayoutResult: Taffy wrapping + arena bridging + result mapping
//! - Build — Render tree builder: consumes LayoutResults → produces RenderTree

use std::cell::RefCell;
use std::collections::HashMap;

use bitflags::bitflags;
use unicode_segmentation::UnicodeSegmentation;

use crate::render::RenderObject;
use crate::render::RenderTree;
use crate::text;
use crate::tree::NodeArena;
use crate::tree::NodeId;
use crate::tree::Overflow;
use crate::tree::Rect;

// ============================================================================
// BACKWARD COMPATIBILITY: Re-export submodules
// ============================================================================

/// Types submodule for backward compatibility with `crate::taffy::types::*`
pub mod types {
    pub use super::{
        AlignContent, AlignItems, AlignSelf, BoxSizing, FlexDirection, FlexWrap, Gap, JustifyContent, LayoutOverflow,
        LayoutProps, Position, RectValues, Sizing,
    };
    /// Display mode for a node (re-exported for backward compatibility)
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub enum Display {
        /// Node is laid out and rendered.
        #[default]
        Flex,
        /// Node is removed from layout entirely (CSS `display: none`).
        None,
    }
}

/// Paint submodule for backward compatibility with `crate::taffy::paint::*`
pub mod paint {
    pub use super::{ClipBounds, PaintBounds, PaintContext, PaintFlags, Viewport};
}

// Re-export types at top level for backward compatibility
pub use types::Display;

// ============================================================================
// TYPES
// ============================================================================

/// Layout properties for a node. Maps directly to CSS flexbox concepts.
///
/// Uses f32 because flex calculations require fractional values.
/// Taffy uses f32 internally. Final positions are rounded to integers
/// only at the last step.
///
/// Size: ~60 bytes. Stack-allocated.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayoutProps {
    pub display: types::Display,
    pub position: Position,
    pub direction: FlexDirection,
    pub flex_wrap: FlexWrap,
    pub justify: JustifyContent,
    pub align: AlignItems,
    pub align_content: Option<AlignContent>,
    pub align_self: Option<AlignSelf>,
    pub flex_grow: f32,
    pub flex_shrink: f32,
    pub flex_basis: Option<Sizing>,
    pub gap: Option<Gap>,
    pub padding: Option<RectValues>,
    pub margin: Option<RectValues>,
    pub border: Option<RectValues>,
    pub width: Option<Sizing>,
    pub height: Option<Sizing>,
    pub min_width: Option<Sizing>,
    pub min_height: Option<Sizing>,
    pub max_width: Option<Sizing>,
    pub max_height: Option<Sizing>,
    pub inset: Option<RectValues>,
    pub aspect_ratio: Option<f32>,
    pub overflow: Option<LayoutOverflow>,
    pub box_sizing: Option<BoxSizing>,
}

impl Default for LayoutProps {
    fn default() -> Self {
        Self {
            display: types::Display::Flex,
            position: Position::Relative,
            direction: FlexDirection::Column,
            flex_wrap: FlexWrap::NoWrap,
            justify: JustifyContent::FlexStart,
            align: AlignItems::Stretch,
            align_content: None,
            align_self: None,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            flex_basis: None,
            gap: None,
            padding: None,
            margin: None,
            border: None,
            width: None,
            height: None,
            min_width: None,
            min_height: None,
            max_width: None,
            max_height: None,
            inset: None,
            aspect_ratio: None,
            overflow: None,
            box_sizing: None,
        }
    }
}

impl LayoutProps {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Width/height values for sizing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Sizing {
    /// Fixed size in terminal cells.
    Points(f32),
    /// Percentage of parent size.
    Percent(f32),
    /// Size determined by content.
    Auto,
}

/// Flex wrap mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexWrap {
    /// All children in a single line (may overflow).
    #[default]
    NoWrap,
    /// Children wrap to next line when overflow.
    Wrap,
    /// Children wrap in reverse direction.
    WrapReverse,
}

/// Flex direction for child layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexDirection {
    /// Children laid out horizontally (left to right).
    Row,
    /// Children laid out vertically (top to bottom).
    #[default]
    Column,
    /// Children laid out horizontally (right to left).
    RowReverse,
    /// Children laid out vertically (bottom to top).
    ColumnReverse,
}

/// Alignment along the main axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JustifyContent {
    #[default]
    FlexStart,
    FlexEnd,
    Center,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

/// Alignment along the cross axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignItems {
    FlexStart,
    FlexEnd,
    Center,
    #[default]
    Stretch,
    Baseline,
}

/// Per-child cross axis alignment override.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignSelf {
    FlexStart,
    FlexEnd,
    Center,
    Stretch,
    Baseline,
}

/// Alignment of flex lines when there's extra space in the cross axis.
/// Only applies when `flex_wrap` is `Wrap` or `WrapReverse`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignContent {
    #[default]
    FlexStart,
    FlexEnd,
    Center,
    Stretch,
    SpaceBetween,
    SpaceAround,
}

/// Positioning mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Position {
    /// Positioned by flexbox flow.
    #[default]
    Relative,
    /// Removed from flow, positioned relative to parent.
    Absolute,
    /// Positioned according to normal flow.
    /// Note: Taffy has no `Static` mode; this maps to `Relative` internally.
    /// The semantic difference is that CSS `static` ignores `inset` properties,
    /// but in terminal UI contexts this distinction rarely matters.
    Static,
}

/// Layout-level overflow behavior for flex items.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LayoutOverflow {
    /// Content is not clipped (may overflow the container).
    #[default]
    Visible,
    /// Content is clipped to the container bounds.
    Hidden,
    /// Content is clipped and scrollable.
    Scroll,
}

/// Box sizing model, mirroring CSS `box-sizing`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BoxSizing {
    /// `border-box`: width/height includes padding and border.
    BorderBox,
    /// `content-box`: width/height excludes padding and border (CSS default).
    #[default]
    ContentBox,
}

/// Gap between children.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Gap {
    /// Gap between rows (main axis for column direction).
    pub row: f32,
    /// Gap between columns (main axis for row direction).
    pub column: f32,
}

impl Gap {
    pub fn new(row: f32, column: f32) -> Self {
        Self { row, column }
    }

    /// Create uniform gap.
    pub fn uniform(gap: f32) -> Self {
        Self { row: gap, column: gap }
    }
}

/// Rectangular values for padding, margin, and inset.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct RectValues {
    pub top: Option<f32>,
    pub right: Option<f32>,
    pub bottom: Option<f32>,
    pub left: Option<f32>,
}

impl RectValues {
    /// Create uniform values on all sides.
    pub fn uniform(value: f32) -> Self {
        Self { top: Some(value), right: Some(value), bottom: Some(value), left: Some(value) }
    }

    /// Create values with horizontal/vertical separation.
    pub fn new(horizontal: f32, vertical: f32) -> Self {
        Self { top: Some(vertical), right: Some(horizontal), bottom: Some(vertical), left: Some(horizontal) }
    }

    /// Create with individual values.
    pub fn sides(top: f32, right: f32, bottom: f32, left: f32) -> Self {
        Self { top: Some(top), right: Some(right), bottom: Some(bottom), left: Some(left) }
    }
}

// ============================================================================
// PAINT
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PaintBounds {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
    pub padding_left: u16,
    pub padding_right: u16,
    pub padding_top: u16,
    pub padding_bottom: u16,
    pub border_top: u16,
    pub border_right: u16,
    pub border_bottom: u16,
    pub border_left: u16,
}

impl PaintBounds {
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self { x, y, width, height, ..Default::default() }
    }

    pub fn with_padding(mut self, left: u16, right: u16, top: u16, bottom: u16) -> Self {
        self.padding_left = left;
        self.padding_right = right;
        self.padding_top = top;
        self.padding_bottom = bottom;
        self
    }

    pub fn with_border(mut self, top: u16, right: u16, bottom: u16, left: u16) -> Self {
        self.border_top = top;
        self.border_right = right;
        self.border_bottom = bottom;
        self.border_left = left;
        self
    }

    pub fn rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.width, self.height)
    }

    pub fn border_rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.width, self.height)
    }

    pub fn content_rect(&self) -> Rect {
        Rect::new(
            self.x + self.border_left + self.padding_left,
            self.y + self.border_top + self.padding_top,
            self.width.saturating_sub(self.border_left + self.border_right + self.padding_left + self.padding_right),
            self.height.saturating_sub(self.border_top + self.border_bottom + self.padding_top + self.padding_bottom),
        )
    }

    pub fn right(&self) -> u16 {
        self.x.saturating_add(self.width)
    }

    pub fn bottom(&self) -> u16 {
        self.y.saturating_add(self.height)
    }

    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }

    pub fn intersects(&self, other: &PaintBounds) -> bool {
        self.x < other.right() && self.right() > other.x && self.y < other.bottom() && self.bottom() > other.y
    }

    pub fn intersect(&self, other: &PaintBounds) -> Option<PaintBounds> {
        let x = self.x.max(other.x);
        let y = self.y.max(other.y);
        let right = self.right().min(other.right());
        let bottom = self.bottom().min(other.bottom());
        if right > x && bottom > y { Some(PaintBounds::new(x, y, right - x, bottom - y)) } else { None }
    }
}

/// Viewport defines the visible region of the terminal.
/// Used for culling: nodes outside the viewport are skipped during render tree building.
/// Unlike ClipBounds (which clips rendering), Viewport is a culling-only concept.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Viewport {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
}

impl Viewport {
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self { x, y, width, height }
    }

    pub fn right(&self) -> u16 {
        self.x.saturating_add(self.width)
    }

    pub fn bottom(&self) -> u16 {
        self.y.saturating_add(self.height)
    }

    pub fn contains_rect(&self, px: u16, py: u16, pw: u16, ph: u16) -> bool {
        let r = px.saturating_add(pw);
        let b = py.saturating_add(ph);
        r > self.x && px < self.right() && b > self.y && py < self.bottom()
    }

    pub fn intersect(&self, other: &Viewport) -> Option<Viewport> {
        let x = self.x.max(other.x);
        let y = self.y.max(other.y);
        let r = self.right().min(other.right());
        let b = self.bottom().min(other.bottom());
        if r > x && b > y { Some(Viewport::new(x, y, r - x, b - y)) } else { None }
    }

    pub fn offset(&self, dx: i32, dy: i32) -> Viewport {
        Viewport::new((self.x as i32 + dx).max(0) as u16, (self.y as i32 + dy).max(0) as u16, self.width, self.height)
    }

    /// Expand viewport by `padding` cells on all sides.
    /// Prevents objects from popping in/out at viewport edges during scroll.
    pub fn with_padding(&self, padding: u16) -> Viewport {
        Viewport::new(
            self.x.saturating_sub(padding),
            self.y.saturating_sub(padding),
            self.width.saturating_add(padding * 2),
            self.height.saturating_add(padding * 2),
        )
    }

    /// Intersect with a rectangle whose origin may be negative (signed coordinates).
    /// Nodes whose layout positions are off-screen (scrolled above the top) have
    /// negative absolute positions; this variant handles them without clamping.
    pub fn intersect_signed(&self, x: i32, y: i32, w: u16, h: u16) -> Option<Viewport> {
        let vx = self.x as i32;
        let vy = self.y as i32;
        let vr = vx + self.width as i32;
        let vb = vy + self.height as i32;
        let ix = x.max(vx);
        let iy = y.max(vy);
        let ir = (x + w as i32).min(vr);
        let ib = (y + h as i32).min(vb);
        if ir > ix && ib > iy {
            Some(Viewport::new(ix as u16, iy as u16, (ir - ix) as u16, (ib - iy) as u16))
        } else {
            None
        }
    }

    /// Overlap test for a rectangle whose origin may be negative (signed coordinates).
    pub fn contains_rect_signed(&self, x: i32, y: i32, w: u16, h: u16) -> bool {
        let vx = self.x as i32;
        let vy = self.y as i32;
        let vr = vx + self.width as i32;
        let vb = vy + self.height as i32;
        let x2 = x + w as i32;
        let y2 = y + h as i32;
        x2 > vx && x < vr && y2 > vy && y < vb
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClipBounds {
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
}

impl ClipBounds {
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self { x, y, width, height }
    }

    pub fn from_rect(rect: &Rect) -> Self {
        Self { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
    }

    pub fn right(&self) -> u16 {
        self.x.saturating_add(self.width)
    }

    pub fn bottom(&self) -> u16 {
        self.y.saturating_add(self.height)
    }

    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }

    pub fn intersect(&self, other: &ClipBounds) -> Option<ClipBounds> {
        let x = self.x.max(other.x);
        let y = self.y.max(other.y);
        let right = self.right().min(other.right());
        let bottom = self.bottom().min(other.bottom());
        if right > x && bottom > y { Some(ClipBounds::new(x, y, right - x, bottom - y)) } else { None }
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct PaintFlags: u8 {
        const EMPTY       = 0b0000_0000;
        const BACKGROUND   = 0b0000_0001;
        const BORDER       = 0b0000_0010;
        const TEXT         = 0b0000_0100;
        const SCROLLBAR    = 0b0000_1000;
        const CURSOR       = 0b0001_0000;
        const OVERLAY      = 0b0010_0000;
        const HIDDEN       = 0b0100_0000;
        const NEEDS_CLIP   = 0b1000_0000;
    }
}

use smallvec::SmallVec;

#[cfg(test)]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(test)]
use std::sync::{Arc, Mutex};

// ============================================================================
// CALLBACK TYPES
// ============================================================================

/// Callback invoked when a node's layout becomes dirty.
/// Useful for invalidating cached layout data or triggering re-renders.
type DirtiedCallback = Box<dyn Fn(NodeId) + Send + 'static>;

/// Result of a custom measure function.
pub struct MeasureResult {
    pub width: f32,
    pub height: f32,
}

/// Callback for measuring a node's intrinsic size.
/// Allows custom measurement strategies (text content, rendered widgets, etc.)
/// instead of using the default text-based heuristic.
///
/// Parameters: (known_width, known_height, available_width, available_height)
/// Returns: (measured_width, measured_height)
type MeasureCallback = Box<dyn Fn(Option<f32>, Option<f32>, f32, f32) -> MeasureResult + Send + 'static>;

#[derive(Clone)]
pub struct PaintContext {
    pub terminal_width: u16,
    pub terminal_height: u16,
    pub clip_stack: SmallVec<[ClipBounds; 8]>,
}

impl PaintContext {
    pub fn new(width: u16, height: u16) -> Self {
        Self { terminal_width: width, terminal_height: height, clip_stack: SmallVec::new() }
    }

    pub fn push_clip(&mut self, clip: ClipBounds) {
        let effective = if let Some(parent) = self.clip_stack.last() {
            parent.intersect(&clip).unwrap_or(ClipBounds::new(0, 0, 0, 0))
        } else {
            clip
        };
        self.clip_stack.push(effective);
    }

    pub fn pop_clip(&mut self) {
        self.clip_stack.pop();
    }

    pub fn current_clip(&self) -> Option<&ClipBounds> {
        self.clip_stack.last()
    }

    pub fn is_visible(&self, bounds: &PaintBounds) -> bool {
        if let Some(clip) = self.clip_stack.last() {
            clip.intersect(&ClipBounds::new(bounds.x, bounds.y, bounds.width, bounds.height)).is_some()
        } else {
            true
        }
    }

    pub fn clipped_bounds(&self, bounds: &PaintBounds) -> Option<PaintBounds> {
        if let Some(clip) = self.clip_stack.last() {
            let cb = ClipBounds::new(bounds.x, bounds.y, bounds.width, bounds.height);
            cb.intersect(clip).map(|c| PaintBounds::new(c.x, c.y, c.width, c.height))
        } else {
            Some(*bounds)
        }
    }
}

// ============================================================================
// CULLING
// ============================================================================

/// Binary search viewport culling for large scrollable lists.
///
/// Pattern adapted from reference implementation's `getObjectsInViewport`.
/// Uses binary search + interval expansion to find visible children
/// in O(log N + K) time where K is the number of visible objects.
///
/// A positioned child in a sorted array for binary search culling.
#[derive(Debug, Clone, Copy)]
pub struct PositionedChild {
    pub id: NodeId,
    /// Primary-axis start position (y for column layout, x for row layout).
    pub start: u16,
    /// Primary-axis size (height for column, width for row).
    pub size: u16,
}

/// Padding to apply when culling — keeps a buffer of visible objects
/// just outside the viewport for smooth scrolling.
pub const CULLING_PADDING: u16 = 5;

/// Returns children that intersect the given viewport along the primary axis.
///
/// `children` must be pre-sorted by `start` ascending.
/// Uses binary search for O(log N) lookup, then expands left/right.
///
/// This is specifically for scroll containers with many children.
/// The viewport should already be offset by scroll position.
///
/// A `CULLING_PADDING` buffer is applied so objects just outside the
/// viewport are still included (prevents pop-in during smooth scrolling).
pub fn get_objects_in_viewport(
    viewport: &Viewport,
    children: &[PositionedChild],
    primary_axis: PrimaryAxis,
) -> Vec<NodeId> {
    if children.is_empty() || viewport.width == 0 || viewport.height == 0 {
        return Vec::new();
    }

    // Apply culling padding to prevent pop-in during scrolling
    let vp_padded = viewport.with_padding(CULLING_PADDING);

    // Small arrays: skip binary search overhead
    if children.len() < 16 {
        return children
            .iter()
            .filter(|c| {
                let end = c.start.saturating_add(c.size);
                end > viewport_start(&vp_padded, primary_axis) && c.start < viewport_end(&vp_padded, primary_axis)
            })
            .map(|c| c.id)
            .collect();
    }

    let vp_start = viewport_start(&vp_padded, primary_axis);
    let vp_end = viewport_end(&vp_padded, primary_axis);

    // Binary search for first overlapping child
    let mut lo = 0i32;
    let mut hi = children.len() as i32 - 1;
    let mut candidate: Option<usize> = None;

    while lo <= hi {
        let mid = ((lo + hi) >> 1) as usize;
        let c = &children[mid];
        let end = c.start.saturating_add(c.size);

        if end <= vp_start {
            lo = mid as i32 + 1;
        } else if c.start >= vp_end {
            hi = mid as i32 - 1;
        } else {
            candidate = Some(mid);
            break;
        }
    }

    let Some(center) = candidate else {
        // Viewport is in a gap — start from where search ended.
        // Clamp to last valid index since `lo` can be children.len()
        // when all children are before the viewport.
        let start_idx = (lo.max(0) as usize).min(children.len().saturating_sub(1));
        return expand_from(children, start_idx, vp_start, vp_end, primary_axis);
    };

    // Expand left with bounded look-behind for spanning objects
    let max_look_behind = 50;
    let mut left = center;
    let mut gap_count = 0;

    while left > 0 {
        let prev = &children[left - 1];
        let prev_end = prev.start.saturating_add(prev.size);

        if prev_end <= vp_start {
            gap_count += 1;
            if gap_count >= max_look_behind {
                break;
            }
        } else {
            gap_count = 0;
        }
        left -= 1;
    }

    // Expand right
    let mut right = center + 1;
    while right < children.len() {
        let next = &children[right];
        if next.start >= vp_end {
            break;
        }
        right += 1;
    }

    // Collect visible children
    children[left..right]
        .iter()
        .filter(|c| {
            let end = c.start.saturating_add(c.size);
            end > vp_start && c.start < vp_end
        })
        .map(|c| c.id)
        .collect()
}

fn expand_from(
    children: &[PositionedChild],
    start_idx: usize,
    vp_start: u16,
    vp_end: u16,
    _axis: PrimaryAxis,
) -> Vec<NodeId> {
    let mut result = Vec::new();
    // Scan backward
    let mut i = start_idx as i32;
    let mut look_behind = 0;
    while i >= 0 {
        let c = &children[i as usize];
        let end = c.start.saturating_add(c.size);
        if end > vp_start.saturating_sub(10) && c.start < vp_end {
            result.push(c.id);
            look_behind = 0;
        } else {
            look_behind += 1;
            if look_behind >= 50 {
                break;
            }
        }
        i -= 1;
    }
    result.reverse();
    // Scan forward with early termination
    let mut i = start_idx;
    while i < children.len() {
        let c = &children[i];
        if c.start >= vp_end {
            break;
        }
        let end = c.start.saturating_add(c.size);
        if end > vp_start {
            result.push(c.id);
        }
        i += 1;
    }
    result
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrimaryAxis {
    Column, // Sort by y (vertical layout)
    Row,    // Sort by x (horizontal layout)
}

fn viewport_start(vp: &Viewport, axis: PrimaryAxis) -> u16 {
    match axis {
        PrimaryAxis::Column => vp.y,
        PrimaryAxis::Row => vp.x,
    }
}

fn viewport_end(vp: &Viewport, axis: PrimaryAxis) -> u16 {
    match axis {
        PrimaryAxis::Column => vp.bottom(),
        PrimaryAxis::Row => vp.right(),
    }
}

// ============================================================================
// CONFIG
// ============================================================================

/// Layout configuration controlling global layout behavior.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayoutConfig {
    /// Scale factor for rounding layout positions.
    /// Terminal cells are 1:1, so this is typically 1.0.
    pub point_scale_factor: f32,
    /// Whether to use web-like defaults for flexbox.
    /// When `true`, nodes default to flex row direction.
    /// When `false` (default), nodes default to column direction.
    pub use_web_defaults: bool,
}

impl Default for LayoutConfig {
    fn default() -> Self {
        Self { point_scale_factor: 1.0, use_web_defaults: false }
    }
}

// ============================================================================
// ENGINE
// ============================================================================

#[derive(Debug)]
pub enum LayoutError {
    NodeNotRegistered(NodeId),
    TaffyError(taffy::TaffyError),
}

impl std::fmt::Display for LayoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LayoutError::NodeNotRegistered(id) => {
                write!(f, "Node {id:?} not registered in layout engine")
            }
            LayoutError::TaffyError(e) => write!(f, "Taffy error: {e}"),
        }
    }
}

impl std::error::Error for LayoutError {}

impl From<taffy::TaffyError> for LayoutError {
    fn from(e: taffy::TaffyError) -> Self {
        LayoutError::TaffyError(e)
    }
}

/// Measure text content for intrinsic layout sizing.
///
/// Uses grapheme-aware width calculation to properly handle:
/// - Wide characters (CJK, emoji)
/// - Zero-width joiners and combining marks
/// - Multi-codepoint graphemes (flag emojis, skin tone modifiers)
///
/// Empty text measures zero columns wide but still one line tall, so blank
/// text nodes keep their line in the layout flow without occupying a cell
/// that would push sibling content sideways.
///
/// Returns (intrinsic_width, line_count).
///
/// # Arguments
/// * `text` - The text content to measure
/// * `available_width` - Available width for wrapping (f32::INFINITY for no wrap)
///
/// # Returns
/// * `intrinsic_width` - The computed width (either max line width or constrained width)
/// * `line_count` - Number of lines after wrapping
fn measure_text(text: &str, available_width: f32) -> (f32, usize) {
    if text.is_empty() {
        return (0.0, 1);
    }

    let line_widths: Vec<usize> = text.lines().map(text::display_width).collect();

    let max_width = line_widths.iter().copied().max().unwrap_or(0);

    if available_width.is_infinite() || available_width <= 0.0 {
        return (max_width.max(1) as f32, line_widths.len().max(1));
    }

    let wrap_width = available_width.floor() as usize;

    if max_width <= wrap_width {
        return (max_width.max(1) as f32, line_widths.len().max(1));
    }

    let mut total_lines = 0usize;
    for line in text.lines() {
        total_lines += count_wrapped_lines(line, wrap_width);
    }

    let intrinsic_width = if wrap_width > 0 { wrap_width.min(max_width) as f32 } else { max_width.max(1) as f32 };

    (intrinsic_width, total_lines.max(1))
}

fn count_wrapped_lines(line: &str, wrap_width: usize) -> usize {
    if line.is_empty() || wrap_width == 0 {
        return 1;
    }

    let line_width = text::display_width(line);
    if line_width <= wrap_width {
        return 1;
    }

    let mut current_line_width = 0usize;
    let mut line_count = 1usize;
    let mut word_width = 0usize;

    for grapheme in line.graphemes(true) {
        let g_width = text::grapheme_width(grapheme);

        if current_line_width + word_width + g_width > wrap_width {
            if current_line_width > 0 {
                line_count += 1;
                current_line_width = 0;
            } else if word_width > 0 {
                line_count += 1;
                current_line_width = g_width;
                word_width = 0;
                continue;
            }
        }

        let is_whitespace = grapheme.chars().all(|c| c.is_whitespace());

        if is_whitespace {
            current_line_width += word_width + g_width;
            word_width = 0;
        } else {
            word_width += g_width;
        }
    }

    if word_width > 0 && current_line_width + word_width > wrap_width && current_line_width > 0 {
        line_count += 1;
    }

    line_count
}

pub struct LayoutEngine {
    taffy: taffy::TaffyTree<()>,
    node_map: HashMap<NodeId, taffy::NodeId>,
    reverse_map: HashMap<taffy::NodeId, NodeId>,
    /// Text content for text nodes. Used by the default measure function to compute intrinsic size.
    text_map: RefCell<HashMap<NodeId, String>>,
    /// Callback invoked when a node's layout becomes dirty.
    dirtied_handler: Option<DirtiedCallback>,
    /// Per-node measure callbacks for custom measurement.
    measure_callbacks: HashMap<NodeId, MeasureCallback>,
    /// Layout configuration.
    config: LayoutConfig,
    last_root_width: Option<f32>,
    last_root_height: Option<f32>,
}

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

impl LayoutEngine {
    pub fn new() -> Self {
        Self {
            taffy: taffy::TaffyTree::new(),
            node_map: HashMap::new(),
            reverse_map: HashMap::new(),
            text_map: RefCell::new(HashMap::new()),
            dirtied_handler: None,
            measure_callbacks: HashMap::new(),
            config: LayoutConfig::default(),
            last_root_width: None,
            last_root_height: None,
        }
    }

    /// Set a callback invoked when any node's layout becomes dirty.
    pub fn set_dirtied_handler<F>(&mut self, handler: F)
    where
        F: Fn(NodeId) + Send + 'static,
    {
        self.dirtied_handler = Some(Box::new(handler));
    }

    /// Remove the dirtied callback.
    pub fn clear_dirtied_handler(&mut self) {
        self.dirtied_handler = None;
    }

    /// Set a custom measure callback for a specific node.
    /// When set, this callback is invoked during layout computation to
    /// determine the node's intrinsic size, instead of using text heuristics.
    pub fn set_measure_callback<F>(&mut self, id: NodeId, callback: F)
    where
        F: Fn(Option<f32>, Option<f32>, f32, f32) -> MeasureResult + Send + 'static,
    {
        self.measure_callbacks.insert(id, Box::new(callback));
    }

    /// Remove the measure callback for a node, reverting to default text-based measurement.
    pub fn remove_measure_callback(&mut self, id: NodeId) {
        self.measure_callbacks.remove(&id);
    }

    /// Check if a node has a custom measure callback registered.
    pub fn has_measure_callback(&self, id: NodeId) -> bool {
        self.measure_callbacks.contains_key(&id)
    }

    /// Get the current layout config.
    pub fn config(&self) -> &LayoutConfig {
        &self.config
    }

    /// Set the layout config.
    pub fn set_config(&mut self, config: LayoutConfig) {
        self.config = config;
    }

    /// Fire the dirtied callback if one is registered.
    fn fire_dirtied(&self, id: NodeId) {
        if let Some(ref handler) = self.dirtied_handler {
            handler(id);
        }
    }

    pub fn has_node(&self, id: NodeId) -> bool {
        self.node_map.contains_key(&id)
    }

    pub fn node_count(&self) -> usize {
        self.node_map.len()
    }

    pub fn register_node(&mut self, id: NodeId) {
        if self.node_map.contains_key(&id) {
            return;
        }
        let style = taffy::Style::default();
        let taffy_id = self.taffy.new_leaf(style).unwrap();
        self.node_map.insert(id, taffy_id);
        self.reverse_map.insert(taffy_id, id);
    }

    pub fn register_container(&mut self, id: NodeId, props: &LayoutProps) {
        if self.node_map.contains_key(&id) {
            self.update_style(id, props);
            return;
        }
        let style = layout_props_to_taffy(props);
        let taffy_id = self.taffy.new_leaf(style).unwrap();
        self.node_map.insert(id, taffy_id);
        self.reverse_map.insert(taffy_id, id);
    }

    pub fn remove_node(&mut self, id: NodeId) {
        if let Some(taffy_id) = self.node_map.remove(&id) {
            self.reverse_map.remove(&taffy_id);
            self.text_map.borrow_mut().remove(&id);
            self.measure_callbacks.remove(&id);
            let _ = self.taffy.remove(taffy_id);
            self.fire_dirtied(id);
        }
    }

    pub fn update_style(&mut self, id: NodeId, props: &LayoutProps) {
        if let Some(&taffy_id) = self.node_map.get(&id) {
            let style = layout_props_to_taffy(props);
            self.taffy.set_style(taffy_id, style).unwrap();
            let _ = self.taffy.mark_dirty(taffy_id);
            self.fire_dirtied(id);
        }
    }

    /// Check if a node's layout needs recomputation.
    pub fn is_dirty(&self, id: NodeId) -> bool {
        if let Some(&taffy_id) = self.node_map.get(&id) { self.taffy.dirty(taffy_id).unwrap_or(false) } else { false }
    }

    /// Mark a node as needing layout recomputation.
    /// This also marks all ancestors as dirty.
    pub fn mark_dirty(&mut self, id: NodeId) {
        if let Some(&taffy_id) = self.node_map.get(&id) {
            let _ = self.taffy.mark_dirty(taffy_id);
            self.fire_dirtied(id);
        }
    }

    /// Check if a node has a freshly computed layout.
    /// Returns `true` if the node's layout was computed and is not dirty.
    pub fn has_new_layout(&self, id: NodeId) -> bool {
        if let Some(&taffy_id) = self.node_map.get(&id) {
            // After compute_layout, Taffy resets dirty flags.
            // A node that is not dirty and has a layout has "new" layout.
            !self.taffy.dirty(taffy_id).unwrap_or(true) && self.taffy.layout(taffy_id).is_ok()
        } else {
            false
        }
    }

    /// Reset a node to its default layout state, clearing any custom style, text, or callbacks.
    pub fn reset_node(&mut self, id: NodeId) {
        if let Some(&taffy_id) = self.node_map.get(&id) {
            self.taffy.set_style(taffy_id, taffy::Style::default()).unwrap();
            let _ = self.taffy.mark_dirty(taffy_id);
            self.text_map.borrow_mut().remove(&id);
            self.measure_callbacks.remove(&id);
            self.fire_dirtied(id);
        }
    }

    /// Copy the layout style from one node to another.
    /// Leaves the source node unchanged; only the target node is updated.
    pub fn copy_style(&mut self, from: NodeId, to: NodeId) {
        let from_taffy_id = match self.node_map.get(&from).copied() {
            Some(id) => id,
            None => return,
        };
        let style = match self.taffy.style(from_taffy_id) {
            Ok(s) => s.clone(),
            Err(_) => return,
        };
        if let Some(&to_taffy_id) = self.node_map.get(&to) {
            let _ = self.taffy.set_style(to_taffy_id, style);
            let _ = self.taffy.mark_dirty(to_taffy_id);
            self.fire_dirtied(to);
        }
    }

    /// Get the computed left edge position for a node.
    pub fn get_computed_left(&self, id: NodeId) -> f32 {
        if let Some(&taffy_id) = self.node_map.get(&id)
            && let Ok(layout) = self.taffy.layout(taffy_id)
        {
            return layout.location.x;
        }
        0.0
    }

    /// Get the computed top edge position for a node.
    pub fn get_computed_top(&self, id: NodeId) -> f32 {
        if let Some(&taffy_id) = self.node_map.get(&id)
            && let Ok(layout) = self.taffy.layout(taffy_id)
        {
            return layout.location.y;
        }
        0.0
    }

    /// Register node as a text node with content for intrinsic sizing.
    /// The measure function will compute the node's size based on text content.
    pub fn register_text_node(&mut self, id: NodeId, props: &LayoutProps, text: &str) {
        if self.node_map.contains_key(&id) {
            self.text_map.borrow_mut().insert(id, text.to_string());
            self.update_style(id, props);
            return;
        }
        let style = layout_props_to_taffy(props);
        let taffy_id = self.taffy.new_leaf(style).unwrap();
        self.node_map.insert(id, taffy_id);
        self.reverse_map.insert(taffy_id, id);
        self.text_map.borrow_mut().insert(id, text.to_string());
    }

    /// Update the text content for an existing text node (for re-measurement).
    pub fn update_text(&mut self, id: NodeId, text: &str) {
        self.text_map.borrow_mut().insert(id, text.to_string());
        if let Some(&taffy_id) = self.node_map.get(&id) {
            let _ = self.taffy.mark_dirty(taffy_id);
            self.fire_dirtied(id);
        }
    }

    pub fn add_child(&mut self, parent: NodeId, child: NodeId) {
        let Some(&p) = self.node_map.get(&parent) else {
            return;
        };
        let Some(&c) = self.node_map.get(&child) else {
            return;
        };
        let _ = self.taffy.add_child(p, c);
    }

    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) {
        let Some(&p) = self.node_map.get(&parent) else {
            return;
        };
        let taffy_children: Vec<_> = children.iter().filter_map(|c| self.node_map.get(c).copied()).collect();
        let _ = self.taffy.set_children(p, &taffy_children);
        self.fire_dirtied(parent);
    }

    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) {
        let Some(&p) = self.node_map.get(&parent) else {
            return;
        };
        let Some(&c) = self.node_map.get(&child) else {
            return;
        };
        let _ = self.taffy.remove_child(p, c);
    }

    pub fn compute_layout(&mut self, root: NodeId, width: f32, height: f32) -> Result<(), LayoutError> {
        let &taffy_root = self.node_map.get(&root).ok_or(LayoutError::NodeNotRegistered(root))?;

        let size_changed = self.last_root_width != Some(width) || self.last_root_height != Some(height);
        if !self.taffy.dirty(taffy_root).unwrap_or(false) && !size_changed {
            return Ok(());
        }
        if size_changed {
            let _ = self.taffy.mark_dirty(taffy_root);
            self.last_root_width = Some(width);
            self.last_root_height = Some(height);
        }

        let size = taffy::Size {
            width: taffy::AvailableSpace::Definite(width),
            height: taffy::AvailableSpace::Definite(height),
        };
        let reverse_map = &self.reverse_map;
        let text_map = &self.text_map;
        let measure_callbacks = &self.measure_callbacks;

        self.taffy.compute_layout_with_measure(
            taffy_root,
            size,
            |known_dimensions, available_space, node_id, _context, _style| {
                if let taffy::Size { width: Some(w), height: Some(h) } = known_dimensions {
                    return taffy::Size { width: w, height: h };
                }

                let our_id = match reverse_map.get(&node_id) {
                    Some(id) => *id,
                    None => return taffy::Size::ZERO,
                };

                // Check for per-node measure callback first
                if let Some(callback) = measure_callbacks.get(&our_id) {
                    let available_width = match available_space.width {
                        taffy::AvailableSpace::Definite(w) => w,
                        taffy::AvailableSpace::MaxContent => f32::INFINITY,
                        taffy::AvailableSpace::MinContent => 0.0,
                    };
                    let available_height = match available_space.height {
                        taffy::AvailableSpace::Definite(h) => h,
                        taffy::AvailableSpace::MaxContent => f32::INFINITY,
                        taffy::AvailableSpace::MinContent => 0.0,
                    };
                    let result =
                        callback(known_dimensions.width, known_dimensions.height, available_width, available_height);
                    return taffy::Size { width: result.width, height: result.height };
                }

                // Fall back to text measurement (default behavior)
                let text = text_map.borrow();
                let content = match text.get(&our_id) {
                    Some(t) => t.as_str(),
                    None => return taffy::Size::ZERO,
                };

                // MinContent: return minimum intrinsic width (longest unbreakable unit)
                // MaxContent: return maximum intrinsic width (no wrapping)
                let available_width = match available_space.width {
                    taffy::AvailableSpace::Definite(w) => w,
                    taffy::AvailableSpace::MaxContent => f32::INFINITY,
                    taffy::AvailableSpace::MinContent => {
                        // Find longest word/line as minimum intrinsic width
                        let max_word = content
                            .lines()
                            .flat_map(|line| line.split_whitespace())
                            .map(text::display_width)
                            .max()
                            .unwrap_or(1);
                        return taffy::Size {
                            width: known_dimensions.width.unwrap_or(max_word.max(1) as f32),
                            height: known_dimensions.height.unwrap_or(content.lines().count().max(1) as f32),
                        };
                    }
                };
                let _available_height = match available_space.height {
                    taffy::AvailableSpace::Definite(h) => h,
                    taffy::AvailableSpace::MaxContent => f32::INFINITY,
                    taffy::AvailableSpace::MinContent => 0.0,
                };

                let (intrinsic_width, line_count) = measure_text(content, available_width);

                taffy::Size {
                    width: known_dimensions.width.unwrap_or(intrinsic_width),
                    height: known_dimensions.height.unwrap_or(line_count as f32),
                }
            },
        )?;
        Ok(())
    }

    /// Force layout computation regardless of dirty state.
    /// Use this when terminal size changes.
    pub fn compute_layout_forced(&mut self, root: NodeId, width: f32, height: f32) -> Result<(), LayoutError> {
        let &taffy_root = self.node_map.get(&root).ok_or(LayoutError::NodeNotRegistered(root))?;
        let _ = self.taffy.mark_dirty(taffy_root);
        self.compute_layout(root, width, height)
    }

    pub fn collect_results(&self) -> HashMap<NodeId, LayoutResult> {
        let mut results = HashMap::new();
        for (&node_id, &taffy_id) in &self.node_map {
            if let Ok(layout) = self.taffy.layout(taffy_id) {
                results.insert(
                    node_id,
                    LayoutResult {
                        x: (layout.location.x.round() as i32).max(0) as u16,
                        y: (layout.location.y.round() as i32).max(0) as u16,
                        width: (layout.size.width.round() as i32).max(0) as u16,
                        height: (layout.size.height.round() as i32).max(0) as u16,
                        content_width: (layout.content_box_width().round() as i32).max(0) as u16,
                        content_height: (layout.content_box_height().round() as i32).max(0) as u16,
                        order: layout.order,
                        scrollbar_width: (layout.scrollbar_size.width.round() as i32).max(0) as u16,
                        scrollbar_height: (layout.scrollbar_size.height.round() as i32).max(0) as u16,
                        padding_top: (layout.padding.top.round() as i32).max(0) as u16,
                        padding_right: (layout.padding.right.round() as i32).max(0) as u16,
                        padding_bottom: (layout.padding.bottom.round() as i32).max(0) as u16,
                        padding_left: (layout.padding.left.round() as i32).max(0) as u16,
                        border_top: (layout.border.top.round() as i32).max(0) as u16,
                        border_right: (layout.border.right.round() as i32).max(0) as u16,
                        border_bottom: (layout.border.bottom.round() as i32).max(0) as u16,
                        border_left: (layout.border.left.round() as i32).max(0) as u16,
                        margin_top: (layout.margin.top.round() as i32).max(0) as u16,
                        margin_right: (layout.margin.right.round() as i32).max(0) as u16,
                        margin_bottom: (layout.margin.bottom.round() as i32).max(0) as u16,
                        margin_left: (layout.margin.left.round() as i32).max(0) as u16,
                    },
                );
            }
        }
        results
    }
}

fn sizing_to_taffy(sizing: Option<Sizing>) -> taffy::Dimension {
    match sizing {
        Some(Sizing::Points(p)) => taffy::Dimension::Length(p),
        // Note: do NOT clamp percentages to [0,1]. CSS and Yoga allow
        // values > 100% (content overflows parent) and < 0% (negative offsets).
        // Clamping was a latent bug that broke percentage-overflow layouts.
        Some(Sizing::Percent(p)) => taffy::Dimension::Percent(p),
        Some(Sizing::Auto) | None => taffy::Dimension::Auto,
    }
}

fn rect_values_to_taffy(r: &RectValues) -> taffy::Rect<taffy::LengthPercentage> {
    taffy::Rect {
        top: r.top.map(taffy::LengthPercentage::Length).unwrap_or(taffy::LengthPercentage::Length(0.0)),
        right: r.right.map(taffy::LengthPercentage::Length).unwrap_or(taffy::LengthPercentage::Length(0.0)),
        bottom: r.bottom.map(taffy::LengthPercentage::Length).unwrap_or(taffy::LengthPercentage::Length(0.0)),
        left: r.left.map(taffy::LengthPercentage::Length).unwrap_or(taffy::LengthPercentage::Length(0.0)),
    }
}

fn rect_values_to_taffy_auto(r: &RectValues) -> taffy::Rect<taffy::LengthPercentageAuto> {
    taffy::Rect {
        top: r.top.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Length(0.0)),
        right: r.right.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Length(0.0)),
        bottom: r.bottom.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Length(0.0)),
        left: r.left.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Length(0.0)),
    }
}

fn map_align_items(val: AlignItems) -> taffy::AlignItems {
    match val {
        AlignItems::FlexStart => taffy::AlignItems::FlexStart,
        AlignItems::FlexEnd => taffy::AlignItems::FlexEnd,
        AlignItems::Center => taffy::AlignItems::Center,
        AlignItems::Stretch => taffy::AlignItems::Stretch,
        AlignItems::Baseline => taffy::AlignItems::Baseline,
    }
}

fn map_justify_content(val: JustifyContent) -> taffy::JustifyContent {
    match val {
        JustifyContent::FlexStart => taffy::JustifyContent::FlexStart,
        JustifyContent::FlexEnd => taffy::JustifyContent::FlexEnd,
        JustifyContent::Center => taffy::JustifyContent::Center,
        JustifyContent::SpaceBetween => taffy::JustifyContent::SpaceBetween,
        JustifyContent::SpaceAround => taffy::JustifyContent::SpaceAround,
        JustifyContent::SpaceEvenly => taffy::JustifyContent::SpaceEvenly,
    }
}

fn map_flex_direction(val: FlexDirection) -> taffy::FlexDirection {
    match val {
        FlexDirection::Row => taffy::FlexDirection::Row,
        FlexDirection::Column => taffy::FlexDirection::Column,
        FlexDirection::RowReverse => taffy::FlexDirection::RowReverse,
        FlexDirection::ColumnReverse => taffy::FlexDirection::ColumnReverse,
    }
}

fn rect_values_to_inset(r: &RectValues) -> taffy::Rect<taffy::LengthPercentageAuto> {
    taffy::Rect {
        top: r.top.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Auto),
        right: r.right.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Auto),
        bottom: r.bottom.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Auto),
        left: r.left.map(taffy::LengthPercentageAuto::Length).unwrap_or(taffy::LengthPercentageAuto::Auto),
    }
}

fn map_flex_wrap(val: FlexWrap) -> taffy::FlexWrap {
    match val {
        FlexWrap::NoWrap => taffy::FlexWrap::NoWrap,
        FlexWrap::Wrap => taffy::FlexWrap::Wrap,
        FlexWrap::WrapReverse => taffy::FlexWrap::WrapReverse,
    }
}

fn map_position(val: Position) -> taffy::Position {
    match val {
        Position::Relative => taffy::Position::Relative,
        Position::Absolute => taffy::Position::Absolute,
        Position::Static => taffy::Position::Relative, // Taffy has no Static; Relative is closest
    }
}

fn map_layout_overflow(val: LayoutOverflow) -> taffy::Overflow {
    match val {
        LayoutOverflow::Visible => taffy::Overflow::Visible,
        LayoutOverflow::Hidden => taffy::Overflow::Hidden,
        LayoutOverflow::Scroll => taffy::Overflow::Scroll,
    }
}

fn map_box_sizing(val: BoxSizing) -> taffy::BoxSizing {
    match val {
        BoxSizing::BorderBox => taffy::BoxSizing::BorderBox,
        BoxSizing::ContentBox => taffy::BoxSizing::ContentBox,
    }
}

fn map_align_self(val: AlignSelf) -> taffy::AlignSelf {
    match val {
        AlignSelf::FlexStart => taffy::AlignSelf::FlexStart,
        AlignSelf::FlexEnd => taffy::AlignSelf::FlexEnd,
        AlignSelf::Center => taffy::AlignSelf::Center,
        AlignSelf::Stretch => taffy::AlignSelf::Stretch,
        AlignSelf::Baseline => taffy::AlignSelf::Baseline,
    }
}

fn map_align_content(val: AlignContent) -> taffy::AlignContent {
    match val {
        AlignContent::FlexStart => taffy::AlignContent::FlexStart,
        AlignContent::FlexEnd => taffy::AlignContent::FlexEnd,
        AlignContent::Center => taffy::AlignContent::Center,
        AlignContent::Stretch => taffy::AlignContent::Stretch,
        AlignContent::SpaceBetween => taffy::AlignContent::SpaceBetween,
        AlignContent::SpaceAround => taffy::AlignContent::SpaceAround,
    }
}

fn layout_props_to_taffy(props: &LayoutProps) -> taffy::Style {
    let padding = props.padding.map(|r| rect_values_to_taffy(&r)).unwrap_or(taffy::Rect {
        top: taffy::LengthPercentage::Length(0.0),
        right: taffy::LengthPercentage::Length(0.0),
        bottom: taffy::LengthPercentage::Length(0.0),
        left: taffy::LengthPercentage::Length(0.0),
    });
    let margin = props.margin.map(|r| rect_values_to_taffy_auto(&r)).unwrap_or(taffy::Rect {
        top: taffy::LengthPercentageAuto::Length(0.0),
        right: taffy::LengthPercentageAuto::Length(0.0),
        bottom: taffy::LengthPercentageAuto::Length(0.0),
        left: taffy::LengthPercentageAuto::Length(0.0),
    });
    let border = props.border.map(|r| rect_values_to_taffy(&r)).unwrap_or(taffy::Rect {
        top: taffy::LengthPercentage::Length(0.0),
        right: taffy::LengthPercentage::Length(0.0),
        bottom: taffy::LengthPercentage::Length(0.0),
        left: taffy::LengthPercentage::Length(0.0),
    });

    let gap = match props.gap {
        Some(g) => taffy::Size {
            width: taffy::LengthPercentage::Length(g.column),
            height: taffy::LengthPercentage::Length(g.row),
        },
        None => {
            taffy::Size { width: taffy::LengthPercentage::Length(0.0), height: taffy::LengthPercentage::Length(0.0) }
        }
    };

    let size = taffy::Size { width: sizing_to_taffy(props.width), height: sizing_to_taffy(props.height) };

    taffy::Style {
        display: match props.display {
            types::Display::Flex => taffy::Display::Flex,
            types::Display::None => taffy::Display::None,
        },
        position: map_position(props.position),
        flex_direction: map_flex_direction(props.direction),
        flex_wrap: map_flex_wrap(props.flex_wrap),
        align_items: Some(map_align_items(props.align)),
        align_content: props.align_content.map(map_align_content),
        align_self: props.align_self.map(map_align_self),
        justify_content: Some(map_justify_content(props.justify)),
        flex_grow: props.flex_grow,
        flex_shrink: props.flex_shrink,
        flex_basis: sizing_to_taffy(props.flex_basis),
        size,
        min_size: taffy::Size { width: sizing_to_taffy(props.min_width), height: sizing_to_taffy(props.min_height) },
        max_size: taffy::Size { width: sizing_to_taffy(props.max_width), height: sizing_to_taffy(props.max_height) },
        inset: props.inset.map(|r| rect_values_to_inset(&r)).unwrap_or(taffy::Rect {
            top: taffy::LengthPercentageAuto::Auto,
            right: taffy::LengthPercentageAuto::Auto,
            bottom: taffy::LengthPercentageAuto::Auto,
            left: taffy::LengthPercentageAuto::Auto,
        }),
        padding,
        margin,
        border,
        gap,
        aspect_ratio: props.aspect_ratio,
        overflow: taffy::Point {
            x: props.overflow.map(map_layout_overflow).unwrap_or(taffy::Overflow::Visible),
            y: props.overflow.map(map_layout_overflow).unwrap_or(taffy::Overflow::Visible),
        },
        box_sizing: props.box_sizing.map(map_box_sizing).unwrap_or(taffy::BoxSizing::BorderBox),
        ..Default::default()
    }
}

pub struct LayoutTreeSync {
    layout: LayoutEngine,
    results: HashMap<NodeId, LayoutResult>,
    /// Generation counter incremented on each layout computation.
    generation: u64,
    /// Revision counter for structural changes (child add/remove, visibility, etc.)
    revision: u64,
    last_width: Option<u16>,
    last_height: Option<u16>,
}

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

impl LayoutTreeSync {
    pub fn new() -> Self {
        Self {
            layout: LayoutEngine::new(),
            results: HashMap::new(),
            generation: 0,
            revision: 0,
            last_width: None,
            last_height: None,
        }
    }

    /// Get current layout generation.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Get current render list revision.
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// Bump revision for structural changes (child add/remove, visibility change, etc.)
    pub fn bump_revision(&mut self) {
        self.revision = self.revision.wrapping_add(1);
    }

    pub fn sync_full(&mut self, arena: &NodeArena) {
        let stale_ids: Vec<NodeId> = self.layout.node_map.keys().filter(|&&id| !arena.contains(id)).copied().collect();
        for id in stale_ids {
            self.layout.remove_node(id);
            self.results.remove(&id);
        }

        for (id, node) in arena.iter() {
            if !self.layout.has_node(id) {
                if let Some(text) = &node.text {
                    self.layout.register_text_node(id, &node.layout, text);
                } else {
                    self.layout.register_container(id, &node.layout);
                }
            } else if node.state.layout_dirty {
                if let Some(text) = &node.text {
                    self.layout.update_text(id, text);
                }
                self.layout.update_style(id, &node.layout);
            }
        }
    }

    pub fn sync_node(&mut self, arena: &NodeArena, id: NodeId) {
        if let Some(node) = arena.get(id) {
            if !self.layout.has_node(id) {
                if let Some(text) = &node.text {
                    self.layout.register_text_node(id, &node.layout, text);
                } else {
                    self.layout.register_container(id, &node.layout);
                }
            } else if node.state.layout_dirty {
                if let Some(text) = &node.text {
                    self.layout.update_text(id, text);
                }
                self.layout.update_style(id, &node.layout);
            }
        }
    }

    pub fn remove_node(&mut self, id: NodeId) {
        self.layout.remove_node(id);
        self.bump_revision();
    }

    pub fn sync_children(&mut self, arena: &NodeArena, parent: NodeId) {
        let children = arena.children(parent);
        let had_changes = !children.is_empty();
        for child in &children {
            self.sync_node(arena, *child);
        }
        self.layout.set_children(parent, &children);
        if had_changes {
            self.bump_revision();
        }
    }

    pub fn compute(&mut self, root: NodeId, width: u16, height: u16) -> Result<(), LayoutError> {
        let size_changed = self.last_width != Some(width) || self.last_height != Some(height);
        if !self.layout.is_dirty(root) && !size_changed {
            return Ok(());
        }
        if size_changed {
            self.layout.mark_dirty(root);
            self.last_width = Some(width);
            self.last_height = Some(height);
        }
        self.layout.compute_layout(root, width as f32, height as f32)?;
        self.results = self.layout.collect_results();
        self.generation = self.generation.wrapping_add(1);
        Ok(())
    }

    /// Force layout computation regardless of dirty state.
    pub fn compute_forced(&mut self, root: NodeId, width: u16, height: u16) -> Result<(), LayoutError> {
        self.layout.mark_dirty(root);
        self.compute(root, width, height)
    }

    pub fn results(&self) -> &HashMap<NodeId, LayoutResult> {
        &self.results
    }

    pub fn node_count(&self) -> usize {
        self.layout.node_count()
    }
}

/// Resolved layout for a single node after layout computation.
///
/// Stores the final position and size in terminal cell coordinates.
/// All values are integers — fractional Taffy output is rounded at the last step.
///
/// **Memory:** 48 bytes per node. Stack-allocated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LayoutResult {
    /// Absolute X position in terminal cells (from left edge).
    pub x: u16,
    /// Absolute Y position in terminal cells (from top edge).
    pub y: u16,
    /// Outer width including padding and border (in cells).
    /// Clamped to minimum 1 for terminal rendering.
    pub width: u16,
    /// Outer height including padding and border (in cells).
    /// Clamped to minimum 1 for terminal rendering.
    pub height: u16,
    /// Inner width excluding padding and border (in cells).
    pub content_width: u16,
    /// Inner height excluding padding and border (in cells).
    pub content_height: u16,
    /// Render order for z-indexing (higher = on top).
    pub order: u32,
    /// Scrollbar dimensions for scroll containers.
    pub scrollbar_width: u16,
    pub scrollbar_height: u16,
    /// Computed padding from Taffy (resolved from percentages to concrete values).
    pub padding_top: u16,
    pub padding_right: u16,
    pub padding_bottom: u16,
    pub padding_left: u16,
    /// Computed border from Taffy.
    pub border_top: u16,
    pub border_right: u16,
    pub border_bottom: u16,
    pub border_left: u16,
    /// Computed margin from Taffy.
    pub margin_top: u16,
    pub margin_right: u16,
    pub margin_bottom: u16,
    pub margin_left: u16,
}

impl LayoutResult {
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self { x, y, width, height, content_width: width, content_height: height, ..Default::default() }
    }

    /// Convert Taffy's f32 pixel output to terminal cell count.
    /// In BetterTUI, 1 "pixel" = 1 terminal cell.
    pub fn pixels_to_cells(pixels: f32) -> u16 {
        (pixels.round() as i32).max(0) as u16
    }

    /// Returns the bounding rectangle for this layout.
    pub fn rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.width, self.height)
    }

    /// Returns the content rectangle (excluding padding/border).
    pub fn content_rect(&self) -> Rect {
        Rect::new(self.x, self.y, self.content_width, self.content_height)
    }

    /// Returns the right edge (x + width).
    pub fn right(&self) -> u16 {
        self.x.saturating_add(self.width)
    }

    /// Returns the bottom edge (y + height).
    pub fn bottom(&self) -> u16 {
        self.y.saturating_add(self.height)
    }

    /// Check if a point is within this layout's bounds.
    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }
}

// ============================================================================
// BUILD
// ============================================================================

/// Minimum children to trigger binary search culling for scroll containers.
const BINARY_SEARCH_MIN_CHILDREN: usize = 32;

pub fn build_render_tree(arena: &NodeArena, layout_results: &HashMap<NodeId, LayoutResult>, tree: &mut RenderTree) {
    build_render_tree_with_viewport(arena, layout_results, None, tree)
}

pub fn build_render_tree_with_viewport(
    arena: &NodeArena,
    layout_results: &HashMap<NodeId, LayoutResult>,
    viewport: Option<&Viewport>,
    tree: &mut RenderTree,
) {
    tree.clear();
    let root = arena.root();
    build_node(arena, layout_results, root, &crate::tree::Style::default(), 0, 0, 1.0, 0, 0, viewport, tree);
}

#[allow(clippy::too_many_arguments)]
fn build_node(
    arena: &NodeArena,
    layout_results: &HashMap<NodeId, LayoutResult>,
    id: NodeId,
    parent_style: &crate::tree::Style,
    clip_x: u16,
    clip_y: u16,
    parent_opacity: f32,
    accum_tx: i32,
    accum_ty: i32,
    viewport: Option<&Viewport>,
    tree: &mut RenderTree,
) {
    let node = match arena.get(id) {
        Some(n) => n,
        None => return,
    };

    if node.visibility.display == crate::tree::Display::None {
        return;
    }

    let opacity = parent_opacity * node.visibility.opacity;

    if opacity == 0.0 {
        return;
    }

    let layout = layout_results.get(&id).cloned().unwrap_or_default();

    // Absolute screen coordinates for this node, accounting for accumulated
    // parent translations.  Two variants:
    //   - raw (signed i32): used for culling so that off-screen nodes with
    //     negative positions are correctly rejected.
    //   - clamped (u16): used for paint clip bounds which require non-negative.
    let node_raw_abs_x: i32 = layout.x as i32 + accum_tx + node.transform.translate_x;
    let node_raw_abs_y: i32 = layout.y as i32 + accum_ty + node.transform.translate_y;
    let node_abs_x = node_raw_abs_x.max(0) as u16;
    let node_abs_y = node_raw_abs_y.max(0) as u16;

    // Child accumulator: absolute offset passed to direct children so that
    // child.layout.x/y + child_accum = child's absolute screen position.
    // Subtracting scroll offsets here means children that are scrolled into
    // view land at the correct screen coordinates automatically.
    let child_accum_tx = accum_tx + layout.x as i32 - node.state.scroll_x + node.transform.translate_x;
    let child_accum_ty = accum_ty + layout.y as i32 - node.state.scroll_y + node.transform.translate_y;

    let (_current_viewport, child_viewport) = match viewport {
        None => (None, None),
        Some(vp) => {
            // Narrow the incoming viewport using this node's *absolute* bounds.
            // Taffy layout positions are parent-relative, so using layout.x/y
            // directly would mix coordinate spaces and produce wrong intersections
            // for nested containers.  Signed intersection handles nodes that are
            // partially or fully above the visible area (negative raw_abs positions).
            let narrowed = if flags_need_clip(node) {
                vp.intersect_signed(node_raw_abs_x, node_raw_abs_y, layout.width, layout.height)
            } else {
                Some(*vp)
            };

            match narrowed {
                None => return, // outside clip → cull entire subtree
                Some(nv) => {
                    if !nv.contains_rect_signed(node_raw_abs_x, node_raw_abs_y, layout.width, layout.height) {
                        return; // outside viewport → cull subtree
                    }
                    // Pass the absolute viewport to children unchanged.  Because
                    // child_accum already subtracts any scroll offset, each child's
                    // absolute screen position (layout.xy + child_accum) is compared
                    // directly against this absolute viewport — no separate offset step.
                    (Some(nv), Some(nv))
                }
            }
        }
    };

    let resolved_style = node.style.resolve(parent_style);

    let mut flags = PaintFlags::empty();
    if matches!(resolved_style.bg, Some(c) if c != crate::tree::Color::Default) {
        flags |= PaintFlags::BACKGROUND;
    }
    if resolved_style.border_style != crate::tree::BorderStyle::None {
        flags |= PaintFlags::BORDER;
    }
    if node.text.is_some() {
        flags |= PaintFlags::TEXT;
    }
    if node.overflow == Overflow::Hidden || node.overflow == Overflow::Scroll {
        flags |= PaintFlags::NEEDS_CLIP;
    }
    if !node.visibility.clip && node.overflow == Overflow::Visible {
        // no clip needed
    } else if node.visibility.clip {
        flags |= PaintFlags::NEEDS_CLIP;
    }

    let mut bounds = PaintBounds::new(layout.x, layout.y, layout.width.max(1), layout.height.max(1));
    bounds = bounds.with_padding(layout.padding_left, layout.padding_right, layout.padding_top, layout.padding_bottom);
    bounds = bounds.with_border(layout.border_top, layout.border_right, layout.border_bottom, layout.border_left);

    let clip = if flags.contains(PaintFlags::NEEDS_CLIP) {
        Some(ClipBounds::new(node_abs_x, node_abs_y, layout.width, layout.height))
    } else {
        None
    };

    let mut obj = RenderObject::new(id);
    obj.bounds = bounds;
    obj.clip = clip;
    obj.style = resolved_style;
    obj.opacity = opacity;
    obj.z_index = node.transform.z_index;
    obj.translate_x = accum_tx + node.transform.translate_x;
    obj.translate_y = accum_ty + node.transform.translate_y;
    obj.text = node.text.clone();
    obj.text_align = resolved_style.text_align;
    obj.text_wrap = node.text_wrap;
    obj.overflow = node.overflow;
    obj.flags = flags;

    tree.push(obj);

    let self_idx = tree.len() - 1;

    let child_clip_x = if flags.contains(PaintFlags::NEEDS_CLIP) { layout.x } else { clip_x };
    let child_clip_y = if flags.contains(PaintFlags::NEEDS_CLIP) { layout.y } else { clip_y };

    let child_ids: Vec<NodeId> = match child_viewport {
        Some(ref vp) if node.overflow == Overflow::Scroll && node.children.len() >= BINARY_SEARCH_MIN_CHILDREN => {
            let primary = determine_primary_axis(&node.layout);
            let mut positioned: Vec<PositionedChild> = node
                .children
                .iter()
                .filter_map(|&cid| {
                    let child_layout = layout_results.get(&cid)?;
                    // Compute each child's absolute screen position using child_accum so
                    // that the binary search operates in the same coordinate space as the
                    // absolute viewport passed in `vp`.
                    let (start, size) = match primary {
                        PrimaryAxis::Column => {
                            let abs = (child_layout.y as i32 + child_accum_ty).max(0) as u16;
                            (abs, child_layout.height)
                        }
                        PrimaryAxis::Row => {
                            let abs = (child_layout.x as i32 + child_accum_tx).max(0) as u16;
                            (abs, child_layout.width)
                        }
                    };
                    Some(PositionedChild { id: cid, start, size })
                })
                .collect();
            positioned.sort_by_key(|c| c.start);
            get_objects_in_viewport(vp, &positioned, primary)
        }
        _ => {
            let mut children: Vec<NodeId> = node.children.iter().copied().collect();
            children.sort_by_key(|&cid| arena.get(cid).map(|n| n.transform.z_index).unwrap_or(0));
            children
        }
    };

    let accumulated_parent_style = crate::tree::Style {
        fg: resolved_style.fg,
        bg: resolved_style.bg,
        underline_color: resolved_style.underline_color,
        bold: Some(resolved_style.bold),
        italic: Some(resolved_style.italic),
        underline: Some(resolved_style.underline),
        dim: Some(resolved_style.dim),
        strikethrough: Some(resolved_style.strikethrough),
        inverse: Some(resolved_style.inverse),
        hidden: Some(resolved_style.hidden),
        border_color: resolved_style.border_color,
        ..node.style
    };

    for &child_id in &child_ids {
        build_node(
            arena,
            layout_results,
            child_id,
            &accumulated_parent_style,
            child_clip_x,
            child_clip_y,
            opacity,
            child_accum_tx,
            child_accum_ty,
            child_viewport.as_ref(),
            tree,
        );
    }

    // Back-fill subtree_size now that all descendants have been pushed.
    let subtree_size = tree.len() - self_idx - 1;
    if let Some(obj) = tree.objects_mut().get_mut(self_idx) {
        obj.subtree_size = subtree_size;
    }
}

fn flags_need_clip(node: &crate::tree::RenderNode) -> bool {
    node.overflow == Overflow::Hidden || node.overflow == Overflow::Scroll || node.visibility.clip
}

fn determine_primary_axis(layout: &LayoutProps) -> PrimaryAxis {
    match layout.direction {
        FlexDirection::Row | FlexDirection::RowReverse => PrimaryAxis::Row,
        FlexDirection::Column | FlexDirection::ColumnReverse => PrimaryAxis::Column,
    }
}

#[cfg(test)]
mod measure_tests {
    use super::*;

    #[test]
    fn measure_empty_text() {
        let (width, lines) = measure_text("", f32::INFINITY);
        assert_eq!(width, 0.0);
        assert_eq!(lines, 1);
    }

    #[test]
    fn measure_ascii_text() {
        let (width, lines) = measure_text("hello", f32::INFINITY);
        assert_eq!(width, 5.0);
        assert_eq!(lines, 1);
    }

    #[test]
    fn measure_multiline_text() {
        let (width, lines) = measure_text("hello\nworld", f32::INFINITY);
        assert_eq!(width, 5.0);
        assert_eq!(lines, 2);
    }

    #[test]
    fn measure_cjk_text() {
        let (width, lines) = measure_text("\u{4e2d}\u{6587}", f32::INFINITY);
        assert_eq!(width, 4.0);
        assert_eq!(lines, 1);
    }

    #[test]
    fn measure_emoji_text() {
        let (width, lines) = measure_text("\u{1F600}", f32::INFINITY);
        assert_eq!(width, 2.0);
        assert_eq!(lines, 1);
    }

    #[test]
    fn measure_with_wrap() {
        let (width, lines) = measure_text("hello world", 6.0);
        assert_eq!(width, 6.0);
        assert_eq!(lines, 2);
    }

    #[test]
    fn count_lines_no_wrap() {
        assert_eq!(count_wrapped_lines("hello", 10), 1);
    }

    #[test]
    fn count_lines_simple_wrap() {
        assert_eq!(count_wrapped_lines("hello world", 5), 3);
    }

    #[test]
    fn count_lines_cjk_wrap() {
        let line = "\u{4e2d}\u{6587}\u{4e2d}\u{6587}\u{4e2d}\u{6587}";
        assert_eq!(count_wrapped_lines(line, 4), 4);
    }

    #[test]
    fn measure_text_long_word() {
        let (width, lines) = measure_text("supercalifragilisticexpialidocious", 10.0);
        assert_eq!(width, 10.0);
        assert!(lines >= 4);
    }

    #[test]
    fn measure_respects_available_width() {
        let (width, _) = measure_text("short", 100.0);
        assert_eq!(width, 5.0);
    }

    #[test]
    fn measure_max_content() {
        let (width, lines) = measure_text("hello\nworld\ntest", f32::INFINITY);
        assert_eq!(width, 5.0);
        assert_eq!(lines, 3);
    }
}

#[cfg(test)]
mod generation_tests {
    use super::*;

    #[test]
    fn layout_tree_sync_generation() {
        let sync = LayoutTreeSync::new();
        assert_eq!(sync.generation(), 0);
        assert_eq!(sync.revision(), 0);
    }
}

#[cfg(test)]
mod dirtied_callback_tests {
    use super::*;
    use crate::tree::NodeArena;

    #[test]
    fn dirtied_handler_fires_on_update_style() {
        let mut engine = LayoutEngine::new();
        let mut arena = NodeArena::new();
        let id = arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box));
        engine.register_container(id, &LayoutProps::default());

        let fired = Arc::new(AtomicBool::new(false));
        let fired_clone = fired.clone();
        let fired_id = Arc::new(Mutex::new(NodeId::default()));
        let fired_id_clone = fired_id.clone();
        engine.set_dirtied_handler(move |nid| {
            fired_clone.store(true, Ordering::SeqCst);
            *fired_id_clone.lock().unwrap() = nid;
        });

        engine.update_style(id, &LayoutProps { flex_grow: 2.0, ..Default::default() });
        assert!(fired.load(Ordering::SeqCst));
        assert_eq!(*fired_id.lock().unwrap(), id);
    }

    #[test]
    fn dirtied_handler_fires_on_mark_dirty() {
        let mut engine = LayoutEngine::new();
        let mut arena = NodeArena::new();
        let id = arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box));
        engine.register_container(id, &LayoutProps::default());

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        engine.set_dirtied_handler(move |_| {
            f.store(true, Ordering::SeqCst);
        });
        engine.mark_dirty(id);
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn dirtied_handler_fires_on_remove_node() {
        let mut engine = LayoutEngine::new();
        let mut arena = NodeArena::new();
        let id = arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box));
        engine.register_container(id, &LayoutProps::default());

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        engine.set_dirtied_handler(move |_| {
            f.store(true, Ordering::SeqCst);
        });
        engine.remove_node(id);
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn dirtied_handler_fires_on_update_text() {
        let mut engine = LayoutEngine::new();
        engine.register_text_node(NodeId::default(), &LayoutProps::default(), "hello");

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        engine.set_dirtied_handler(move |_| {
            f.store(true, Ordering::SeqCst);
        });
        engine.update_text(NodeId::default(), "world");
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn clear_dirtied_handler_stops_firing() {
        let mut engine = LayoutEngine::new();
        let mut arena = NodeArena::new();
        let id = arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box));
        engine.register_container(id, &LayoutProps::default());

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        engine.set_dirtied_handler(move |_| {
            f.store(true, Ordering::SeqCst);
        });
        engine.clear_dirtied_handler();
        engine.mark_dirty(id);
        assert!(!fired.load(Ordering::SeqCst));
    }

    #[test]
    fn dirtied_handler_fires_on_reset_node() {
        let mut engine = LayoutEngine::new();
        let mut arena = NodeArena::new();
        let id = arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box));
        engine.register_container(id, &LayoutProps::default());

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        engine.set_dirtied_handler(move |_| {
            f.store(true, Ordering::SeqCst);
        });
        engine.reset_node(id);
        assert!(fired.load(Ordering::SeqCst));
    }
}

#[cfg(test)]
mod measure_callback_tests {
    use super::*;

    #[test]
    fn set_and_has_measure_callback() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        assert!(!engine.has_measure_callback(id));

        engine.set_measure_callback(id, |_, _, _, _| MeasureResult { width: 10.0, height: 5.0 });
        assert!(engine.has_measure_callback(id));
    }

    #[test]
    fn remove_measure_callback() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.set_measure_callback(id, |_, _, _, _| MeasureResult { width: 10.0, height: 5.0 });
        assert!(engine.has_measure_callback(id));

        engine.remove_measure_callback(id);
        assert!(!engine.has_measure_callback(id));
    }

    #[test]
    fn measure_callback_invoked_during_compute() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.register_text_node(
            id,
            &LayoutProps { width: Some(Sizing::Points(50.0)), height: Some(Sizing::Auto), ..Default::default() },
            "hello",
        );

        engine.set_measure_callback(id, |known_w, known_h, _avail_w, _avail_h| MeasureResult {
            width: known_w.unwrap_or(20.0),
            height: known_h.unwrap_or(10.0),
        });

        // Force dirty and compute
        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();

        // Callback returned width=50 (known) and height=10 (default)
        let results = engine.collect_results();
        let result = results.get(&id).unwrap();
        assert_eq!(result.width, 50);
        assert_eq!(result.height, 10);
    }

    #[test]
    fn measure_callback_overrides_text_measurement() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();

        // Register with text, but override with callback.
        // Use Auto sizing so the callback fully controls the result.
        engine.register_text_node(
            id,
            &LayoutProps { width: Some(Sizing::Auto), height: Some(Sizing::Auto), ..Default::default() },
            "this is long text that would measure wide",
        );

        engine.set_measure_callback(id, |_, _, _, _| MeasureResult { width: 5.0, height: 1.0 });
        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();

        let results = engine.collect_results();
        let result = results.get(&id).unwrap();
        // Callback returned (5, 1), so width should be 5, height 1
        assert_eq!(result.width, 5);
        assert_eq!(result.height, 1);
    }
}

#[cfg(test)]
mod config_tests {
    use super::*;

    #[test]
    fn default_config() {
        let config = LayoutConfig::default();
        assert_eq!(config.point_scale_factor, 1.0);
        assert!(!config.use_web_defaults);
    }

    #[test]
    fn set_and_get_config() {
        let mut engine = LayoutEngine::new();
        let config = LayoutConfig { point_scale_factor: 2.0, use_web_defaults: true };
        engine.set_config(config);
        assert_eq!(engine.config().point_scale_factor, 2.0);
        assert!(engine.config().use_web_defaults);
    }
}

#[cfg(test)]
mod new_style_props_tests {
    use super::*;

    #[test]
    fn layout_props_default_aspect_ratio() {
        let props = LayoutProps::default();
        assert_eq!(props.aspect_ratio, None);
    }

    #[test]
    fn layout_props_aspect_ratio_set() {
        let props = LayoutProps { aspect_ratio: Some(2.0), ..Default::default() };
        assert_eq!(props.aspect_ratio, Some(2.0));
    }

    #[test]
    fn position_static_variant() {
        let pos = Position::Static;
        match pos {
            Position::Static => {}
            _ => panic!("expected Static"),
        }
    }

    #[test]
    fn layout_overflow_default() {
        assert_eq!(LayoutOverflow::default(), LayoutOverflow::Visible);
    }

    #[test]
    fn box_sizing_default() {
        assert_eq!(BoxSizing::default(), BoxSizing::ContentBox);
    }

    #[test]
    fn map_layout_overflow_roundtrip() {
        let _ = map_layout_overflow(LayoutOverflow::Visible);
        let _ = map_layout_overflow(LayoutOverflow::Hidden);
        let _ = map_layout_overflow(LayoutOverflow::Scroll);
    }

    #[test]
    fn map_box_sizing_roundtrip() {
        let _ = map_box_sizing(BoxSizing::BorderBox);
        let _ = map_box_sizing(BoxSizing::ContentBox);
    }
}

#[cfg(test)]
mod node_operation_tests {
    use super::*;
    use crate::tree::NodeArena;

    #[test]
    fn has_new_layout_after_compute() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.register_container(
            id,
            &LayoutProps {
                width: Some(Sizing::Points(100.0)),
                height: Some(Sizing::Points(50.0)),
                ..Default::default()
            },
        );

        assert!(!engine.has_new_layout(id));
        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();
        assert!(engine.has_new_layout(id));
    }

    #[test]
    fn reset_node_clears_style() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.register_container(id, &LayoutProps { flex_grow: 2.0, ..Default::default() });
        engine.reset_node(id);

        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();

        // After reset, style should be default
        let results = engine.collect_results();
        let result = results.get(&id).unwrap();
        // Default style has flex_grow=0, so width/height should be 0 in 80x24
        assert!(result.width <= 80);
    }

    #[test]
    fn copy_style_transfers_props() {
        let mut engine = LayoutEngine::new();
        let id_from = NodeId::default();
        let id_to = {
            let mut arena = NodeArena::new();
            arena.insert(crate::tree::RenderNode::new(crate::tree::NodeKind::Box))
        };

        engine.register_container(
            id_from,
            &LayoutProps {
                flex_grow: 3.0,
                width: Some(Sizing::Points(200.0)),
                height: Some(Sizing::Points(100.0)),
                ..Default::default()
            },
        );
        engine.register_container(id_to, &LayoutProps::default());

        engine.copy_style(id_from, id_to);

        // Both should now have same layout positions
        engine.mark_dirty(id_from);
        engine.mark_dirty(id_to);
        engine.compute_layout(id_from, 80.0, 24.0).unwrap();
        engine.compute_layout(id_to, 80.0, 24.0).unwrap();

        let results = engine.collect_results();
        let from_result = results.get(&id_from).unwrap();
        let to_result = results.get(&id_to).unwrap();
        assert_eq!(from_result.width, to_result.width);
        assert_eq!(from_result.height, to_result.height);
    }

    #[test]
    fn get_computed_left_and_top() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.register_container(
            id,
            &LayoutProps {
                width: Some(Sizing::Points(100.0)),
                height: Some(Sizing::Points(50.0)),
                ..Default::default()
            },
        );
        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();

        // Left and top should be 0 for root
        assert_eq!(engine.get_computed_left(id), 0.0);
        assert_eq!(engine.get_computed_top(id), 0.0);
    }

    #[test]
    fn get_computed_edge_for_unregistered_node() {
        let engine = LayoutEngine::new();
        assert_eq!(engine.get_computed_left(NodeId::default()), 0.0);
        assert_eq!(engine.get_computed_top(NodeId::default()), 0.0);
    }
}

#[cfg(test)]
mod align_content_tests {
    use super::*;

    #[test]
    fn align_content_default_is_none() {
        let props = LayoutProps::default();
        assert!(props.align_content.is_none());
    }

    #[test]
    fn align_content_variants() {
        let props = LayoutProps { align_content: Some(AlignContent::Center), ..Default::default() };
        assert_eq!(props.align_content, Some(AlignContent::Center));
    }

    #[test]
    fn map_align_content_all_variants() {
        let _ = map_align_content(AlignContent::FlexStart);
        let _ = map_align_content(AlignContent::FlexEnd);
        let _ = map_align_content(AlignContent::Center);
        let _ = map_align_content(AlignContent::Stretch);
        let _ = map_align_content(AlignContent::SpaceBetween);
        let _ = map_align_content(AlignContent::SpaceAround);
    }
}

#[cfg(test)]
mod layout_result_extended_tests {
    use super::*;

    #[test]
    fn layout_result_has_order_field() {
        let mut engine = LayoutEngine::new();
        let id = NodeId::default();
        engine.register_container(
            id,
            &LayoutProps {
                width: Some(Sizing::Points(50.0)),
                height: Some(Sizing::Points(30.0)),
                ..Default::default()
            },
        );
        engine.mark_dirty(id);
        engine.compute_layout(id, 80.0, 24.0).unwrap();

        let results = engine.collect_results();
        let result = results.get(&id).unwrap();
        // Order should be 0 for root node
        assert_eq!(result.order, 0);
    }

    #[test]
    fn layout_result_has_scrollbar_and_margin_fields() {
        let result = LayoutResult::new(10, 20, 30, 40);
        // Default values should be 0
        assert_eq!(result.scrollbar_width, 0);
        assert_eq!(result.scrollbar_height, 0);
        assert_eq!(result.margin_top, 0);
        assert_eq!(result.margin_right, 0);
        assert_eq!(result.margin_bottom, 0);
        assert_eq!(result.margin_left, 0);
    }
}