azul-layout 0.0.12

Layout solver + font and image loader the Azul GUI 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
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
//! Handling Viewport Resizing and Layout Thrashing
//!
//! The viewport size is a fundamental input to the entire layout process.
//! A change in viewport size must trigger a relayout.
//!
//! 1. The `layout_document` function takes the `viewport` as an argument. The `LayoutCache` stores
//!    the `viewport` from the previous frame.
//! 2. The `reconcile_and_invalidate` function detects that the viewport has changed size
//! 3. This single change—marking the root as a layout root—forces a full top-down pass
//!    (`calculate_layout_for_subtree` starting from the root). This correctly recalculates all
//!    percentage-based sizes and repositions all elements according to the new viewport dimensions.
//! 4. The intrinsic size calculation (bottom-up) can often be skipped, as it's independent of the
//!    container size, which is a significant optimization.

use std::{
    collections::{BTreeMap, BTreeSet, HashMap},
    hash::{DefaultHasher, Hash, Hasher},
};

/// Floating-point comparison epsilon for cache size lookups.
/// Controls the tolerance for cache hit matching in the per-node multi-slot cache.
const CACHE_SIZE_EPSILON: f32 = 0.1;

use azul_core::{
    diff::NodeDataFingerprint,
    dom::{FormattingContext, NodeId, NodeType},
    geom::{LogicalPosition, LogicalRect, LogicalSize},
    styled_dom::{StyledDom, StyledNode},
};
use azul_css::{
    css::CssPropertyValue,
    props::{
        layout::{
            LayoutDisplay, LayoutHeight, LayoutOverflow,
            LayoutPosition, LayoutWritingMode,
        },
        property::{CssProperty, CssPropertyType},
        style::StyleTextAlign,
    },
    LayoutDebugMessage, LayoutDebugMessageType,
};

use crate::{
    font_traits::{FontLoaderTrait, ParsedFontTrait, TextLayoutCache},
    solver3::{
        fc::{self, layout_formatting_context, LayoutConstraints, OverflowBehavior},
        geometry::PositionedRectangle,
        getters::{
            get_css_height, get_display_property, get_overflow_x,
            get_overflow_y, get_scrollbar_gutter_property, get_text_align, get_white_space_property, get_writing_mode,
            MultiValue,
        },
        layout_tree::{
            get_display_type, is_block_level, AnonymousBoxType, DirtyFlag, LayoutNode, LayoutNodeHot, LayoutTreeBuilder, SubtreeHash,
        },
        positioning::get_position_type,
        scrollbar::ScrollbarRequirements,
        sizing::calculate_used_size_for_node,
        LayoutContext, LayoutError, LayoutTree, Result,
    },
    text3::cache::AvailableSpace as Text3AvailableSpace,
};

// ============================================================================
// Per-Node Multi-Slot Cache (inspired by Taffy's 9+1 slot cache architecture)
//
// Instead of a global BTreeMap keyed by (node_index, available_size), each node
// gets its own deterministic cache with 9 measurement slots + 1 full layout slot.
// This eliminates O(log n) lookups, prevents slot collisions between MinContent/
// MaxContent/Definite measurements, and cleanly separates sizing from positioning.
//
// Reference: https://github.com/DioxusLabs/taffy — Cache struct in src/tree/cache.rs
// Azul improvement: cache is EXTERNAL (Vec<NodeCache> parallel to LayoutTree.nodes)
// rather than stored on the node, keeping LayoutNode slim and avoiding &mut tree
// for cache operations.
// ============================================================================

/// Determines whether `calculate_layout_for_subtree` should only compute
/// the node's size (for parent's sizing pass) or perform full layout
/// including child positioning.
///
/// Inspired by Taffy's `RunMode` enum. The two-mode approach enables the
/// classic CSS two-pass layout: Pass 1 (`ComputeSize`) measures all children,
/// Pass 2 (`PerformLayout`) positions them using the measured sizes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComputeMode {
    /// Only compute the node's border-box size and baseline.
    /// Does NOT store child positions. Used in BFC Pass 1 (sizing).
    ComputeSize,
    /// Compute size AND position all children.
    /// Stores the full layout result including child positions.
    /// Used in BFC Pass 2 (positioning) and as the final layout step.
    PerformLayout,
}

/// Constraint classification for deterministic cache slot selection.
///
/// Inspired by Taffy's `AvailableSpace` enum. Each constraint type maps to a
/// different cache slot, preventing collisions between e.g. `MinContent` and
/// Definite measurements of the same node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AvailableWidthType {
    /// A definite pixel value (or percentage resolved to pixels).
    Definite,
    /// Shrink-to-fit: the smallest size that doesn't cause overflow.
    MinContent,
    /// Use all available space: the largest size the content can use.
    MaxContent,
}

/// Cache entry for sizing (`ComputeSize` mode) — stores NO positions.
///
/// This is the lightweight entry stored in the 9 measurement slots.
/// It records what constraints were provided and what size resulted,
/// enabling Taffy's "result matches request" optimization.
#[derive(Copy, Debug, Clone)]
pub struct SizingCacheEntry {
    /// The available size that was provided as input.
    pub available_size: LogicalSize,
    /// The computed border-box size (output).
    pub result_size: LogicalSize,
    /// Baseline for inline alignment (if applicable).
    pub baseline: Option<f32>,
    /// First child's escaped top margin (CSS 2.2 § 8.3.1).
    pub escaped_top_margin: Option<f32>,
    /// Last child's escaped bottom margin (CSS 2.2 § 8.3.1).
    pub escaped_bottom_margin: Option<f32>,
}

/// Cache entry for full layout (`PerformLayout` mode).
///
/// This is the single "final layout" slot. It includes child positions
/// (relative to parent's content-box) and overflow/scrollbar info.
#[derive(Debug, Clone)]
pub struct LayoutCacheEntry {
    /// The available size that was provided as input.
    pub available_size: LogicalSize,
    /// The computed border-box size (output).
    pub result_size: LogicalSize,
    /// Content overflow size (for scrolling).
    pub content_size: LogicalSize,
    /// Child positions relative to parent's content-box (NOT absolute).
    pub child_positions: Vec<(usize, LogicalPosition)>,
    /// First child's escaped top margin.
    pub escaped_top_margin: Option<f32>,
    /// Last child's escaped bottom margin.
    pub escaped_bottom_margin: Option<f32>,
    /// Scrollbar requirements for this node.
    pub scrollbar_info: ScrollbarRequirements,
}

/// Per-node cache entry with 9 measurement slots + 1 full layout slot.
///
/// Inspired by Taffy's `Cache` struct (9+1 slots per node). The deterministic
/// slot index is computed from the constraint combination, so entries never
/// clobber each other (unlike the old global `BTreeMap` where fixed-point
/// collisions were possible).
///
/// NOT stored on `LayoutNode` — lives in the external `LayoutCacheMap`.
#[derive(Debug, Clone)]
pub struct NodeCache {
    /// 9 measurement slots (Taffy's deterministic scheme):
    /// - Slot 0: both dimensions known
    /// - Slots 1-2: only width known (MaxContent/Definite vs `MinContent`)
    /// - Slots 3-4: only height known (MaxContent/Definite vs `MinContent`)
    /// - Slots 5-8: neither known (2×2 combos of width/height constraint types)
    pub measure_entries: [Option<SizingCacheEntry>; 9],

    /// 1 full layout slot (with child positions, overflow, baseline).
    /// Only populated after `PerformLayout`, not after `ComputeSize`.
    pub layout_entry: Option<LayoutCacheEntry>,

    /// Fast check for dirty propagation (Taffy optimization).
    /// When true, all slots are empty — ancestors are also dirty.
    pub is_empty: bool,
}

impl Default for NodeCache {
    fn default() -> Self {
        Self {
            measure_entries: [None, None, None, None, None, None, None, None, None],
            layout_entry: None,
            is_empty: true, // fresh cache is empty/dirty
        }
    }
}

impl NodeCache {
    /// Clear all cache entries, marking this node as dirty.
    pub fn clear(&mut self) {
        self.measure_entries = [None, None, None, None, None, None, None, None, None];
        self.layout_entry = None;
        self.is_empty = true;
    }

    /// Compute the deterministic slot index from constraint dimensions.
    ///
    /// This is Taffy's slot selection scheme: given whether width/height are
    /// "known" (definite constraint provided by parent) and what type of
    /// constraint applies to the unknown dimension(s), we get a unique slot 0–8.
    ///
    /// TODO(superplan): currently unused — the layout cache only ever touches
    /// slot 0 (see the `get_size(0, ..)` / `store_size(0, ..)` call sites). This
    /// is the intended entry point for wiring the full 9-slot scheme.
    #[must_use] pub fn slot_index(
        width_known: bool,
        height_known: bool,
        width_type: AvailableWidthType,
        height_type: AvailableWidthType,
    ) -> usize {
        match (width_known, height_known) {
            (true, true) => 0,
            (true, false) => {
                if width_type == AvailableWidthType::MinContent { 2 } else { 1 }
            }
            (false, true) => {
                if height_type == AvailableWidthType::MinContent { 4 } else { 3 }
            }
            (false, false) => {
                let w = usize::from(width_type == AvailableWidthType::MinContent);
                let h = usize::from(height_type == AvailableWidthType::MinContent);
                5 + w * 2 + h
            }
        }
    }

    /// Look up a sizing cache entry, implementing Taffy's "result matches request"
    /// optimization: if the caller provides the result size as a known dimension
    /// (common in Pass1→Pass2 transitions), it's still a cache hit.
    #[must_use] pub fn get_size(&self, slot: usize, known_dims: LogicalSize) -> Option<&SizingCacheEntry> {
        let entry = self.measure_entries[slot].as_ref()?;
        // Exact match on input constraints
        if (known_dims.width - entry.available_size.width).abs() < CACHE_SIZE_EPSILON
            && (known_dims.height - entry.available_size.height).abs() < CACHE_SIZE_EPSILON
        {
            return Some(entry);
        }
        // "Result matches request" — if the caller provides the result size
        // as a known dimension, it's still a hit. This is the key optimization
        // that makes two-pass layout O(n): Pass 1 measures a node, Pass 2
        // provides the measured size as a constraint → automatic cache hit.
        if (known_dims.width - entry.result_size.width).abs() < CACHE_SIZE_EPSILON
            && (known_dims.height - entry.result_size.height).abs() < CACHE_SIZE_EPSILON
        {
            return Some(entry);
        }
        None
    }

    /// Store a sizing result in the given slot.
    pub const fn store_size(&mut self, slot: usize, entry: SizingCacheEntry) {
        self.measure_entries[slot] = Some(entry);
        self.is_empty = false;
    }

    /// Look up the full layout cache entry.
    #[must_use] pub fn get_layout(&self, known_dims: LogicalSize) -> Option<&LayoutCacheEntry> {
        let entry = self.layout_entry.as_ref()?;
        if (known_dims.width - entry.available_size.width).abs() < CACHE_SIZE_EPSILON
            && (known_dims.height - entry.available_size.height).abs() < CACHE_SIZE_EPSILON
        {
            return Some(entry);
        }
        // "Result matches request" for layout too
        if (known_dims.width - entry.result_size.width).abs() < CACHE_SIZE_EPSILON
            && (known_dims.height - entry.result_size.height).abs() < CACHE_SIZE_EPSILON
        {
            return Some(entry);
        }
        None
    }

    /// Store a full layout result.
    pub fn store_layout(&mut self, entry: LayoutCacheEntry) {
        self.layout_entry = Some(entry);
        self.is_empty = false;
    }
}

/// External layout cache, parallel to `LayoutTree.nodes`.
///
/// `cache_map.entries[i]` holds the cache for `LayoutTree.nodes[i]`.
/// Stored on `LayoutCache` (persists across frames).
///
/// This is Azul's improvement over Taffy's on-node cache:
/// - `LayoutNode` stays slim (0 bytes overhead)
/// - No `&mut tree` needed to read/write cache entries
/// - Cache can be resized independently after reconciliation
/// - O(1) indexed lookup (Vec) instead of O(log n) (`BTreeMap`)
#[derive(Debug, Clone, Default)]
pub struct LayoutCacheMap {
    pub entries: Vec<NodeCache>,
}

impl LayoutCacheMap {
    /// Resize to match tree length after reconciliation.
    /// New nodes get empty (dirty) caches. Removed nodes' caches are dropped.
    pub fn resize_to_tree(&mut self, tree_len: usize) {
        self.entries.resize_with(tree_len, NodeCache::default);
    }

    /// O(1) lookup by layout tree index.
    #[inline]
    #[must_use] pub fn get(&self, node_index: usize) -> &NodeCache {
        &self.entries[node_index]
    }

    /// O(1) mutable lookup by layout tree index.
    #[inline]
    pub fn get_mut(&mut self, node_index: usize) -> &mut NodeCache {
        &mut self.entries[node_index]
    }

    /// Invalidate a node and propagate dirty flags upward through ancestors.
    ///
    /// Implements Taffy's early-stop optimization: propagation halts at the
    /// first ancestor whose cache is already empty (i.e., already dirty).
    /// This prevents redundant O(depth) propagation when multiple children
    /// of the same parent are dirtied.
    pub fn mark_dirty(&mut self, node_index: usize, tree: &[LayoutNodeHot]) {
        if node_index >= self.entries.len() {
            return;
        }
        let cache = &mut self.entries[node_index];
        if cache.is_empty {
            return; // Already dirty → ancestors are too
        }
        cache.clear();

        // Propagate upward (Taffy's early-stop optimization)
        let mut current = tree.get(node_index).and_then(|n| n.parent);
        while let Some(parent_idx) = current {
            if parent_idx >= self.entries.len() {
                break;
            }
            let parent_cache = &mut self.entries[parent_idx];
            if parent_cache.is_empty {
                break; // Stop early — ancestor already dirty
            }
            parent_cache.clear();
            current = tree.get(parent_idx).and_then(|n| n.parent);
        }
    }
}

/// The persistent cache that holds the layout state between frames.
#[derive(Debug, Clone, Default)]
pub struct LayoutCache {
    /// The fully laid-out tree from the previous frame. This is our primary cache.
    pub tree: Option<LayoutTree>,
    /// The final, absolute positions of all nodes from the previous frame.
    pub calculated_positions: super::PositionVec,
    /// The viewport size from the last layout pass, used to detect resizes.
    pub viewport: Option<LogicalRect>,
    /// Stable scroll IDs computed from `node_data_hash` (layout index -> scroll ID)
    pub scroll_ids: HashMap<usize, u64>,
    /// Mapping from scroll ID to DOM `NodeId` for hit testing
    pub scroll_id_to_node_id: HashMap<u64, NodeId>,
    /// CSS counter values for each node and counter name.
    /// Key: (`layout_index`, `counter_name`), Value: counter value
    /// This stores the computed counter values after processing counter-reset and
    /// counter-increment.
    pub counters: HashMap<(usize, String), i32>,
    /// Cache of positioned floats for each BFC node (`layout_index` -> `FloatingContext`).
    /// This persists float positions across multiple layout passes, ensuring IFC
    /// children always have access to correct float exclusions even when layout is
    /// recalculated.
    pub float_cache: HashMap<usize, fc::FloatingContext>,
    /// Per-node multi-slot cache (inspired by Taffy's 9+1 architecture).
    /// External to `LayoutTree` — indexed by node index for O(1) lookup.
    /// Persists across frames; resized after reconciliation.
    pub cache_map: LayoutCacheMap,
    /// Snapshot of `calculated_positions` from the previous frame, used by the
    /// compositor to compute damage rects (old bounds vs new bounds).
    pub previous_positions: super::PositionVec,
    /// Cached display list keyed by `(root_subtree_hash, viewport)`.
    /// When the reconciled tree has the same root `subtree_hash` AND
    /// the same viewport as the cached one, the display list is
    /// returned as-is — skipping layout, positioning, and
    /// display-list generation entirely. Cleared whenever
    /// `mark_dirty` fires on any node (since the root's upstream
    /// invalidation chain clears its ancestors).
    pub cached_display_list: Option<(SubtreeHash, LogicalRect, super::display_list::DisplayList)>,
    /// Raw pointer of the `StyledDom` from the previous layout pass. When the
    /// same `&StyledDom` reference is passed again AND the viewport is unchanged,
    /// skip reconcile entirely and return the cached display list (saves ~0.8 ms).
    pub prev_dom_ptr: usize,
    pub prev_viewport: LogicalRect,
}

/// Approximate heap-byte breakdown of the solver3 `LayoutCache`.
#[derive(Copy, Debug, Clone, Default)]
pub struct Solver3CacheMemoryReport {
    pub tree_bytes: usize,
    pub tree_report: Option<super::layout_tree::LayoutTreeMemoryReport>,
    pub calculated_positions_bytes: usize,
    pub previous_positions_bytes: usize,
    pub scroll_ids_bytes: usize,
    pub scroll_id_to_node_id_bytes: usize,
    pub counters_bytes: usize,
    pub float_cache_bytes: usize,
    pub cache_map_bytes: usize,
    pub cached_display_list_bytes: usize,
}

impl Solver3CacheMemoryReport {
    #[must_use] pub const fn total_bytes(&self) -> usize {
        self.tree_bytes
            + self.calculated_positions_bytes
            + self.previous_positions_bytes
            + self.scroll_ids_bytes
            + self.scroll_id_to_node_id_bytes
            + self.counters_bytes
            + self.float_cache_bytes
            + self.cache_map_bytes
            + self.cached_display_list_bytes
    }
}

impl LayoutCache {
    /// Drop all incremental-reuse state so the next `layout_document` lays the
    /// DOM out from scratch (cold path), as if no previous frame existed.
    ///
    /// Required before laying out a DOM whose `NodeIds` are NOT a stable evolution
    /// of whatever this (shared) cache last held — namely `VirtualView` / iframe
    /// child DOMs, which their callbacks rebuild wholesale on every invocation.
    /// Incremental reconciliation matches/reuses subtrees by `NodeId` + subtree
    /// hash; on a wholesale rebuild those `NodeIds` are reassigned, so reusing the
    /// prior tree can graft `NodeIds` that no longer exist in the new `StyledDom`
    /// (panic: out-of-bounds `node_data` index when the DOM shrinks — e.g. the map
    /// dropping tiles on zoom-out).
    pub fn reset_incremental(&mut self) {
        self.tree = None;
        self.cache_map = LayoutCacheMap::default();
        self.cached_display_list = None;
        self.prev_dom_ptr = 0;
        self.counters.clear();
        self.float_cache.clear();
    }

    /// Approximate heap bytes retained by this `LayoutCache`.
    #[must_use] pub fn memory_report(&self) -> Solver3CacheMemoryReport {
        let tree_report = self.tree.as_ref().map(LayoutTree::memory_report);
        let tree_bytes = tree_report.as_ref().map_or(0, super::layout_tree::LayoutTreeMemoryReport::total_bytes);
        // cache_map: Vec<NodeCache>; NodeCache has 9 Option<SizingCacheEntry>
        // + 1 Option<LayoutCacheEntry>. Count filled layout entries' child_positions.
        let mut cache_map_bytes = self.cache_map.entries.capacity()
            * size_of::<NodeCache>();
        for e in &self.cache_map.entries {
            if let Some(le) = &e.layout_entry {
                cache_map_bytes += le.child_positions.capacity()
                    * size_of::<(usize, LogicalPosition)>();
            }
        }
        Solver3CacheMemoryReport {
            tree_bytes,
            tree_report,
            calculated_positions_bytes: self.calculated_positions.len()
                * size_of::<LogicalPosition>(),
            previous_positions_bytes: self.previous_positions.len()
                * size_of::<LogicalPosition>(),
            scroll_ids_bytes: self.scroll_ids.len()
                * (size_of::<usize>() + size_of::<u64>()),
            scroll_id_to_node_id_bytes: self.scroll_id_to_node_id.len()
                * (size_of::<u64>() + size_of::<NodeId>()),
            counters_bytes: self.counters.iter().map(|((_, name), _)| {
                size_of::<(usize, String)>()
                    + size_of::<i32>()
                    + name.capacity()
            }).sum(),
            float_cache_bytes: self.float_cache.len() * 256, // conservative per-FC
            cache_map_bytes,
            cached_display_list_bytes: if self.cached_display_list.is_some() { 2048 } else { 0 },
        }
    }
}

/// The result of a reconciliation pass.
#[derive(Debug, Default)]
pub struct ReconciliationResult {
    /// Set of nodes whose intrinsic size needs to be recalculated (bottom-up pass).
    pub intrinsic_dirty: BTreeSet<usize>,
    /// Set of layout roots whose subtrees need a new top-down layout pass.
    pub layout_roots: BTreeSet<usize>,
    /// Set of nodes that only need a paint/display-list update (no relayout).
    pub paint_dirty: BTreeSet<usize>,
}

impl ReconciliationResult {
    /// Checks if any layout or paint work is needed.
    #[must_use] pub fn is_clean(&self) -> bool {
        self.intrinsic_dirty.is_empty()
            && self.layout_roots.is_empty()
            && self.paint_dirty.is_empty()
    }

    /// Returns true if full layout work is needed for at least one node.
    #[must_use] pub fn needs_layout(&self) -> bool {
        !self.intrinsic_dirty.is_empty() || !self.layout_roots.is_empty()
    }

    /// Returns true if only paint work is needed (no layout).
    #[must_use] pub fn needs_paint_only(&self) -> bool {
        !self.needs_layout() && !self.paint_dirty.is_empty()
    }
}

/// After dirty subtrees are laid out, this repositions their clean siblings
/// without recalculating their internal layout. This is a critical optimization.
///
/// This function acts as a dispatcher, inspecting the parent's formatting context
/// and calling the appropriate repositioning algorithm. For complex layout modes
/// like Flexbox or Grid, this optimization is skipped, as a full relayout is
/// often required to correctly recalculate spacing and sizing for all siblings.
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't merge)
pub fn reposition_clean_subtrees(
    styled_dom: &StyledDom,
    tree: &LayoutTree,
    layout_roots: &BTreeSet<usize>,
    calculated_positions: &mut super::PositionVec,
) {
    // Find the unique parents of all dirty layout roots. These are the containers
    // where sibling positions need to be adjusted.
    let mut parents_to_reposition = BTreeSet::new();
    for &root_idx in layout_roots {
        if let Some(parent_idx) = tree.get(root_idx).and_then(|n| n.parent) {
            parents_to_reposition.insert(parent_idx);
        }
    }

    for parent_idx in parents_to_reposition {
        let Some(parent_node) = tree.get(parent_idx) else {
            continue;
        };

        // Dispatch to the correct repositioning logic based on the parent's layout mode.
        match parent_node.formatting_context {
            // Cases that use simple block-flow stacking can be optimized.
            FormattingContext::Block { .. } | FormattingContext::TableRowGroup => {
                reposition_block_flow_siblings(
                    styled_dom,
                    parent_idx,
                    tree,
                    layout_roots,
                    calculated_positions,
                );
            }

            FormattingContext::Flex | FormattingContext::Grid => {
                // Taffy handles this, so if a child is dirty, the parent would have
                // already been marked as a layout_root and re-laid out by Taffy.
                // We do nothing here for Flex or Grid.
            }

            FormattingContext::Table | FormattingContext::TableRow => {
                // TODO: Table layout is interdependent. A change in one cell's size
                // can affect the entire column's width or row's height, requiring a
                // full relayout of the table. This optimization is skipped.
            }

            // Other contexts either don't contain children in a way that this
            // optimization applies (e.g., Inline, TableCell) or are handled by other
            // layout mechanisms (e.g., OutOfFlow).
            _ => { /* Do nothing */ }
        }
    }
}

/// Convert `LayoutOverflow` to `OverflowBehavior`
/// CSS Overflow Module Level 3: initial value of `overflow` is `visible`.
// +spec:overflow:3a6297 - initial value 'visible', maps hidden/scroll/auto overflow behaviors
fn to_overflow_behavior(overflow: MultiValue<LayoutOverflow>) -> fc::OverflowBehavior {
    match overflow.unwrap_or(LayoutOverflow::Visible) {
        LayoutOverflow::Visible => fc::OverflowBehavior::Visible,
        LayoutOverflow::Hidden | LayoutOverflow::Clip => fc::OverflowBehavior::Hidden,
        LayoutOverflow::Scroll => fc::OverflowBehavior::Scroll,
        LayoutOverflow::Auto => fc::OverflowBehavior::Auto,
    }
}

/// Convert `StyleTextAlign` to `fc::TextAlign`
// +spec:text-alignment-spacing:43ea0a - text-align-all shorthand: aligns all lines except last (overridden by text-align-last)
const fn style_text_align_to_fc(text_align: StyleTextAlign) -> fc::TextAlign {
    match text_align {
        StyleTextAlign::Start | StyleTextAlign::Left => fc::TextAlign::Start,
        StyleTextAlign::End | StyleTextAlign::Right => fc::TextAlign::End,
        StyleTextAlign::Center => fc::TextAlign::Center,
        StyleTextAlign::Justify => fc::TextAlign::Justify,
    }
}

/// Collects DOM child IDs from the node hierarchy into a Vec.
///
/// This is a helper function that flattens the sibling iteration into a simple loop.
/// Children with `display: none` are filtered out since they generate no boxes.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
#[must_use] pub fn collect_children_dom_ids(styled_dom: &StyledDom, parent_dom_id: NodeId) -> Vec<NodeId> {
    let hierarchy_container = styled_dom.node_hierarchy.as_container();
    let mut children = Vec::new();

    let Some(hierarchy_item) = hierarchy_container.get(parent_dom_id) else {
        return children;
    };

    let Some(mut child_id) = hierarchy_item.first_child_id(parent_dom_id) else {
        // DEBUG (2026-06-02 children-None): first_child_id returned None for this
        // parent → 0xC0000000 marker @0x40540+parent*4. REVERT before commit.
        unsafe {
            let pi = parent_dom_id.index();
            if pi < 8 { crate::az_mark((0x40540 + pi * 4) as u32, (0xC000_0000u32)); }
        }
        return children;
    };

    // +spec:display-property:9f02c6 - display:none elements generate no boxes
    // +spec:display-property:3b507e - display:none excludes subtree from box tree
    if get_display_type(styled_dom, child_id) != LayoutDisplay::None {
        children.push(child_id);
    }
    while let Some(hierarchy_item) = hierarchy_container.get(child_id) {
        let Some(next) = hierarchy_item.next_sibling_id() else {
            break;
        };
        if get_display_type(styled_dom, next) != LayoutDisplay::None {
            children.push(next);
        }
        child_id = next;
    }

    // DEBUG (2026-06-02 children-None): record collected child count per parent
    // @0x40540+parent*4 (0xCC00_00NN). N=0 with first_child Some ⇒ get_display_type
    // mis-lift skipped them; N>0 ⇒ walk works. REVERT before commit.
    unsafe {
        let pi = parent_dom_id.index();
        if pi < 8 {
            crate::az_mark((0x40540 + pi * 4) as u32, (0xCC00_0000u32 | (children.len() as u32 & 0xffff)));
        }
    }
    children
}

/// Repositions clean children within a simple block-flow layout (like a BFC or a
/// table-row-group). It stacks children along the main axis, preserving their
/// previously calculated cross-axis alignment.
pub fn reposition_block_flow_siblings(
    styled_dom: &StyledDom,
    parent_idx: usize,
    tree: &LayoutTree,
    layout_roots: &BTreeSet<usize>,
    calculated_positions: &mut super::PositionVec,
) {
    let Some(parent_node) = tree.get(parent_idx) else {
        return;
    };
    let dom_id = parent_node.dom_node_id.unwrap_or(NodeId::ZERO);
    let styled_node_state = styled_dom
        .styled_nodes
        .as_container()
        .get(dom_id)
        .map(|n| n.styled_node_state)
        .unwrap_or_default();

    let writing_mode = get_writing_mode(styled_dom, dom_id, &styled_node_state).unwrap_or_default();

    let parent_pos = calculated_positions
        .get(parent_idx)
        .copied()
        .unwrap_or_default();

    let parent_bp = parent_node.box_props.unpack();
    let content_box_origin = LogicalPosition::new(
        parent_pos.x + parent_bp.padding.left,
        parent_pos.y + parent_bp.padding.top,
    );

    let mut main_pen = 0.0;

    for &child_idx in tree.children(parent_idx) {
        let Some(child_node) = tree.get(child_idx) else {
            continue;
        };

        let child_size = child_node.used_size.unwrap_or_default();
        let child_bp = child_node.box_props.unpack();
        let child_main_sum = child_bp.margin.main_sum(writing_mode);
        let margin_box_main_size = child_size.main(writing_mode) + child_main_sum;

        if layout_roots.contains(&child_idx) {
            // This child was DIRTY and has been correctly repositioned.
            // Update the pen to the position immediately after this child.
            let new_pos = match calculated_positions.get(child_idx) {
                Some(p) => *p,
                None => continue,
            };

            let main_axis_offset = if writing_mode.is_vertical() {
                new_pos.x - content_box_origin.x
            } else {
                new_pos.y - content_box_origin.y
            };

            main_pen = main_axis_offset
                + child_size.main(writing_mode)
                + child_bp.margin.main_end(writing_mode);
        } else {
            // This child is *clean*. Calculate its new position and shift its
            // entire subtree.
            let old_pos = match calculated_positions.get(child_idx) {
                Some(p) => *p,
                None => continue,
            };

            let child_main_start = child_bp.margin.main_start(writing_mode);
            let new_main_pos = main_pen + child_main_start;
            let old_relative_pos = tree.warm(child_idx)
                .and_then(|w| w.relative_position)
                .unwrap_or_default();
            let cross_pos = if writing_mode.is_vertical() {
                old_relative_pos.y
            } else {
                old_relative_pos.x
            };
            let new_relative_pos =
                LogicalPosition::from_main_cross(new_main_pos, cross_pos, writing_mode);

            let new_absolute_pos = LogicalPosition::new(
                content_box_origin.x + new_relative_pos.x,
                content_box_origin.y + new_relative_pos.y,
            );

            if old_pos != new_absolute_pos {
                let delta = LogicalPosition::new(
                    new_absolute_pos.x - old_pos.x,
                    new_absolute_pos.y - old_pos.y,
                );
                shift_subtree_position(child_idx, delta, tree, calculated_positions);
            }

            main_pen += margin_box_main_size;
        }
    }
}

/// Helper to recursively shift the absolute position of a node and all its descendants.
fn shift_subtree_position(
    node_idx: usize,
    delta: LogicalPosition,
    tree: &LayoutTree,
    calculated_positions: &mut super::PositionVec,
) {
    if let Some(pos) = calculated_positions.get_mut(node_idx) {
        pos.x += delta.x;
        pos.y += delta.y;
    }

    if let Some(node) = tree.get(node_idx) {
        let children = tree.children(node_idx).to_vec();
        for &child_idx in &children {
            shift_subtree_position(child_idx, delta, tree, calculated_positions);
        }
    }
}

/// Compares the new DOM against the cached tree, creating a new tree
/// and identifying which parts need to be re-laid out.
/// Count how many of the supplied DOM children would actually end up
/// in the layout tree. Mirrors the filters applied by
/// `LayoutTreeBuilder::build_recursive` so reconciliation can compare
/// like-for-like:
///
/// - `display: none` nodes are skipped entirely.
/// - In table structural contexts (table, row-group, row) whitespace
///   text nodes are skipped (CSS 2.2 §17.2.1, matches
///   `should_skip_for_table_structure`).
/// - Whitespace-only inline runs that sit between block siblings
///   collapse to zero boxes (CSS 2.2 §9.2.2.1).
///
/// The first two rules drop children unconditionally; the third only
/// fires on siblings surrounding a block-level child, so we detect it
/// by walking the run pairs. We do not build the runs — just count
/// survivors.
fn layout_relevant_child_count(
    styled_dom: &StyledDom,
    children: &[NodeId],
    parent_id: NodeId,
) -> usize {
    use super::getters::{get_display_property, MultiValue};
    use super::layout_tree::{is_block_level, is_whitespace_only_text};

    let parent_display = match get_display_property(styled_dom, Some(parent_id)) {
        MultiValue::Exact(d) => d,
        _ => LayoutDisplay::Block,
    };
    let is_table_structural = matches!(
        parent_display,
        LayoutDisplay::Table
            | LayoutDisplay::InlineTable
            | LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableRow
    );

    let has_any_block_child = children
        .iter()
        .any(|&id| is_block_level(styled_dom, id));

    let mut count = 0usize;
    // When parent has any block child, whitespace-only inline runs
    // surrounding blocks collapse. We approximate that by skipping
    // whitespace text whenever any block sibling exists.
    let collapse_inline_whitespace = has_any_block_child;
    for &id in children {
        // display:none drops
        let display = match get_display_property(styled_dom, Some(id)) {
            MultiValue::Exact(d) => d,
            _ => LayoutDisplay::Block,
        };
        if matches!(display, LayoutDisplay::None) {
            continue;
        }
        // Table-structural whitespace drops.
        if is_table_structural && is_whitespace_only_text(styled_dom, id) {
            continue;
        }
        // Whitespace-only inline run collapse when mixed with blocks.
        if collapse_inline_whitespace
            && !is_block_level(styled_dom, id)
            && is_whitespace_only_text(styled_dom, id)
        {
            continue;
        }
        count += 1;
    }
    count
}

/// # Errors
///
/// Returns a `LayoutError` if layout reconciliation fails.
pub fn reconcile_and_invalidate<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    cache: &LayoutCache,
    viewport: LogicalRect,
) -> Result<(LayoutTree, ReconciliationResult)> {
    let _probe_outer = crate::probe::Probe::span("reconcile_and_invalidate");
    let mut new_tree_builder = LayoutTreeBuilder::new(ctx.viewport_size);
    let mut recon_result = ReconciliationResult::default();
    // A viewport SIZE change invalidates every computed size: percentage, flex,
    // and absolute insets (top/right/bottom/left) all resolve against the
    // viewport / containing block. Incrementally reusing the cached layout tree
    // left out-of-flow and VirtualView nodes sized against the OLD viewport — e.g.
    // the map's absolutely-positioned container kept its old size, so a maximized
    // window showed tiles only in the original rect and grey everywhere else
    // (#9 "grey on resize"). On a size change, drop the cached tree so the whole
    // tree is laid out fresh against the new viewport. (Position-only moves keep
    // the incremental path.)
    let viewport_resized = cache.viewport.is_none_or(|v| v.size != viewport.size);
    let old_tree = if viewport_resized {
        None
    } else {
        cache.tree.as_ref()
    };

    if viewport_resized {
        recon_result.layout_roots.insert(0); // Root is always index 0
    }

    let root_dom_id = ctx
        .styled_dom
        .root
        .into_crate_internal()
        .unwrap_or(NodeId::ZERO);
    let root_idx = reconcile_recursive(
        ctx.styled_dom,
        root_dom_id,
        old_tree.map(|t| t.root),
        None,
        old_tree,
        &mut new_tree_builder,
        &mut recon_result,
        ctx.debug_messages,
    )?;

    // Clean up layout roots: if a parent is a layout root, its children don't need to be.
    let final_layout_roots = recon_result
        .layout_roots
        .iter()
        .filter(|&&idx| {
            let mut current = new_tree_builder.get(idx).and_then(|n| n.parent);
            while let Some(p_idx) = current {
                if recon_result.layout_roots.contains(&p_idx) {
                    return false;
                }
                current = new_tree_builder.get(p_idx).and_then(|n| n.parent);
            }
            true
        })
        .copied()
        .collect();
    recon_result.layout_roots = final_layout_roots;

    let new_tree = new_tree_builder.build(root_idx);
    // layout_document's step marker is stuck at 1 (post-`?` not reached), the
    // lifted `?` mis-discriminated this Ok as Err (niche-Result mis-lift).
    { let _ = (0xCC00_0001u32); }
    Ok((new_tree, recon_result))
}

/// CSS 2.2 § 9.2.2.1: Checks whether an inline run consists entirely of
/// whitespace-only text nodes, in which case it should NOT generate an
/// anonymous IFC wrapper in a BFC mixed-content context.
///
/// This prevents whitespace between block elements from creating empty
/// anonymous blocks that take up vertical space (regression c33e94b0).
///
/// Exception: if the parent (or any ancestor) has `white-space: pre`,
/// `pre-wrap`, or `pre-line`, whitespace IS significant and the wrapper
/// must still be created.
fn is_whitespace_only_inline_run(
    styled_dom: &StyledDom,
    inline_run: &[(usize, NodeId)],
    parent_dom_id: NodeId,
) -> bool {
    use azul_css::props::style::text::StyleWhiteSpace;

    if inline_run.is_empty() {
        return true;
    }

    // Check if the parent preserves whitespace
    let parent_state = &styled_dom.styled_nodes.as_container()[parent_dom_id].styled_node_state;
    let white_space = match get_white_space_property(styled_dom, parent_dom_id, parent_state) {
        MultiValue::Exact(ws) => Some(ws),
        _ => None,
    };

    // If white-space preserves whitespace, don't strip
    if matches!(
        white_space,
        Some(StyleWhiteSpace::Pre | StyleWhiteSpace::PreWrap |
StyleWhiteSpace::PreLine)
    ) {
        return false;
    }

    // Check that every node in the run is a whitespace-only text node
    let binding = styled_dom.node_data.as_container();
    for &(_, dom_id) in inline_run {
        if let Some(data) = binding.get(dom_id) {
            match data.get_node_type() {
                NodeType::Text(text) => {
                    let s = text.as_str();
                    if !s.chars().all(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0C')) {
                        return false; // Non-whitespace text → must create wrapper
                    }
                }
                _ => {
                    return false; // Non-text inline element → must create wrapper
                }
            }
        }
    }

    true // All nodes are whitespace-only text
}

/// Recursively traverses the new DOM and old tree, building a new tree and marking dirty nodes.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if recursive reconciliation fails.
pub fn reconcile_recursive(
    styled_dom: &StyledDom,
    new_dom_id: NodeId,
    old_tree_idx: Option<usize>,
    new_parent_idx: Option<usize>,
    old_tree: Option<&LayoutTree>,
    new_tree_builder: &mut LayoutTreeBuilder,
    recon: &mut ReconciliationResult,
    debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
) -> Result<usize> {
    // Cache the env check in a `OnceLock<bool>`: this branch
    // fires once per dirty node (hundreds on cold layout),
    // and a direct `env::var` is a mutex + hashmap lookup
    // on macOS (~100 ns/call) even when the env var is unset.
    static FP_DUMP_ENABLED: std::sync::OnceLock<bool> =
        std::sync::OnceLock::new();
    let node_data = &styled_dom.node_data.as_container()[new_dom_id];

    let old_cold = old_tree.and_then(|t| old_tree_idx.and_then(|idx| t.cold(idx)));
    match (old_tree.is_some(), old_tree_idx.is_some(), old_cold.is_some()) {
        (false, _, _) => drop(crate::probe::Probe::span("recon_old_tree_none")),
        (true, false, _) => drop(crate::probe::Probe::span("recon_old_idx_none")),
        (true, true, false) => drop(crate::probe::Probe::span("recon_cold_none")),
        (true, true, true) => drop(crate::probe::Probe::span("recon_cold_some")),
    }

    // Compute the new multi-field fingerprint instead of a single hash.
    let new_fingerprint = {
        let _p = crate::probe::Probe::span("fingerprint_compute");
        NodeDataFingerprint::compute(
            node_data,
            styled_dom.styled_nodes.as_container().get(new_dom_id).map(|n| &n.styled_node_state),
        )
    };

    // Compare fingerprints to determine what changed (Layout, Paint, or Nothing).
    let dirty_flag = old_cold.map_or_else(|| {
            drop(crate::probe::Probe::span("fp_new_node"));
            DirtyFlag::Layout // new node → full layout
        }, |old_c| {
            let change_set = old_c.node_data_fingerprint.diff(&new_fingerprint);
            if change_set.needs_layout() {
                drop(crate::probe::Probe::span("fp_needs_layout"));
                let enabled = *FP_DUMP_ENABLED.get_or_init(|| {
                    std::env::var_os("AZ_FP_DUMP").is_some()
                });
                if enabled {
                    use std::sync::atomic::{AtomicUsize, Ordering};
                    static DUMPED: AtomicUsize = AtomicUsize::new(0);
                    let n = DUMPED.fetch_add(1, Ordering::Relaxed);
                    if n < 10 {
                        eprintln!(
                            "[fp_diff {n}] dom={} old={:?} new={:?}",
                            new_dom_id.index(),
                            old_c.node_data_fingerprint,
                            new_fingerprint,
                        );
                    }
                }
                DirtyFlag::Layout
            } else if change_set.needs_paint() {
                drop(crate::probe::Probe::span("fp_needs_paint"));
                DirtyFlag::Paint
            } else {
                drop(crate::probe::Probe::span("fp_clean"));
                DirtyFlag::None
            }
        });
    let is_dirty = dirty_flag >= DirtyFlag::Paint;

    // M12.7: `|| old_tree.is_none()` — on COLD layout there is no old tree to
    // clone, so we MUST create a fresh node; taking the else-branch would hit
    // `ok_or(InvalidTree)` on a None old_tree. This is both semantically correct
    // AND robust against a mis-lifted `dirty_flag`/Option match (the suspected
    // niche-enum mis-discriminant) wrongly steering cold nodes into the else.
    let new_node_idx = if dirty_flag >= DirtyFlag::Layout || old_tree.is_none() {
        { let _ = (0xBB00_0001u32); }
        let idx = new_tree_builder.create_node_from_dom(
            styled_dom,
            new_dom_id,
            new_parent_idx,
            debug_messages,
        );
        // Blockify replaced/inline flex-or-grid items (CSS Display 3 §2.7). The
        // full `process_node` build does this; this incremental path called
        // `create_node_from_dom` directly and skipped it, so a flex-item <img>
        // (e.g. the AzulPaint canvas) stayed inline and ignored flex-grow.
        new_tree_builder.blockify_node_display(styled_dom, new_dom_id, idx, new_parent_idx);
        idx
    } else {
        { let _ = (0xBB00_0002u32); }
        // Paint-only or clean: clone the old node (preserving layout cache)
        let old_full_node = old_tree
            .and_then(|t| old_tree_idx.and_then(|idx| t.get_full_node(idx)))
            .ok_or(LayoutError::InvalidTree)?;
        let mut idx = new_tree_builder.clone_node_from_old(&old_full_node, new_parent_idx);
        // If paint-only change, update the fingerprint and dirty flag
        if dirty_flag == DirtyFlag::Paint {
            if let Some(cloned) = new_tree_builder.get_mut(idx) {
                cloned.node_data_fingerprint = new_fingerprint;
                cloned.dirty_flag = DirtyFlag::Paint;
            }
        }
        idx
    };

    // reconcile_recursive sees it. 0 = correct (the first node); 64 (matching the
    // build-marker root_idx) = the usize return mis-reads here.
    { let _ = (0xAB00_0000u32 | (new_node_idx as u32 & 0xffff)); }

    // CRITICAL: For list-items, create a ::marker pseudo-element as the first child
    // This must be done after the node is created but before processing children
    // Per CSS Lists Module Level 3, ::marker is generated as the first child of list-items
    {
        use crate::solver3::getters::get_display_property;
        let display = get_display_property(styled_dom, Some(new_dom_id))
            .exact();

        if matches!(display, Some(LayoutDisplay::ListItem)) {
            // Create ::marker pseudo-element for this list-item
            new_tree_builder.create_marker_pseudo_element(styled_dom, new_dom_id, new_node_idx);
        }
    }

    // Reconcile children to check for structural changes and build the new tree structure.
    let mut new_children_dom_ids: Vec<_> = collect_children_dom_ids(styled_dom, new_dom_id);

    // CSS 2.2 §17.2.1: Filter whitespace-only text nodes from table structural elements
    // (table, row-group, row). Without this, the reconciler sees them as "inline" children
    // mixed with block-level <td>/<th>, triggering incorrect anonymous IFC wrapping.
    // The layout tree builder already does this via should_skip_for_table_structure().
    {
        use super::getters::{get_display_property, MultiValue};
        let parent_display = match get_display_property(styled_dom, Some(new_dom_id)) {
            MultiValue::Exact(d) => d,
            _ => LayoutDisplay::Block,
        };
        if matches!(parent_display,
            LayoutDisplay::Table
            | LayoutDisplay::InlineTable
            | LayoutDisplay::TableRowGroup
            | LayoutDisplay::TableHeaderGroup
            | LayoutDisplay::TableFooterGroup
            | LayoutDisplay::TableRow
        ) {
            new_children_dom_ids.retain(|&id| {
                !super::layout_tree::is_whitespace_only_text(styled_dom, id)
            });
        }
    }

    // Compute both positional and DOM-keyed lookups for the old
    // tree's children. The DOM-keyed map is authoritative for
    // reconciliation (positional drifts every time the layout-tree
    // builder drops a DOM child — whitespace text, display:none,
    // table-structural whitespace — or inserts an anonymous
    // wrapper that isn't in the DOM).
    let old_children_indices: Vec<usize> = old_tree
        .and_then(|t| old_tree_idx.map(|idx| t.children(idx).to_vec()))
        .unwrap_or_default();
    let old_children_by_dom: alloc::collections::BTreeMap<NodeId, usize> = old_tree
        .and_then(|t| old_tree_idx.map(|idx| {
            t.children(idx).iter()
                .filter_map(|&cidx| t.get(cidx).and_then(|n| n.dom_node_id).map(|did| (did, cidx)))
                .collect()
        }))
        .unwrap_or_default();

    // Count of old layout children that correspond to a real DOM
    // node (exclude anonymous wrappers). This is what we compare
    // against the layout-relevant subset of new DOM children to
    // decide whether the structural shape actually changed.
    let old_layout_relevant_count = old_children_by_dom.len();

    // Filter new DOM children to the subset the layout-tree builder
    // would actually emit. This mirrors `should_skip_for_table_structure`
    // and the `is_whitespace_only_inline_run` logic. Without this
    // filter, `children_are_different` fires on every reconcile
    // because the DOM has whitespace text nodes the layout tree
    // drops.
    let new_layout_relevant_count = layout_relevant_child_count(styled_dom, &new_children_dom_ids, new_dom_id);

    let mut children_are_different = new_layout_relevant_count != old_layout_relevant_count;
    let mut new_child_hashes = Vec::new();

    // +spec:display-property:42f9c0 - anonymous block boxes wrap inline runs when block container has mixed block/inline children
    // CSS 2.2 Section 9.2.1.1: Anonymous Block Boxes
    // When a block container has mixed block/inline children, we must:
    // 1. Wrap consecutive inline children in anonymous block boxes
    // 2. Leave block-level children as direct children

    let has_block_child = new_children_dom_ids
        .iter()
        .any(|&id| is_block_level(styled_dom, id));

    // CSS Flexbox §4 / Grid §6: every in-flow child of a flex/grid container
    // becomes a (blockified) flex/grid item. Anonymous-block wrapping of inline
    // runs is a BLOCK-container concept and must NOT apply here — otherwise an
    // inline-level child (e.g. an <img> with flex-grow, default display
    // inline-block) gets wrapped in an anonymous IFC block, so it's no longer a
    // direct flex item and its flex-grow is ignored (laid out 300×0). Processing
    // each child directly lets `blockify_node_display` (in create_node_from_dom)
    // see the flex/grid parent and blockify the child into a real flex item.
    let parent_is_flex_or_grid = matches!(
        get_display_type(styled_dom, new_dom_id),
        LayoutDisplay::Flex
            | LayoutDisplay::InlineFlex
            | LayoutDisplay::Grid
            | LayoutDisplay::InlineGrid
    );

    if !has_block_child || parent_is_flex_or_grid {
        // All children are inline (block container) OR the parent is a flex/grid
        // container (all children are direct items) — no anonymous boxes needed.
        // Process each child directly.
        for (i, &new_child_dom_id) in new_children_dom_ids.iter().enumerate() {
            // DOM-ID match rather than positional — tree builder
            // may have dropped some DOM children (whitespace text
            // nodes) so positional drift mis-aligns the cache.
            // DOM-id match only: positional fallback would align
            // anonymous wrappers against real DOM nodes and trigger
            // spurious fingerprint mismatches (see fp_diff dump).
            let old_child_idx = old_children_by_dom.get(&new_child_dom_id).copied();

            let reconciled_child_idx = reconcile_recursive(
                styled_dom,
                new_child_dom_id,
                old_child_idx,
                Some(new_node_idx),
                old_tree,
                new_tree_builder,
                recon,
                debug_messages,
            )?;
            if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
                new_child_hashes.push(child_node.subtree_hash.0);
            }

            if old_tree.and_then(|t| t.cold(old_child_idx?).map(|n| n.subtree_hash))
                != new_tree_builder
                    .get(reconciled_child_idx)
                    .map(|n| n.subtree_hash)
            {
                children_are_different = true;
            }
        }
    } else {
        // Mixed content: block and inline children
        // We must create anonymous block boxes around consecutive inline runs

        if let Some(msgs) = debug_messages.as_mut() {
            msgs.push(LayoutDebugMessage::info(format!(
                "[reconcile_recursive] Mixed content in node {}: creating anonymous IFC wrappers",
                new_dom_id.index()
            )));
        }

        let mut inline_run: Vec<(usize, NodeId)> = Vec::new(); // (dom_child_index, dom_id)

        for (i, &new_child_dom_id) in new_children_dom_ids.iter().enumerate() {
            if is_block_level(styled_dom, new_child_dom_id) {
                // End current inline run if any
                if !inline_run.is_empty() {
                    // CSS 2.2 § 9.2.2.1: If the inline run consists entirely of
                    // whitespace-only text nodes (and white-space doesn't preserve it),
                    // skip creating the anonymous IFC wrapper. This prevents inter-block
                    // whitespace from creating empty blocks that take up vertical space.
                    // +spec:display-property:bef3fc - anonymous blocks of only collapsible whitespace removed from rendering tree
                    if is_whitespace_only_inline_run(styled_dom, &inline_run, new_dom_id) {
                        if let Some(msgs) = debug_messages.as_mut() {
                            msgs.push(LayoutDebugMessage::info(format!(
                                "[reconcile_recursive] Skipping whitespace-only inline run ({} nodes) between blocks in node {}",
                                inline_run.len(),
                                new_dom_id.index()
                            )));
                        }
                        inline_run.clear();
                    } else {
                    // Create anonymous IFC wrapper for the inline run
                    // This wrapper establishes an Inline Formatting Context
                    let anon_idx = new_tree_builder.create_anonymous_node(
                        new_node_idx,
                        AnonymousBoxType::InlineWrapper,
                        FormattingContext::Inline, // IFC for inline content
                    );

                    if let Some(msgs) = debug_messages.as_mut() {
                        msgs.push(LayoutDebugMessage::info(format!(
                            "[reconcile_recursive] Created anonymous IFC wrapper (layout_idx={}) for {} inline children: {:?}",
                            anon_idx,
                            inline_run.len(),
                            inline_run.iter().map(|(_, id)| id.index()).collect::<Vec<_>>()
                        )));
                    }

                    // Process each inline child under the anonymous wrapper
                    #[allow(clippy::iter_with_drain)] // accumulator Vec reused across runs; drain(..) empties it while retaining the allocation
                    for (pos, inline_dom_id) in inline_run.drain(..) {
                        // Inline children live under the anon wrapper
                        // in the old tree, so the parent's direct
                        // `old_children_by_dom` map won't hit them.
                        // Fall through to the global `dom_to_layout`
                        // map; we don't care which anon wrapper they
                        // were under, only that their cold data
                        // (fingerprint) gets matched correctly.
                        let old_child_idx = old_children_by_dom.get(&inline_dom_id).copied()
                            .or_else(|| old_tree
                                .and_then(|t| t.dom_to_layout.get(&inline_dom_id))
                                .and_then(|v| v.first().copied()));
                        let reconciled_child_idx = reconcile_recursive(
                            styled_dom,
                            inline_dom_id,
                            old_child_idx,
                            Some(anon_idx), // Parent is the anonymous wrapper
                            old_tree,
                            new_tree_builder,
                            recon,
                            debug_messages,
                        )?;
                        if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
                            new_child_hashes.push(child_node.subtree_hash.0);
                        }
                    }

                    // NOTE: We intentionally do NOT unconditionally
                    // mark the anonymous wrapper as intrinsic_dirty
                    // here. If any of the inline children are
                    // themselves dirty, their own `mark_dirty` call
                    // propagates upward through this wrapper, so
                    // wrappers whose content is unchanged keep their
                    // cached layout. Setting `children_are_different`
                    // when the wrapper is newly created (no matching
                    // old anon) flips the parent to layout-dirty,
                    // which is what triggers a fresh wrapper layout.
                    children_are_different = true;
                    } // end else (non-whitespace run)
                }

                // Process block-level child directly under parent
                let old_child_idx = old_children_by_dom.get(&new_child_dom_id).copied()
                    .or_else(|| old_children_indices.get(i).copied());
                let reconciled_child_idx = reconcile_recursive(
                    styled_dom,
                    new_child_dom_id,
                    old_child_idx,
                    Some(new_node_idx),
                    old_tree,
                    new_tree_builder,
                    recon,
                    debug_messages,
                )?;
                if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
                    new_child_hashes.push(child_node.subtree_hash.0);
                }

                if old_tree.and_then(|t| t.cold(old_child_idx?).map(|n| n.subtree_hash))
                    != new_tree_builder
                        .get(reconciled_child_idx)
                        .map(|n| n.subtree_hash)
                {
                    children_are_different = true;
                }
            } else {
                // Inline-level child - add to current run
                inline_run.push((i, new_child_dom_id));
            }
        }

        // Process any remaining inline run at the end
        if !inline_run.is_empty() {
            // CSS 2.2 § 9.2.2.1: Skip whitespace-only trailing inline runs
            if is_whitespace_only_inline_run(styled_dom, &inline_run, new_dom_id) {
                if let Some(msgs) = debug_messages.as_mut() {
                    msgs.push(LayoutDebugMessage::info(format!(
                        "[reconcile_recursive] Skipping trailing whitespace-only inline run ({} nodes) in node {}",
                        inline_run.len(),
                        new_dom_id.index()
                    )));
                }
                // Don't create a wrapper — just drop the run
            } else {
            let anon_idx = new_tree_builder.create_anonymous_node(
                new_node_idx,
                AnonymousBoxType::InlineWrapper,
                FormattingContext::Inline, // IFC for inline content
            );

            if let Some(msgs) = debug_messages.as_mut() {
                msgs.push(LayoutDebugMessage::info(format!(
                    "[reconcile_recursive] Created trailing anonymous IFC wrapper (layout_idx={}) for {} inline children: {:?}",
                    anon_idx,
                    inline_run.len(),
                    inline_run.iter().map(|(_, id)| id.index()).collect::<Vec<_>>()
                )));
            }

            #[allow(clippy::iter_with_drain)] // accumulator Vec reused across runs; drain(..) empties it while retaining the allocation
            for (pos, inline_dom_id) in inline_run.drain(..) {
                let old_child_idx = old_children_by_dom.get(&inline_dom_id).copied();
                let reconciled_child_idx = reconcile_recursive(
                    styled_dom,
                    inline_dom_id,
                    old_child_idx,
                    Some(anon_idx),
                    old_tree,
                    new_tree_builder,
                    recon,
                    debug_messages,
                )?;
                if let Some(child_node) = new_tree_builder.get(reconciled_child_idx) {
                    new_child_hashes.push(child_node.subtree_hash.0);
                }
            }

            // See note in main mixed-content branch: rely on
            // children's own mark_dirty to propagate upward rather
            // than invalidating the whole wrapper each reconcile.
            children_are_different = true;
            } // end else (non-whitespace trailing run)
        }
    }

    // After reconciling children, calculate this node's full subtree hash.
    // Use a combined hash of the fingerprint fields for the subtree hash.
    let node_self_hash = {
        use std::hash::{DefaultHasher, Hash, Hasher};
        let mut h = DefaultHasher::new();
        new_fingerprint.hash(&mut h);
        h.finish()
    };
    let final_subtree_hash = calculate_subtree_hash(node_self_hash, &new_child_hashes);
    if let Some(current_node) = new_tree_builder.get_mut(new_node_idx) {
        current_node.subtree_hash = final_subtree_hash;
    }

    // Classify this node into the appropriate dirty set based on what changed.
    if dirty_flag >= DirtyFlag::Layout || children_are_different {
        recon.intrinsic_dirty.insert(new_node_idx);
        recon.layout_roots.insert(new_node_idx);
    } else if dirty_flag == DirtyFlag::Paint {
        recon.paint_dirty.insert(new_node_idx);
    }

    Ok(new_node_idx)
}

/// Result of `prepare_layout_context`: contains the layout constraints and
/// intermediate values needed for `calculate_layout_for_subtree`.
struct PreparedLayoutContext<'a> {
    constraints: LayoutConstraints<'a>,
    /// DOM ID for the node. None for anonymous boxes.
    dom_id: Option<NodeId>,
    writing_mode: LayoutWritingMode,
    final_used_size: LogicalSize,
    box_props: crate::solver3::geometry::BoxProps,
}

/// Prepares the layout context for a single node by calculating its used size
/// and building the layout constraints for its children.
///
/// For anonymous boxes (no `dom_node_id`), we use default values and inherit
/// from the containing block.
fn prepare_layout_context<'a, T: ParsedFontTrait>(
    ctx: &LayoutContext<'a, T>,
    tree: &LayoutTree,
    node_index: usize,
    containing_block_size: LogicalSize,
) -> Result<PreparedLayoutContext<'a>> {
    let node = tree.get(node_index).ok_or(LayoutError::InvalidTree)?;
    let warm = tree.warm(node_index).ok_or(LayoutError::InvalidTree)?;
    let dom_id = node.dom_node_id; // Can be None for anonymous boxes

    // Phase 1: Calculate this node's provisional used size

    // This size is based on the node's CSS properties (width, height, etc.) and
    // its containing block. If height is 'auto', this is a temporary value.
    let intrinsic = warm.intrinsic_sizes.unwrap_or_default();
    let final_used_size = calculate_used_size_for_node(
        ctx.styled_dom,
        dom_id, // Now Option<NodeId>
        &containing_block_size,
        intrinsic,
        &node.box_props.unpack(),
        &ctx.viewport_size,
    )?;

    // Phase 2: Layout children using a formatting context
    // Use pre-computed styles from LayoutNodeWarm instead of repeated lookups
    let writing_mode = warm.computed_style.writing_mode;
    let text_align = warm.computed_style.text_align;
    let display = warm.computed_style.display;
    let overflow_y = warm.computed_style.overflow_y;

    // Check if height is auto (no explicit height set)
    let height_is_auto = warm.computed_style.height.is_none();

    let available_size_for_children = if height_is_auto {
        // Height is auto - use containing block size as available size
        let inner_size = node.box_props.inner_size(final_used_size, writing_mode);

        // For inline elements (display: inline), the available width comes from
        // the containing block, not from the element's own intrinsic size.
        // CSS 2.2 § 10.3.1: Inline, non-replaced elements use containing block width.
        let available_width = match display {
            LayoutDisplay::Inline => containing_block_size.width,
            _ => inner_size.width,
        };

        LogicalSize {
            width: available_width,
            // Use containing block height!
            height: containing_block_size.height,
        }
    } else {
        // Height is explicit - use inner size (after padding/border)
        node.box_props.inner_size(final_used_size, writing_mode)
    };

    // NOTE: Scrollbar reservation is handled inside layout_bfc() where it subtracts
    // scrollbar width from children_containing_block_size. We do NOT subtract here
    // to avoid double-subtraction (layout_bfc already handles both the used_size
    // and available_size code paths).

    let wm_ctx = crate::solver3::geometry::WritingModeContext::new(
        writing_mode,
        warm.computed_style.direction,
        warm.computed_style.text_orientation,
    );
    let constraints = LayoutConstraints {
        available_size: available_size_for_children,
        bfc_state: None,
        writing_mode,
        writing_mode_ctx: wm_ctx,
        text_align: style_text_align_to_fc(text_align),
        containing_block_size,
        available_width_type: Text3AvailableSpace::Definite(available_size_for_children.width),
    };

    Ok(PreparedLayoutContext {
        constraints,
        dom_id,
        writing_mode,
        final_used_size,
        box_props: node.box_props.unpack(),
    })
}

/// Core scrollbar info computation: given pre-computed content and container sizes plus
/// a DOM node for style look-up, determines whether scrollbars are needed.
///
/// This is the single source of truth for scrollbar detection. Both the BFC path
/// (`compute_scrollbar_info`) and the Taffy flex/grid path (`compute_child_layout`
/// in `taffy_bridge.rs`) call this function, ensuring consistent behaviour.
///
/// For paged media (PDF), scrollbars are never added since they don't exist in print.
pub fn compute_scrollbar_info_core<T: ParsedFontTrait>(
    ctx: &LayoutContext<'_, T>,
    dom_id: NodeId,
    styled_node_state: &azul_core::styled_dom::StyledNodeState,
    content_size: LogicalSize,
    container_size: LogicalSize,
) -> ScrollbarRequirements {
    // +spec:overflow:08b60d - non-interactive media: UA may show scroll indicators but we skip them for print
    if ctx.fragmentation_context.is_some() {
        return ScrollbarRequirements::default();
    }

    let overflow_x = get_overflow_x(ctx.styled_dom, dom_id, styled_node_state);
    let overflow_y = get_overflow_y(ctx.styled_dom, dom_id, styled_node_state);

    // Resolve the full scrollbar style **once** and reuse it
    // across the rest of this function + any further calls from
    // the same layout pass via `LayoutContext::scrollbar_style_cache`.
    // Previously we called `get_layout_scrollbar_width_px` (which
    // builds the full scrollbar_style internally, keeps only
    // `reserve_width_px`, then drops it) and then
    // `get_scrollbar_style` again — each build performs 9 cascade
    // walks (track/thumb/button/corner/width/color/visibility/
    // fade-delay/fade-duration). With the memo, subsequent calls
    // on the same (dom_id, state) are a HashMap hit.
    let scrollbar_style = crate::solver3::getters::get_scrollbar_style_cached(
        ctx, dom_id, styled_node_state,
    );
    let scrollbar_width_px = scrollbar_style.reserve_width_px;

    let mut reqs = fc::check_scrollbar_necessity(
        content_size,
        container_size,
        to_overflow_behavior(overflow_x),
        to_overflow_behavior(overflow_y),
        scrollbar_width_px,
    );
    reqs.visual_width_px = scrollbar_style.visual_width_px;

    // +spec:overflow:e90f12 - scrollbar-gutter reserves space independently of scrollbar presence
    // +spec:overflow:3c44cc - scrollbar-gutter: stable reserves gutter even when no scrollbar is shown
    // +spec:overflow:3a6966 - classic scrollbar gutter width == scrollbar width; overlay scrollbars have no gutter
    //
    // scrollbar-gutter only applies to scroll containers (overflow: auto or scroll).
    // "stable" reserves gutter on the inline-end edge even if no scrollbar is needed.
    // "stable both-edges" reserves gutter on both inline edges.
    let scrollbar_gutter = get_scrollbar_gutter_property(ctx.styled_dom, dom_id, styled_node_state)
        .unwrap_or(azul_css::props::layout::overflow::StyleScrollbarGutter::Auto);
    let ob_y = to_overflow_behavior(overflow_y);
    let is_scroll_container = matches!(ob_y, fc::OverflowBehavior::Scroll | fc::OverflowBehavior::Auto);

    if is_scroll_container {
        use azul_css::props::layout::overflow::StyleScrollbarGutter;
        match scrollbar_gutter {
            StyleScrollbarGutter::Stable => {
                // Reserve gutter on inline-end even if no scrollbar is currently needed
                if !reqs.needs_vertical {
                    reqs.scrollbar_width = scrollbar_width_px;
                }
            }
            StyleScrollbarGutter::StableBothEdges => {
                // Reserve gutter on both inline edges
                reqs.scrollbar_width = scrollbar_width_px * 2.0;
            }
            StyleScrollbarGutter::Auto => {
                // Default: gutter only present when scrollbar is present (already handled)
            }
        }
    }

    reqs
}

/// Determines scrollbar requirements for a node based on content overflow.
///
/// Convenience wrapper around `compute_scrollbar_info_core` for the BFC layout path,
/// where the container size is derived from `box_props.inner_size(final_used_size, …)`.
fn compute_scrollbar_info<T: ParsedFontTrait>(
    ctx: &LayoutContext<'_, T>,
    dom_id: NodeId,
    styled_node_state: &azul_core::styled_dom::StyledNodeState,
    content_size: LogicalSize,
    box_props: &crate::solver3::geometry::BoxProps,
    final_used_size: LogicalSize,
    writing_mode: LayoutWritingMode,
) -> ScrollbarRequirements {
    let container_size = box_props.inner_size(final_used_size, writing_mode);
    compute_scrollbar_info_core(ctx, dom_id, styled_node_state, content_size, container_size)
}

/// Checks if scrollbars changed compared to previous layout and if reflow is needed.
///
/// Detects both addition AND removal of scrollbars. Oscillation (add → remove → add)
/// is prevented by the outer layout loop's iteration limit (`loop_count > 10` in mod.rs),
/// not by suppressing removal detection here. This allows scrollbars to correctly
/// disappear when content shrinks or the window is resized larger.
fn check_scrollbar_change(
    tree: &LayoutTree,
    node_index: usize,
    scrollbar_info: &ScrollbarRequirements,
    skip_scrollbar_check: bool,
) -> bool {
    if skip_scrollbar_check {
        return false;
    }

    let Some(warm_node) = tree.warm(node_index) else {
        return false;
    };

    warm_node.scrollbar_info.as_ref().map_or_else(|| scrollbar_info.needs_reflow(), |old_info| {
            // Trigger reflow if scrollbar state changed in either direction
            let horizontal_changed = old_info.needs_horizontal != scrollbar_info.needs_horizontal;
            let vertical_changed = old_info.needs_vertical != scrollbar_info.needs_vertical;
            horizontal_changed || vertical_changed
        })
}

/// Calculates the content-box position from a margin-box position.
///
/// The content-box is offset from the margin-box by border + padding.
/// Margin is NOT added here because `containing_block_pos` already accounts for it.
fn calculate_content_box_pos(
    containing_block_pos: LogicalPosition,
    box_props: &crate::solver3::geometry::BoxProps,
) -> LogicalPosition {
    LogicalPosition::new(
        containing_block_pos.x + box_props.border.left + box_props.padding.left,
        containing_block_pos.y + box_props.border.top + box_props.padding.top,
    )
}

/// Emits debug logging for content-box calculation if debug messages are enabled.
fn log_content_box_calculation<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    node_index: usize,
    current_node: &LayoutNodeHot,
    containing_block_pos: LogicalPosition,
    self_content_box_pos: LogicalPosition,
) {
    let Some(debug_msgs) = ctx.debug_messages.as_mut() else {
        return;
    };

    let dom_name = current_node
        .dom_node_id
        .and_then(|id| {
            ctx.styled_dom
                .node_data
                .as_container()
                .internal
                .get(id.index())
        }).map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));

    let cbp = current_node.box_props.unpack();
    debug_msgs.push(LayoutDebugMessage::new(
        LayoutDebugMessageType::PositionCalculation,
        format!(
            "[CONTENT BOX {}] {} - margin-box pos=({:.2}, {:.2}) + border=({:.2},{:.2}) + \
             padding=({:.2},{:.2}) = content-box pos=({:.2}, {:.2})",
            node_index,
            dom_name,
            containing_block_pos.x,
            containing_block_pos.y,
            cbp.border.left,
            cbp.border.top,
            cbp.padding.left,
            cbp.padding.top,
            self_content_box_pos.x,
            self_content_box_pos.y
        ),
    ));
}

/// Emits debug logging for child positioning if debug messages are enabled.
fn log_child_positioning<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    child_index: usize,
    child_node: &LayoutNodeHot,
    self_content_box_pos: LogicalPosition,
    child_relative_pos: LogicalPosition,
    child_absolute_pos: LogicalPosition,
) {
    // Always print positioning info for debugging
    let child_dom_name = child_node
        .dom_node_id
        .and_then(|id| {
            ctx.styled_dom
                .node_data
                .as_container()
                .internal
                .get(id.index())
        }).map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));

    let Some(debug_msgs) = ctx.debug_messages.as_mut() else {
        return;
    };

    debug_msgs.push(LayoutDebugMessage::new(
        LayoutDebugMessageType::PositionCalculation,
        format!(
            "[CHILD POS {}] {} - parent content-box=({:.2}, {:.2}) + relative=({:.2}, {:.2}) + \
             margin=({:.2}, {:.2}) = absolute=({:.2}, {:.2})",
            child_index,
            child_dom_name,
            self_content_box_pos.x,
            self_content_box_pos.y,
            child_relative_pos.x,
            child_relative_pos.y,
            child_node.box_props.unpack().margin.left,
            child_node.box_props.unpack().margin.top,
            child_absolute_pos.x,
            child_absolute_pos.y
        ),
    ));
}

/// Processes a single in-flow child: sets position and recurses.
///
/// For Flex/Grid containers, Taffy has already laid out the children completely.
/// We only recurse to position their grandchildren.
/// For Block/Inline/Table, `layout_bfc/layout_ifc` already laid out children in Pass 1.
/// We only need to set absolute positions and recurse for positioning grandchildren.
fn process_inflow_child<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    tree: &mut LayoutTree,
    text_cache: &TextLayoutCache,
    child_index: usize,
    child_relative_pos: LogicalPosition,
    self_content_box_pos: LogicalPosition,
    inner_size_after_scrollbars: LogicalSize,
    writing_mode: LayoutWritingMode,
    is_flex_or_grid: bool,
    calculated_positions: &mut super::PositionVec,
    reflow_needed_for_scrollbars: bool,
    float_cache: &HashMap<usize, fc::FloatingContext>,
) -> Result<()> {
    // Set relative position on child
    // child_relative_pos is [CoordinateSpace::Parent] - relative to parent's content-box
    let child_warm = tree.warm_mut(child_index).ok_or(LayoutError::InvalidTree)?;
    child_warm.relative_position = Some(child_relative_pos);

    // Calculate absolute position
    // self_content_box_pos is [CoordinateSpace::Window] - absolute position of parent's content-box
    // child_absolute_pos becomes [CoordinateSpace::Window] - absolute window position of child
    let child_absolute_pos = LogicalPosition::new(
        self_content_box_pos.x + child_relative_pos.x,
        self_content_box_pos.y + child_relative_pos.y,
    );

    // Debug logging
    {
        let child_node = tree.get(child_index).ok_or(LayoutError::InvalidTree)?;
        log_child_positioning(
            ctx,
            child_index,
            child_node,
            self_content_box_pos,
            child_relative_pos,
            child_absolute_pos,
        );
    }

    // calculated_positions stores [CoordinateSpace::Window] - absolute positions
    super::pos_set(calculated_positions, child_index, child_absolute_pos);

    // Get child's properties for recursion
    let child_node = tree.get(child_index).ok_or(LayoutError::InvalidTree)?;
    let child_bp = child_node.box_props.unpack();
    let child_content_box_pos =
        calculate_content_box_pos(child_absolute_pos, &child_bp);
    let child_inner_size = child_bp
        .inner_size(child_node.used_size.unwrap_or_default(), writing_mode);
    let child_children: Vec<usize> = tree.children(child_index).to_vec();
    let child_fc = child_node.formatting_context;

    // Recurse to position grandchildren
    // OPTIMIZATION: For BFC/IFC children, layout_bfc/layout_ifc already computed their layout.
    // We just need to set absolute positions for descendants.
    // Only recurse if child has children to position.
    if !child_children.is_empty() {
        if is_flex_or_grid {
            // For Flex/Grid: Taffy already set used_size. Only recurse for grandchildren.
            position_flex_child_descendants(
                tree,
                child_index,
                child_content_box_pos,
                child_inner_size,
                calculated_positions,
            )?;
        } else {
            // For Block/Inline/Table: The formatting context already laid out children.
            // Recursively position grandchildren using their cached layout data.
            position_bfc_child_descendants(
                tree,
                child_index,
                child_content_box_pos,
                calculated_positions,
            );
        }
    }

    Ok(())
}

/// Recursively positions descendants of a BFC/IFC child without re-computing layout.
/// The layout was already computed by `layout_bfc/layout_ifc`.
/// We only need to convert relative positions to absolute positions.
fn position_bfc_child_descendants(
    tree: &LayoutTree,
    node_index: usize,
    content_box_pos: LogicalPosition,
    calculated_positions: &mut super::PositionVec,
) {
    let Some(node) = tree.get(node_index) else { return };

    for &child_index in tree.children(node_index) {
        let Some(child_node) = tree.get(child_index) else { continue };

        // Use the relative_position that was set during formatting context layout
        let child_rel_pos = tree.warm(child_index)
            .and_then(|w| w.relative_position)
            .unwrap_or_default();
        let child_abs_pos = LogicalPosition::new(
            content_box_pos.x + child_rel_pos.x,
            content_box_pos.y + child_rel_pos.y,
        );

        super::pos_set(calculated_positions, child_index, child_abs_pos);

        // Calculate child's content-box position for recursion
        let cbp = child_node.box_props.unpack();
        let child_content_box_pos = LogicalPosition::new(
            child_abs_pos.x + cbp.border.left + cbp.padding.left,
            child_abs_pos.y + cbp.border.top + cbp.padding.top,
        );
        
        // Recurse to grandchildren
        position_bfc_child_descendants(tree, child_index, child_content_box_pos, calculated_positions);
    }
}

/// Processes out-of-flow children (absolute/fixed positioned elements).
///
/// Out-of-flow elements don't appear in `layout_output.positions` but still need
/// a static position for when no explicit offsets are specified. This sets their
/// static position to the parent's content-box origin.
fn process_out_of_flow_children<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    tree: &mut LayoutTree,
    text_cache: &mut TextLayoutCache,
    node_index: usize,
    self_content_box_pos: LogicalPosition,
    containing_block_size: LogicalSize,
    calculated_positions: &mut super::PositionVec,
    reflow_needed_for_scrollbars: &mut bool,
    float_cache: &mut HashMap<usize, fc::FloatingContext>,
) -> Result<()> {
    // Collect out-of-flow children (those not already positioned)
    let out_of_flow_children: Vec<(usize, Option<NodeId>)> = {
        let current_node = tree.get(node_index).ok_or(LayoutError::InvalidTree)?;
        tree.children(node_index)
            .iter()
            .filter_map(|&child_index| {
                if super::pos_contains(calculated_positions, child_index) {
                    return None;
                }
                let child = tree.get(child_index)?;
                Some((child_index, child.dom_node_id))
            })
            .collect()
    };

    for (child_index, child_dom_id_opt) in out_of_flow_children {
        let Some(child_dom_id) = child_dom_id_opt else {
            continue;
        };

        let position_type = get_position_type(ctx.styled_dom, Some(child_dom_id));
        if position_type != LayoutPosition::Absolute && position_type != LayoutPosition::Fixed {
            continue;
        }

        // Set static position to parent's content-box origin
        super::pos_set(calculated_positions, child_index, self_content_box_pos);

        // Perform full layout for the absolutely positioned child so its
        // inline_layout_result is populated (text rendering needs this).
        // The containing block for abs-pos is the parent's padding box.
        calculate_layout_for_subtree(
            ctx,
            tree,
            text_cache,
            child_index,
            self_content_box_pos,
            containing_block_size,
            calculated_positions,
            reflow_needed_for_scrollbars,
            float_cache,
            ComputeMode::PerformLayout,
        )?;
    }

    Ok(())
}

/// Recursive, top-down pass to calculate used sizes and positions for a given subtree.
/// This is the single, authoritative function for in-flow layout.
///
/// Uses the per-node multi-slot cache (inspired by Taffy's 9+1 architecture) to
/// avoid O(n²) complexity. Each node has 9 measurement slots + 1 full layout slot.
///
/// ## Two-Mode Architecture (CSS Two-Pass Layout)
///
/// `compute_mode` determines behavior:
///
/// - **`ComputeSize`** (BFC Pass 1 — sizing):
///   Computes only the node's border-box size. On cache hit from measurement slots,
///   sets `used_size` and returns immediately — no child positioning. This is the
///   key to O(n) two-pass BFC: Pass 1 fills measurement caches cheaply.
///
/// - **`PerformLayout`** (BFC Pass 2 — positioning):
///   Computes size AND positions all children. On cache hit from layout slot,
///   applies cached child positions recursively. When Pass 2 provides the same
///   constraints as Pass 1, the "result matches request" optimization triggers
///   automatic cache hits.
///
/// ## Cache Hit Rates (Taffy's "result matches request" optimization)
///
/// When Pass 1 measures a node with `available_size` A and gets `result_size` R,
/// then Pass 2 provides R as a `known_dimension`, `get_size()` / `get_layout()`
/// recognize R == `cached.result_size` as a cache hit. This is the fundamental
/// mechanism ensuring O(n) total complexity across both passes.
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher HashMap/HashSet
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if laying out the subtree fails.
pub fn calculate_layout_for_subtree<T: ParsedFontTrait>(
    ctx: &mut LayoutContext<'_, T>,
    tree: &mut LayoutTree,
    text_cache: &mut TextLayoutCache,
    node_index: usize,
    containing_block_pos: LogicalPosition,
    containing_block_size: LogicalSize,
    calculated_positions: &mut super::PositionVec,
    reflow_needed_for_scrollbars: &mut bool,
    float_cache: &mut HashMap<usize, fc::FloatingContext>,
    compute_mode: ComputeMode,
) -> Result<()> {
    // [g147b az-web-lift DIAG] per-node calculate_layout_for_subtree entry (0x60980+slot): records the
    // last compute_mode that reached this node (PerformLayout=2 wins, runs after ComputeSize=1). If a div
    // shows 0x...0002 here but its layout_formatting_context marker (0x609A0+) is UNSET → positioning
    // reached calculate but short-circuited (cache hit) before dispatching to the formatting context.
    #[cfg(feature = "web_lift")]
    unsafe {
        let m = match compute_mode { ComputeMode::PerformLayout => 0xC0DE0002u32, _ => 0xC0DE0001u32 };
        crate::az_mark(((0x60980 + (node_index & 7) * 4)) as u32, (m) as u32);
    }
    let _probe = match compute_mode {
        ComputeMode::ComputeSize => crate::probe::Probe::span("size_node"),
        ComputeMode::PerformLayout => crate::probe::Probe::span("pos_node"),
    };
    // HIT path; 0x60 = reached cache-miss compute.) Distinguishes stub/not-entered vs an
    // early Err in the cache-check vs the compute path.
    // === PER-NODE CACHE CHECK (Taffy-inspired 9+1 slot cache) ===
    //
    // Two-mode cache lookup (CSS two-pass architecture):
    //
    // ComputeSize (Pass 1 — sizing):
    //   1. Check measurement slots (get_size) → if hit, set used_size and return.
    //      No child positioning needed — we only need the node's border-box size.
    //   2. Fall back to layout slot → if hit, extract size from full layout result.
    //
    // PerformLayout (Pass 2 — positioning):
    //   1. Check layout slot (get_layout) → if hit, apply cached child positions.
    //   2. No fallback to measurement slots (we need full positions, not just size).
    //
    // This split is critical for O(n) two-pass BFC:
    // - Pass 1 populates measurement slots (cheap: no absolute positioning)
    // - Pass 2 hits layout slot or re-computes with positions
    if node_index < ctx.cache_map.entries.len() {
        match compute_mode {
            ComputeMode::ComputeSize => {
                // ComputeSize: check measurement slot first (Taffy's 9-slot scheme).
                // TODO(superplan): only slot 0 is ever read/written — the other 8
                // measurement slots are dead. To wire the full multi-slot scheme,
                // classify `containing_block_size` into (width_known, height_known,
                // width_type, height_type) and select the slot via
                // `NodeCache::slot_index(..)` here and at the matching `store_size`.
                let sizing_hit = ctx.cache_map.entries[node_index]
                    .get_size(0, containing_block_size)
                    .copied();
                if let Some(cached_sizing) = sizing_hit {
                    // SIZING CACHE HIT — set used_size and return immediately.
                    // No child positioning needed in ComputeSize mode.
                    drop(crate::probe::Probe::span("size_cache_hit_sizing"));
                    if let Some(node) = tree.get_mut(node_index) {
                        node.used_size = Some(cached_sizing.result_size);
                    }
                    if let Some(warm) = tree.warm_mut(node_index) {
                        warm.escaped_top_margin = cached_sizing.escaped_top_margin;
                        warm.escaped_bottom_margin = cached_sizing.escaped_bottom_margin;
                        warm.baseline = cached_sizing.baseline;
                    }
                    return Ok(());
                }
                // Fall through to layout slot check
                let layout_hit = ctx.cache_map.entries[node_index]
                    .get_layout(containing_block_size)
                    .cloned();
                if let Some(cached_layout) = layout_hit {
                    // Layout slot hit in ComputeSize mode — extract size only
                    drop(crate::probe::Probe::span("size_cache_hit_layout"));
                    if let Some(node) = tree.get_mut(node_index) {
                        node.used_size = Some(cached_layout.result_size);
                    }
                    if let Some(warm) = tree.warm_mut(node_index) {
                        warm.overflow_content_size = Some(cached_layout.content_size);
                        warm.scrollbar_info = Some(cached_layout.scrollbar_info);
                    }
                    return Ok(());
                }
                // [g147c az-web-lift DIAG] ComputeSize cache MISS for this node (0x60A60+slot): the
                // compute path WILL run → layout_formatting_context should fire. If a div is sized by
                // Pass-1 (0x60A40 set) but this miss-flag is UNSET → calculate(child,ComputeSize) hit
                // the cache instead (so layout_formatting_context/layout_ifc were skipped).
                #[cfg(feature = "web_lift")]
                unsafe { crate::az_mark(((0x60A60 + (node_index & 7) * 4)) as u32, (0xC0DE0001) as u32); }
                drop(crate::probe::Probe::span("size_cache_miss"));
            }
            ComputeMode::PerformLayout => {
                // PerformLayout: check layout slot (the single "full layout" slot)
                let layout_hit = ctx.cache_map.entries[node_index]
                    .get_layout(containing_block_size)
                    .cloned();
                if let Some(cached_layout) = layout_hit {
                    drop(crate::probe::Probe::span("pos_cache_hit"));
                    // LAYOUT CACHE HIT — apply cached results with child positions
                    if let Some(node) = tree.get_mut(node_index) {
                        node.used_size = Some(cached_layout.result_size);
                    }
                    if let Some(warm) = tree.warm_mut(node_index) {
                        warm.overflow_content_size = Some(cached_layout.content_size);
                        warm.scrollbar_info = Some(cached_layout.scrollbar_info);
                    }

                    let box_props = tree.get(node_index)
                        .map(|n| n.box_props.unpack())
                        .unwrap_or_default();
                    let writing_mode = tree
                        .warm(node_index)
                        .map(|w| w.computed_style.writing_mode)
                        .unwrap_or_default();
                    let self_content_box_pos = calculate_content_box_pos(containing_block_pos, &box_props);

                    // Apply cached child positions and recurse
                    let result_size = cached_layout.result_size;
                    for (child_index, child_relative_pos) in &cached_layout.child_positions {
                        let child_abs_pos = LogicalPosition::new(
                            self_content_box_pos.x + child_relative_pos.x,
                            self_content_box_pos.y + child_relative_pos.y,
                        );
                        super::pos_set(calculated_positions, *child_index, child_abs_pos);

                        let inner = box_props.inner_size(
                            result_size,
                            writing_mode,
                        );
                        // Subtract scrollbar reservation from the available size
                        // passed to children. This mirrors what layout_bfc does in
                        // the MISS path — without it, a reflow-loop cache hit
                        // would hand children the full content-box width, ignoring
                        // any vertical/horizontal scrollbar that was detected.
                        let child_available_size =
                            cached_layout.scrollbar_info.shrink_size(inner);
                        calculate_layout_for_subtree(
                            ctx,
                            tree,
                            text_cache,
                            *child_index,
                            child_abs_pos,
                            child_available_size,
                            calculated_positions,
                            reflow_needed_for_scrollbars,
                            float_cache,
                            compute_mode,
                        )?;
                    }

                    return Ok(());
                }
            }
        }
    }
    
    // === CACHE MISS — compute layout ===
    if compute_mode == ComputeMode::PerformLayout {
        drop(crate::probe::Probe::span("pos_cache_miss"));
    }

    // returned Ok; 0x64 = layout_formatting_context returned Ok. Last value before the
    // Err pins the failing phase (fires per recursive node; bare body is shallow).
    // Phase 1: Prepare layout context (calculate used size, constraints)
    let PreparedLayoutContext {
        constraints,
        dom_id,
        writing_mode,
        mut final_used_size,
        box_props,
    } = {
        let _p = crate::probe::Probe::span("prepare_layout_context");
        prepare_layout_context(ctx, tree, node_index, containing_block_size)?
    };

    // Phase 1.5: Update used_size BEFORE calling layout_formatting_context.
    //
    // When a node is cloned from the old tree (clone_node_from_old), its used_size
    // retains the value from the previous layout pass. If the containing block changed
    // (e.g. viewport resize), the stale used_size would cause layout_bfc() to compute
    // an incorrect children_containing_block_size. By updating used_size here, we ensure
    // that layout_bfc reads the freshly resolved size from prepare_layout_context.
    {
        let is_table_cell = tree.get(node_index).is_some_and(|n| {
            matches!(n.formatting_context, FormattingContext::TableCell)
        });
        if !is_table_cell {
            if let Some(node) = tree.get_mut(node_index) {
                node.used_size = Some(final_used_size);
            }
        }
    }

    // Phase 2: Layout children using the formatting context
    let layout_result = {
        let _p = crate::probe::Probe::span("layout_formatting_context");
        layout_formatting_context(ctx, tree, text_cache, node_index, &constraints, float_cache)?
    };
    let content_size = layout_result.output.overflow_size;

    // If layout_formatting_context adjusted this node's used_size (e.g.
    // layout_flex_grid auto-applying box-sizing:border-box on the root),
    // propagate that back into final_used_size so Phase 3 (scrollbars),
    // Phase 4 (final write), and the self_content_box_pos calculation all
    // see the same border-box that the children were laid out inside.
    if let Some(adjusted) = tree.get(node_index).and_then(|n| n.used_size) {
        final_used_size = adjusted;
    }

    // Phase 2.5: Resolve 'auto' main-axis size based on content
    // For anonymous boxes, use default styled node state
    let styled_node_state = dom_id
        .and_then(|id| ctx.styled_dom.styled_nodes.as_container().get(id).cloned())
        .map(|n| n.styled_node_state)
        .unwrap_or_default();

    let css_height: MultiValue<LayoutHeight> = match dom_id {
        Some(id) => get_css_height(ctx.styled_dom, id, &styled_node_state),
        None => MultiValue::Auto, // Anonymous boxes have auto height
    };

    // +spec:overflow:44ef3b - scroll container detection: overflow scroll/auto makes box a scroll container
    // Check if this node is a scroll container (overflow: scroll/auto).
    // Scroll containers must NOT expand to fit content — their height is
    // determined by the containing block, and overflow is scrollable.
    //
    // Exception: if the containing block height is infinite (unconstrained),
    // we must still grow, since you can't scroll inside an infinitely tall box.
    let is_scroll_container = dom_id.is_some_and(|id| {
        let ov_x = get_overflow_x(ctx.styled_dom, id, &styled_node_state);
        let ov_y = get_overflow_y(ctx.styled_dom, id, &styled_node_state);
        matches!(ov_x, MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto))
            || matches!(ov_y, MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto))
    });

    if should_use_content_height(&css_height) {
        let skip_expansion = is_scroll_container
            && containing_block_size.height.is_finite()
            && containing_block_size.height > 0.0;

        if !skip_expansion {
            final_used_size = apply_content_based_height(
                final_used_size,
                content_size,
                tree,
                node_index,
                writing_mode,
            )?;
        }
    }

    // Phase 3: Scrollbar handling
    // Anonymous boxes don't have scrollbars
    let skip_scrollbar_check = ctx.fragmentation_context.is_some();
    let scrollbar_info = dom_id.map_or_else(ScrollbarRequirements::default, |id| {
        compute_scrollbar_info(
            ctx,
            id,
            &styled_node_state,
            content_size,
            &box_props,
            final_used_size,
            writing_mode,
        )
    });

    if check_scrollbar_change(tree, node_index, &scrollbar_info, skip_scrollbar_check) {
        *reflow_needed_for_scrollbars = true;
    }

    let merged_scrollbar_info = scrollbar_info;
    let content_box_size = box_props.inner_size(final_used_size, writing_mode);
    let inner_size_after_scrollbars = merged_scrollbar_info.shrink_size(content_box_size);

    // Phase 4: Update this node's state
    let self_content_box_pos = {
        {
            let current_node = tree.get_mut(node_index).ok_or(LayoutError::InvalidTree)?;

            // Table cells get their size from the table layout algorithm, don't overwrite
            let is_table_cell = matches!(
                current_node.formatting_context,
                FormattingContext::TableCell
            );
            if !is_table_cell || current_node.used_size.is_none() {
                current_node.used_size = Some(final_used_size);
            }
        }

        // Update warm fields
        if let Some(warm) = tree.warm_mut(node_index) {
            warm.scrollbar_info = Some(merged_scrollbar_info);
            // Store overflow content size for scroll frame calculation
            // +spec:overflow:f28d6a - hanging glyphs should be ink overflow, not scrollable overflow (not yet subtracted from content_size)
            warm.overflow_content_size = Some(content_size);
        }

        // self_content_box_pos is [CoordinateSpace::Window] - the absolute position of this node's content-box
        let current_node = tree.get(node_index).ok_or(LayoutError::InvalidTree)?;
        let current_bp = current_node.box_props.unpack();
        let pos = calculate_content_box_pos(containing_block_pos, &current_bp);
        log_content_box_calculation(ctx, node_index, current_node, containing_block_pos, pos);
        pos
    };

    // Phase 5: Determine formatting context type
    let is_flex_or_grid = {
        let node = tree.get(node_index).ok_or(LayoutError::InvalidTree)?;
        matches!(
            node.formatting_context,
            FormattingContext::Flex | FormattingContext::Grid
        )
    };

    // Phase 6: Process in-flow children
    // Positions in layout_result.output.positions are [CoordinateSpace::Parent] - relative to this node's content-box
    let positions: Vec<_> = layout_result
        .output
        .positions
        .iter()
        .map(|(&idx, &pos)| (idx, pos))
        .collect();

    // Store child positions for cache
    let child_positions_for_cache: Vec<(usize, LogicalPosition)> = positions.clone();

    for (child_index, child_relative_pos) in positions {
        process_inflow_child(
            ctx,
            tree,
            text_cache,
            child_index,
            child_relative_pos,
            self_content_box_pos,
            inner_size_after_scrollbars,
            writing_mode,
            is_flex_or_grid,
            calculated_positions,
            *reflow_needed_for_scrollbars,
            float_cache,
        )?;
    }

    // Phase 7: Process out-of-flow children (absolute/fixed)
    process_out_of_flow_children(
        ctx,
        tree,
        text_cache,
        node_index,
        self_content_box_pos,
        inner_size_after_scrollbars,
        calculated_positions,
        reflow_needed_for_scrollbars,
        float_cache,
    )?;

    // === STORE RESULT IN PER-NODE CACHE (Taffy-inspired 9+1 slot cache) ===
    // Store both the full layout entry and a sizing measurement entry.
    // This enables O(n) two-pass BFC: Pass 1 populates cache, Pass 2 reads it.
    if node_index < ctx.cache_map.entries.len() {
        let warm_ref = tree.warm(node_index);
        let baseline = warm_ref.and_then(|n| n.baseline);
        let escaped_top = warm_ref.and_then(|n| n.escaped_top_margin);
        let escaped_bottom = warm_ref.and_then(|n| n.escaped_bottom_margin);

        // Store in the layout slot (PerformLayout result)
        ctx.cache_map.get_mut(node_index).store_layout(LayoutCacheEntry {
            available_size: containing_block_size,
            result_size: final_used_size,
            content_size,
            child_positions: child_positions_for_cache,
            escaped_top_margin: escaped_top,
            escaped_bottom_margin: escaped_bottom,
            scrollbar_info: merged_scrollbar_info,
        });

        // Also store in a measurement slot (slot 0: both dimensions known).
        // This enables the "result matches request" optimization (Taffy pattern):
        // when Pass 2 provides the same size as Pass 1 measured, it's a cache hit.
        // TODO(superplan): see the matching note at the `get_size(0, ..)` site —
        // slots 1-8 are unused; wire `NodeCache::slot_index(..)` to populate them.
        ctx.cache_map.get_mut(node_index).store_size(0, SizingCacheEntry {
            available_size: containing_block_size,
            result_size: final_used_size,
            baseline,
            escaped_top_margin: escaped_top,
            escaped_bottom_margin: escaped_bottom,
        });
    }

    Ok(())
}

/// Recursively set static positions for out-of-flow descendants without doing layout
/// Recursively positions descendants of Flex/Grid children.
///
/// When a Flex container lays out its children via Taffy, the children have their
/// `used_size` and `relative_position` set, but their GRANDCHILDREN don't have positions
/// in `calculated_positions` yet. This function traverses down the tree and positions
/// all descendants properly.
fn position_flex_child_descendants(
    tree: &mut LayoutTree,
    node_index: usize,
    content_box_pos: LogicalPosition,
    available_size: LogicalSize,
    calculated_positions: &mut super::PositionVec,
) -> Result<()> {
    let children: Vec<usize> = tree.children(node_index).to_vec();

    for &child_index in &children {
        let child_node = tree.get(child_index).ok_or(LayoutError::InvalidTree)?;
        let child_rel_pos = tree.warm(child_index)
            .and_then(|w| w.relative_position)
            .unwrap_or_default();
        let child_abs_pos = LogicalPosition::new(
            content_box_pos.x + child_rel_pos.x,
            content_box_pos.y + child_rel_pos.y,
        );

        // Insert position
        super::pos_set(calculated_positions, child_index, child_abs_pos);

        // Get child's content box for recursion
        let cbp = child_node.box_props.unpack();
        let child_writing_mode = tree
            .warm(child_index)
            .map(|w| w.computed_style.writing_mode)
            .unwrap_or_default();
        let child_content_box = LogicalPosition::new(
            child_abs_pos.x
                + cbp.border.left
                + cbp.padding.left,
            child_abs_pos.y
                + cbp.border.top
                + cbp.padding.top,
        );
        let child_inner_size = cbp.inner_size(
            child_node.used_size.unwrap_or_default(),
            child_writing_mode,
        );

        // Recurse
        position_flex_child_descendants(
            tree,
            child_index,
            child_content_box,
            child_inner_size,
            calculated_positions,
        )?;
    }

    Ok(())
}

/// Checks if the given CSS height value should use content-based sizing
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't merge)
fn should_use_content_height(css_height: &MultiValue<LayoutHeight>) -> bool {
    match css_height {
        MultiValue::Auto | MultiValue::Initial | MultiValue::Inherit => {
            // Auto/Initial/Inherit height should use content-based sizing
            true
        }
        MultiValue::Exact(height) => match height {
            LayoutHeight::Auto => {
                // Auto height should use content-based sizing
                true
            }
            LayoutHeight::Px(px) => {
                // Check if it's zero or if it has explicit value
                // If it's a percentage or em, it's not auto
                use azul_css::props::basic::{pixel::PixelValue, SizeMetric};
                px == &PixelValue::zero()
                    || (px.metric != SizeMetric::Px
                        && px.metric != SizeMetric::Percent
                        && px.metric != SizeMetric::Em
                        && px.metric != SizeMetric::Rem)
            }
            LayoutHeight::MinContent | LayoutHeight::MaxContent | LayoutHeight::FitContent(_) => {
                // These are content-based, so they should use the content size
                true
            }
            LayoutHeight::Calc(_) => {
                // Calc expressions are not auto, they compute to a specific value
                false
            }
        },
    }
}

/// Applies content-based height sizing to a node
///
/// **Note**: This function respects min-height/max-height constraints from Phase 1.
///
/// According to CSS 2.2 § 10.7, when height is 'auto', the final height must be
/// `max(min_height`, `min(content_height`, `max_height`)).
///
/// The `used_size` parameter already contains the size constrained by
/// min-height/max-height from the initial sizing pass. We must take the
/// maximum of this constrained size and the new content-based size to ensure
/// min-height is not lost.
fn apply_content_based_height(
    mut used_size: LogicalSize,
    content_size: LogicalSize,
    tree: &LayoutTree,
    node_index: usize,
    writing_mode: LayoutWritingMode,
) -> Result<LogicalSize> {
    let node_props = tree.get(node_index).ok_or(LayoutError::InvalidTree)?.box_props.unpack();
    let main_axis_padding_border =
        node_props.padding.main_sum(writing_mode) + node_props.border.main_sum(writing_mode);

    // CRITICAL: 'old_main_size' holds the size constrained by min-height/max-height from Phase 1
    let old_main_size = used_size.main(writing_mode);
    let new_main_size = content_size.main(writing_mode) + main_axis_padding_border;

    // Final size = max(min_height_constrained_size, content_size)
    // This ensures that min-height is respected even when content is smaller
    let final_main_size = old_main_size.max(new_main_size);

    used_size = used_size.with_main(writing_mode, final_main_size);

    Ok(used_size)
}

// hash_styled_node_data() removed — replaced by NodeDataFingerprint::compute()

fn calculate_subtree_hash(node_self_hash: u64, child_hashes: &[u64]) -> SubtreeHash {
    let mut hasher = DefaultHasher::new();
    node_self_hash.hash(&mut hasher);
    child_hashes.hash(&mut hasher);
    SubtreeHash(hasher.finish())
}

/// Computes CSS counter values for all nodes in the layout tree.
///
/// This function traverses the tree in document order and processes counter-reset
/// and counter-increment properties. The computed values are stored in cache.counters.
///
/// CSS counters work with a stack-based scoping model:
/// - `counter-reset` creates a new scope and sets the counter to a value
/// - `counter-increment` increments the counter in the current scope
/// - When leaving a subtree, counter scopes are popped
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher HashMap/HashSet
pub fn compute_counters(
    styled_dom: &StyledDom,
    tree: &LayoutTree,
    counters: &mut HashMap<(usize, String), i32>,
) {
    // Track counter stacks: counter_name -> Vec<value>
    // Each entry in the Vec represents a nested scope
    let mut counter_stacks: HashMap<String, Vec<i32>> = HashMap::new();

    // Stack to track which counters were reset at each tree level
    // When we pop back up the tree, we need to pop these counter scopes
    let mut scope_stack: Vec<Vec<String>> = Vec::new();

    compute_counters_recursive(
        styled_dom,
        tree,
        tree.root,
        counters,
        &mut counter_stacks,
        &mut scope_stack,
    );
}

#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
fn compute_counters_recursive(
    styled_dom: &StyledDom,
    tree: &LayoutTree,
    node_idx: usize,
    counters: &mut HashMap<(usize, String), i32>,
    counter_stacks: &mut HashMap<String, Vec<i32>>,
    scope_stack: &mut Vec<Vec<String>>,
) {
    let Some(node) = tree.get(node_idx) else {
        return;
    };

    // Skip pseudo-elements (::marker, ::before, ::after) for counter processing
    // Pseudo-elements inherit counter values from their parent element
    // but don't participate in counter-reset or counter-increment themselves
    if tree.warm(node_idx).and_then(|w| w.pseudo_element.as_ref()).is_some() {
        // Store the parent's counter values for this pseudo-element
        // so it can be looked up during marker text generation
        if let Some(parent_idx) = node.parent {
            // Copy all counter values from parent to this pseudo-element
            let parent_counters: Vec<_> = counters
                .iter()
                .filter(|((idx, _), _)| *idx == parent_idx)
                .map(|((_, name), &value)| (name.clone(), value))
                .collect();

            for (counter_name, value) in parent_counters {
                counters.insert((node_idx, counter_name), value);
            }
        }

        // Don't recurse to children of pseudo-elements
        // (pseudo-elements shouldn't have children in normal circumstances)
        return;
    }

    // Only process real DOM nodes, not anonymous boxes
    let Some(dom_id) = node.dom_node_id else {
        // For anonymous boxes, just recurse to children
        for &child_idx in tree.children(node_idx) {
            compute_counters_recursive(
                styled_dom,
                tree,
                child_idx,
                counters,
                counter_stacks,
                scope_stack,
            );
        }
        return;
    };

    let node_data = &styled_dom.node_data.as_container()[dom_id];
    let node_state = &styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
    let cache = &styled_dom.css_property_cache.ptr;

    // Track which counters we reset at this level (for cleanup later)
    let mut reset_counters_at_this_level = Vec::new();

    // CSS Lists §3: display: list-item automatically increments the "list-item" counter
    // Check if this is a list-item
    let display = {
        use crate::solver3::getters::get_display_property;
        get_display_property(styled_dom, Some(dom_id)).exact()
    };
    let is_list_item = matches!(display, Some(LayoutDisplay::ListItem));

    // FAST PATH: almost no nodes declare counter-reset/counter-increment.
    // Single-bit check in compact cache lets us skip two cascade walks per node.
    let has_counter_css = node_state.is_normal()
        && cache.compact_cache.as_ref().is_none_or(|cc| cc.has_counter(dom_id.index()));

    // Process counter-reset (now properly typed)
    let counter_reset = if has_counter_css {
        cache
            .get_counter_reset(node_data, &dom_id, node_state)
            .and_then(|v| v.get_property())
    } else {
        None
    };

    if let Some(counter_reset) = counter_reset {
        let counter_name_str = counter_reset.counter_name.as_str();
        if counter_name_str != "none" {
            let counter_name = counter_name_str.to_string();
            let reset_value = counter_reset.value;

            // Reset the counter by pushing a new scope
            counter_stacks
                .entry(counter_name.clone())
                .or_default()
                .push(reset_value);
            reset_counters_at_this_level.push(counter_name);
        }
    }

    // Process counter-increment (now properly typed)
    let counter_inc = if has_counter_css {
        cache
            .get_counter_increment(node_data, &dom_id, node_state)
            .and_then(|v| v.get_property())
    } else {
        None
    };

    if let Some(counter_inc) = counter_inc {
        let counter_name_str = counter_inc.counter_name.as_str();
        if counter_name_str != "none" {
            let counter_name = counter_name_str.to_string();
            let inc_value = counter_inc.value;

            // Increment the counter in the current scope
            let stack = counter_stacks.entry(counter_name).or_default();
            if stack.is_empty() {
                // Auto-initialize if counter doesn't exist
                stack.push(inc_value);
            } else if let Some(current) = stack.last_mut() {
                *current += inc_value;
            }
        }
    }

    // CSS Lists §3: display: list-item automatically increments "list-item" counter
    if is_list_item {
        let counter_name = "list-item".to_string();
        let stack = counter_stacks.entry(counter_name).or_default();
        if stack.is_empty() {
            // Auto-initialize if counter doesn't exist
            stack.push(1);
        } else if let Some(current) = stack.last_mut() {
            *current += 1;
        }
    }

    // Store the current counter values for this node
    for (counter_name, stack) in counter_stacks.iter() {
        if let Some(&value) = stack.last() {
            counters.insert((node_idx, counter_name.clone()), value);
        }
    }

    // Push scope tracking for cleanup
    scope_stack.push(reset_counters_at_this_level.clone());

    // Recurse to children
    for &child_idx in tree.children(node_idx) {
        compute_counters_recursive(
            styled_dom,
            tree,
            child_idx,
            counters,
            counter_stacks,
            scope_stack,
        );
    }

    // Pop counter scopes that were created at this level
    if let Some(reset_counters) = scope_stack.pop() {
        for counter_name in reset_counters {
            if let Some(stack) = counter_stacks.get_mut(&counter_name) {
                stack.pop();
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod autotest_generated {
    use azul_core::dom::{Dom, IdOrClass};
    use azul_css::props::{
        basic::{pixel::PixelValue, SizeMetric},
        layout::dimensions::CalcAstItemVec,
    };

    use super::*;
    use crate::solver3::{
        display_list::DisplayList,
        geometry::{EdgeSizes, MarginAuto, PackedBoxProps, ResolvedBoxProps},
        layout_tree::{LayoutNodeCold, LayoutNodeWarm},
        pos_get, PositionVec, POSITION_UNSET,
    };

    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------

    fn size(w: f32, h: f32) -> LogicalSize {
        LogicalSize::new(w, h)
    }

    fn pos(x: f32, y: f32) -> LogicalPosition {
        LogicalPosition::new(x, y)
    }

    fn sizing_entry(available: LogicalSize, result: LogicalSize) -> SizingCacheEntry {
        SizingCacheEntry {
            available_size: available,
            result_size: result,
            baseline: None,
            escaped_top_margin: None,
            escaped_bottom_margin: None,
        }
    }

    fn layout_entry(available: LogicalSize, result: LogicalSize) -> LayoutCacheEntry {
        LayoutCacheEntry {
            available_size: available,
            result_size: result,
            content_size: result,
            child_positions: Vec::new(),
            escaped_top_margin: None,
            escaped_bottom_margin: None,
            scrollbar_info: ScrollbarRequirements::default(),
        }
    }

    fn edges(top: f32, right: f32, bottom: f32, left: f32) -> EdgeSizes {
        EdgeSizes {
            top,
            right,
            bottom,
            left,
        }
    }

    fn box_props(margin: EdgeSizes, border: EdgeSizes, padding: EdgeSizes) -> ResolvedBoxProps {
        ResolvedBoxProps {
            margin,
            padding,
            border,
            margin_auto: MarginAuto::default(),
        }
    }

    fn zero_box_props() -> ResolvedBoxProps {
        box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
        )
    }

    fn hot(
        parent: Option<usize>,
        dom_node_id: Option<NodeId>,
        used_size: Option<LogicalSize>,
        bp: &ResolvedBoxProps,
    ) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::pack(bp),
            dom_node_id,
            used_size,
            formatting_context: FormattingContext::Block {
                establishes_new_context: false,
            },
            parent,
        }
    }

    /// Plain hot node with no box props and no DOM id.
    fn plain(parent: Option<usize>) -> LayoutNodeHot {
        hot(parent, None, Some(size(0.0, 0.0)), &zero_box_props())
    }

    /// Builds a `LayoutTree` from hot nodes + per-node child lists.
    /// `child_lists[i]` are the children of node `i`.
    fn build_tree(
        nodes: Vec<LayoutNodeHot>,
        warm: Vec<LayoutNodeWarm>,
        child_lists: &[Vec<usize>],
    ) -> LayoutTree {
        let n = nodes.len();
        let mut children_arena: Vec<usize> = Vec::new();
        let mut children_offsets: Vec<(u32, u32)> = Vec::with_capacity(n);
        for cl in child_lists {
            let start = u32::try_from(children_arena.len()).unwrap();
            children_arena.extend_from_slice(cl);
            children_offsets.push((start, u32::try_from(cl.len()).unwrap()));
        }
        while children_offsets.len() < n {
            children_offsets.push((0, 0));
        }
        LayoutTree {
            nodes,
            warm,
            cold: vec![LayoutNodeCold::default(); n],
            root: 0,
            dom_to_layout: BTreeMap::new(),
            children_arena,
            children_offsets,
            subtree_needs_intrinsic: Vec::new(),
        }
    }

    fn warm_default(n: usize) -> Vec<LayoutNodeWarm> {
        vec![LayoutNodeWarm::default(); n]
    }

    fn div_class(class: &str) -> Dom {
        Dom::create_div().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
    }

    fn styled(dom: Dom, css_str: &str) -> StyledDom {
        let mut dom = dom;
        let (css, _warnings) = azul_css::parser2::new_from_str(css_str);
        StyledDom::create(&mut dom, css)
    }

    /// `body(0) > .p(1) > [ text " \n\t"(2), text "hi"(3), div(4), text NBSP(5) ]`
    ///
    /// DOM ids follow the depth-first pre-order numbering of `CompactDom`.
    fn whitespace_dom(css_str: &str) -> StyledDom {
        styled(
            Dom::create_body().with_child(
                div_class("p")
                    .with_child(Dom::create_text(" \n\t"))
                    .with_child(Dom::create_text("hi"))
                    .with_child(Dom::create_div())
                    .with_child(Dom::create_text("\u{00A0}")),
            ),
            css_str,
        )
    }

    // ==================================================================
    // NodeCache — slot cache (numeric / round-trip)
    // ==================================================================

    #[test]
    fn nodecache_default_is_empty_and_never_hits() {
        let c = NodeCache::default();
        assert!(c.is_empty);
        assert!(c.layout_entry.is_none());
        assert!(c.measure_entries.iter().all(Option::is_none));
        for slot in 0..9 {
            assert!(c.get_size(slot, size(0.0, 0.0)).is_none());
            assert!(c.get_size(slot, size(100.0, 100.0)).is_none());
        }
        assert!(c.get_layout(size(0.0, 0.0)).is_none());
    }

    #[test]
    fn nodecache_store_size_then_exact_lookup_round_trips() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(200.0, 100.0), size(50.0, 40.0)));
        assert!(!c.is_empty);

        let hit = c.get_size(0, size(200.0, 100.0)).expect("exact hit");
        assert_eq!(hit.available_size, size(200.0, 100.0));
        assert_eq!(hit.result_size, size(50.0, 40.0));
    }

    #[test]
    fn nodecache_get_size_result_matches_request() {
        // Taffy's key optimization: Pass 2 hands back the size Pass 1 produced.
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(200.0, 100.0), size(50.0, 40.0)));

        let hit = c.get_size(0, size(50.0, 40.0)).expect("result-matches-request hit");
        assert_eq!(hit.result_size, size(50.0, 40.0));
        // A size matching neither the request nor the result must miss.
        assert!(c.get_size(0, size(51.0, 41.0)).is_none());
    }

    #[test]
    fn nodecache_get_size_epsilon_boundary() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(100.0, 100.0), size(10.0, 10.0)));

        // Sub-epsilon drift on either axis is still a hit (CACHE_SIZE_EPSILON = 0.1).
        assert!(c.get_size(0, size(100.05, 99.95)).is_some());
        // A drift clearly past the epsilon is a miss on both the request and the
        // result comparison. (The exact `== EPSILON` boundary is deliberately not
        // asserted: `100.1f32 - 100.0f32` rounds to 0.09999847, just under it.)
        assert!(c.get_size(0, size(100.2, 100.0)).is_none());
        assert!(c.get_size(0, size(100.0, 99.5)).is_none());
    }

    #[test]
    fn nodecache_get_size_nan_request_misses_instead_of_panicking() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(100.0, 100.0), size(10.0, 10.0)));

        // NaN - x = NaN, and every NaN comparison is false → miss, not a hit.
        assert!(c.get_size(0, size(f32::NAN, 100.0)).is_none());
        assert!(c.get_size(0, size(100.0, f32::NAN)).is_none());
        assert!(c.get_size(0, size(f32::NAN, f32::NAN)).is_none());
    }

    #[test]
    fn nodecache_nan_and_infinite_entries_are_unreachable() {
        // An entry stored with a non-finite available/result size can never be
        // hit again (inf - inf = NaN, NaN - NaN = NaN) — the node simply gets
        // re-measured. That is safe, but it means such slots are dead weight.
        let mut c = NodeCache::default();
        c.store_size(
            0,
            sizing_entry(size(f32::INFINITY, f32::INFINITY), size(f32::INFINITY, f32::INFINITY)),
        );
        assert!(c.get_size(0, size(f32::INFINITY, f32::INFINITY)).is_none());

        c.store_size(1, sizing_entry(size(f32::NAN, f32::NAN), size(f32::NAN, f32::NAN)));
        assert!(c.get_size(1, size(f32::NAN, f32::NAN)).is_none());
        // ...but the cache still reports itself as populated.
        assert!(!c.is_empty);
    }

    #[test]
    fn nodecache_handles_zero_and_negative_sizes() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(0.0, 0.0), size(0.0, 0.0)));
        assert!(c.get_size(0, size(0.0, 0.0)).is_some());
        assert!(c.get_size(0, size(-0.0, -0.0)).is_some());

        c.store_size(1, sizing_entry(size(-100.0, -50.0), size(-1.0, -1.0)));
        let hit = c.get_size(1, size(-100.0, -50.0)).expect("negative sizes are deterministic");
        assert_eq!(hit.result_size, size(-1.0, -1.0));
    }

    #[test]
    fn nodecache_extreme_finite_sizes_do_not_panic() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(f32::MAX, f32::MIN), size(f32::MAX, f32::MIN)));
        // MAX - MAX == 0 → exact hit; no overflow panic on the subtraction.
        assert!(c.get_size(0, size(f32::MAX, f32::MIN)).is_some());
        // MIN - MAX overflows to -inf, abs() = inf, inf < 0.1 is false → miss.
        assert!(c.get_size(0, size(f32::MIN, f32::MAX)).is_none());
    }

    #[test]
    fn nodecache_slots_are_independent() {
        let mut c = NodeCache::default();
        c.store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        c.store_size(8, sizing_entry(size(2.0, 2.0), size(2.0, 2.0)));

        assert!(c.get_size(0, size(1.0, 1.0)).is_some());
        assert!(c.get_size(8, size(2.0, 2.0)).is_some());
        // No cross-talk between slots.
        assert!(c.get_size(0, size(2.0, 2.0)).is_none());
        assert!(c.get_size(8, size(1.0, 1.0)).is_none());
        assert!(c.get_size(4, size(1.0, 1.0)).is_none());
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn nodecache_get_size_slot_out_of_range_panics() {
        // There are exactly 9 measurement slots; slot 9 is a caller bug and is
        // reported as an index panic rather than silently returning None.
        let c = NodeCache::default();
        let _ = c.get_size(9, size(0.0, 0.0));
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn nodecache_store_size_slot_out_of_range_panics() {
        let mut c = NodeCache::default();
        c.store_size(9, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
    }

    #[test]
    fn nodecache_layout_slot_round_trips_and_matches_result() {
        let mut c = NodeCache::default();
        c.store_layout(layout_entry(size(800.0, 600.0), size(800.0, 123.0)));
        assert!(!c.is_empty);

        assert!(c.get_layout(size(800.0, 600.0)).is_some());
        // "Result matches request" applies to the layout slot too.
        let hit = c.get_layout(size(800.0, 123.0)).expect("result-matches-request");
        assert_eq!(hit.result_size, size(800.0, 123.0));
        assert!(c.get_layout(size(400.0, 300.0)).is_none());
        assert!(c.get_layout(size(f32::NAN, f32::NAN)).is_none());
    }

    #[test]
    fn nodecache_clear_wipes_every_slot() {
        let mut c = NodeCache::default();
        for slot in 0..9 {
            c.store_size(slot, sizing_entry(size(10.0, 10.0), size(10.0, 10.0)));
        }
        c.store_layout(layout_entry(size(10.0, 10.0), size(10.0, 10.0)));
        assert!(!c.is_empty);

        c.clear();

        assert!(c.is_empty);
        assert!(c.layout_entry.is_none());
        assert!(c.measure_entries.iter().all(Option::is_none));
        assert!(c.get_size(0, size(10.0, 10.0)).is_none());
        assert!(c.get_layout(size(10.0, 10.0)).is_none());

        // Clearing twice is harmless.
        c.clear();
        assert!(c.is_empty);
    }

    #[test]
    fn slot_index_always_lands_in_range_and_partitions_the_unknown_case() {
        use AvailableWidthType::{Definite, MaxContent, MinContent};
        let types = [Definite, MinContent, MaxContent];

        for &wt in &types {
            for &ht in &types {
                for wk in [true, false] {
                    for hk in [true, false] {
                        let slot = NodeCache::slot_index(wk, hk, wt, ht);
                        assert!(slot < 9, "slot {slot} out of the 9-slot range");
                    }
                }
            }
        }

        // Both known → always slot 0, regardless of the constraint types.
        for &wt in &types {
            for &ht in &types {
                assert_eq!(NodeCache::slot_index(true, true, wt, ht), 0);
            }
        }

        // Neither known → the 4 MinContent combos partition slots 5..=8.
        let mut neither: Vec<usize> = Vec::new();
        for &wt in &[Definite, MinContent] {
            for &ht in &[Definite, MinContent] {
                neither.push(NodeCache::slot_index(false, false, wt, ht));
            }
        }
        neither.sort_unstable();
        assert_eq!(neither, vec![5, 6, 7, 8]);
    }

    #[test]
    fn slot_index_collapses_definite_and_maxcontent_onto_one_slot() {
        use AvailableWidthType::{Definite, MaxContent, MinContent};
        // Documented: "MaxContent/Definite vs MinContent" share a slot.
        assert_eq!(
            NodeCache::slot_index(true, false, Definite, Definite),
            NodeCache::slot_index(true, false, MaxContent, Definite)
        );
        assert_ne!(
            NodeCache::slot_index(true, false, Definite, Definite),
            NodeCache::slot_index(true, false, MinContent, Definite)
        );
    }

    #[test]
    fn slot_index_keys_the_single_unknown_axis_off_the_known_axis_type() {
        use AvailableWidthType::{Definite, MinContent};
        // BEHAVIOUR PIN (deviates from Taffy): when only the width is known, the
        // slot is chosen from `width_type` — the type of the *known* axis — even
        // though the doc comment says it keys off "the unknown dimension(s)".
        // Taffy keys slot 1/2 off the height (the unknown axis) here. Same for
        // the mirrored (false, true) case, which keys off `height_type`.
        // Consequence: the height's MinContent-ness cannot select slot 2 at all,
        // so a MinContent and a Definite height measurement would collide in a
        // single slot once slots 1-8 are wired up (they are unused today).
        assert_eq!(NodeCache::slot_index(true, false, Definite, MinContent), 1);
        assert_eq!(NodeCache::slot_index(true, false, MinContent, Definite), 2);
        assert_eq!(NodeCache::slot_index(false, true, MinContent, Definite), 3);
        assert_eq!(NodeCache::slot_index(false, true, Definite, MinContent), 4);
    }

    // ==================================================================
    // LayoutCacheMap
    // ==================================================================

    #[test]
    fn cachemap_resize_to_tree_grows_shrinks_and_zeroes() {
        let mut m = LayoutCacheMap::default();
        assert!(m.entries.is_empty());

        m.resize_to_tree(0);
        assert!(m.entries.is_empty());

        m.resize_to_tree(3);
        assert_eq!(m.entries.len(), 3);
        assert!(m.entries.iter().all(|e| e.is_empty));

        // Populated entries survive a grow; new entries are dirty.
        m.get_mut(1).store_size(0, sizing_entry(size(5.0, 5.0), size(5.0, 5.0)));
        m.resize_to_tree(5);
        assert_eq!(m.entries.len(), 5);
        assert!(!m.get(1).is_empty);
        assert!(m.get(4).is_empty);

        // Shrink drops the tail.
        m.resize_to_tree(1);
        assert_eq!(m.entries.len(), 1);
        m.resize_to_tree(0);
        assert!(m.entries.is_empty());
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn cachemap_get_out_of_range_panics() {
        let m = LayoutCacheMap::default();
        let _ = m.get(0);
    }

    #[test]
    fn cachemap_mark_dirty_out_of_range_index_is_a_noop() {
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(2);
        m.get_mut(0).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));

        m.mark_dirty(99, &[]);
        m.mark_dirty(usize::MAX, &[]);

        // Guard clause hit: nothing was touched.
        assert!(!m.get(0).is_empty);
        assert_eq!(m.entries.len(), 2);
    }

    #[test]
    fn cachemap_mark_dirty_propagates_up_the_ancestor_chain() {
        // 0 <- 1 <- 2
        let tree = vec![plain(None), plain(Some(0)), plain(Some(1))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }

        m.mark_dirty(2, &tree);

        assert!(m.get(2).is_empty);
        assert!(m.get(1).is_empty);
        assert!(m.get(0).is_empty);
    }

    #[test]
    fn cachemap_mark_dirty_stops_at_the_first_dirty_ancestor() {
        // 0 (clean) <- 1 (already dirty) <- 2 (clean)
        let tree = vec![plain(None), plain(Some(0)), plain(Some(1))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        m.get_mut(0).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        m.get_mut(2).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));

        m.mark_dirty(2, &tree);

        assert!(m.get(2).is_empty);
        assert!(m.get(1).is_empty);
        // Early stop: the grandparent keeps its cached entry.
        assert!(!m.get(0).is_empty);
    }

    #[test]
    fn cachemap_mark_dirty_on_an_already_dirty_node_leaves_ancestors_alone() {
        let tree = vec![plain(None), plain(Some(0))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(2);
        m.get_mut(0).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        // entry 1 is fresh → already dirty

        m.mark_dirty(1, &tree);

        assert!(m.get(1).is_empty);
        assert!(!m.get(0).is_empty);
    }

    #[test]
    fn cachemap_mark_dirty_terminates_on_cyclic_parent_links() {
        // A malformed tree (0 <-> 1, and 2 as its own parent) must not spin
        // forever: the `is_empty` early-stop breaks every cycle after one lap.
        let tree = vec![plain(Some(1)), plain(Some(0)), plain(Some(2))];
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }

        m.mark_dirty(0, &tree);
        assert!(m.get(0).is_empty);
        assert!(m.get(1).is_empty);

        m.mark_dirty(2, &tree);
        assert!(m.get(2).is_empty);
    }

    #[test]
    fn cachemap_mark_dirty_survives_a_tree_that_disagrees_with_the_cache() {
        let mut m = LayoutCacheMap::default();
        m.resize_to_tree(3);
        for i in 0..3 {
            m.get_mut(i).store_size(0, sizing_entry(size(1.0, 1.0), size(1.0, 1.0)));
        }

        // Tree shorter than the cache: parent lookup returns None → stop.
        let short_tree = vec![plain(None)];
        m.mark_dirty(2, &short_tree);
        assert!(m.get(2).is_empty);
        assert!(!m.get(0).is_empty);

        // Parent index past the end of the cache: break, don't index-panic.
        let dangling = vec![plain(Some(usize::MAX)), plain(None), plain(None)];
        m.mark_dirty(0, &dangling);
        assert!(m.get(0).is_empty);
    }

    // ==================================================================
    // Solver3CacheMemoryReport / LayoutCache (getters)
    // ==================================================================

    #[test]
    fn memory_report_total_bytes_sums_every_field_exactly_once() {
        assert_eq!(Solver3CacheMemoryReport::default().total_bytes(), 0);

        // Distinct powers of two: a missing or double-counted field shows up as
        // a wrong total rather than an accidental coincidence.
        let r = Solver3CacheMemoryReport {
            tree_bytes: 1,
            tree_report: None,
            calculated_positions_bytes: 2,
            previous_positions_bytes: 4,
            scroll_ids_bytes: 8,
            scroll_id_to_node_id_bytes: 16,
            counters_bytes: 32,
            float_cache_bytes: 64,
            cache_map_bytes: 128,
            cached_display_list_bytes: 256,
        };
        assert_eq!(r.total_bytes(), 511);
    }

    #[test]
    fn memory_report_of_a_default_cache_is_all_zero() {
        let cache = LayoutCache::default();
        let r = cache.memory_report();
        assert_eq!(r.total_bytes(), 0);
        assert_eq!(r.tree_bytes, 0);
        assert!(r.tree_report.is_none());
        assert_eq!(r.cache_map_bytes, 0);
        assert_eq!(r.cached_display_list_bytes, 0);
    }

    #[test]
    fn memory_report_accounts_for_populated_state() {
        let mut cache = LayoutCache::default();
        cache.cache_map.resize_to_tree(4);
        cache.calculated_positions = vec![pos(1.0, 2.0), pos(3.0, 4.0), pos(5.0, 6.0)];
        cache.previous_positions = vec![pos(0.0, 0.0)];
        cache.counters.insert((0, "list-item".to_string()), 7);
        cache.float_cache.insert(0, fc::FloatingContext::default());
        cache.scroll_ids.insert(0, 42);
        cache.scroll_id_to_node_id.insert(42, NodeId::ZERO);
        cache.cached_display_list = Some((
            SubtreeHash(1),
            LogicalRect::new(pos(0.0, 0.0), size(10.0, 10.0)),
            DisplayList::default(),
        ));

        let r = cache.memory_report();

        assert!(r.cache_map_bytes >= 4 * size_of::<NodeCache>());
        assert_eq!(r.calculated_positions_bytes, 3 * size_of::<LogicalPosition>());
        assert_eq!(r.previous_positions_bytes, size_of::<LogicalPosition>());
        assert!(r.counters_bytes >= "list-item".len());
        assert_eq!(r.float_cache_bytes, 256);
        assert_eq!(r.cached_display_list_bytes, 2048);
        assert_eq!(
            r.total_bytes(),
            r.tree_bytes
                + r.calculated_positions_bytes
                + r.previous_positions_bytes
                + r.scroll_ids_bytes
                + r.scroll_id_to_node_id_bytes
                + r.counters_bytes
                + r.float_cache_bytes
                + r.cache_map_bytes
                + r.cached_display_list_bytes
        );
    }

    #[test]
    fn reset_incremental_drops_reuse_state_keeps_the_rest_and_is_idempotent() {
        let mut cache = LayoutCache {
            tree: Some(build_tree(vec![plain(None)], warm_default(1), &[vec![]])),
            ..Default::default()
        };
        cache.cache_map.resize_to_tree(2);
        cache.cached_display_list = Some((
            SubtreeHash(9),
            LogicalRect::new(pos(0.0, 0.0), size(1.0, 1.0)),
            DisplayList::default(),
        ));
        cache.prev_dom_ptr = 0xDEAD_BEEF;
        cache.counters.insert((0, "c".to_string()), 1);
        cache.float_cache.insert(0, fc::FloatingContext::default());
        // Not incremental-reuse state — must survive.
        cache.calculated_positions = vec![pos(1.0, 2.0)];
        cache.scroll_ids.insert(0, 5);
        cache.viewport = Some(LogicalRect::new(pos(0.0, 0.0), size(800.0, 600.0)));

        cache.reset_incremental();

        assert!(cache.tree.is_none());
        assert!(cache.cache_map.entries.is_empty());
        assert!(cache.cached_display_list.is_none());
        assert_eq!(cache.prev_dom_ptr, 0);
        assert!(cache.counters.is_empty());
        assert!(cache.float_cache.is_empty());
        assert_eq!(cache.calculated_positions.len(), 1);
        assert_eq!(cache.scroll_ids.len(), 1);
        assert!(cache.viewport.is_some());

        // Idempotent: a second reset on the already-cold cache is a no-op.
        cache.reset_incremental();
        assert!(cache.tree.is_none());
        // Only the two retained fields (1 position + 1 scroll id) still cost bytes.
        assert_eq!(
            cache.memory_report().total_bytes(),
            size_of::<LogicalPosition>() + size_of::<usize>() + size_of::<u64>()
        );
    }

    // ==================================================================
    // ReconciliationResult (predicates)
    // ==================================================================

    #[test]
    fn reconciliation_result_default_is_clean() {
        let r = ReconciliationResult::default();
        assert!(r.is_clean());
        assert!(!r.needs_layout());
        assert!(!r.needs_paint_only());
    }

    #[test]
    fn reconciliation_result_predicates_hold_over_every_combination() {
        for intrinsic in [false, true] {
            for roots in [false, true] {
                for paint in [false, true] {
                    let mut r = ReconciliationResult::default();
                    if intrinsic {
                        r.intrinsic_dirty.insert(0);
                    }
                    if roots {
                        r.layout_roots.insert(usize::MAX);
                    }
                    if paint {
                        r.paint_dirty.insert(7);
                    }

                    let expect_layout = intrinsic || roots;
                    assert_eq!(r.needs_layout(), expect_layout);
                    assert_eq!(r.is_clean(), !intrinsic && !roots && !paint);
                    assert_eq!(r.needs_paint_only(), !expect_layout && paint);
                    // Invariants: clean ⇒ no work; layout and paint-only are exclusive.
                    assert!(!(r.is_clean() && (r.needs_layout() || r.needs_paint_only())));
                    assert!(!(r.needs_layout() && r.needs_paint_only()));
                }
            }
        }
    }

    // ==================================================================
    // to_overflow_behavior / style_text_align_to_fc (mapping tables)
    // ==================================================================

    #[test]
    fn to_overflow_behavior_maps_every_layout_overflow_variant() {
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Visible)),
            fc::OverflowBehavior::Visible
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Hidden)),
            fc::OverflowBehavior::Hidden
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Scroll)),
            fc::OverflowBehavior::Scroll
        );
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Auto)),
            fc::OverflowBehavior::Auto
        );
        // BEHAVIOUR PIN: `overflow: clip` is folded into Hidden, so the distinct
        // `OverflowBehavior::Clip` variant is never produced here. Clip differs
        // from hidden in CSS Overflow 3 (no scroll container, no scrollport), so
        // a `clip` box is currently treated as a (non-scrollable) hidden box.
        assert_eq!(
            to_overflow_behavior(MultiValue::Exact(LayoutOverflow::Clip)),
            fc::OverflowBehavior::Hidden
        );
    }

    #[test]
    fn to_overflow_behavior_falls_back_to_the_initial_value() {
        // CSS Overflow 3: initial value is `visible`. Auto/Initial/Inherit here
        // are the *CSS-wide keyword* arms of MultiValue, not `overflow: auto`.
        for mv in [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit] {
            assert_eq!(to_overflow_behavior(mv), fc::OverflowBehavior::Visible);
        }
    }

    #[test]
    fn overflow_auto_keyword_is_a_typed_value_not_a_css_wide_keyword() {
        // Regression guard: if `overflow: auto` were parsed as the generic
        // CSS-wide `auto` keyword it would arrive as MultiValue::Auto and
        // to_overflow_behavior would silently downgrade it to Visible — i.e. no
        // scrollbars at all. It must arrive as Exact(LayoutOverflow::Auto).
        let sd = styled(
            Dom::create_body().with_child(div_class("s")),
            ".s { overflow-x: auto; overflow-y: scroll; }",
        );
        let id = NodeId::new(1);
        let state = sd.styled_nodes.as_container()[id].styled_node_state;

        assert_eq!(
            to_overflow_behavior(get_overflow_x(&sd, id, &state)),
            fc::OverflowBehavior::Auto
        );
        assert_eq!(
            to_overflow_behavior(get_overflow_y(&sd, id, &state)),
            fc::OverflowBehavior::Scroll
        );
    }

    #[test]
    fn style_text_align_to_fc_maps_every_variant() {
        // fc::TextAlign has no PartialEq, so match on the variant.
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Start),
            fc::TextAlign::Start
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Left),
            fc::TextAlign::Start
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::End),
            fc::TextAlign::End
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Right),
            fc::TextAlign::End
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Center),
            fc::TextAlign::Center
        ));
        assert!(matches!(
            style_text_align_to_fc(StyleTextAlign::Justify),
            fc::TextAlign::Justify
        ));
    }

    // ==================================================================
    // should_use_content_height (predicate)
    // ==================================================================

    #[test]
    fn should_use_content_height_for_css_wide_keywords_and_auto() {
        assert!(should_use_content_height(&MultiValue::Auto));
        assert!(should_use_content_height(&MultiValue::Initial));
        assert!(should_use_content_height(&MultiValue::Inherit));
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::Auto)));
    }

    #[test]
    fn should_use_content_height_is_false_for_definite_lengths() {
        for pv in [
            PixelValue::px(100.0),
            PixelValue::px(-10.0),
            PixelValue::percent(50.0),
            PixelValue::percent(0.0),
            PixelValue::em(2.0),
            PixelValue::rem(2.0),
        ] {
            assert!(
                !should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(pv))),
                "expected a definite height for {pv:?}"
            );
        }
    }

    #[test]
    fn should_use_content_height_treats_zero_px_as_content_based() {
        // BEHAVIOUR PIN: `height: 0px` is indistinguishable from `auto` here, so
        // an explicitly zero-height box falls back to content sizing.
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(
            PixelValue::zero()
        ))));
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(
            PixelValue::px(0.0)
        ))));
        // ...but `height: 0%` is NOT (its metric is Percent, not Px).
        assert!(!should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(
            PixelValue::percent(0.0)
        ))));
    }

    #[test]
    fn should_use_content_height_treats_non_px_metrics_as_content_based() {
        // BEHAVIOUR PIN (suspected bug): only Px/Percent/Em/Rem are recognised as
        // definite. Every other metric — pt, vh, vw, cm, in, mm — is reported as
        // content-based, so `height: 100vh` behaves like a *minimum* height (see
        // apply_content_based_height, which takes max(used, content)) instead of
        // a definite one.
        for metric in [
            SizeMetric::Pt,
            SizeMetric::Vh,
            SizeMetric::Vw,
            SizeMetric::Cm,
            SizeMetric::Mm,
            SizeMetric::In,
        ] {
            let pv = PixelValue::from_metric(metric, 100.0);
            assert!(
                should_use_content_height(&MultiValue::Exact(LayoutHeight::Px(pv))),
                "{metric:?} is currently treated as content-based"
            );
        }
    }

    #[test]
    fn should_use_content_height_for_intrinsic_keywords_but_not_calc() {
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::MinContent)));
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::MaxContent)));
        assert!(should_use_content_height(&MultiValue::Exact(LayoutHeight::FitContent(
            PixelValue::px(10.0)
        ))));
        // calc() resolves to a definite value.
        assert!(!should_use_content_height(&MultiValue::Exact(LayoutHeight::Calc(
            CalcAstItemVec::from_vec(Vec::new())
        ))));
    }

    // ==================================================================
    // apply_content_based_height (numeric)
    // ==================================================================

    fn one_node_tree_with(bp: &ResolvedBoxProps) -> LayoutTree {
        build_tree(
            vec![hot(None, None, Some(size(100.0, 100.0)), bp)],
            warm_default(1),
            &[vec![]],
        )
    }

    #[test]
    fn apply_content_based_height_keeps_the_larger_of_min_height_and_content() {
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(0.0, 0.0, 0.0, 0.0),
            edges(10.0, 0.0, 10.0, 0.0), // padding: 20px on the block axis
        );
        let tree = one_node_tree_with(&bp);
        let wm = LayoutWritingMode::HorizontalTb;

        // Content (50 + 20 padding = 70) is smaller than the min-height-constrained
        // 100 → the Phase-1 size wins (CSS 2.2 § 10.7).
        let out = apply_content_based_height(size(100.0, 100.0), size(0.0, 50.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out, size(100.0, 100.0));

        // Content wins when it is taller.
        let out = apply_content_based_height(size(100.0, 40.0), size(0.0, 50.0), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out, size(100.0, 70.0));
    }

    #[test]
    fn apply_content_based_height_at_zero_and_in_vertical_writing_modes() {
        let tree = one_node_tree_with(&zero_box_props());

        let out = apply_content_based_height(
            size(0.0, 0.0),
            size(0.0, 0.0),
            &tree,
            0,
            LayoutWritingMode::HorizontalTb,
        )
        .expect("valid node");
        assert_eq!(out, size(0.0, 0.0));

        // Vertical writing mode: the main axis is the *width*.
        let out = apply_content_based_height(
            size(10.0, 80.0),
            size(50.0, 0.0),
            &tree,
            0,
            LayoutWritingMode::VerticalRl,
        )
        .expect("valid node");
        assert_eq!(out, size(50.0, 80.0));
    }

    #[test]
    fn apply_content_based_height_does_not_propagate_nan() {
        let tree = one_node_tree_with(&zero_box_props());
        let wm = LayoutWritingMode::HorizontalTb;

        // f32::max ignores a NaN operand, so a NaN content size cannot poison the
        // used size — the Phase-1 height survives.
        let out = apply_content_based_height(size(100.0, 40.0), size(0.0, f32::NAN), &tree, 0, wm)
            .expect("valid node");
        assert!(!out.height.is_nan());
        assert_eq!(out.height, 40.0);

        // ...and symmetrically, a NaN used size is replaced by the content size.
        let out =
            apply_content_based_height(size(100.0, f32::NAN), size(0.0, 50.0), &tree, 0, wm)
                .expect("valid node");
        assert!(!out.height.is_nan());
        assert_eq!(out.height, 50.0);
    }

    #[test]
    fn apply_content_based_height_saturates_at_infinity_and_rejects_bad_indices() {
        let tree = one_node_tree_with(&zero_box_props());
        let wm = LayoutWritingMode::HorizontalTb;

        let out =
            apply_content_based_height(size(10.0, 10.0), size(0.0, f32::INFINITY), &tree, 0, wm)
                .expect("valid node");
        assert!(out.height.is_infinite() && out.height.is_sign_positive());

        // A huge finite content size stays finite (no overflow panic).
        let out = apply_content_based_height(size(10.0, 10.0), size(0.0, f32::MAX), &tree, 0, wm)
            .expect("valid node");
        assert_eq!(out.height, f32::MAX);

        // Out-of-range node → Err, not a panic.
        assert!(apply_content_based_height(size(1.0, 1.0), size(1.0, 1.0), &tree, 1, wm).is_err());
        assert!(
            apply_content_based_height(size(1.0, 1.0), size(1.0, 1.0), &tree, usize::MAX, wm)
                .is_err()
        );
    }

    // ==================================================================
    // calculate_subtree_hash (numeric / round-trip-ish)
    // ==================================================================

    #[test]
    fn subtree_hash_is_deterministic() {
        let a = calculate_subtree_hash(42, &[1, 2, 3]);
        let b = calculate_subtree_hash(42, &[1, 2, 3]);
        assert_eq!(a, b);
        assert_eq!(a, calculate_subtree_hash(42, &[1, 2, 3]));
    }

    #[test]
    fn subtree_hash_depends_on_child_order_and_arity() {
        let base = calculate_subtree_hash(1, &[10, 20]);
        assert_ne!(base, calculate_subtree_hash(1, &[20, 10]), "order must matter");
        assert_ne!(base, calculate_subtree_hash(1, &[10, 20, 30]), "arity must matter");
        assert_ne!(base, calculate_subtree_hash(1, &[10]), "a dropped child must matter");
        assert_ne!(base, calculate_subtree_hash(2, &[10, 20]), "self hash must matter");
    }

    #[test]
    fn subtree_hash_distinguishes_no_children_from_a_zero_child() {
        // Length is folded in (slice Hash writes the length), so an empty child
        // list is not confusable with a single 0-hash child.
        assert_ne!(
            calculate_subtree_hash(0, &[]),
            calculate_subtree_hash(0, &[0])
        );
        assert_ne!(
            calculate_subtree_hash(0, &[0]),
            calculate_subtree_hash(0, &[0, 0])
        );
    }

    #[test]
    fn subtree_hash_does_not_swap_self_hash_and_child_hash() {
        assert_ne!(
            calculate_subtree_hash(7, &[9]),
            calculate_subtree_hash(9, &[7])
        );
    }

    #[test]
    fn subtree_hash_handles_extremes_and_large_child_lists() {
        let extremes = calculate_subtree_hash(u64::MAX, &[u64::MAX, 0, u64::MAX]);
        assert_eq!(
            extremes,
            calculate_subtree_hash(u64::MAX, &[u64::MAX, 0, u64::MAX])
        );
        assert_ne!(extremes, calculate_subtree_hash(0, &[0, 0, 0]));

        // 10k children: no overflow, no panic, still deterministic.
        let many: Vec<u64> = (0..10_000).collect();
        assert_eq!(
            calculate_subtree_hash(1, &many),
            calculate_subtree_hash(1, &many)
        );
    }

    // ==================================================================
    // calculate_content_box_pos (numeric)
    // ==================================================================

    #[test]
    fn content_box_pos_adds_border_and_padding_but_not_margin() {
        let bp = box_props(
            edges(999.0, 999.0, 999.0, 999.0), // margin must be ignored
            edges(2.0, 0.0, 0.0, 3.0),         // border top/left
            edges(5.0, 0.0, 0.0, 7.0),         // padding top/left
        );
        let out = calculate_content_box_pos(pos(10.0, 20.0), &bp);
        assert_eq!(out, pos(10.0 + 3.0 + 7.0, 20.0 + 2.0 + 5.0));

        // Zero box props → identity.
        assert_eq!(
            calculate_content_box_pos(pos(4.0, 5.0), &zero_box_props()),
            pos(4.0, 5.0)
        );
    }

    #[test]
    fn content_box_pos_with_negative_edges_shifts_backwards() {
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(-1.0, 0.0, 0.0, -2.0),
            edges(-3.0, 0.0, 0.0, -4.0),
        );
        assert_eq!(
            calculate_content_box_pos(pos(0.0, 0.0), &bp),
            pos(-6.0, -4.0)
        );
    }

    #[test]
    fn content_box_pos_with_non_finite_edges_is_deterministic() {
        let nan_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::NAN, 0.0, 0.0, f32::NAN),
            edges(0.0, 0.0, 0.0, 0.0),
        );
        let out = calculate_content_box_pos(pos(1.0, 1.0), &nan_bp);
        assert!(out.x.is_nan() && out.y.is_nan(), "NaN edges propagate, no panic");

        // +inf border with a -inf containing block → NaN, still no panic.
        let inf_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::INFINITY, 0.0, 0.0, f32::INFINITY),
            edges(0.0, 0.0, 0.0, 0.0),
        );
        let out = calculate_content_box_pos(pos(f32::NEG_INFINITY, f32::NEG_INFINITY), &inf_bp);
        assert!(out.x.is_nan() && out.y.is_nan());

        // Saturation rather than wrap-around at the top of the f32 range.
        let max_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(f32::MAX, 0.0, 0.0, f32::MAX),
            edges(f32::MAX, 0.0, 0.0, f32::MAX),
        );
        let out = calculate_content_box_pos(pos(f32::MAX, f32::MAX), &max_bp);
        assert!(out.x.is_infinite() && out.x.is_sign_positive());
        assert!(out.y.is_infinite() && out.y.is_sign_positive());
    }

    // ==================================================================
    // check_scrollbar_change (numeric / predicate)
    // ==================================================================

    fn scrollbars(h: bool, v: bool, w: f32) -> ScrollbarRequirements {
        ScrollbarRequirements {
            needs_horizontal: h,
            needs_vertical: v,
            scrollbar_width: w,
            scrollbar_height: w,
            visual_width_px: w,
        }
    }

    fn tree_with_scrollbar_info(info: Option<ScrollbarRequirements>) -> LayoutTree {
        let mut warm = warm_default(1);
        warm[0].scrollbar_info = info;
        build_tree(vec![plain(None)], warm, &[vec![]])
    }

    #[test]
    fn check_scrollbar_change_skip_flag_short_circuits_everything() {
        let tree = tree_with_scrollbar_info(Some(scrollbars(false, false, 0.0)));
        // Even a full add of both scrollbars is suppressed by the skip flag.
        assert!(!check_scrollbar_change(&tree, 0, &scrollbars(true, true, 16.0), true));
    }

    #[test]
    fn check_scrollbar_change_out_of_range_node_is_false() {
        let tree = tree_with_scrollbar_info(None);
        assert!(!check_scrollbar_change(&tree, 1, &scrollbars(true, true, 16.0), false));
        assert!(!check_scrollbar_change(&tree, usize::MAX, &scrollbars(true, true, 16.0), false));
    }

    #[test]
    fn check_scrollbar_change_without_previous_info_uses_needs_reflow() {
        let tree = tree_with_scrollbar_info(None);
        // No reserved space → nothing to reflow for.
        assert!(!check_scrollbar_change(&tree, 0, &scrollbars(true, true, 0.0), false));
        // Reserved space → reflow.
        assert!(check_scrollbar_change(&tree, 0, &scrollbars(false, false, 16.0), false));
        // NaN reserved width: `NaN > 0.0` is false → deterministic `false`, no panic.
        assert!(!check_scrollbar_change(&tree, 0, &scrollbars(true, true, f32::NAN), false));
    }

    #[test]
    fn check_scrollbar_change_detects_both_addition_and_removal() {
        let had_vertical = tree_with_scrollbar_info(Some(scrollbars(false, true, 16.0)));
        // Removal (vertical true → false) must be detected, not suppressed.
        assert!(check_scrollbar_change(&had_vertical, 0, &scrollbars(false, false, 0.0), false));
        // Addition of the horizontal bar.
        assert!(check_scrollbar_change(&had_vertical, 0, &scrollbars(true, true, 16.0), false));
        // No change at all.
        assert!(!check_scrollbar_change(&had_vertical, 0, &scrollbars(false, true, 16.0), false));
    }

    #[test]
    fn check_scrollbar_change_ignores_width_only_changes() {
        // BEHAVIOUR PIN: only the needs_horizontal/needs_vertical booleans are
        // compared. A scrollbar that keeps existing but changes reserved width
        // (e.g. a restyle from a classic to a thin scrollbar) does not trigger a
        // reflow here.
        let tree = tree_with_scrollbar_info(Some(scrollbars(false, true, 16.0)));
        assert!(!check_scrollbar_change(&tree, 0, &scrollbars(false, true, 4.0), false));
    }

    // ==================================================================
    // shift_subtree_position (numeric)
    // ==================================================================

    /// 0 -> [1, 2]; 1 -> [3]
    fn shift_fixture() -> (LayoutTree, PositionVec) {
        let tree = build_tree(
            vec![plain(None), plain(Some(0)), plain(Some(0)), plain(Some(1))],
            warm_default(4),
            &[vec![1, 2], vec![3], vec![], vec![]],
        );
        let positions = vec![
            pos(0.0, 0.0),
            pos(10.0, 10.0),
            pos(20.0, 20.0),
            pos(30.0, 30.0),
        ];
        (tree, positions)
    }

    #[test]
    fn shift_subtree_position_zero_delta_is_identity() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        shift_subtree_position(0, pos(0.0, 0.0), &tree, &mut positions);
        assert_eq!(positions, before);
    }

    #[test]
    fn shift_subtree_position_moves_the_subtree_and_leaves_siblings_alone() {
        let (tree, mut positions) = shift_fixture();
        shift_subtree_position(1, pos(5.0, -3.0), &tree, &mut positions);

        assert_eq!(positions[0], pos(0.0, 0.0), "parent untouched");
        assert_eq!(positions[1], pos(15.0, 7.0), "shifted node");
        assert_eq!(positions[2], pos(20.0, 20.0), "sibling untouched");
        assert_eq!(positions[3], pos(35.0, 27.0), "descendant follows");
    }

    #[test]
    fn shift_subtree_position_out_of_range_node_is_a_noop() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        shift_subtree_position(99, pos(5.0, 5.0), &tree, &mut positions);
        shift_subtree_position(usize::MAX, pos(5.0, 5.0), &tree, &mut positions);
        assert_eq!(positions, before);
    }

    #[test]
    fn shift_subtree_position_skips_nodes_without_a_stored_position() {
        let (tree, _) = shift_fixture();
        // Only node 0 has a position; 1..3 are missing from the vec entirely.
        let mut positions = vec![pos(1.0, 1.0)];
        shift_subtree_position(0, pos(2.0, 2.0), &tree, &mut positions);
        assert_eq!(positions.len(), 1, "the vec is not grown by the shift");
        assert_eq!(positions[0], pos(3.0, 3.0));
    }

    #[test]
    fn shift_subtree_position_leaves_the_unset_sentinel_unset() {
        // POSITION_UNSET is f32::MIN; adding a small delta to it is a no-op at
        // f32 precision, so an un-positioned node stays "unset" after a shift
        // instead of turning into a bogus near-MIN coordinate.
        let (tree, _) = shift_fixture();
        let mut positions = vec![pos(0.0, 0.0), POSITION_UNSET, POSITION_UNSET, POSITION_UNSET];
        shift_subtree_position(0, pos(7.0, 9.0), &tree, &mut positions);

        assert_eq!(pos_get(&positions, 0), Some(pos(7.0, 9.0)));
        assert!(pos_get(&positions, 1).is_none());
        assert!(pos_get(&positions, 3).is_none());
    }

    #[test]
    fn shift_subtree_position_nan_delta_is_confined_to_the_subtree() {
        let (tree, mut positions) = shift_fixture();
        shift_subtree_position(1, pos(f32::NAN, f32::NAN), &tree, &mut positions);

        assert!(positions[1].x.is_nan() && positions[1].y.is_nan());
        assert!(positions[3].x.is_nan(), "NaN reaches the descendant");
        assert!(!positions[2].x.is_nan(), "the sibling is untouched");
        assert_eq!(positions[0], pos(0.0, 0.0));
    }

    #[test]
    fn shift_subtree_position_walks_a_deep_chain_without_blowing_the_stack() {
        const DEPTH: usize = 500;
        let mut nodes = vec![plain(None)];
        let mut child_lists: Vec<Vec<usize>> = vec![vec![1]];
        for i in 1..DEPTH {
            nodes.push(plain(Some(i - 1)));
            child_lists.push(if i + 1 < DEPTH { vec![i + 1] } else { vec![] });
        }
        let tree = build_tree(nodes, warm_default(DEPTH), &child_lists);
        let mut positions = vec![pos(0.0, 0.0); DEPTH];

        shift_subtree_position(0, pos(1.0, 2.0), &tree, &mut positions);

        assert_eq!(positions[0], pos(1.0, 2.0));
        assert_eq!(positions[DEPTH - 1], pos(1.0, 2.0));
    }

    // ==================================================================
    // position_bfc_child_descendants / position_flex_child_descendants
    // ==================================================================

    #[test]
    fn position_bfc_child_descendants_out_of_range_node_is_a_noop() {
        let (tree, mut positions) = shift_fixture();
        let before = positions.clone();
        position_bfc_child_descendants(&tree, 99, pos(1.0, 1.0), &mut positions);
        assert_eq!(positions, before);
    }

    #[test]
    fn position_bfc_child_descendants_converts_relative_to_absolute() {
        // 0 -> [1] -> [2]; node 1 has a 2px border + 3px padding on top/left.
        let bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(2.0, 0.0, 0.0, 2.0),
            edges(3.0, 0.0, 0.0, 3.0),
        );
        let mut warm = warm_default(3);
        warm[1].relative_position = Some(pos(10.0, 20.0));
        warm[2].relative_position = Some(pos(1.0, 1.0));
        let tree = build_tree(
            vec![
                plain(None),
                hot(Some(0), None, Some(size(50.0, 50.0)), &bp),
                plain(Some(1)),
            ],
            warm,
            &[vec![1], vec![2], vec![]],
        );

        let mut positions: PositionVec = Vec::new();
        position_bfc_child_descendants(&tree, 0, pos(100.0, 200.0), &mut positions);

        // child: content-box origin + relative
        assert_eq!(pos_get(&positions, 1), Some(pos(110.0, 220.0)));
        // grandchild: child's own content box (abs + border + padding) + relative
        assert_eq!(pos_get(&positions, 2), Some(pos(110.0 + 5.0 + 1.0, 220.0 + 5.0 + 1.0)));
    }

    #[test]
    fn position_bfc_child_descendants_defaults_a_missing_relative_position_to_the_origin() {
        let tree = build_tree(
            vec![plain(None), plain(Some(0))],
            warm_default(2), // relative_position: None
            &[vec![1], vec![]],
        );
        let mut positions: PositionVec = Vec::new();
        position_bfc_child_descendants(&tree, 0, pos(7.0, 8.0), &mut positions);
        assert_eq!(pos_get(&positions, 1), Some(pos(7.0, 8.0)));
    }

    #[test]
    fn position_flex_child_descendants_rejects_a_dangling_child_index() {
        // children_arena points at a node that does not exist → Err, not a panic.
        let mut tree = build_tree(vec![plain(None)], warm_default(1), &[vec![99]]);
        let mut positions: PositionVec = Vec::new();
        let r = position_flex_child_descendants(
            &mut tree,
            0,
            pos(0.0, 0.0),
            size(100.0, 100.0),
            &mut positions,
        );
        assert!(r.is_err());
    }

    #[test]
    fn position_flex_child_descendants_positions_children_and_grandchildren() {
        let mut warm = warm_default(3);
        warm[1].relative_position = Some(pos(5.0, 5.0));
        warm[2].relative_position = Some(pos(2.0, 2.0));
        let mut tree = build_tree(
            vec![plain(None), plain(Some(0)), plain(Some(1))],
            warm,
            &[vec![1], vec![2], vec![]],
        );

        let mut positions: PositionVec = Vec::new();
        position_flex_child_descendants(
            &mut tree,
            0,
            pos(50.0, 60.0),
            size(100.0, 100.0),
            &mut positions,
        )
        .expect("well-formed tree");

        assert_eq!(pos_get(&positions, 1), Some(pos(55.0, 65.0)));
        assert_eq!(pos_get(&positions, 2), Some(pos(57.0, 67.0)));
    }

    // ==================================================================
    // collect_children_dom_ids / layout_relevant_child_count
    // ==================================================================

    #[test]
    fn collect_children_dom_ids_skips_display_none_children() {
        // body(0) > [ div(1), div.hide(2), div(3) ]
        let sd = styled(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(div_class("hide"))
                .with_child(Dom::create_div()),
            ".hide { display: none; }",
        );

        let children = collect_children_dom_ids(&sd, NodeId::ZERO);
        assert_eq!(children, vec![NodeId::new(1), NodeId::new(3)]);
    }

    #[test]
    fn collect_children_dom_ids_for_leaves_and_unknown_parents_is_empty() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");

        // A leaf has no children.
        assert!(collect_children_dom_ids(&sd, NodeId::new(1)).is_empty());
        // An id past the end of the hierarchy must not panic.
        assert!(collect_children_dom_ids(&sd, NodeId::new(999)).is_empty());
        assert!(collect_children_dom_ids(&sd, NodeId::new(usize::MAX)).is_empty());
    }

    #[test]
    fn layout_relevant_child_count_counts_only_boxes_the_builder_would_emit() {
        // body(0) > [ div(1), text " "(2), div.hide(3) ]
        let sd = styled(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(Dom::create_text(" "))
                .with_child(div_class("hide")),
            ".hide { display: none; }",
        );
        let children = [NodeId::new(1), NodeId::new(2), NodeId::new(3)];

        // display:none is dropped, and the whitespace-only inline run between
        // block siblings collapses → only the first div survives.
        assert_eq!(layout_relevant_child_count(&sd, &children, NodeId::ZERO), 1);
        // Empty input → 0, no panic.
        assert_eq!(layout_relevant_child_count(&sd, &[], NodeId::ZERO), 0);
    }

    // ==================================================================
    // is_whitespace_only_inline_run (predicate)
    // ==================================================================

    #[test]
    fn is_whitespace_only_inline_run_empty_run_is_true() {
        let sd = whitespace_dom("");
        assert!(is_whitespace_only_inline_run(&sd, &[], NodeId::new(1)));
    }

    #[test]
    fn is_whitespace_only_inline_run_detects_collapsible_whitespace_text() {
        let sd = whitespace_dom("");
        // " \n\t" — only ASCII whitespace.
        assert!(is_whitespace_only_inline_run(&sd, &[(0, NodeId::new(2))], NodeId::new(1)));
        // "hi" — real text.
        assert!(!is_whitespace_only_inline_run(&sd, &[(1, NodeId::new(3))], NodeId::new(1)));
        // A mixed run is not whitespace-only.
        assert!(!is_whitespace_only_inline_run(
            &sd,
            &[(0, NodeId::new(2)), (1, NodeId::new(3))],
            NodeId::new(1)
        ));
    }

    #[test]
    fn is_whitespace_only_inline_run_rejects_elements_and_non_ascii_spaces() {
        let sd = whitespace_dom("");
        // A <div> in the run is not a text node → wrapper required.
        assert!(!is_whitespace_only_inline_run(&sd, &[(2, NodeId::new(4))], NodeId::new(1)));
        // U+00A0 NO-BREAK SPACE is *not* collapsible whitespace in CSS, and the
        // ASCII-only char set correctly treats it as real content.
        assert!(!is_whitespace_only_inline_run(&sd, &[(3, NodeId::new(5))], NodeId::new(1)));
    }

    #[test]
    fn is_whitespace_only_inline_run_respects_white_space_pre() {
        // With `white-space: pre` on the parent, whitespace is significant and the
        // anonymous IFC wrapper must still be created.
        let sd = whitespace_dom(".p { white-space: pre; }");
        assert!(!is_whitespace_only_inline_run(&sd, &[(0, NodeId::new(2))], NodeId::new(1)));

        // Sanity: the same run collapses without the `pre`.
        let sd = whitespace_dom(".p { white-space: normal; }");
        assert!(is_whitespace_only_inline_run(&sd, &[(0, NodeId::new(2))], NodeId::new(1)));
    }

    // ==================================================================
    // reposition_clean_subtrees / reposition_block_flow_siblings
    // ==================================================================

    #[test]
    fn reposition_clean_subtrees_ignores_empty_and_dangling_roots() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let tree = build_tree(
            vec![
                hot(None, Some(NodeId::ZERO), Some(size(100.0, 100.0)), &zero_box_props()),
                plain(Some(0)),
            ],
            warm_default(2),
            &[vec![1], vec![]],
        );
        let mut positions = vec![pos(0.0, 0.0), pos(1.0, 1.0)];
        let before = positions.clone();

        // No dirty roots → nothing to reposition.
        reposition_clean_subtrees(&sd, &tree, &BTreeSet::new(), &mut positions);
        assert_eq!(positions, before);

        // A layout root that isn't in the tree must not panic.
        let mut roots = BTreeSet::new();
        roots.insert(99);
        roots.insert(usize::MAX);
        reposition_clean_subtrees(&sd, &tree, &roots, &mut positions);
        assert_eq!(positions, before);
    }

    #[test]
    fn reposition_clean_subtrees_skips_flex_parents() {
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let mut nodes = vec![
            hot(None, Some(NodeId::ZERO), Some(size(100.0, 100.0)), &zero_box_props()),
            plain(Some(0)),
        ];
        nodes[0].formatting_context = FormattingContext::Flex;
        let tree = build_tree(nodes, warm_default(2), &[vec![1], vec![]]);

        let mut positions = vec![pos(0.0, 0.0), pos(1.0, 1.0)];
        let before = positions.clone();
        let mut roots = BTreeSet::new();
        roots.insert(1);

        // Taffy owns flex layout; the sibling-repositioning shortcut is skipped.
        reposition_clean_subtrees(&sd, &tree, &roots, &mut positions);
        assert_eq!(positions, before);
    }

    #[test]
    fn reposition_block_flow_siblings_stacks_clean_children_from_the_content_origin() {
        // body(0) is the parent; children 1 and 2 are clean, 3 is a grandchild.
        let sd = styled(Dom::create_body().with_child(Dom::create_div()), "");
        let parent_bp = box_props(
            edges(0.0, 0.0, 0.0, 0.0),
            edges(5.0, 5.0, 5.0, 5.0), // border — see the note below
            edges(3.0, 3.0, 3.0, 3.0), // padding
        );
        let tree = build_tree(
            vec![
                hot(None, Some(NodeId::ZERO), Some(size(200.0, 200.0)), &parent_bp),
                hot(Some(0), None, Some(size(200.0, 50.0)), &zero_box_props()),
                hot(Some(0), None, Some(size(200.0, 30.0)), &zero_box_props()),
                plain(Some(1)),
            ],
            warm_default(4),
            &[vec![1, 2], vec![3], vec![], vec![]],
        );
        let mut positions = vec![
            pos(10.0, 20.0), // parent (border-box origin)
            pos(0.0, 0.0),
            pos(0.0, 0.0),
            pos(0.0, 0.0),
        ];

        reposition_block_flow_siblings(&sd, 0, &tree, &BTreeSet::new(), &mut positions);

        // BEHAVIOUR PIN: the content origin is computed as parent_pos + PADDING
        // only — the parent's border is NOT added, unlike calculate_content_box_pos
        // (which adds border + padding to the same border-box origin). With a
        // bordered parent the clean siblings therefore land 5px up/left of where
        // the full layout pass would put them.
        assert_eq!(positions[1], pos(13.0, 23.0));
        assert_eq!(positions[2], pos(13.0, 73.0), "second child stacked below the first");
        // The grandchild moved with its parent's subtree.
        assert_eq!(positions[3], pos(13.0, 23.0));
    }

    // ==================================================================
    // compute_counters
    // ==================================================================

    #[test]
    fn compute_counters_on_an_empty_or_anonymous_tree_does_not_panic() {
        let sd = styled(Dom::create_body(), "");
        let mut counters: HashMap<(usize, String), i32> = HashMap::new();

        // Root index past the end of the node list.
        let empty = build_tree(Vec::new(), Vec::new(), &[]);
        compute_counters(&sd, &empty, &mut counters);
        assert!(counters.is_empty());

        // Anonymous root (no dom_node_id) with an anonymous child.
        let anon = build_tree(
            vec![plain(None), plain(Some(0))],
            warm_default(2),
            &[vec![1], vec![]],
        );
        compute_counters(&sd, &anon, &mut counters);
        assert!(counters.is_empty());
    }

    #[test]
    fn compute_counters_increments_the_list_item_counter_in_document_order() {
        // body(0) > [ div.li(1), div.li(2) ]
        let sd = styled(
            Dom::create_body()
                .with_child(div_class("li"))
                .with_child(div_class("li")),
            ".li { display: list-item; }",
        );
        let tree = build_tree(
            vec![
                hot(None, Some(NodeId::ZERO), Some(size(100.0, 100.0)), &zero_box_props()),
                hot(Some(0), Some(NodeId::new(1)), Some(size(100.0, 10.0)), &zero_box_props()),
                hot(Some(0), Some(NodeId::new(2)), Some(size(100.0, 10.0)), &zero_box_props()),
            ],
            warm_default(3),
            &[vec![1, 2], vec![], vec![]],
        );

        let mut counters: HashMap<(usize, String), i32> = HashMap::new();
        compute_counters(&sd, &tree, &mut counters);

        // CSS Lists 3 § 3: `display: list-item` auto-increments "list-item".
        assert_eq!(counters.get(&(1, "list-item".to_string())), Some(&1));
        assert_eq!(counters.get(&(2, "list-item".to_string())), Some(&2));
        // The non-list-item root never enters a counter scope.
        assert_eq!(counters.get(&(0, "list-item".to_string())), None);
    }

    #[test]
    fn compute_counters_leaves_plain_elements_alone() {
        let sd = styled(
            Dom::create_body().with_child(Dom::create_div()),
            "",
        );
        let tree = build_tree(
            vec![
                hot(None, Some(NodeId::ZERO), Some(size(100.0, 100.0)), &zero_box_props()),
                hot(Some(0), Some(NodeId::new(1)), Some(size(100.0, 10.0)), &zero_box_props()),
            ],
            warm_default(2),
            &[vec![1], vec![]],
        );

        let mut counters: HashMap<(usize, String), i32> = HashMap::new();
        compute_counters(&sd, &tree, &mut counters);
        assert!(counters.is_empty(), "no counter-reset/increment → no counters");
    }
}