azul-layout 0.0.8

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
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
// +spec:box-model:b3a79e - box assigned same styles as generating element; getters read from styled DOM per node
//! Centralized CSS property getters for the layout solver pipeline

use azul_core::{
    dom::{NodeId, NodeType},
    geom::LogicalSize,
    id::NodeId as CoreNodeId,
    styled_dom::{StyledDom, StyledNodeState},
};
use azul_css::{
    css::CssPropertyValue,
    props::{
        basic::{
            font::{StyleFontFamily, StyleFontFamilyVec, StyleFontWeight, StyleFontStyle},
            pixel::{DEFAULT_FONT_SIZE, PT_TO_PX},
            ColorU, PhysicalSize, PixelValue, PropertyContext, ResolutionContext,
        },
        layout::{
            BoxDecorationBreak, BreakInside, LayoutBoxSizing, LayoutClear, LayoutDisplay,
            LayoutFlexDirection, LayoutFlexWrap, LayoutFloat, LayoutHeight,
            LayoutJustifyContent, LayoutAlignItems, LayoutAlignContent, LayoutOverflow,
            LayoutPosition, LayoutWidth, LayoutWritingMode, Orphans, PageBreak, Widows,
            StyleScrollbarGutter, StyleOverflowClipMargin,
            grid::GridTemplateAreas,
        },
        property::{CssProperty, CssPropertyType,
            LayoutFlexBasisValue, LayoutFlexDirectionValue, LayoutFlexWrapValue,
            LayoutFlexGrowValue, LayoutFlexShrinkValue,
            LayoutAlignItemsValue, LayoutAlignSelfValue, LayoutAlignContentValue,
            LayoutJustifyContentValue, LayoutJustifyItemsValue, LayoutJustifySelfValue,
            LayoutGapValue,
            LayoutGridTemplateColumnsValue, LayoutGridTemplateRowsValue,
            LayoutGridAutoColumnsValue, LayoutGridAutoRowsValue,
            LayoutGridAutoFlowValue, LayoutGridColumnValue, LayoutGridRowValue,
        },
        style::{
            border_radius::StyleBorderRadius,
            lists::{StyleListStylePosition, StyleListStyleType},
            StyleDirection, StyleTextAlign, StyleUserSelect, StyleVerticalAlign,
            StyleVisibility, StyleWhiteSpace,
            StyleUnicodeBidi, StyleTextBoxTrim, StyleTextBoxEdge,
            StyleDominantBaseline, StyleAlignmentBaseline,
            StyleInitialLetterAlign, StyleInitialLetterWrap,
        },
    },
};

use crate::{
    font_traits::{ParsedFontTrait, StyleProperties},
    solver3::{
        display_list::{BorderRadius, PhysicalSizeImport},
        layout_tree::LayoutNode,
        scrollbar::ScrollbarRequirements,
    },
};

// Font-size resolution helper functions

/// Helper function to get element's computed font-size.
///
/// **Memoised** for the common `Normal` pseudo-state: the first
/// call on a given `StyledDom` populates
/// `css_property_cache.ptr.resolved_font_sizes_px` via a single
/// bottom-up DOM walk (N cascade walks total, stored as
/// `Vec<f32>`); every subsequent call is a single Vec index.
/// Non-normal state falls through to [`resolve_font_size_slow`].
///
/// Motivation: `AZ_PROP_COUNT=1` measured 329 629 `font-size`
/// cascade walks per cold layout on excel.html (~730 per node).
/// With this cache that collapses to ~500 total (one per node,
/// once), and subsequent layouts hit the Vec directly.
///
/// The semantics of the slow path are preserved exactly: the
/// `compute_all_font_sizes_px` walker mirrors the original's
/// `computed_values` → cascade → `DEFAULT_FONT_SIZE` ordering,
/// so rendered pixels are byte-identical.
pub fn get_element_font_size(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    // M12.7 FIX: the OnceLock-cached fast path
    // (`is_normal → resolved_font_sizes_px.get_or_init(|| compute_all_font_sizes_px) →
    // sizes.get`) MIS-LIFTS to wasm — it diverges (create_node_from_dom never returns →
    // empty LayoutTree → 0 rects). PROVEN by isolation: skipping it lets
    // get_element_font_size reach + return via resolve_font_size_slow, and
    // create_resolution_context completes (sub-step 1→4). resolve_font_size_slow is the
    // same resolution unmemoized (correct), so we always use it. (Native desktop is
    // unaffected in correctness; it loses the per-DOM memoization — a minor perf cost
    // only on the lifted web path's small DOMs. The cache-block lift bug — likely the
    // compute_all_font_sizes_px closure's control/FP — is documented for a later remill
    // fix that can restore the fast path.)
    let _ = compute_all_font_sizes_px; // referenced so other callers / native keep it
    resolve_font_size_slow(styled_dom, dom_id, node_state)
}

/// Bottom-up single-pass resolve of every node's font-size.
/// Parents are computed before children (DFS pre-order invariant
/// on `NodeId::index()`), so `em` inherits via the parent's
/// already-stored pixel value. `rem` reads from `sizes[0]` once
/// the root is populated (the root's own size resolves via the
/// `computed_values` short-circuit if set, otherwise DEFAULT).
///
/// Preserves the original resolution order exactly:
///
/// 1. `computed_values` binary search → if FontSize is pre-
///    resolved to a px value, use that.
/// 2. Full cascade via `cache.get_font_size(...)`; if an explicit
///    value is present, resolve with context.
/// 3. `DEFAULT_FONT_SIZE` fallback — NOT `parent_font_size`,
///    because the `computed_values` short-circuit at step 1 is
///    the cascade's inheritance channel (pre-populated for every
///    inheriting node).
fn compute_all_font_sizes_px(styled_dom: &StyledDom) -> alloc::vec::Vec<f32> {
    use azul_css::props::{
        basic::length::SizeMetric,
        property::{CssProperty, CssPropertyType},
    };

    let n = styled_dom.node_data.len();
    let mut sizes = alloc::vec![DEFAULT_FONT_SIZE; n];
    if n == 0 {
        return sizes;
    }

    let data_container = styled_dom.node_data.as_container();
    let state_container = styled_dom.styled_nodes.as_container();
    let hierarchy = styled_dom.node_hierarchy.as_container();
    let cache = &styled_dom.css_property_cache.ptr;

    for idx in 0..n {
        let dom_id = NodeId::new(idx);

        // Step 1: computed_values short-circuit (matches original).
        if let Some(vec) = cache.computed_values.get(idx) {
            if let Ok(cv_idx) =
                vec.binary_search_by_key(&CssPropertyType::FontSize, |(k, _)| *k)
            {
                if let CssProperty::FontSize(css_val) = &vec[cv_idx].1.property {
                    if let Some(fs) = css_val.get_property() {
                        if fs.inner.metric == SizeMetric::Px {
                            sizes[idx] = fs.inner.number.get();
                            continue;
                        }
                    }
                }
            }
        }

        // Step 2: full cascade walk.
        let parent_font_size = hierarchy
            .get(dom_id)
            .and_then(|node| node.parent_id())
            .map(|p| sizes[p.index()])
            .unwrap_or(DEFAULT_FONT_SIZE);
        let root_font_size = sizes[0];

        let Some(node_data) = data_container.internal.get(idx) else {
            sizes[idx] = DEFAULT_FONT_SIZE;
            continue;
        };
        let Some(styled) = state_container.internal.get(idx) else {
            sizes[idx] = DEFAULT_FONT_SIZE;
            continue;
        };
        let node_state = &styled.styled_node_state;

        // Step 2.5: compact cache fast path — avoids a full cascade walk
        // per node. The build-time pass has already resolved em/% to px,
        // so the raw u32 here is the final pixel value when set.
        let mut fast_fs: Option<f32> = None;
        let mut compact_said_inherit = false;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                let raw = cc.get_font_size_raw(idx);
                if raw == azul_css::compact_cache::U32_SENTINEL
                    || raw == azul_css::compact_cache::U32_INHERIT
                    || raw == azul_css::compact_cache::U32_INITIAL
                {
                    compact_said_inherit = true;
                } else if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
                    // Already-resolved pixel value (em/% eliminated during build).
                    if pv.metric == SizeMetric::Px {
                        fast_fs = Some(pv.number.get());
                    } else {
                        // Shouldn't normally happen post-resolve, but fall through safely.
                        let context = ResolutionContext {
                            element_font_size: DEFAULT_FONT_SIZE,
                            parent_font_size,
                            root_font_size,
                            containing_block_size: PhysicalSize::new(0.0, 0.0),
                            element_size: None,
                            viewport_size: PhysicalSize::new(0.0, 0.0),
                        };
                        fast_fs = Some(pv.resolve_with_context(&context, PropertyContext::FontSize));
                    }
                }
            }
        }
        if let Some(fs) = fast_fs {
            sizes[idx] = fs;
            continue;
        }
        if compact_said_inherit {
            sizes[idx] = parent_font_size;
            continue;
        }

        let resolved = cache
            .get_font_size(node_data, &dom_id, node_state)
            .and_then(|v| v.get_property().cloned())
            .map(|v| {
                let context = ResolutionContext {
                    element_font_size: DEFAULT_FONT_SIZE,
                    parent_font_size,
                    root_font_size,
                    containing_block_size: PhysicalSize::new(0.0, 0.0),
                    element_size: None,
                    viewport_size: PhysicalSize::new(0.0, 0.0),
                };
                v.inner
                    .resolve_with_context(&context, PropertyContext::FontSize)
            });

        // Step 3: fallback to DEFAULT (matches original .unwrap_or).
        sizes[idx] = resolved.unwrap_or(DEFAULT_FONT_SIZE);
    }
    sizes
}

/// Un-memoised recursive resolution, used as the fallback for
/// non-normal pseudo-states in [`get_element_font_size`] and
/// directly by tests that bypass the StyledDom-scoped cache.
/// Keeps the original semantics verbatim.
fn resolve_font_size_slow(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    let node_data = &styled_dom.node_data.as_container()[dom_id];
    let cache = &styled_dom.css_property_cache.ptr;

    if let Some(vec) = cache.computed_values.get(dom_id.index()) {
        if let Ok(idx) = vec.binary_search_by_key(
            &azul_css::props::property::CssPropertyType::FontSize,
            |(k, _)| *k,
        ) {
            if let azul_css::props::property::CssProperty::FontSize(css_val) = &vec[idx].1.property {
                if let Some(fs) = css_val.get_property() {
                    if fs.inner.metric == azul_css::props::basic::length::SizeMetric::Px {
                        return fs.inner.number.get();
                    }
                }
            }
        }
    }

    let parent_font_size = styled_dom
        .node_hierarchy
        .as_container()
        .get(dom_id)
        .and_then(|node| node.parent_id())
        .map(|parent_id| resolve_font_size_slow(styled_dom, parent_id, node_state))
        .unwrap_or(DEFAULT_FONT_SIZE);

    let root_font_size = if dom_id == NodeId::new(0) {
        DEFAULT_FONT_SIZE
    } else {
        resolve_font_size_slow(styled_dom, NodeId::new(0), node_state)
    };

    cache
        .get_font_size(node_data, &dom_id, node_state)
        .and_then(|v| v.get_property().cloned())
        .map(|v| {
            let context = ResolutionContext {
                element_font_size: DEFAULT_FONT_SIZE,
                parent_font_size,
                root_font_size,
                containing_block_size: PhysicalSize::new(0.0, 0.0),
                element_size: None,
                viewport_size: PhysicalSize::new(0.0, 0.0),
            };
            v.inner
                .resolve_with_context(&context, PropertyContext::FontSize)
        })
        .unwrap_or(DEFAULT_FONT_SIZE)
}

/// Helper function to get parent's computed font-size.
///
/// Retrieves the parent's own `StyledNodeState` so that pseudo-class-specific
/// font-size rules (e.g. `div:hover { font-size: 32px }`) are resolved
/// against the parent's actual state, not the child's.
pub fn get_parent_font_size(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    _node_state: &StyledNodeState, // child's state — intentionally unused
) -> f32 {
    styled_dom
        .node_hierarchy
        .as_container()
        .get(dom_id)
        .and_then(|node| node.parent_id())
        .map(|parent_id| {
            let parent_state = &styled_dom.styled_nodes.as_container()[parent_id].styled_node_state;
            get_element_font_size(styled_dom, parent_id, parent_state)
        })
        .unwrap_or(azul_css::props::basic::pixel::DEFAULT_FONT_SIZE)
}

/// Helper function to get root element's font-size.
///
/// Uses the root element's own `StyledNodeState` so that pseudo-class-specific
/// rules are resolved correctly regardless of which node triggered the call.
pub fn get_root_font_size(styled_dom: &StyledDom, _node_state: &StyledNodeState) -> f32 {
    let root_id = NodeId::new(0);
    let root_state = &styled_dom.styled_nodes.as_container()[root_id].styled_node_state;
    get_element_font_size(styled_dom, root_id, root_state)
}

/// A value that can be Auto, Initial, Inherit, or an explicit value.
/// This preserves CSS cascade semantics better than Option<T>.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MultiValue<T> {
    /// CSS 'auto' keyword
    Auto,
    /// CSS 'initial' keyword - use initial value
    Initial,
    /// CSS 'inherit' keyword - inherit from parent
    Inherit,
    /// Explicit value (e.g., "10px", "50%")
    Exact(T),
}

impl<T> MultiValue<T> {
    /// Returns true if this is an Auto value
    pub fn is_auto(&self) -> bool {
        matches!(self, MultiValue::Auto)
    }

    /// Returns true if this is an explicit value
    pub fn is_exact(&self) -> bool {
        matches!(self, MultiValue::Exact(_))
    }

    /// Gets the exact value if present
    pub fn exact(self) -> Option<T> {
        match self {
            MultiValue::Exact(v) => Some(v),
            _ => None,
        }
    }

    /// Gets the exact value or returns the provided default
    pub fn unwrap_or(self, default: T) -> T {
        match self {
            MultiValue::Exact(v) => v,
            _ => default,
        }
    }

    /// Gets the exact value or returns T::default()
    pub fn unwrap_or_default(self) -> T
    where
        T: Default,
    {
        match self {
            MultiValue::Exact(v) => v,
            _ => T::default(),
        }
    }

    /// Maps the inner value if Exact, otherwise returns self unchanged
    pub fn map<U, F>(self, f: F) -> MultiValue<U>
    where
        F: FnOnce(T) -> U,
    {
        match self {
            MultiValue::Exact(v) => MultiValue::Exact(f(v)),
            MultiValue::Auto => MultiValue::Auto,
            MultiValue::Initial => MultiValue::Initial,
            MultiValue::Inherit => MultiValue::Inherit,
        }
    }
}

// Implement helper methods for LayoutOverflow specifically
impl MultiValue<LayoutOverflow> {
    /// Returns true if this overflow value causes content to be clipped.
    /// This includes Hidden, Clip, Auto, and Scroll (all values except Visible).
    pub fn is_clipped(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(
                LayoutOverflow::Hidden
                    | LayoutOverflow::Clip
                    | LayoutOverflow::Auto
                    | LayoutOverflow::Scroll
            )
        )
    }

    pub fn is_scroll(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
        )
    }

    pub fn is_auto_overflow(&self) -> bool {
        matches!(self, MultiValue::Exact(LayoutOverflow::Auto))
    }

    pub fn is_hidden(&self) -> bool {
        matches!(self, MultiValue::Exact(LayoutOverflow::Hidden))
    }

    pub fn is_hidden_or_clip(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(LayoutOverflow::Hidden | LayoutOverflow::Clip)
        )
    }

    pub fn is_scroll_explicit(&self) -> bool {
        matches!(self, MultiValue::Exact(LayoutOverflow::Scroll))
    }

    pub fn is_clip(&self) -> bool {
        matches!(self, MultiValue::Exact(LayoutOverflow::Clip))
    }

    pub fn is_visible_or_clip(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(LayoutOverflow::Visible | LayoutOverflow::Clip)
        )
    }

    // +spec:overflow:833078 - visible/clip compute to auto/hidden if other axis is scrollable
    /// Resolves the computed value per CSS Overflow 3 § 3.1:
    /// visible/clip values compute to auto/hidden (respectively)
    /// if the other axis is neither visible nor clip.
    pub fn resolve_computed(&self, other_axis: &MultiValue<LayoutOverflow>) -> MultiValue<LayoutOverflow> {
        match (self, other_axis) {
            (MultiValue::Exact(val), MultiValue::Exact(other)) => {
                MultiValue::Exact(val.resolve_computed(*other))
            }
            _ => *self,
        }
    }
}

// Implement helper methods for LayoutPosition
impl MultiValue<LayoutPosition> {
    pub fn is_absolute_or_fixed(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(LayoutPosition::Absolute | LayoutPosition::Fixed)
        )
    }
}

// Implement helper methods for LayoutFloat
impl MultiValue<LayoutFloat> {
    pub fn is_none(&self) -> bool {
        matches!(
            self,
            MultiValue::Auto
                | MultiValue::Initial
                | MultiValue::Inherit
                | MultiValue::Exact(LayoutFloat::None)
        )
    }
}

impl<T: Default> Default for MultiValue<T> {
    fn default() -> Self {
        MultiValue::Auto
    }
}

/// Helper macro to reduce boilerplate for simple CSS property getters
/// Returns the inner PixelValue wrapped in MultiValue
macro_rules! get_css_property_pixel {
    // Variant WITH compact cache fast path for i16-encoded resolved px properties
    ($fn_name:ident, $cache_method:ident, $ua_property:expr, compact_i16 = $compact_method:ident) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<PixelValue> {
            // FAST PATH: compact cache for normal state (O(1) array lookup)
            if node_state.is_normal() {
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
                    let raw = cc.$compact_method(node_id.index());
                    if raw == azul_css::compact_cache::I16_AUTO {
                        return MultiValue::Auto;
                    }
                    if raw == azul_css::compact_cache::I16_INITIAL {
                        return MultiValue::Initial;
                    }
                    if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                        // Valid value: decode i16 ×10 → px
                        return MultiValue::Exact(PixelValue::px(raw as f32 / 10.0));
                    }
                    // I16_SENTINEL or I16_INHERIT → fall through to slow path
                }
            }

            let node_data = &styled_dom.node_data.as_container()[node_id];

            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            if let Some(ref val) = author_css {
                if val.is_auto() {
                    return MultiValue::Auto;
                }
                if let Some(exact) = val.get_property().copied() {
                    return MultiValue::Exact(exact.inner);
                }
            }

            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(inner) = ua_prop.get_pixel_inner() {
                    return MultiValue::Exact(inner);
                }
            }

            MultiValue::Initial
        }
    };
    // Variant WITHOUT compact cache (original behavior)
    ($fn_name:ident, $cache_method:ident, $ua_property:expr) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<PixelValue> {
            let node_data = &styled_dom.node_data.as_container()[node_id];

            // 1. Check author CSS first (includes inline styles - highest priority)
            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            // NOTE: Check for Auto FIRST — CssPropertyValue::Auto is a valid value
            // that should NOT fall through to UA CSS. Previously, get_property()
            // returned None for Auto, causing inline "margin: auto" to be ignored.
            if let Some(ref val) = author_css {
                if val.is_auto() {
                    return MultiValue::Auto;
                }
                if let Some(exact) = val.get_property().copied() {
                    return MultiValue::Exact(exact.inner);
                }
                // For Initial, Inherit, None, Revert, Unset - fall through to UA CSS
            }

            // 2. Check User Agent CSS (only if author CSS didn't set a value)
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(inner) = ua_prop.get_pixel_inner() {
                    return MultiValue::Exact(inner);
                }
            }

            // 3. Fallback to Initial (not set)
            // IMPORTANT: Use Initial, not Auto! In CSS, the initial value for 
            // margin is 0, not auto. Using Auto here caused margins to be treated
            // as "margin: auto" which blocks align-self: stretch in flexbox.
            MultiValue::Initial
        }
    };
}

/// Helper trait to extract PixelValue from any CssProperty variant
trait CssPropertyPixelInner {
    fn get_pixel_inner(&self) -> Option<PixelValue>;
}

impl CssPropertyPixelInner for azul_css::props::property::CssProperty {
    fn get_pixel_inner(&self) -> Option<PixelValue> {
        match self {
            CssProperty::Left(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::Right(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::Top(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::Bottom(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::MarginLeft(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::MarginRight(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::MarginTop(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::MarginBottom(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::PaddingLeft(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::PaddingRight(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::PaddingTop(CssPropertyValue::Exact(v)) => Some(v.inner),
            CssProperty::PaddingBottom(CssPropertyValue::Exact(v)) => Some(v.inner),
            _ => None,
        }
    }
}

/// Generic macro for CSS properties with UA CSS fallback - returns MultiValue<T>
macro_rules! get_css_property {
    // Variant WITH compact cache fast path (for enum properties in Tier 1)
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact = $compact_method:ident) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<$return_type> {
            // FAST PATH: compact cache for normal state (O(1) array + bitshift)
            // NOTE (M12.7): skipping this fast path does NOT fix get_display_type's
            // divergence — the slow path / the `match get_display_type(...)` on the
            // LayoutDisplay enum (a niche-discriminant) mis-lifts too. So this isn't the
            // cache (unlike the font-size fix); it's the deeper niche/enum decode. Kept.
            if node_state.is_normal() {
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
                    return MultiValue::Exact(cc.$compact_method(node_id.index()));
                }
            }

            // SLOW PATH: full cascade resolution
            let node_data = &styled_dom.node_data.as_container()[node_id];

            // 1. Check author CSS first
            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
                return MultiValue::Exact(val);
            }

            // 2. Check User Agent CSS
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
                    return MultiValue::Exact(val);
                }
            }

            // 3. Fallback to Auto (not set)
            MultiValue::Auto
        }
    };
    // Variant WITH compact cache for u32-encoded dimension enums (LayoutWidth/LayoutHeight)
    // These types have Auto, Px(PixelValue), MinContent, MaxContent, Calc variants
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact_u32_dim = $compact_raw_method:ident, $px_variant:path, $auto_variant:path, $min_content_variant:path, $max_content_variant:path) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<$return_type> {
            // FAST PATH: compact cache for normal state
            if node_state.is_normal() {
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
                    let raw = cc.$compact_raw_method(node_id.index());
                    match raw {
                        azul_css::compact_cache::U32_AUTO => return MultiValue::Auto,
                        azul_css::compact_cache::U32_INITIAL => return MultiValue::Initial,
                        azul_css::compact_cache::U32_NONE => return MultiValue::Auto,
                        azul_css::compact_cache::U32_MIN_CONTENT => return MultiValue::Exact($min_content_variant),
                        azul_css::compact_cache::U32_MAX_CONTENT => return MultiValue::Exact($max_content_variant),
                        azul_css::compact_cache::U32_SENTINEL | azul_css::compact_cache::U32_INHERIT => {
                            // fall through to slow path
                        }
                        _ => {
                            // Valid encoded pixel value
                            if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
                                return MultiValue::Exact($px_variant(pv));
                            }
                            // decode failed → slow path
                        }
                    }
                }
            }

            // SLOW PATH: full cascade resolution
            let node_data = &styled_dom.node_data.as_container()[node_id];

            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
                return MultiValue::Exact(val);
            }

            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
                    return MultiValue::Exact(val);
                }
            }

            MultiValue::Auto
        }
    };
    // Variant WITH compact cache for u32-encoded dimension structs (LayoutMinWidth etc.)
    // These types are struct { inner: PixelValue }
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact_u32_struct = $compact_raw_method:ident) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<$return_type> {
            // FAST PATH: compact cache for normal state
            if node_state.is_normal() {
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
                    let raw = cc.$compact_raw_method(node_id.index());
                    match raw {
                        azul_css::compact_cache::U32_AUTO | azul_css::compact_cache::U32_NONE => return MultiValue::Auto,
                        azul_css::compact_cache::U32_INITIAL => return MultiValue::Initial,
                        azul_css::compact_cache::U32_SENTINEL | azul_css::compact_cache::U32_INHERIT => {
                            // fall through to slow path
                        }
                        _ => {
                            if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
                                return MultiValue::Exact(
                                    <$return_type as azul_css::props::PixelValueTaker>::from_pixel_value(pv)
                                );
                            }
                        }
                    }
                }
            }

            // SLOW PATH
            let node_data = &styled_dom.node_data.as_container()[node_id];

            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
                return MultiValue::Exact(val);
            }

            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
                    return MultiValue::Exact(val);
                }
            }

            MultiValue::Auto
        }
    };
    // Variant WITHOUT compact cache (original behavior)
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> MultiValue<$return_type> {
            let node_data = &styled_dom.node_data.as_container()[node_id];

            // 1. Check author CSS first
            let author_css = styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state);

            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
                return MultiValue::Exact(val);
            }

            // 2. Check User Agent CSS
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);

            if let Some(ua_prop) = ua_css {
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
                    return MultiValue::Exact(val);
                }
            }

            // 3. Fallback to Auto (not set)
            MultiValue::Auto
        }
    };
}

/// Helper trait to extract typed values from UA CSS properties
trait ExtractPropertyValue<T> {
    fn extract(&self) -> Option<T>;
}

fn extract_property_value<T>(prop: &azul_css::props::property::CssProperty) -> Option<T>
where
    azul_css::props::property::CssProperty: ExtractPropertyValue<T>,
{
    prop.extract()
}

// Implement extraction for all layout types

impl ExtractPropertyValue<LayoutWidth> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutWidth> {
        match self {
            Self::Width(CssPropertyValue::Exact(v)) => Some(v.clone()),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutHeight> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutHeight> {
        match self {
            Self::Height(CssPropertyValue::Exact(v)) => Some(v.clone()),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutMinWidth> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutMinWidth> {
        match self {
            Self::MinWidth(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutMinHeight> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutMinHeight> {
        match self {
            Self::MinHeight(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutMaxWidth> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutMaxWidth> {
        match self {
            Self::MaxWidth(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutMaxHeight> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutMaxHeight> {
        match self {
            Self::MaxHeight(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutDisplay> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutDisplay> {
        match self {
            Self::Display(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutWritingMode> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutWritingMode> {
        match self {
            Self::WritingMode(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutFlexWrap> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutFlexWrap> {
        match self {
            Self::FlexWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutJustifyContent> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutJustifyContent> {
        match self {
            Self::JustifyContent(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleTextAlign> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleTextAlign> {
        match self {
            Self::TextAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutFloat> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutFloat> {
        match self {
            Self::Float(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutClear> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutClear> {
        match self {
            Self::Clear(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutOverflow> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutOverflow> {
        match self {
            Self::OverflowX(CssPropertyValue::Exact(v)) => Some(*v),
            Self::OverflowY(CssPropertyValue::Exact(v)) => Some(*v),
            Self::OverflowBlock(CssPropertyValue::Exact(v)) => Some(*v),
            Self::OverflowInline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutPosition> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutPosition> {
        match self {
            Self::Position(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutBoxSizing> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutBoxSizing> {
        match self {
            Self::BoxSizing(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<PixelValue> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<PixelValue> {
        self.get_pixel_inner()
    }
}

impl ExtractPropertyValue<LayoutFlexDirection> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutFlexDirection> {
        match self {
            Self::FlexDirection(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutAlignItems> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutAlignItems> {
        match self {
            Self::AlignItems(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutAlignContent> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<LayoutAlignContent> {
        match self {
            Self::AlignContent(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleFontWeight> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleFontWeight> {
        match self {
            Self::FontWeight(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleFontStyle> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleFontStyle> {
        match self {
            Self::FontStyle(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleVisibility> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleVisibility> {
        match self {
            Self::Visibility(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleWhiteSpace> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleWhiteSpace> {
        match self {
            Self::WhiteSpace(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleDirection> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleDirection> {
        match self {
            Self::Direction(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleUnicodeBidi> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleUnicodeBidi> {
        match self {
            Self::UnicodeBidi(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleTextBoxTrim> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleTextBoxTrim> {
        match self {
            Self::TextBoxTrim(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleTextBoxEdge> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleTextBoxEdge> {
        match self {
            Self::TextBoxEdge(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleDominantBaseline> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleDominantBaseline> {
        match self {
            Self::DominantBaseline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleAlignmentBaseline> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleAlignmentBaseline> {
        match self {
            Self::AlignmentBaseline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleInitialLetterAlign> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleInitialLetterAlign> {
        match self {
            Self::InitialLetterAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleInitialLetterWrap> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleInitialLetterWrap> {
        match self {
            Self::InitialLetterWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleScrollbarGutter> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleScrollbarGutter> {
        match self {
            Self::ScrollbarGutter(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleOverflowClipMargin> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleOverflowClipMargin> {
        match self {
            Self::OverflowClipMargin(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleVerticalAlign> for azul_css::props::property::CssProperty {
    fn extract(&self) -> Option<StyleVerticalAlign> {
        match self {
            Self::VerticalAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

get_css_property!(
    get_writing_mode,
    get_writing_mode,
    LayoutWritingMode,
    azul_css::props::property::CssPropertyType::WritingMode,
    compact = get_writing_mode
);

get_css_property!(
    get_css_width,
    get_width,
    LayoutWidth,
    azul_css::props::property::CssPropertyType::Width,
    compact_u32_dim = get_width_raw, LayoutWidth::Px, LayoutWidth::Auto, LayoutWidth::MinContent, LayoutWidth::MaxContent
);

get_css_property!(
    get_css_height,
    get_height,
    LayoutHeight,
    azul_css::props::property::CssPropertyType::Height,
    compact_u32_dim = get_height_raw, LayoutHeight::Px, LayoutHeight::Auto, LayoutHeight::MinContent, LayoutHeight::MaxContent
);

get_css_property!(
    get_wrap,
    get_flex_wrap,
    LayoutFlexWrap,
    azul_css::props::property::CssPropertyType::FlexWrap,
    compact = get_flex_wrap
);

get_css_property!(
    get_justify_content,
    get_justify_content,
    LayoutJustifyContent,
    azul_css::props::property::CssPropertyType::JustifyContent,
    compact = get_justify_content
);

get_css_property!(
    get_text_align,
    get_text_align,
    StyleTextAlign,
    azul_css::props::property::CssPropertyType::TextAlign,
    compact = get_text_align
);

get_css_property!(
    get_float,
    get_float,
    LayoutFloat,
    azul_css::props::property::CssPropertyType::Float,
    compact = get_float
);

get_css_property!(
    get_clear,
    get_clear,
    LayoutClear,
    azul_css::props::property::CssPropertyType::Clear,
    compact = get_clear
);

get_css_property!(
    get_overflow_x,
    get_overflow_x,
    LayoutOverflow,
    azul_css::props::property::CssPropertyType::OverflowX,
    compact = get_overflow_x
);

get_css_property!(
    get_overflow_y,
    get_overflow_y,
    LayoutOverflow,
    azul_css::props::property::CssPropertyType::OverflowY,
    compact = get_overflow_y
);

// +spec:overflow:17654b - overflow-block and overflow-inline logical properties resolve to physical overflow based on writing mode
get_css_property!(
    get_overflow_block,
    get_overflow_block,
    LayoutOverflow,
    azul_css::props::property::CssPropertyType::OverflowBlock
);

get_css_property!(
    get_overflow_inline,
    get_overflow_inline,
    LayoutOverflow,
    azul_css::props::property::CssPropertyType::OverflowInline
);

get_css_property!(
    get_position,
    get_position,
    LayoutPosition,
    azul_css::props::property::CssPropertyType::Position,
    compact = get_position
);

get_css_property!(
    get_css_box_sizing,
    get_box_sizing,
    LayoutBoxSizing,
    azul_css::props::property::CssPropertyType::BoxSizing,
    compact = get_box_sizing
);

get_css_property!(
    get_flex_direction,
    get_flex_direction,
    LayoutFlexDirection,
    azul_css::props::property::CssPropertyType::FlexDirection,
    compact = get_flex_direction
);

get_css_property!(
    get_align_items,
    get_align_items,
    LayoutAlignItems,
    azul_css::props::property::CssPropertyType::AlignItems,
    compact = get_align_items
);

get_css_property!(
    get_align_content,
    get_align_content,
    LayoutAlignContent,
    azul_css::props::property::CssPropertyType::AlignContent,
    compact = get_align_content
);

get_css_property!(
    get_font_weight_property,
    get_font_weight,
    StyleFontWeight,
    azul_css::props::property::CssPropertyType::FontWeight,
    compact = get_font_weight
);

get_css_property!(
    get_font_style_property,
    get_font_style,
    StyleFontStyle,
    azul_css::props::property::CssPropertyType::FontStyle,
    compact = get_font_style
);

get_css_property!(
    get_visibility,
    get_visibility,
    StyleVisibility,
    azul_css::props::property::CssPropertyType::Visibility,
    compact = get_visibility
);

get_css_property!(
    get_white_space_property,
    get_white_space,
    StyleWhiteSpace,
    azul_css::props::property::CssPropertyType::WhiteSpace,
    compact = get_white_space
);

// +spec:writing-modes:3af12f - unicode-bidi does not affect direction for layout; we use direction property directly
get_css_property!(
    get_direction_property,
    get_direction,
    StyleDirection,
    azul_css::props::property::CssPropertyType::Direction,
    compact = get_direction
);

// +spec:display-property:346799 - inline-level elements with unicode-bidi:normal have no effect on text ordering
// +spec:writing-modes:3e2632 - unicode-bidi property resolves embedding level for bidi algorithm (LRE/RLE/PDF)
// +spec:writing-modes:d2c94f - direction+unicode-bidi properties map to UAX#9 bidirectional algorithm
get_css_property!(
    get_unicode_bidi_property,
    get_unicode_bidi,
    StyleUnicodeBidi,
    azul_css::props::property::CssPropertyType::UnicodeBidi
);

// +spec:display-property:db5125 - text-box-trim on inline boxes trims content box to text-box-edge metric
// +spec:display-property:dceb24 - text-box-trim on inline boxes: content edges coincide with text baselines
get_css_property!(
    get_text_box_trim_property,
    get_text_box_trim,
    StyleTextBoxTrim,
    azul_css::props::property::CssPropertyType::TextBoxTrim
);

get_css_property!(
    get_text_box_edge_property,
    get_text_box_edge,
    StyleTextBoxEdge,
    azul_css::props::property::CssPropertyType::TextBoxEdge
);

get_css_property!(
    get_dominant_baseline_property,
    get_dominant_baseline,
    StyleDominantBaseline,
    azul_css::props::property::CssPropertyType::DominantBaseline
);

get_css_property!(
    get_alignment_baseline_property,
    get_alignment_baseline,
    StyleAlignmentBaseline,
    azul_css::props::property::CssPropertyType::AlignmentBaseline
);

get_css_property!(
    get_initial_letter_align_property,
    get_initial_letter_align,
    StyleInitialLetterAlign,
    azul_css::props::property::CssPropertyType::InitialLetterAlign
);

get_css_property!(
    get_initial_letter_wrap_property,
    get_initial_letter_wrap,
    StyleInitialLetterWrap,
    azul_css::props::property::CssPropertyType::InitialLetterWrap
);

// +spec:overflow:5d15e2 - block-start/block-end scrollbar gutter follows same rules as inline gutters when auto
//
// Hand-rolled fast path: 99% of nodes don't set scrollbar-gutter, and the
// default is `auto`. The compact cache stores the enum in 2 bits of
// tier2_cold.hot_flags, so we can return the answer without a cascade walk.
pub fn get_scrollbar_gutter_property(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> MultiValue<StyleScrollbarGutter> {
    // FAST PATH: 2-bit enum in hot_flags
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let bits = cc.get_scrollbar_gutter_bits(node_id.index());
            let val = match bits {
                azul_css::compact_cache::SCROLLBAR_GUTTER_AUTO => StyleScrollbarGutter::Auto,
                azul_css::compact_cache::SCROLLBAR_GUTTER_STABLE => StyleScrollbarGutter::Stable,
                azul_css::compact_cache::SCROLLBAR_GUTTER_BOTH_EDGES => StyleScrollbarGutter::StableBothEdges,
                _ => StyleScrollbarGutter::Auto,
            };
            return MultiValue::Exact(val);
        }
    }

    // SLOW PATH: cascade resolution for pseudo-states or missing cache
    let node_data = &styled_dom.node_data.as_container()[node_id];
    let author_css = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_gutter(node_data, &node_id, node_state);
    if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
        return MultiValue::Exact(val);
    }
    MultiValue::Auto
}

get_css_property!(
    get_overflow_clip_margin_property,
    get_overflow_clip_margin,
    StyleOverflowClipMargin,
    azul_css::props::property::CssPropertyType::OverflowClipMargin
);

get_css_property!(
    get_object_fit_property,
    get_object_fit,
    StyleObjectFit,
    azul_css::props::property::CssPropertyType::ObjectFit
);

// +spec:writing-modes:257296 - text-orientation getter for vertical typesetting (upright/sideways)
//
// Hand-rolled (not macro-generated) to attach a negative fast-path: most
// nodes have no text-orientation declared (default = Mixed), so we avoid a
// cascade walk per fc.rs call (which is called ~2× per node).
pub fn get_text_orientation_property(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> MultiValue<StyleTextOrientation> {
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_text_orientation(node_id.index()) {
                return MultiValue::Auto;
            }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    if let Some(val) = styled_dom
        .css_property_cache
        .ptr
        .get_text_orientation(node_data, &node_id, node_state)
        .and_then(|v| v.get_property().cloned())
    {
        return MultiValue::Exact(val);
    }
    let ua = azul_core::ua_css::get_ua_property(
        &node_data.node_type,
        azul_css::props::property::CssPropertyType::TextOrientation,
    );
    if let Some(ua_prop) = ua {
        if let Some(val) = extract_property_value::<StyleTextOrientation>(ua_prop) {
            return MultiValue::Exact(val);
        }
    }
    MultiValue::Auto
}

get_css_property!(
    get_object_position_property,
    get_object_position,
    StyleObjectPosition,
    azul_css::props::property::CssPropertyType::ObjectPosition
);

get_css_property!(
    get_aspect_ratio_property,
    get_aspect_ratio,
    StyleAspectRatio,
    azul_css::props::property::CssPropertyType::AspectRatio
);

// NOTE: vertical-align does NOT use the compact cache because the compact cache
// only stores keyword variants (3 bits = 8 values) and silently drops
// Percentage/Length values by mapping them to Baseline. Always use the slow path.
pub fn get_vertical_align_property(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> MultiValue<StyleVerticalAlign> {
    let node_data = &styled_dom.node_data.as_container()[node_id];

    let author_css = styled_dom
        .css_property_cache
        .ptr
        .get_vertical_align(node_data, &node_id, node_state);

    if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
        return MultiValue::Exact(val);
    }

    let ua_css = azul_core::ua_css::get_ua_property(
        &node_data.node_type,
        azul_css::props::property::CssPropertyType::VerticalAlign,
    );

    if let Some(ua_prop) = ua_css {
        if let Some(val) = extract_property_value::<StyleVerticalAlign>(ua_prop) {
            return MultiValue::Exact(val);
        }
    }

    MultiValue::Auto
}
// Complex Property Getters

/// Get border radius for all four corners (raw CSS property values)
pub fn get_style_border_radius(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> azul_css::props::style::border_radius::StyleBorderRadius {
    use azul_css::props::basic::pixel::PixelValue;
    // FAST PATH: all four corners live in tier2_cold as i16 px × 10. The
    // common case (no rounded corners anywhere) reads four bytes and bails.
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let idx = node_id.index();
            let decode = |raw: i16| -> PixelValue {
                if raw >= azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                    PixelValue::px(0.0)
                } else {
                    PixelValue::px(raw as f32 / 10.0)
                }
            };
            return StyleBorderRadius {
                top_left: decode(cc.get_border_top_left_radius_raw(idx)),
                top_right: decode(cc.get_border_top_right_radius_raw(idx)),
                bottom_right: decode(cc.get_border_bottom_right_radius_raw(idx)),
                bottom_left: decode(cc.get_border_bottom_left_radius_raw(idx)),
            };
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];

    let top_left = styled_dom
        .css_property_cache
        .ptr
        .get_border_top_left_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property_or_default())
        .map(|v| v.inner)
        .unwrap_or_default();

    let top_right = styled_dom
        .css_property_cache
        .ptr
        .get_border_top_right_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property_or_default())
        .map(|v| v.inner)
        .unwrap_or_default();

    let bottom_right = styled_dom
        .css_property_cache
        .ptr
        .get_border_bottom_right_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property_or_default())
        .map(|v| v.inner)
        .unwrap_or_default();

    let bottom_left = styled_dom
        .css_property_cache
        .ptr
        .get_border_bottom_left_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property_or_default())
        .map(|v| v.inner)
        .unwrap_or_default();

    StyleBorderRadius {
        top_left,
        top_right,
        bottom_right,
        bottom_left,
    }
}

/// Get border radius for all four corners (resolved to pixels)
///
/// # Arguments
/// * `element_size` - The element's own size (width × height) for % resolution. According to CSS
///   spec, border-radius % uses element's own dimensions.
pub fn get_border_radius(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
    element_size: PhysicalSizeImport,
    viewport_size: LogicalSize,
) -> BorderRadius {
    use azul_css::props::basic::{PhysicalSize, PropertyContext, ResolutionContext};

    // FAST PATH: all four corners as i16 px × 10 in tier2_cold. The
    // overwhelmingly common case (no rounded corners) reads four bytes and
    // returns zeros without a cascade walk.
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let idx = node_id.index();
            let tl = cc.get_border_top_left_radius_raw(idx);
            let tr = cc.get_border_top_right_radius_raw(idx);
            let br = cc.get_border_bottom_right_radius_raw(idx);
            let bl = cc.get_border_bottom_left_radius_raw(idx);
            // sentinel = "unset" = 0 px (no corner radius)
            let thresh = azul_css::compact_cache::I16_SENTINEL_THRESHOLD;
            let decode = |raw: i16| -> f32 {
                if raw >= thresh { 0.0 } else { raw as f32 / 10.0 }
            };
            return BorderRadius {
                top_left: decode(tl),
                top_right: decode(tr),
                bottom_right: decode(br),
                bottom_left: decode(bl),
            };
        }
    }

    let node_data = &styled_dom.node_data.as_container()[node_id];

    // Get font sizes for em/rem resolution
    let element_font_size = get_element_font_size(styled_dom, node_id, node_state);
    let parent_font_size = styled_dom
        .node_hierarchy
        .as_container()
        .get(node_id)
        .and_then(|node| node.parent_id())
        .map(|p| get_element_font_size(styled_dom, p, node_state))
        .unwrap_or(azul_css::props::basic::pixel::DEFAULT_FONT_SIZE);
    let root_font_size = get_root_font_size(styled_dom, node_state);

    // Create resolution context
    let context = ResolutionContext {
        element_font_size,
        parent_font_size,
        root_font_size,
        containing_block_size: PhysicalSize::new(0.0, 0.0), // Not used for border-radius
        element_size: Some(PhysicalSize::new(element_size.width, element_size.height)),
        viewport_size: PhysicalSize::new(viewport_size.width, viewport_size.height),
    };

    let top_left = styled_dom
        .css_property_cache
        .ptr
        .get_border_top_left_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property().cloned())
        .unwrap_or_default();

    let top_right = styled_dom
        .css_property_cache
        .ptr
        .get_border_top_right_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property().cloned())
        .unwrap_or_default();

    let bottom_right = styled_dom
        .css_property_cache
        .ptr
        .get_border_bottom_right_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property().cloned())
        .unwrap_or_default();

    let bottom_left = styled_dom
        .css_property_cache
        .ptr
        .get_border_bottom_left_radius(node_data, &node_id, node_state)
        .and_then(|br| br.get_property().cloned())
        .unwrap_or_default();

    BorderRadius {
        top_left: top_left
            .inner
            .resolve_with_context(&context, PropertyContext::BorderRadius),
        top_right: top_right
            .inner
            .resolve_with_context(&context, PropertyContext::BorderRadius),
        bottom_right: bottom_right
            .inner
            .resolve_with_context(&context, PropertyContext::BorderRadius),
        bottom_left: bottom_left
            .inner
            .resolve_with_context(&context, PropertyContext::BorderRadius),
    }
}

// +spec:stacking-contexts:a93e62 - stack level from z-index for stacking context ordering
// +spec:stacking-contexts:ae50ae - z-index specifies stack level; auto resolves to 0 (inherited from parent stacking context)
/// Get z-index for stacking context ordering.
///
/// Returns the resolved integer z-index value:
/// - `z-index: auto` → 0 (participates in parent's stacking context)
/// - `z-index: <integer>` → that integer value
pub fn get_z_index(styled_dom: &StyledDom, node_id: Option<NodeId>) -> i32 {
    use azul_css::props::layout::position::LayoutZIndex;

    let node_id = match node_id {
        Some(id) => id,
        None => return 0,
    };

    let node_state = &styled_dom.styled_nodes.as_container()[node_id].styled_node_state;

    // FAST PATH: compact cache for normal state
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let raw = cc.get_z_index(node_id.index());
            if raw == azul_css::compact_cache::I16_AUTO {
                return 0;
            }
            if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                return raw as i32;
            }
            // I16_SENTINEL → fall through to slow path
        }
    }

    // SLOW PATH
    let node_data = &styled_dom.node_data.as_container()[node_id];

    styled_dom
        .css_property_cache
        .ptr
        .get_z_index(node_data, &node_id, &node_state)
        .and_then(|v| v.get_property())
        .map(|z| match z {
            LayoutZIndex::Auto => 0,
            LayoutZIndex::Integer(i) => *i,
        })
        .unwrap_or(0)
}

// +spec:positioning:c041c4 - positioned elements with z-index != auto establish stacking contexts
// z-index:<integer> ALWAYS establishes new stacking context on positioned elements
/// Returns true if z-index is `auto` (the initial value), false if it's an explicit `<integer>`.
/// This distinction matters for stacking context creation per §9.9.1.
pub fn is_z_index_auto(styled_dom: &StyledDom, node_id: Option<NodeId>) -> bool {
    use azul_css::props::layout::position::LayoutZIndex;

    let node_id = match node_id {
        Some(id) => id,
        None => return true,
    };

    let node_state = &styled_dom.styled_nodes.as_container()[node_id].styled_node_state;

    // FAST PATH: compact cache for normal state
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let raw = cc.get_z_index(node_id.index());
            if raw == azul_css::compact_cache::I16_AUTO {
                return true;
            }
            if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                return false; // explicit integer
            }
            // I16_SENTINEL → fall through to slow path
        }
    }

    // SLOW PATH
    let node_data = &styled_dom.node_data.as_container()[node_id];

    styled_dom
        .css_property_cache
        .ptr
        .get_z_index(node_data, &node_id, &node_state)
        .and_then(|v| v.get_property())
        .map(|z| matches!(z, LayoutZIndex::Auto))
        .unwrap_or(true) // no value = auto
}

// Rendering Property Getters

/// Information about background color for a node
///
/// # CSS Background Propagation (Special Case for HTML Root)
///
/// According to CSS Backgrounds and Borders Module Level 3, Section "The Canvas Background
/// and the HTML `<body>` Element":
///
/// For HTML documents where the root element is `<html>`, if the computed value of
/// `background-image` on the root element is `none` AND its `background-color` is `transparent`,
/// user agents **must propagate** the computed values of the background properties from the
/// first `<body>` child element to the root element.
///
/// This behavior exists for backwards compatibility with older HTML where backgrounds were
/// typically set on `<body>` using `bgcolor` attributes, and ensures that the `<body>`
/// background covers the entire viewport/canvas even when `<body>` itself has constrained
/// dimensions.
///
/// Implementation: When requesting the background of an `<html>` node, we first check if it
/// has a transparent background with no image. If so, we look for a `<body>` child and use
/// its background instead.
pub fn get_background_color(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> ColorU {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    let cache = &styled_dom.css_property_cache.ptr;

    // Fast path: Get this node's background.
    // Negative fast path: if compact cache says `has_background == 0` on a
    // normal-state node, skip the cascade walk entirely. Only declared backgrounds
    // set the bit, so `false` is a safe "unconditionally transparent" signal.
    let get_node_bg = |nid: NodeId, ndata: &azul_core::dom::NodeData, state: &StyledNodeState| {
        if state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if !cc.has_background(nid.index()) {
                    return None;
                }
            }
        }
        cache
            .get_background_content(ndata, &nid, state)
            .and_then(|bg| bg.get_property())
            .and_then(|bg_vec| bg_vec.get(0).cloned())
            .and_then(|first_bg| match &first_bg {
                azul_css::props::style::StyleBackgroundContent::Color(color) => Some(color.clone()),
                azul_css::props::style::StyleBackgroundContent::Image(_) => None, // Has image, not transparent
                _ => None,
            })
    };

    let own_bg = get_node_bg(node_id, node_data, node_state);

    // CSS Background Propagation: Special handling for <html> root element
    // Only check propagation if this is an Html node AND has transparent background (no
    // color/image)
    if !matches!(node_data.node_type, NodeType::Html) || own_bg.is_some() {
        // Not Html or has its own background - return own background or transparent
        return own_bg.unwrap_or(ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        });
    }

    // Html node with transparent background - check if we should propagate from <body>
    let first_child = styled_dom
        .node_hierarchy
        .as_container()
        .get(node_id)
        .and_then(|node| node.first_child_id(node_id));

    let Some(first_child) = first_child else {
        return ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        };
    };

    let first_child_data = &styled_dom.node_data.as_container()[first_child];

    // Check if first child is <body>
    if !matches!(first_child_data.node_type, NodeType::Body) {
        return ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        };
    }

    // Propagate <body>'s background to <html> (canvas)
    let first_child_state = &styled_dom.styled_nodes.as_container()[first_child].styled_node_state;
    get_node_bg(first_child, first_child_data, first_child_state).unwrap_or(ColorU {
        r: 0,
        g: 0,
        b: 0,
        a: 0,
    })
}

/// Returns all background content layers for a node (colors, gradients, images).
/// This is used for rendering backgrounds that may include linear/radial/conic gradients.
///
/// CSS Background Propagation (CSS Backgrounds 3, Section 2.11.2):
/// For HTML documents, if the root `<html>` element has no background (transparent with no image),
/// propagate the background from the first `<body>` child element.
pub fn get_background_contents(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Vec<azul_css::props::style::StyleBackgroundContent> {
    use azul_core::dom::NodeType;
    use azul_css::props::style::StyleBackgroundContent;

    let node_data = &styled_dom.node_data.as_container()[node_id];
    let cache = &styled_dom.css_property_cache.ptr;

    // Helper to get backgrounds for a node.
    // Negative fast path: if compact cache says `has_background == 0` on a normal
    // pseudo-state node, return empty without walking the cascade.
    let get_node_backgrounds =
        |nid: NodeId, ndata: &azul_core::dom::NodeData, state: &StyledNodeState|
        -> Vec<StyleBackgroundContent> {
            if state.is_normal() {
                if let Some(ref cc) = cache.compact_cache {
                    if !cc.has_background(nid.index()) {
                        return Vec::new();
                    }
                }
            }
            cache
                .get_background_content(ndata, &nid, state)
                .and_then(|bg| bg.get_property())
                .map(|bg_vec| bg_vec.iter().cloned().collect())
                .unwrap_or_default()
        };

    let own_backgrounds = get_node_backgrounds(node_id, node_data, node_state);

    // CSS Background Propagation: Special handling for <html> root element
    // Only check propagation if this is an Html node AND has no backgrounds
    if !matches!(node_data.node_type, NodeType::Html) || !own_backgrounds.is_empty() {
        return own_backgrounds;
    }

    // Html node with no backgrounds - check if we should propagate from <body>
    let first_child = styled_dom
        .node_hierarchy
        .as_container()
        .get(node_id)
        .and_then(|node| node.first_child_id(node_id));

    let Some(first_child) = first_child else {
        return own_backgrounds;
    };

    let first_child_data = &styled_dom.node_data.as_container()[first_child];

    // Check if first child is <body>
    if !matches!(first_child_data.node_type, NodeType::Body) {
        return own_backgrounds;
    }

    // Propagate <body>'s backgrounds to <html> (canvas)
    let first_child_state = &styled_dom.styled_nodes.as_container()[first_child].styled_node_state;
    get_node_backgrounds(first_child, first_child_data, first_child_state)
}

/// Information about border rendering
pub struct BorderInfo {
    pub widths: crate::solver3::display_list::StyleBorderWidths,
    pub colors: crate::solver3::display_list::StyleBorderColors,
    pub styles: crate::solver3::display_list::StyleBorderStyles,
}

pub fn get_border_info(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> BorderInfo {
    use crate::solver3::display_list::{StyleBorderColors, StyleBorderStyles, StyleBorderWidths};
    use azul_css::css::CssPropertyValue;
    use azul_css::props::basic::color::ColorU;
    use azul_css::props::basic::pixel::PixelValue;
    use azul_css::props::style::{
        LayoutBorderTopWidth, LayoutBorderRightWidth,
        LayoutBorderBottomWidth, LayoutBorderLeftWidth,
    };
    use azul_css::props::style::border::{
        BorderStyle, StyleBorderTopColor, StyleBorderRightColor,
        StyleBorderBottomColor, StyleBorderLeftColor,
        StyleBorderTopStyle, StyleBorderRightStyle,
        StyleBorderBottomStyle, StyleBorderLeftStyle,
    };

    // FAST PATH: compact cache for normal state
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let idx = node_id.index();

            // Border widths: decode from compact i16 (resolved px × 10).
            // Previously this block called the slow convenience getters
            // despite being in the "fast path" branch — 2014 slow walks
            // per width × 4 widths per cold excel.html layout. Fixed
            // 2026-04-17.
            let make_width_px = |raw: i16| -> Option<PixelValue> {
                if raw == azul_css::compact_cache::I16_AUTO
                    || raw == azul_css::compact_cache::I16_INITIAL
                    || raw >= azul_css::compact_cache::I16_SENTINEL_THRESHOLD
                {
                    None
                } else {
                    Some(PixelValue::px(raw as f32 / 10.0))
                }
            };
            let widths = StyleBorderWidths {
                top: make_width_px(cc.get_border_top_width_raw(idx))
                    .map(|px| CssPropertyValue::Exact(LayoutBorderTopWidth { inner: px })),
                right: make_width_px(cc.get_border_right_width_raw(idx))
                    .map(|px| CssPropertyValue::Exact(LayoutBorderRightWidth { inner: px })),
                bottom: make_width_px(cc.get_border_bottom_width_raw(idx))
                    .map(|px| CssPropertyValue::Exact(LayoutBorderBottomWidth { inner: px })),
                left: make_width_px(cc.get_border_left_width_raw(idx))
                    .map(|px| CssPropertyValue::Exact(LayoutBorderLeftWidth { inner: px })),
            };

            // Border colors from compact cache
            let make_color = |raw: u32| -> Option<ColorU> {
                if raw == 0 { None } else {
                    Some(ColorU {
                        r: ((raw >> 24) & 0xFF) as u8,
                        g: ((raw >> 16) & 0xFF) as u8,
                        b: ((raw >> 8) & 0xFF) as u8,
                        a: (raw & 0xFF) as u8,
                    })
                }
            };

            let colors = StyleBorderColors {
                top: make_color(cc.get_border_top_color_raw(idx))
                    .map(|c| CssPropertyValue::Exact(StyleBorderTopColor { inner: c })),
                right: make_color(cc.get_border_right_color_raw(idx))
                    .map(|c| CssPropertyValue::Exact(StyleBorderRightColor { inner: c })),
                bottom: make_color(cc.get_border_bottom_color_raw(idx))
                    .map(|c| CssPropertyValue::Exact(StyleBorderBottomColor { inner: c })),
                left: make_color(cc.get_border_left_color_raw(idx))
                    .map(|c| CssPropertyValue::Exact(StyleBorderLeftColor { inner: c })),
            };

            // Border styles from compact cache
            let styles = StyleBorderStyles {
                top: Some(CssPropertyValue::Exact(StyleBorderTopStyle {
                    inner: cc.get_border_top_style(idx),
                })),
                right: Some(CssPropertyValue::Exact(StyleBorderRightStyle {
                    inner: cc.get_border_right_style(idx),
                })),
                bottom: Some(CssPropertyValue::Exact(StyleBorderBottomStyle {
                    inner: cc.get_border_bottom_style(idx),
                })),
                left: Some(CssPropertyValue::Exact(StyleBorderLeftStyle {
                    inner: cc.get_border_left_style(idx),
                })),
            };

            return BorderInfo { widths, colors, styles };
        }
    }

    // SLOW PATH: full cascade
    let node_data = &styled_dom.node_data.as_container()[node_id];

    // Get all border widths
    let widths = StyleBorderWidths {
        top: styled_dom
            .css_property_cache
            .ptr
            .get_border_top_width(node_data, &node_id, node_state)
            .cloned(),
        right: styled_dom
            .css_property_cache
            .ptr
            .get_border_right_width(node_data, &node_id, node_state)
            .cloned(),
        bottom: styled_dom
            .css_property_cache
            .ptr
            .get_border_bottom_width(node_data, &node_id, node_state)
            .cloned(),
        left: styled_dom
            .css_property_cache
            .ptr
            .get_border_left_width(node_data, &node_id, node_state)
            .cloned(),
    };

    // Get all border colors
    let colors = StyleBorderColors {
        top: styled_dom
            .css_property_cache
            .ptr
            .get_border_top_color(node_data, &node_id, node_state)
            .cloned(),
        right: styled_dom
            .css_property_cache
            .ptr
            .get_border_right_color(node_data, &node_id, node_state)
            .cloned(),
        bottom: styled_dom
            .css_property_cache
            .ptr
            .get_border_bottom_color(node_data, &node_id, node_state)
            .cloned(),
        left: styled_dom
            .css_property_cache
            .ptr
            .get_border_left_color(node_data, &node_id, node_state)
            .cloned(),
    };

    // Get all border styles
    let styles = StyleBorderStyles {
        top: styled_dom
            .css_property_cache
            .ptr
            .get_border_top_style(node_data, &node_id, node_state)
            .cloned(),
        right: styled_dom
            .css_property_cache
            .ptr
            .get_border_right_style(node_data, &node_id, node_state)
            .cloned(),
        bottom: styled_dom
            .css_property_cache
            .ptr
            .get_border_bottom_style(node_data, &node_id, node_state)
            .cloned(),
        left: styled_dom
            .css_property_cache
            .ptr
            .get_border_left_style(node_data, &node_id, node_state)
            .cloned(),
    };

    BorderInfo {
        widths,
        colors,
        styles,
    }
}

/// Convert BorderInfo to InlineBorderInfo for inline elements
///
/// This resolves the CSS property values to concrete pixel values and colors
/// that can be used during text rendering.
pub fn get_inline_border_info(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
    border_info: &BorderInfo,
) -> Option<crate::text3::cache::InlineBorderInfo> {
    use crate::text3::cache::InlineBorderInfo;

    // Helper to extract pixel value from border width
    fn get_border_width_px(
        width: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::LayoutBorderTopWidth>,
        >,
    ) -> f32 {
        width
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|w| w.inner.number.get())
            .unwrap_or(0.0)
    }

    fn get_border_width_px_right(
        width: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::LayoutBorderRightWidth>,
        >,
    ) -> f32 {
        width
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|w| w.inner.number.get())
            .unwrap_or(0.0)
    }

    fn get_border_width_px_bottom(
        width: &Option<
            azul_css::css::CssPropertyValue<
                azul_css::props::style::border::LayoutBorderBottomWidth,
            >,
        >,
    ) -> f32 {
        width
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|w| w.inner.number.get())
            .unwrap_or(0.0)
    }

    fn get_border_width_px_left(
        width: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::LayoutBorderLeftWidth>,
        >,
    ) -> f32 {
        width
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|w| w.inner.number.get())
            .unwrap_or(0.0)
    }

    // Helper to extract color from border color
    fn get_border_color_top(
        color: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::StyleBorderTopColor>,
        >,
    ) -> ColorU {
        color
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|c| c.inner)
            .unwrap_or(ColorU::BLACK)
    }

    fn get_border_color_right(
        color: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::StyleBorderRightColor>,
        >,
    ) -> ColorU {
        color
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|c| c.inner)
            .unwrap_or(ColorU::BLACK)
    }

    fn get_border_color_bottom(
        color: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::StyleBorderBottomColor>,
        >,
    ) -> ColorU {
        color
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|c| c.inner)
            .unwrap_or(ColorU::BLACK)
    }

    fn get_border_color_left(
        color: &Option<
            azul_css::css::CssPropertyValue<azul_css::props::style::border::StyleBorderLeftColor>,
        >,
    ) -> ColorU {
        color
            .as_ref()
            .and_then(|v| v.get_property())
            .map(|c| c.inner)
            .unwrap_or(ColorU::BLACK)
    }

    // Extract border-radius (simplified - uses the average of all corners if uniform)
    fn get_border_radius_px(
        styled_dom: &StyledDom,
        node_id: NodeId,
        node_state: &StyledNodeState,
    ) -> Option<f32> {
        let node_data = &styled_dom.node_data.as_container()[node_id];

        let top_left = styled_dom
            .css_property_cache
            .ptr
            .get_border_top_left_radius(node_data, &node_id, node_state)
            .and_then(|br| br.get_property().cloned())
            .map(|v| v.inner.number.get());

        let top_right = styled_dom
            .css_property_cache
            .ptr
            .get_border_top_right_radius(node_data, &node_id, node_state)
            .and_then(|br| br.get_property().cloned())
            .map(|v| v.inner.number.get());

        let bottom_left = styled_dom
            .css_property_cache
            .ptr
            .get_border_bottom_left_radius(node_data, &node_id, node_state)
            .and_then(|br| br.get_property().cloned())
            .map(|v| v.inner.number.get());

        let bottom_right = styled_dom
            .css_property_cache
            .ptr
            .get_border_bottom_right_radius(node_data, &node_id, node_state)
            .and_then(|br| br.get_property().cloned())
            .map(|v| v.inner.number.get());

        // If any radius is defined, use the maximum (for inline, uniform radius is most common)
        let radii: Vec<f32> = [top_left, top_right, bottom_left, bottom_right]
            .into_iter()
            .filter_map(|r| r)
            .collect();

        if radii.is_empty() {
            None
        } else {
            Some(radii.into_iter().fold(0.0f32, |a, b| a.max(b)))
        }
    }

    let top = get_border_width_px(&border_info.widths.top);
    let right = get_border_width_px_right(&border_info.widths.right);
    let bottom = get_border_width_px_bottom(&border_info.widths.bottom);
    let left = get_border_width_px_left(&border_info.widths.left);

    // Fetch padding values for inline elements
    fn resolve_padding(mv: MultiValue<PixelValue>) -> f32 {
        match mv {
            MultiValue::Exact(pv) => {
                super::calc::resolve_pixel_value(&pv, 0.0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE)
            }
            _ => 0.0,
        }
    }

    let p_top = resolve_padding(get_css_padding_top(styled_dom, node_id, node_state));
    let p_right = resolve_padding(get_css_padding_right(styled_dom, node_id, node_state));
    let p_bottom = resolve_padding(get_css_padding_bottom(styled_dom, node_id, node_state));
    let p_left = resolve_padding(get_css_padding_left(styled_dom, node_id, node_state));

    // Only return Some if there's actually a border or padding
    let has_border = top > 0.0 || right > 0.0 || bottom > 0.0 || left > 0.0;
    let has_padding = p_top > 0.0 || p_right > 0.0 || p_bottom > 0.0 || p_left > 0.0;
    if !has_border && !has_padding {
        return None;
    }

    // CSS 2.2 §8.6: detect direction for visual-order border/padding rendering in bidi
    let is_rtl = matches!(
        get_direction_property(styled_dom, node_id, node_state),
        MultiValue::Exact(StyleDirection::Rtl)
    );

    Some(InlineBorderInfo {
        top,
        right,
        bottom,
        left,
        top_color: get_border_color_top(&border_info.colors.top),
        right_color: get_border_color_right(&border_info.colors.right),
        bottom_color: get_border_color_bottom(&border_info.colors.bottom),
        left_color: get_border_color_left(&border_info.colors.left),
        radius: get_border_radius_px(styled_dom, node_id, node_state),
        padding_top: p_top,
        padding_right: p_right,
        padding_bottom: p_bottom,
        padding_left: p_left,
        is_first_fragment: true,
        is_last_fragment: true,
        is_rtl,
    })
}

// Selection and Caret Styling

/// Style information for text selection rendering
#[derive(Debug, Clone, Copy, Default)]
pub struct SelectionStyle {
    /// Background color of the selection highlight
    pub bg_color: ColorU,
    /// Text color when selected (overrides normal text color)
    pub text_color: Option<ColorU>,
    /// Border radius for selection rectangles
    pub radius: f32,
}

/// Get selection style for a node
pub fn get_selection_style(
    styled_dom: &StyledDom, 
    node_id: Option<NodeId>,
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
) -> SelectionStyle {
    let Some(node_id) = node_id else {
        return SelectionStyle::default();
    };

    let node_data = &styled_dom.node_data.as_container()[node_id];
    let node_state = &StyledNodeState::default();

    // Try to get selection background from CSS, otherwise use system color, otherwise hard-coded default
    let default_bg = system_style
        .and_then(|ss| ss.colors.selection_background.as_option().copied())
        .unwrap_or(ColorU {
            r: 51,
            g: 153,
            b: 255, // Standard blue selection color
            a: 128, // Semi-transparent
        });

    let bg_color = styled_dom
        .css_property_cache
        .ptr
        .get_selection_background_color(node_data, &node_id, node_state)
        .and_then(|c| c.get_property().cloned())
        .map(|c| c.inner)
        .unwrap_or(default_bg);

    // Try to get selection text color from CSS, otherwise use system color
    let default_text = system_style
        .and_then(|ss| ss.colors.selection_text.as_option().copied());

    let text_color = styled_dom
        .css_property_cache
        .ptr
        .get_selection_color(node_data, &node_id, node_state)
        .and_then(|c| c.get_property().cloned())
        .map(|c| c.inner)
        .or(default_text);

    let radius = styled_dom
        .css_property_cache
        .ptr
        .get_selection_radius(node_data, &node_id, node_state)
        .and_then(|r| r.get_property().cloned())
        .map(|r| r.inner.to_pixels_internal(0.0, 16.0, 16.0)) // percent=0, em=16px default font size
        .unwrap_or(0.0);

    SelectionStyle {
        bg_color,
        text_color,
        radius,
    }
}

/// Style information for caret rendering.
#[derive(Debug, Clone, Copy)]
pub struct CaretStyle {
    /// Color of the caret bar
    pub color: ColorU,
    /// Width of the caret bar in pixels
    pub width: f32,
    /// Blink animation duration in milliseconds (0 = no blink)
    pub animation_duration: u32,
}

impl Default for CaretStyle {
    fn default() -> Self {
        Self {
            color: ColorU::BLACK,
            width: 2.0,
            animation_duration: 500,
        }
    }
}

/// Get caret style for a node
pub fn get_caret_style(styled_dom: &StyledDom, node_id: Option<NodeId>) -> CaretStyle {
    let Some(node_id) = node_id else {
        return CaretStyle::default();
    };

    let node_data = &styled_dom.node_data.as_container()[node_id];
    let node_state = &StyledNodeState::default();

    let color = styled_dom
        .css_property_cache
        .ptr
        .get_caret_color(node_data, &node_id, node_state)
        .and_then(|c| c.get_property().cloned())
        .map(|c| c.inner)
        .unwrap_or(ColorU::BLACK);

    let width = styled_dom
        .css_property_cache
        .ptr
        .get_caret_width(node_data, &node_id, node_state)
        .and_then(|w| w.get_property().cloned())
        .map(|w| w.inner.to_pixels_internal(0.0, 16.0, 16.0)) // 16.0 as default em size
        .unwrap_or(2.0); // 2px width by default

    let animation_duration = styled_dom
        .css_property_cache
        .ptr
        .get_caret_animation_duration(node_data, &node_id, node_state)
        .and_then(|d| d.get_property().cloned())
        .map(|d| d.inner.inner) // Duration.inner is the u32 milliseconds value
        .unwrap_or(500); // 500ms blink by default

    CaretStyle {
        color,
        width,
        animation_duration,
    }
}

// Scrollbar Information

/// Get scrollbar information from a layout node.
///
/// Scrollbar requirements are computed during the layout phase in two paths:
/// - BFC layout: `compute_scrollbar_info()` + `merge_scrollbar_info()` in cache.rs
/// - Taffy layout: set in the measure callback in taffy_bridge.rs
///
/// If neither path set `scrollbar_info`, the node genuinely does not need
/// scrollbars. The previous heuristic (>3 children = force overflow) caused
/// false-positive scrollbars on normal containers.
pub fn get_scrollbar_info_from_layout(node: &LayoutNode) -> ScrollbarRequirements {
    node.scrollbar_info
        .clone()
        .unwrap_or_default()
}

/// Resolve the **layout-effective** scrollbar width for a node, in pixels.
///
/// This combines three inputs:
/// 1. CSS `scrollbar-width` property on the node (`auto` → 16, `thin` → 8, `none` → 0)
/// 2. OS-level `ScrollbarPreferences.visibility` (overlay scrollbars → 0 layout reservation)
/// 3. Custom `-azul-scrollbar-style` width override
///
/// For **overlay** scrollbars (macOS `WhenScrolling`, or equivalent), this returns `0.0`
/// because overlay scrollbars are painted on top of content and do not consume layout space.
/// The scrollbar is still *rendered*, but no space is reserved during layout.
// +spec:overflow:b83014 - overlay scrollbars do not create scrollbar gutters
///
/// During display-list generation, use `get_scrollbar_style()` instead — that returns
/// the full visual style including the *paint* width (which may be non-zero for overlay).
pub fn get_layout_scrollbar_width_px<T: crate::font_traits::ParsedFontTrait>(
    ctx: &crate::solver3::LayoutContext<'_, T>,
    dom_id: NodeId,
    styled_node_state: &StyledNodeState,
) -> f32 {
    // Resolve the full scrollbar style (includes per-node CSS overrides + system style).
    // `reserve_width_px` already accounts for overlay vs legacy:
    //   overlay (WhenScrolling) → 0.0
    //   legacy (Always)         → visual_width_px
    let style = get_scrollbar_style(
        ctx.styled_dom,
        dom_id,
        styled_node_state,
        ctx.system_style.as_deref(),
    );
    style.reserve_width_px
}

get_css_property!(
    get_display_property_internal,
    get_display,
    LayoutDisplay,
    azul_css::props::property::CssPropertyType::Display,
    compact = get_display
);

pub fn get_display_property(
    styled_dom: &StyledDom,
    dom_id: Option<NodeId>,
) -> MultiValue<LayoutDisplay> {
    let Some(id) = dom_id else {
        return MultiValue::Exact(LayoutDisplay::Inline);
    };
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    get_display_property_internal(styled_dom, id, node_state)
}

/// CSS Display Module Level 3: Blockification of display values.
///
/// When an element is floated, absolutely positioned, or is the root element,
/// its computed display value may be "blockified" per the table in CSS Display 3 §2.7.
/// This function returns the blockified display value without mutating any state.
pub fn blockify_display(raw_display: LayoutDisplay) -> LayoutDisplay {
    match raw_display {
        // Inline-level display types become their block-level equivalents
        LayoutDisplay::Inline => LayoutDisplay::Block,
        // Per CSS Display 3 §2.7: inline-block blockifies to block
        // (for legacy reasons, loses its flow-root nature)
        LayoutDisplay::InlineBlock => LayoutDisplay::Block,
        LayoutDisplay::InlineFlex => LayoutDisplay::Flex,
        LayoutDisplay::InlineTable => LayoutDisplay::Table,
        LayoutDisplay::InlineGrid => LayoutDisplay::Grid,
        // CSS 2.2 §9.7: table-internal display values blockify to block
        // for absolutely positioned, floated, or root elements
        LayoutDisplay::TableRowGroup
        | LayoutDisplay::TableColumn
        | LayoutDisplay::TableColumnGroup
        | LayoutDisplay::TableHeaderGroup
        | LayoutDisplay::TableFooterGroup
        | LayoutDisplay::TableRow
        | LayoutDisplay::TableCell
        | LayoutDisplay::TableCaption => LayoutDisplay::Block,
        // Already block-level types are unchanged
        other => other,
    }
}

/// // +spec:positioning:c31c24 - blockification is a computed-value change for absolute/float/root elements
/// Resolves the computed display value for an element, applying blockification
/// rules per CSS Display Module Level 3 §2.7.
// +spec:display-property:641ac5 - computed display value applies blockification/inlinification (not "as specified")
///
/// This centralizes the blockification decision so that all layout phases
/// (layout_tree, sizing, positioning) use consistent display values.
// +spec:floats:52aea6 - computed display blockified for floated/positioned/root elements
// +spec:positioning:ce02a1 - out-of-flow boxes (floated or absolutely positioned) get blockified display
pub fn get_computed_display(
    raw_display: LayoutDisplay,
    is_absolute_or_fixed: bool,
    is_floated: bool,
    is_root: bool,
    is_flex_grid_child: bool,
) -> LayoutDisplay {
    if raw_display == LayoutDisplay::None {
        return LayoutDisplay::None;
    }
    // +spec:positioning:69468c - absolute/fixed blockifies the box
    if is_absolute_or_fixed || is_floated || is_root || is_flex_grid_child {
        blockify_display(raw_display)
    } else {
        raw_display
    }
}

// +spec:font-metrics:f7affa - vertical-align shorthand: maps CSS vertical-align values to inline layout alignment
/// Reads the CSS `vertical-align` property for a DOM node and converts it to
/// the text3 `VerticalAlign` enum used during inline layout.
// +spec:display-property:24c160 - vertical-align aligns inline-level box within the line
pub fn get_vertical_align_for_node(
    styled_dom: &StyledDom,
    dom_id: NodeId,
) -> crate::text3::cache::VerticalAlign {
    let node_state = &styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
    let va = match get_vertical_align_property(styled_dom, dom_id, node_state) {
        MultiValue::Exact(v) => v,
        _ => StyleVerticalAlign::default(),
    };
    match va {
        StyleVerticalAlign::Baseline => crate::text3::cache::VerticalAlign::Baseline,
        StyleVerticalAlign::Top => crate::text3::cache::VerticalAlign::Top,
        StyleVerticalAlign::Middle => crate::text3::cache::VerticalAlign::Middle,
        StyleVerticalAlign::Bottom => crate::text3::cache::VerticalAlign::Bottom,
        StyleVerticalAlign::Sub => crate::text3::cache::VerticalAlign::Sub,
        StyleVerticalAlign::Superscript => crate::text3::cache::VerticalAlign::Super,
        StyleVerticalAlign::TextTop => crate::text3::cache::VerticalAlign::TextTop,
        StyleVerticalAlign::TextBottom => crate::text3::cache::VerticalAlign::TextBottom,
        // +spec:line-height:b41ee3 - percentage vertical-align: raise/lower by % of line-height, 0% = baseline
        StyleVerticalAlign::Percentage(p) => {
            let font_size = get_element_font_size(styled_dom, dom_id, node_state);
            let line_height = get_line_height_value(styled_dom, dom_id, node_state)
                .map(|lh| lh.inner.normalized() * font_size)
                .unwrap_or(font_size * 1.2);
            crate::text3::cache::VerticalAlign::Offset(p.normalized() * line_height)
        }
        // §10.8.1: <length> is absolute offset from baseline
        StyleVerticalAlign::Length(l) => {
            let font_size = get_element_font_size(styled_dom, dom_id, node_state);
            let px = super::calc::resolve_pixel_value(&l, 0.0, font_size, font_size);
            crate::text3::cache::VerticalAlign::Offset(px)
        }
    }
}

pub fn get_style_properties(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
    viewport_size: azul_css::props::basic::PhysicalSize,
) -> StyleProperties {
    use azul_css::props::basic::{PhysicalSize, PropertyContext, ResolutionContext};

    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;

    use azul_css::props::basic::font::{StyleFontFamily, StyleFontFamilyVec};

    // Fast path: use compact cache reverse map (works for inherited values on text nodes).
    // Slow path: only for non-normal pseudo states (:hover, :focus, etc.)
    let font_families = if node_state.is_normal() {
        cache.compact_cache.as_ref()
            .and_then(|cc| {
                let fh = cc.tier2b_text[dom_id.index()].font_family_hash;
                if fh == 0 { return None; }
                cc.font_hash_to_families.get(&fh).cloned()
            })
            .unwrap_or_else(|| {
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
            })
    } else {
        cache
            .get_font_family(node_data, &dom_id, node_state)
            .and_then(|v| v.get_property().cloned())
            .unwrap_or_else(|| {
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
            })
    };

    // Get parent's font-size for proper em resolution in font-size property.
    // FAST PATH: `get_parent_font_size` goes through `get_element_font_size`
    // which hits the memoised `resolved_font_sizes_px` Vec (O(1) array index).
    // The old code here walked the full CSS cascade for every call — 1485
    // slow walks per cold excel.html layout. Replaced 2026-04-17.
    let parent_font_size = get_parent_font_size(styled_dom, dom_id, node_state);

    let root_font_size = get_root_font_size(styled_dom, node_state);

    // Create resolution context for font-size (em refers to parent)
    let font_size_context = ResolutionContext {
        element_font_size: azul_css::props::basic::pixel::DEFAULT_FONT_SIZE, /* Not used for font-size property */
        parent_font_size,
        root_font_size,
        containing_block_size: PhysicalSize::new(0.0, 0.0),
        element_size: None,
        viewport_size,
    };

    // Get font-size: either from this node's CSS, or inherit from parent
    // font-size is an inheritable property, so if the node doesn't have
    // an explicit font-size, it should inherit from the parent (not default to 16px)
    let font_size = {
        // FAST PATH: compact cache for normal state.
        // Sentinel/inherit/initial → inherit from parent directly (which is
        // what the slow cascade walk would fall back to via `.unwrap_or(parent_font_size)`
        // anyway — avoid the walk entirely).
        let mut fast_font_size: Option<f32> = None;
        let mut compact_said_inherit = false;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                let raw = cc.get_font_size_raw(dom_id.index());
                if raw == azul_css::compact_cache::U32_SENTINEL
                    || raw == azul_css::compact_cache::U32_INHERIT
                    || raw == azul_css::compact_cache::U32_INITIAL
                {
                    compact_said_inherit = true;
                } else if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
                    fast_font_size = Some(pv.resolve_with_context(
                        &font_size_context,
                        PropertyContext::FontSize,
                    ));
                }
            }
        }
        if let Some(fs) = fast_font_size {
            fs
        } else if compact_said_inherit {
            parent_font_size
        } else {
            cache
                .get_font_size(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| {
                    v.inner
                        .resolve_with_context(&font_size_context, PropertyContext::FontSize)
                })
                .unwrap_or(parent_font_size)
        }
    };

    let color_from_cache = {
        // FAST PATH: compact cache for text color
        let mut fast_color = None;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                let raw = cc.get_text_color_raw(dom_id.index());
                if raw != 0 {
                    // Decode 0xRRGGBBAA → ColorU
                    fast_color = Some(ColorU {
                        r: (raw >> 24) as u8,
                        g: (raw >> 16) as u8,
                        b: (raw >> 8) as u8,
                        a: raw as u8,
                    });
                }
            }
        }
        fast_color.or_else(|| {
            cache
                .get_text_color(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| v.inner)
        })
    };

    // CSS initial value for 'color' is UA-dependent but conventionally black.
    // Do NOT use system_style.colors.text here — that reflects the OS theme
    // (e.g. white on macOS dark mode) and would produce white text on
    // explicitly light-colored backgrounds.  System colors (CanvasText etc.)
    // should only be used when referenced through CSS system-color keywords.
    let color = color_from_cache.unwrap_or(ColorU::BLACK);

    // +spec:font-metrics:e480da - line-height: normal/number/length/percentage resolution
    let line_height = {
        // FAST PATH: compact cache for line-height (stored as normalized × 1000 i16).
        // When the cache returns Some → we have a resolved value.
        // When it returns None AND node_state is normal → the compact cache stored
        // the sentinel, which means "line-height: normal" (the spec default).
        // Previously we fell through to a cascade walk here — but the default
        // has already been authoritatively decided by the builder, so the walk
        // would only ever re-confirm "no value, normal". 1600 pure-waste walks
        // per cold excel.html layout. Short-circuit to Normal directly.
        let mut fast_lh = None;
        let mut sentinel_normal = false;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if let Some(normalized) = cc.get_line_height(dom_id.index()) {
                    fast_lh = Some(crate::text3::cache::LineHeight::Px(normalized / 100.0 * font_size));
                } else {
                    // Sentinel in compact cache = "normal" (CSS default).
                    sentinel_normal = true;
                }
            }
        }
        if sentinel_normal {
            crate::text3::cache::LineHeight::Normal
        } else {
            fast_lh.unwrap_or_else(|| {
                cache
                    .get_line_height(node_data, &dom_id, node_state)
                    .and_then(|v| v.get_property().cloned())
                    .map(|v| crate::text3::cache::LineHeight::Px(v.inner.normalized() * font_size))
                    .unwrap_or(crate::text3::cache::LineHeight::Normal)
            })
        }
    };

    // Get background color for INLINE elements only
    // CSS background-color is NOT inherited. For block-level elements (th, td, div, etc.),
    // the background is painted separately by paint_element_background() in display_list.rs.
    // Only inline elements (span, em, strong, a, etc.) should have their background color
    // propagated through StyleProperties for the text rendering pipeline.
    //
    // FAST PATH: use the compact-cache-backed display getter. The old code
    // here called `cache.get_display(..)` (the 3-arg convenience method on
    // CssPropertyCache) which routes through `get_property_slow` — 1485 slow
    // walks per cold excel.html layout. Replaced 2026-04-17.
    use azul_css::props::layout::LayoutDisplay;
    let display = match get_display_property(styled_dom, Some(dom_id)) {
        MultiValue::Exact(v) => v,
        _ => LayoutDisplay::Inline,
    };

    // For inline and inline-block elements, get background content and border info
    // Block elements have their backgrounds/borders painted by display_list.rs
    let (background_color, background_content, border) =
        if matches!(display, LayoutDisplay::Inline | LayoutDisplay::InlineBlock) {
            let bg = get_background_color(styled_dom, dom_id, node_state);
            let bg_color = if bg.a > 0 { Some(bg) } else { None };

            // Get full background contents (including gradients)
            let bg_contents = get_background_contents(styled_dom, dom_id, node_state);

            // Get border info for inline elements
            let border_info = get_border_info(styled_dom, dom_id, node_state);
            let inline_border =
                get_inline_border_info(styled_dom, dom_id, node_state, &border_info);

            (bg_color, bg_contents, inline_border)
        } else {
            // Block-level elements: background/border is painted by display_list.rs
            // via push_backgrounds_and_border() in DisplayListBuilder
            (None, Vec::new(), None)
        };

    // Query font-weight from CSS cache
    let font_weight = match get_font_weight_property(styled_dom, dom_id, node_state) {
        MultiValue::Exact(v) => v,
        _ => StyleFontWeight::Normal,
    };

    // Query font-style from CSS cache
    let font_style = match get_font_style_property(styled_dom, dom_id, node_state) {
        MultiValue::Exact(v) => v,
        _ => StyleFontStyle::Normal,
    };

    // Convert StyleFontWeight/StyleFontStyle to fontconfig types
    let fc_weight = super::fc::convert_font_weight(font_weight);
    let fc_style = super::fc::convert_font_style(font_style);

    // Check if any font family is a FontRef - if so, use FontStack::Ref
    // This allows embedded fonts (like Material Icons) to bypass fontconfig
    let font_stack = {
        // Look for a Ref in the font families
        let font_ref = (0..font_families.len())
            .find_map(|i| {
                match font_families.get(i).unwrap() {
                    azul_css::props::basic::font::StyleFontFamily::Ref(r) => Some(r.clone()),
                    _ => None,
                }
            });
        
        // Get platform for resolving system font types
        let platform = system_style.map(|ss| &ss.platform);

        if let Some(font_ref) = font_ref {
            // Use FontStack::Ref for embedded fonts
            FontStack::Ref(font_ref)
        } else {
            // Build regular font stack from all font families
            let mut stack = Vec::with_capacity(font_families.len() + 3);

            for i in 0..font_families.len() {
                let family = font_families.get(i).unwrap();

                // Handle SystemFontType specially - resolve to actual OS font names
                // (e.g., "system:ui" → ["System Font", "Helvetica Neue", "Lucida Grande"] on macOS)
                if let azul_css::props::basic::font::StyleFontFamily::SystemType(system_type) = family {
                    if let Some(platform) = platform {
                        let font_names = system_type.get_fallback_chain(platform);
                        let system_weight = if system_type.is_bold() {
                            rust_fontconfig::FcWeight::Bold
                        } else {
                            fc_weight
                        };
                        let system_style_val = if system_type.is_italic() {
                            crate::text3::cache::FontStyle::Italic
                        } else {
                            fc_style
                        };
                        for font_name in font_names {
                            stack.push(crate::text3::cache::FontSelector {
                                family: font_name.to_string(),
                                weight: system_weight,
                                style: system_style_val,
                                unicode_ranges: Vec::new(),
                            });
                        }
                    } else {
                        // No platform info - fall back to generic sans-serif
                        stack.push(crate::text3::cache::FontSelector {
                            family: "sans-serif".to_string(),
                            weight: fc_weight,
                            style: fc_style,
                            unicode_ranges: Vec::new(),
                        });
                    }
                } else {
                    stack.push(crate::text3::cache::FontSelector {
                        family: family.as_string(),
                        weight: fc_weight,
                        style: fc_style,
                        unicode_ranges: Vec::new(),
                    });
                }
            }

            // Add generic fallbacks (serif/sans-serif will be resolved based on Unicode ranges later)
            let generic_fallbacks = ["sans-serif", "serif", "monospace"];
            for fallback in &generic_fallbacks {
                if !stack
                    .iter()
                    .any(|f| f.family.to_lowercase() == fallback.to_lowercase())
                {
                    stack.push(crate::text3::cache::FontSelector {
                        family: fallback.to_string(),
                        weight: rust_fontconfig::FcWeight::Normal,
                        style: crate::text3::cache::FontStyle::Normal,
                        unicode_ranges: Vec::new(),
                    });
                }
            }

            FontStack::Stack(stack)
        }
    };

    // Get letter-spacing from CSS
    let letter_spacing = {
        // FAST PATH: compact cache for letter-spacing (i16 resolved px × 10)
        let mut fast_ls = None;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if let Some(px_val) = cc.get_letter_spacing(dom_id.index()) {
                    fast_ls = Some(crate::text3::cache::Spacing::Px(px_val.round() as i32));
                }
            }
        }
        fast_ls.unwrap_or_else(|| {
            cache
                .get_letter_spacing(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| {
                    let px_value = v.inner.resolve_with_context(&font_size_context, PropertyContext::FontSize);
                    crate::text3::cache::Spacing::Px(px_value.round() as i32)
                })
                .unwrap_or_default()
        })
    };

    // Get word-spacing from CSS
    let word_spacing = {
        // FAST PATH: compact cache for word-spacing (i16 resolved px × 10)
        let mut fast_ws = None;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if let Some(px_val) = cc.get_word_spacing(dom_id.index()) {
                    fast_ws = Some(crate::text3::cache::Spacing::Px(px_val.round() as i32));
                }
            }
        }
        fast_ws.unwrap_or_else(|| {
            cache
                .get_word_spacing(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| {
                    let px_value = v.inner.resolve_with_context(&font_size_context, PropertyContext::FontSize);
                    crate::text3::cache::Spacing::Px(px_value.round() as i32)
                })
                .unwrap_or_default()
        })
    };

    // Get text-decoration from CSS.
    //
    // Fast path: the compact cache keeps a `has_text_decoration` flag. If
    // unset (the overwhelmingly common case — plain body text has no
    // decoration set), skip the 4-pseudo-state × 6-layer cascade walk
    // entirely. Only nodes that actually set text-decoration pay the walk.
    let text_decoration = {
        let mut skip_walk = false;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if !cc.has_text_decoration(dom_id.index()) {
                    skip_walk = true;
                }
            }
        }
        if skip_walk {
            crate::text3::cache::TextDecoration::default()
        } else {
            cache
                .get_text_decoration(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| crate::text3::cache::TextDecoration::from_css(v))
                .unwrap_or_default()
        }
    };

    // Get tab-size (tab-size) from CSS.
    //
    // tab-size defaults to `I16_SENTINEL` in the compact cache builder
    // (spec default is "8", meaning 8 space widths). The old fallback
    // called `cache.get_tab_size(..)` (slow cascade) for every node whose
    // raw was SENTINEL — virtually every node, because almost nothing sets
    // tab-size. That was 1485 pure-waste slow walks per cold layout.
    //
    // New behaviour: sentinel → 8.0 directly. Only walk the cascade when
    // the compact cache is genuinely unavailable (no `compact_cache`) or
    // the node is in a pseudo-state that bypassed the cache.
    let tab_size = {
        let mut fast_tab = None;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                let raw = cc.get_tab_size_raw(dom_id.index());
                if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                    fast_tab = Some(raw as f32 / 10.0);
                } else {
                    // Sentinel / Inherit / Initial → spec default is 8.
                    fast_tab = Some(8.0);
                }
            }
        }
        fast_tab.unwrap_or_else(|| {
            cache
                .get_tab_size(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| v.inner.number.get())
                .unwrap_or(8.0)
        })
    };

    let properties = StyleProperties {
        font_stack,
        font_size_px: font_size,
        color,
        background_color,
        background_content,
        border,
        line_height,
        letter_spacing,
        word_spacing,
        text_decoration,
        tab_size,
        // These still use defaults - could be extended in future:
        // font_features, font_variations, text_transform, writing_mode, 
        // text_orientation, text_combine_upright, font_variant_*
        ..Default::default()
    };

    properties
}

pub fn get_list_style_type(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> StyleListStyleType {
    let Some(id) = dom_id else {
        return StyleListStyleType::default();
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_list_style_type(node_data, &id, node_state)
        .and_then(|v| v.get_property().copied())
        .unwrap_or_default()
}

pub fn get_list_style_position(
    styled_dom: &StyledDom,
    dom_id: Option<NodeId>,
) -> StyleListStylePosition {
    let Some(id) = dom_id else {
        return StyleListStylePosition::default();
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_list_style_position(node_data, &id, node_state)
        .and_then(|v| v.get_property().copied())
        .unwrap_or_default()
}

// New: Taffy Bridge Getters - Box Model Properties with Ua Css Fallback

use azul_css::props::layout::{
    LayoutInsetBottom, LayoutLeft, LayoutMarginBottom, LayoutMarginLeft, LayoutMarginRight,
    LayoutMarginTop, LayoutMaxHeight, LayoutMaxWidth, LayoutMinHeight, LayoutMinWidth,
    LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop, LayoutRight,
    LayoutTop,
};

/// Get inset (position) properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_left,
    get_left,
    azul_css::props::property::CssPropertyType::Left,
    compact_i16 = get_left
);
get_css_property_pixel!(
    get_css_right,
    get_right,
    azul_css::props::property::CssPropertyType::Right,
    compact_i16 = get_right
);
get_css_property_pixel!(
    get_css_top,
    get_top,
    azul_css::props::property::CssPropertyType::Top,
    compact_i16 = get_top
);
get_css_property_pixel!(
    get_css_bottom,
    get_bottom,
    azul_css::props::property::CssPropertyType::Bottom,
    compact_i16 = get_bottom
);

/// Get margin properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_margin_left,
    get_margin_left,
    azul_css::props::property::CssPropertyType::MarginLeft,
    compact_i16 = get_margin_left_raw
);
get_css_property_pixel!(
    get_css_margin_right,
    get_margin_right,
    azul_css::props::property::CssPropertyType::MarginRight,
    compact_i16 = get_margin_right_raw
);
get_css_property_pixel!(
    get_css_margin_top,
    get_margin_top,
    azul_css::props::property::CssPropertyType::MarginTop,
    compact_i16 = get_margin_top_raw
);
get_css_property_pixel!(
    get_css_margin_bottom,
    get_margin_bottom,
    azul_css::props::property::CssPropertyType::MarginBottom,
    compact_i16 = get_margin_bottom_raw
);

/// Get padding properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_padding_left,
    get_padding_left,
    azul_css::props::property::CssPropertyType::PaddingLeft,
    compact_i16 = get_padding_left_raw
);
get_css_property_pixel!(
    get_css_padding_right,
    get_padding_right,
    azul_css::props::property::CssPropertyType::PaddingRight,
    compact_i16 = get_padding_right_raw
);
get_css_property_pixel!(
    get_css_padding_top,
    get_padding_top,
    azul_css::props::property::CssPropertyType::PaddingTop,
    compact_i16 = get_padding_top_raw
);
get_css_property_pixel!(
    get_css_padding_bottom,
    get_padding_bottom,
    azul_css::props::property::CssPropertyType::PaddingBottom,
    compact_i16 = get_padding_bottom_raw
);

/// Get min/max size properties
get_css_property!(
    get_css_min_width,
    get_min_width,
    LayoutMinWidth,
    azul_css::props::property::CssPropertyType::MinWidth,
    compact_u32_struct = get_min_width_raw
);

get_css_property!(
    get_css_min_height,
    get_min_height,
    LayoutMinHeight,
    azul_css::props::property::CssPropertyType::MinHeight,
    compact_u32_struct = get_min_height_raw
);

get_css_property!(
    get_css_max_width,
    get_max_width,
    LayoutMaxWidth,
    azul_css::props::property::CssPropertyType::MaxWidth,
    compact_u32_struct = get_max_width_raw
);

get_css_property!(
    get_css_max_height,
    get_max_height,
    LayoutMaxHeight,
    azul_css::props::property::CssPropertyType::MaxHeight,
    compact_u32_struct = get_max_height_raw
);

/// Get border width properties (no UA CSS fallback needed, defaults to 0)
get_css_property_pixel!(
    get_css_border_left_width,
    get_border_left_width,
    azul_css::props::property::CssPropertyType::BorderLeftWidth,
    compact_i16 = get_border_left_width_raw
);
get_css_property_pixel!(
    get_css_border_right_width,
    get_border_right_width,
    azul_css::props::property::CssPropertyType::BorderRightWidth,
    compact_i16 = get_border_right_width_raw
);
get_css_property_pixel!(
    get_css_border_top_width,
    get_border_top_width,
    azul_css::props::property::CssPropertyType::BorderTopWidth,
    compact_i16 = get_border_top_width_raw
);
get_css_property_pixel!(
    get_css_border_bottom_width,
    get_border_bottom_width,
    azul_css::props::property::CssPropertyType::BorderBottomWidth,
    compact_i16 = get_border_bottom_width_raw
);

// Fragmentation (page breaking) properties

/// Get break-before property for paged media
pub fn get_break_before(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> PageBreak {
    let Some(id) = dom_id else {
        return PageBreak::Auto;
    };
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    // Negative fast path: break-* is almost never declared.
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_break(id.index()) {
                return PageBreak::Auto;
            }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[id];
    styled_dom
        .css_property_cache
        .ptr
        .get_break_before(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or(PageBreak::Auto)
}

/// Get break-after property for paged media
pub fn get_break_after(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> PageBreak {
    let Some(id) = dom_id else {
        return PageBreak::Auto;
    };
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_break(id.index()) {
                return PageBreak::Auto;
            }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[id];
    styled_dom
        .css_property_cache
        .ptr
        .get_break_after(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or(PageBreak::Auto)
}

/// Check if a PageBreak value forces a page break (always, page, left, right, etc.)
pub fn is_forced_page_break(page_break: PageBreak) -> bool {
    matches!(
        page_break,
        PageBreak::Always
            | PageBreak::Page
            | PageBreak::Left
            | PageBreak::Right
            | PageBreak::Recto
            | PageBreak::Verso
            | PageBreak::All
    )
}

/// Get break-inside property for paged media
pub fn get_break_inside(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> BreakInside {
    let Some(id) = dom_id else {
        return BreakInside::Auto;
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_break_inside(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or(BreakInside::Auto)
}

/// Get orphans property (minimum lines at bottom of page)
pub fn get_orphans(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> u32 {
    let Some(id) = dom_id else {
        return 2; // Default value
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_orphans(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .map(|o| o.inner)
        .unwrap_or(2)
}

/// Get widows property (minimum lines at top of page)
pub fn get_widows(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> u32 {
    let Some(id) = dom_id else {
        return 2; // Default value
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_widows(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .map(|w| w.inner)
        .unwrap_or(2)
}

/// Get box-decoration-break property
pub fn get_box_decoration_break(
    styled_dom: &StyledDom,
    dom_id: Option<NodeId>,
) -> BoxDecorationBreak {
    let Some(id) = dom_id else {
        return BoxDecorationBreak::Slice;
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_box_decoration_break(node_data, &id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or(BoxDecorationBreak::Slice)
}

// Helper functions for break properties

/// Check if a PageBreak value is avoid
pub fn is_avoid_page_break(page_break: &PageBreak) -> bool {
    matches!(page_break, PageBreak::Avoid | PageBreak::AvoidPage)
}

/// Check if a BreakInside value prevents breaks
pub fn is_avoid_break_inside(break_inside: &BreakInside) -> bool {
    matches!(
        break_inside,
        BreakInside::Avoid | BreakInside::AvoidPage | BreakInside::AvoidColumn
    )
}

// Font Chain Resolution - Pre-Layout Font Loading

use std::collections::HashMap;

use rust_fontconfig::{
    FcFontCache, FcWeight, FontFallbackChain, PatternMatch, UnicodeRange,
    DEFAULT_UNICODE_FALLBACK_SCRIPTS,
};

use crate::text3::cache::{FontChainKey, FontChainKeyOrRef, FontSelector, FontStack, FontStyle};

/// Result of collecting font stacks from a StyledDom
/// Contains all unique font stacks and the mapping from StyleFontFamiliesHash to FontChainKey
#[derive(Debug, Clone)]
pub struct CollectedFontStacks {
    /// All unique font stacks found in the document (system/file fonts via fontconfig)
    pub font_stacks: Vec<Vec<FontSelector>>,
    /// Map from the font stack hash to the index in font_stacks
    pub hash_to_index: HashMap<u64, usize>,
    /// Direct FontRefs that bypass fontconfig (e.g., embedded icon fonts)
    /// These are keyed by their pointer address for uniqueness
    pub font_refs: HashMap<usize, azul_css::props::basic::font::FontRef>,
}

/// Resolved font chains ready for use in layout
/// This is the result of resolving font stacks against FcFontCache
#[derive(Debug, Clone)]
pub struct ResolvedFontChains {
    /// Map from FontChainKeyOrRef to the resolved FontFallbackChain
    /// For FontChainKeyOrRef::Ref variants, the FontFallbackChain contains
    /// a single-font chain that covers the entire Unicode range.
    pub chains: HashMap<FontChainKeyOrRef, FontFallbackChain>,
}

impl ResolvedFontChains {
    /// Get a font chain by its key
    pub fn get(&self, key: &FontChainKeyOrRef) -> Option<&FontFallbackChain> {
        self.chains.get(key)
    }
    
    /// Get a font chain by FontChainKey (for system fonts)
    pub fn get_by_chain_key(&self, key: &FontChainKey) -> Option<&FontFallbackChain> {
        self.chains.get(&FontChainKeyOrRef::Chain(key.clone()))
    }

    /// Get a font chain for a font stack (via fontconfig)
    pub fn get_for_font_stack(&self, font_stack: &[FontSelector]) -> Option<&FontFallbackChain> {
        let key = FontChainKeyOrRef::Chain(FontChainKey::from_selectors(font_stack));
        self.chains.get(&key)
    }
    
    /// Get a font chain for a FontRef pointer
    pub fn get_for_font_ref(&self, ptr: usize) -> Option<&FontFallbackChain> {
        self.chains.get(&FontChainKeyOrRef::Ref(ptr))
    }

    /// Consume self and return the inner HashMap with FontChainKeyOrRef keys
    ///
    /// This is useful when you need access to both Chain and Ref variants.
    pub fn into_inner(self) -> HashMap<FontChainKeyOrRef, FontFallbackChain> {
        self.chains
    }

    /// Consume self and return only the fontconfig-resolved chains
    /// 
    /// This filters out FontRef entries and returns only the chains
    /// resolved via fontconfig. This is what FontManager expects.
    pub fn into_fontconfig_chains(self) -> HashMap<FontChainKey, FontFallbackChain> {
        self.chains
            .into_iter()
            .filter_map(|(key, chain)| {
                match key {
                    FontChainKeyOrRef::Chain(chain_key) => Some((chain_key, chain)),
                    FontChainKeyOrRef::Ref(_) => None,
                }
            })
            .collect()
    }

    /// Get the number of resolved chains
    pub fn len(&self) -> usize {
        self.chains.len()
    }

    /// Check if there are no resolved chains
    pub fn is_empty(&self) -> bool {
        self.chains.is_empty()
    }
    
    /// Get the number of direct FontRefs
    pub fn font_refs_len(&self) -> usize {
        self.chains.keys().filter(|k| k.is_ref()).count()
    }
}

/// Collect all unique font stacks from a StyledDom
///
/// This is a pure function that iterates over all nodes in the DOM and
/// extracts the font-family property from each node that has text content.
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font stacks from
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A `CollectedFontStacks` containing all unique font stacks and a hash-to-index mapping
pub fn collect_font_stacks_from_styled_dom(
    styled_dom: &StyledDom,
    platform: &azul_css::system::Platform,
) -> CollectedFontStacks {
    use azul_css::compact_cache::{FONT_WEIGHT_SHIFT, FONT_WEIGHT_MASK, FONT_STYLE_SHIFT, FONT_STYLE_MASK};

    let mut font_stacks = Vec::new();
    let mut hash_to_index: HashMap<u64, usize> = HashMap::new();
    let mut font_refs: HashMap<usize, azul_css::props::basic::font::FontRef> = HashMap::new();

    let node_data = styled_dom.node_data.as_container();
    let cache = &styled_dom.css_property_cache.ptr;
    let compact = match cache.compact_cache.as_ref() {
        Some(c) => c,
        None => return CollectedFontStacks { font_stacks, hash_to_index, font_refs },
    };

    // Phase 1: Scan compact cache arrays (just u64 reads) to find unique
    // (font_family_hash, weight, style) tuples. Record one representative
    // node index per unique tuple for the expensive CSS lookup in Phase 2.
    // Key: (font_family_hash, weight_encoded, style_encoded) → representative node index
    let mut unique_font_keys: HashMap<(u64, u8, u8), usize> = HashMap::new();
    let node_count = node_data.internal.len();

    for i in 0..node_count {
        // Only text nodes need fonts
        if !matches!(node_data.internal[i].node_type, NodeType::Text(_)) {
            continue;
        }
        let fh = compact.tier2b_text[i].font_family_hash;
        let t1 = compact.tier1_enums[i];
        let weight_bits = ((t1 >> FONT_WEIGHT_SHIFT) & FONT_WEIGHT_MASK) as u8;
        let style_bits = ((t1 >> FONT_STYLE_SHIFT) & FONT_STYLE_MASK) as u8;
        let key = (fh, weight_bits, style_bits);
        unique_font_keys.entry(key).or_insert(i);
    }

    // Phase 2: For each unique tuple, do ONE expensive CSS lookup on the
    // representative node to get the actual font-family names.
    let styled_nodes = styled_dom.styled_nodes.as_container();

    for (&(fh, _wb, _sb), &repr_idx) in &unique_font_keys {
        let dom_id = match NodeId::from_usize(repr_idx) {
            Some(id) => id,
            None => continue,
        };
        let node_state = &styled_nodes[dom_id].styled_node_state;

        // Use reverse map from compact cache: hash → actual font families.
        // This works for ALL nodes including text nodes that inherit font-family
        // via compact cache (where get_property_slow would return None).
        let font_families = compact.font_hash_to_families
            .get(&fh)
            .cloned()
            .unwrap_or_else(|| {
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
            });

        // Check for embedded FontRef
        if let Some(first_family) = font_families.get(0) {
            if let StyleFontFamily::Ref(font_ref) = first_family {
                let ptr = font_ref.parsed as usize;
                font_refs.entry(ptr).or_insert_with(|| font_ref.clone());
                continue;
            }
        }

        let font_weight = match get_font_weight_property(styled_dom, dom_id, node_state) {
            MultiValue::Exact(v) => v,
            _ => StyleFontWeight::Normal,
        };
        let font_style = match get_font_style_property(styled_dom, dom_id, node_state) {
            MultiValue::Exact(v) => v,
            _ => StyleFontStyle::Normal,
        };

        let fc_weight = super::fc::convert_font_weight(font_weight);
        let fc_style = super::fc::convert_font_style(font_style);

        let mut font_stack = Vec::with_capacity(font_families.len() + 3);

        for i in 0..font_families.len() {
            let family = font_families.get(i).unwrap();
            if matches!(family, StyleFontFamily::Ref(_)) {
                continue;
            }
            if let StyleFontFamily::SystemType(system_type) = family {
                let font_names = system_type.get_fallback_chain(platform);
                let system_weight = if system_type.is_bold() { FcWeight::Bold } else { fc_weight };
                let system_style = if system_type.is_italic() { FontStyle::Italic } else { fc_style };
                for font_name in font_names {
                    font_stack.push(FontSelector {
                        family: font_name.to_string(),
                        weight: system_weight,
                        style: system_style,
                        unicode_ranges: Vec::new(),
                    });
                }
            } else {
                font_stack.push(FontSelector {
                    family: family.as_string(),
                    weight: fc_weight,
                    style: fc_style,
                    unicode_ranges: Vec::new(),
                });
            }
        }

        // Add generic fallbacks
        for fallback in &["sans-serif", "serif", "monospace"] {
            if !font_stack.iter().any(|f| f.family.eq_ignore_ascii_case(fallback)) {
                font_stack.push(FontSelector {
                    family: fallback.to_string(),
                    weight: FcWeight::Normal,
                    style: FontStyle::Normal,
                    unicode_ranges: Vec::new(),
                });
            }
        }

        if font_stack.is_empty() {
            continue;
        }

        let key = FontChainKey::from_selectors(&font_stack);
        let hash = {
            use std::hash::{Hash, Hasher};
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            key.hash(&mut hasher);
            hasher.finish()
        };

        if !hash_to_index.contains_key(&hash) {
            let idx = font_stacks.len();
            font_stacks.push(font_stack);
            hash_to_index.insert(hash, idx);
        }
    }

    CollectedFontStacks {
        font_stacks,
        hash_to_index,
        font_refs,
    }
}

/// Resolve all font chains for the collected font stacks
///
/// This is a pure function that takes the collected font stacks and resolves
/// them against the FcFontCache to produce FontFallbackChains.
///
/// # Arguments
/// * `collected` - The collected font stacks from `collect_font_stacks_from_styled_dom`
/// * `fc_cache` - The fontconfig cache to resolve fonts against
///
/// # Returns
/// A `ResolvedFontChains` containing all resolved font chains
/// Walk every text node in `styled_dom` and collect the set of
/// non-ASCII codepoints actually present in the document.
///
/// Used by [`prune_chain_to_used_chars`] to drop CSS-fallback fonts
/// from a resolved chain when the *first* match in a `css_fallbacks`
/// group already covers everything the page asks for. ASCII (`< 0x80`)
/// is universally covered by every Latin font we'd resolve, so we
/// skip it here to keep the set small. Unicode characters in the
/// returned set are deduped + sorted via `BTreeSet`.
///
/// Cost: O(total text length). Cheap relative to layout itself.
pub fn collect_used_codepoints(
    styled_dom: &StyledDom,
) -> std::collections::BTreeSet<u32> {
    let mut out = std::collections::BTreeSet::new();
    let node_data = styled_dom.node_data.as_container();
    for node in node_data.internal.iter() {
        let azul_core::dom::NodeType::Text(s) = &node.node_type else {
            continue;
        };
        for c in s.as_str().chars() {
            let cp = c as u32;
            if cp >= 0x80 {
                out.insert(cp);
            }
        }
    }
    out
}

/// Like [`collect_used_codepoints`] but keeps ASCII. The fast-probe
/// path (`FcFontRegistry::request_fonts_fast`) *does* need ASCII:
/// "the font has to cover every codepoint I will render" is only
/// true if we tell it every codepoint, and "Segoe UI" not being
/// installed on macOS means even ASCII has to fall through to a
/// system default.
///
/// `collect_used_codepoints` strips ASCII because its caller
/// (`prune_chain_to_used_chars`) runs *after* resolution to trim an
/// already-resolved chain and every Latin-covering font passes ASCII
/// trivially. That assumption doesn't hold during probing.
pub fn collect_used_codepoints_all(
    styled_dom: &StyledDom,
) -> std::collections::BTreeSet<char> {
    let mut out = std::collections::BTreeSet::new();
    let node_data = styled_dom.node_data.as_container();
    for node in node_data.internal.iter() {
        let azul_core::dom::NodeType::Text(s) = &node.node_type else {
            continue;
        };
        for c in s.as_str().chars() {
            out.insert(c);
        }
    }
    out
}

/// Trim a [`FontFallbackChain`] down to the minimum set of `FontMatch`
/// entries needed to cover `used_chars` (typically from
/// [`collect_used_codepoints`]).
///
/// For each `css_fallbacks` group, walk matches in the resolver's
/// preferred order and keep them until every codepoint in
/// `used_chars` is covered (per the OS/2 unicode-range bits cached
/// in `FontMatch.unicode_ranges`). Always keeps at least the first
/// match per group so a font listed in CSS doesn't disappear.
///
/// `unicode_fallbacks` is filtered to only include fonts whose
/// ranges intersect `used_chars` — Phase-6's
/// [`scripts_present_in_styled_dom`] already scopes the *script
/// blocks* but a single block (e.g. CJK Unified, U+4E00..U+9FFF)
/// can have hundreds of matching system fonts; this prunes them
/// down to the few that actually cover the codepoints used.
///
/// On excel.html (~ASCII-only) this drops the per-chain
/// `css_fallbacks` from 5 → 1 in each group, eliminating ~20 of
/// the 26 fonts that would otherwise be parsed by
/// `load_fonts_from_disk`.
pub fn prune_chain_to_used_chars(
    chain: &mut rust_fontconfig::FontFallbackChain,
    used_chars: &std::collections::BTreeSet<u32>,
) {
    fn fm_covers(fm: &rust_fontconfig::FontMatch, cp: u32) -> bool {
        fm.unicode_ranges
            .iter()
            .any(|r| cp >= r.start && cp <= r.end)
    }

    for group in &mut chain.css_fallbacks {
        if group.fonts.is_empty() {
            continue;
        }
        // Track which non-ASCII chars still need coverage as we walk
        // matches in order. We always keep at least the first match.
        let mut needed: Vec<u32> = used_chars.iter().copied().collect();
        needed.retain(|&cp| !fm_covers(&group.fonts[0], cp));
        let mut keep = 1;
        for fm in group.fonts.iter().skip(1) {
            if needed.is_empty() {
                break;
            }
            keep += 1;
            needed.retain(|&cp| !fm_covers(fm, cp));
        }
        group.fonts.truncate(keep);
    }

    chain.unicode_fallbacks.retain(|fm| {
        used_chars.iter().any(|&cp| fm_covers(fm, cp))
    });
}

/// Scan text-node content in `styled_dom` and return the subset of
/// [`rust_fontconfig::DEFAULT_UNICODE_FALLBACK_SCRIPTS`] whose code-point
/// ranges actually appear in any text. Short-circuits once all seven
/// ranges have been seen.
///
/// Callers pass the result as `scripts_hint` to
/// [`resolve_font_chains`] / [`collect_and_resolve_font_chains_with_registration`];
/// `rust_fontconfig::FcFontCache::resolve_font_chain_with_scripts` then
/// only pulls in Unicode-fallback fonts for scripts the document
/// actually uses. An ASCII-only page returns an empty vector, which
/// avoids dragging Arial Unicode MS, CJK fonts, etc. into the
/// resolved chain and therefore into the eager-load step.
pub fn scripts_present_in_styled_dom(styled_dom: &StyledDom) -> Vec<UnicodeRange> {
    let scripts = DEFAULT_UNICODE_FALLBACK_SCRIPTS;
    let mut seen = vec![false; scripts.len()];
    let mut hits = 0usize;
    let node_data = styled_dom.node_data.as_container();
    'outer: for node in node_data.internal.iter() {
        let text: &str = match &node.node_type {
            azul_core::dom::NodeType::Text(s) => s.as_str(),
            _ => continue,
        };
        for c in text.chars() {
            let cp = c as u32;
            // Cheap reject: everything below the first fallback-script
            // range (Cyrillic starts at U+0400) is covered by the CSS
            // fallbacks' own glyphs — no reason to probe.
            if cp < 0x0400 {
                continue;
            }
            for (idx, r) in scripts.iter().enumerate() {
                if !seen[idx] && cp >= r.start && cp <= r.end {
                    seen[idx] = true;
                    hits += 1;
                    if hits == scripts.len() {
                        break 'outer;
                    }
                    break;
                }
            }
        }
    }
    scripts
        .iter()
        .enumerate()
        .filter_map(|(i, r)| if seen[i] { Some(*r) } else { None })
        .collect()
}

/// Resolve font chains for a collected set of stacks.
///
/// `scripts_hint`:
/// - `None` keeps the original "all 7 default scripts" behaviour
///   (Cyrillic / Arabic / Devanagari / Hiragana / Katakana / CJK /
///   Hangul) — equivalent to passing
///   `Some(rust_fontconfig::DEFAULT_UNICODE_FALLBACK_SCRIPTS)`.
/// - `Some(&[])` attaches *no* Unicode fallbacks, suitable for
///   ASCII-only documents. Combined with `prune_chain_to_used_chars`
///   this is what eliminates Arial Unicode MS / CJK / Arabic font
///   loads on Latin-only pages.
/// - `Some(ranges)` attaches fallbacks only for the listed scripts.
///   Production callers compute this via
///   [`scripts_present_in_styled_dom`].
pub fn resolve_font_chains(
    collected: &CollectedFontStacks,
    fc_cache: &FcFontCache,
    scripts_hint: Option<&[UnicodeRange]>,
) -> ResolvedFontChains {
    resolve_font_chains_with_registry(collected, fc_cache, None, scripts_hint)
}

/// Registry-aware variant of [`resolve_font_chains`]. When `registry`
/// is `Some`, each chain resolution goes through
/// [`rust_fontconfig::registry::FcFontRegistry::request_and_resolve_with_scripts`]
/// which priority-bumps the builder for families not yet in the
/// snapshot and waits for them — the "scout-on-demand" path that
/// avoids the eager common-stack pre-parse.
///
/// When `registry` is `None`, falls back to
/// [`rust_fontconfig::FcFontCache::resolve_font_chain_with_scripts`]
/// against the passed-in snapshot, which is what
/// [`resolve_font_chains`] does and what every code path did before
/// Phase 3.
pub fn resolve_font_chains_with_registry(
    collected: &CollectedFontStacks,
    fc_cache: &FcFontCache,
    registry: Option<&rust_fontconfig::registry::FcFontRegistry>,
    scripts_hint: Option<&[UnicodeRange]>,
) -> ResolvedFontChains {
    let mut chains = HashMap::new();

    // Resolve system/file font stacks via fontconfig
    for font_stack in &collected.font_stacks {
        if font_stack.is_empty() {
            continue;
        }

        // Build font families list
        let font_families: Vec<String> = font_stack
            .iter()
            .map(|s| s.family.clone())
            .filter(|f| !f.is_empty())
            .collect();

        let font_families = if font_families.is_empty() {
            vec!["sans-serif".to_string()]
        } else {
            font_families
        };

        let weight = font_stack[0].weight;
        let is_italic = font_stack[0].style == FontStyle::Italic;
        let is_oblique = font_stack[0].style == FontStyle::Oblique;

        let cache_key = FontChainKeyOrRef::Chain(FontChainKey {
            font_families: font_families.clone(),
            weight,
            italic: is_italic,
            oblique: is_oblique,
        });

        // Skip if already resolved
        if chains.contains_key(&cache_key) {
            continue;
        }

        // Resolve the font chain
        // IMPORTANT: Use False (not DontCare) when style is Normal.
        // DontCare means "accept italic too" which can match italic fonts.
        // False means "must NOT be italic" which correctly prefers Normal.
        let italic = if is_italic {
            PatternMatch::True
        } else {
            PatternMatch::False
        };
        let oblique = if is_oblique {
            PatternMatch::True
        } else {
            PatternMatch::False
        };

        // Registry-aware resolve: scout-on-demand path when available.
        // See `resolve_font_chains_with_registry` doc for rationale.
        let chain = if let Some(reg) = registry {
            reg.request_and_resolve_with_scripts(
                &font_families, weight, italic, oblique, scripts_hint,
            )
        } else {
            let mut trace = Vec::new();
            fc_cache.resolve_font_chain_with_scripts(
                &font_families, weight, italic, oblique, scripts_hint, &mut trace,
            )
        };

        chains.insert(cache_key, chain);
    }

    // NOTE: FontRefs bypass fontconfig entirely — the shaping code checks
    // style.font_stack for FontStack::Ref and uses the font data directly.
    // No entries are inserted into `chains` for them.

    ResolvedFontChains { chains }
}

/// Convenience function that collects and resolves font chains in one call
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font stacks from
/// * `fc_cache` - The fontconfig cache to resolve fonts against
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A `ResolvedFontChains` containing all resolved font chains
/// Collect font stacks, register embedded fonts, and resolve font chains
/// in a single pass over the DOM nodes. Replaces the old two-pass approach
/// where `register_embedded_fonts_from_styled_dom` + `collect_and_resolve_font_chains`
/// each independently scanned all nodes.
pub fn collect_and_resolve_font_chains_with_registration<T: crate::font_traits::ParsedFontTrait>(
    styled_dom: &StyledDom,
    fc_cache: &FcFontCache,
    font_manager: &crate::text3::cache::FontManager<T>,
    platform: &azul_css::system::Platform,
) -> ResolvedFontChains {
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);

    // Register embedded FontRefs (from the same scan, no second pass)
    for (_ptr, font_ref) in &collected.font_refs {
        font_manager.register_embedded_font(font_ref);
    }

    // Fast path (rust-fontconfig 4.2): when a registry is attached
    // we can resolve each stack by cmap-probing candidate files
    // against the codepoints the DOM actually uses, instead of
    // letting `request_fonts` eagerly parse every CSS fallback
    // via allsorts. On excel.html this drops `font_chain_resolve`
    // from ~128 ms / 49 faces parsed to ~5 ms / 3 faces.
    //
    // Falls back to the legacy pattern-map resolver when:
    //   - no registry is present (offline `FcFontCache` callers)
    //   - the DOM has no text codepoints (no shaping to be done,
    //     so cmap-probing has nothing to check and partial-cover
    //     entries would be surprising)
    if let Some(registry) = font_manager.registry.as_deref() {
        let used_chars = collect_used_codepoints_all(styled_dom);
        if !used_chars.is_empty() {
            return resolve_font_chains_fast(
                &collected,
                registry,
                &used_chars,
            );
        }
    }

    // Legacy path: pattern-map resolver. Only reached when the
    // caller passes an `FcFontCache` without a live registry
    // (ad-hoc tests, the PDF writer, etc.).
    let scripts = scripts_present_in_styled_dom(styled_dom);
    let mut resolved = resolve_font_chains_with_registry(
        &collected,
        fc_cache,
        font_manager.registry.as_deref(),
        Some(&scripts),
    );

    let used_chars = collect_used_codepoints(styled_dom);
    for chain in resolved.chains.values_mut() {
        prune_chain_to_used_chars(chain, &used_chars);
    }
    resolved
}

/// Fast-path resolver backed by [`FcFontRegistry::request_fonts_fast`].
///
/// Iterates `collected.font_stacks`, shapes each `(stack, weight,
/// italic, oblique)` combo into a cmap-probe request carrying the
/// DOM's codepoint set, calls the registry, and returns a
/// `ResolvedFontChains` keyed by `FontChainKeyOrRef::Chain` — the
/// same keys the legacy resolver emits, so downstream code
/// (`load_missing_for_chains`, `shape_with_font_fallback`) is
/// unchanged.
pub fn resolve_font_chains_fast(
    collected: &CollectedFontStacks,
    registry: &rust_fontconfig::registry::FcFontRegistry,
    codepoints: &std::collections::BTreeSet<char>,
) -> ResolvedFontChains {
    use rust_fontconfig::PatternMatch;

    static DBG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let dbg = *DBG.get_or_init(|| std::env::var_os("AZ_FAST_RESOLVE_DEBUG").is_some());

    let mut chains: HashMap<FontChainKeyOrRef, rust_fontconfig::FontFallbackChain> =
        HashMap::new();

    for font_stack in &collected.font_stacks {
        if font_stack.is_empty() {
            continue;
        }

        let font_families: Vec<String> = font_stack
            .iter()
            .map(|s| s.family.clone())
            .filter(|f| !f.is_empty())
            .collect();

        let font_families = if font_families.is_empty() {
            vec!["sans-serif".to_string()]
        } else {
            font_families
        };

        let weight = font_stack[0].weight;
        let is_italic = font_stack[0].style == FontStyle::Italic;
        let is_oblique = font_stack[0].style == FontStyle::Oblique;

        let cache_key = FontChainKeyOrRef::Chain(FontChainKey {
            font_families: font_families.clone(),
            weight,
            italic: is_italic,
            oblique: is_oblique,
        });

        if chains.contains_key(&cache_key) {
            continue;
        }

        let italic_match = if is_italic {
            PatternMatch::True
        } else {
            PatternMatch::False
        };

        let request = vec![(font_families.clone(), codepoints.clone())];
        let mut chains_out = registry.request_fonts_fast(&request, weight, italic_match);
        if dbg {
            let total_fonts: usize = chains_out
                .iter()
                .map(|c| c.css_fallbacks.iter().map(|g| g.fonts.len()).sum::<usize>())
                .sum();
            eprintln!(
                "[FAST] stack {:?} w={:?} i={:?} → {} groups, {} faces",
                font_families,
                weight,
                italic_match,
                chains_out.first().map(|c| c.css_fallbacks.len()).unwrap_or(0),
                total_fonts,
            );
        }
        if let Some(chain) = chains_out.pop() {
            chains.insert(cache_key, chain);
        }
    }

    ResolvedFontChains { chains }
}

/// Legacy wrapper: collect + resolve without registration. Kept for
/// backward compatibility; defaults to the full 7-script unicode
/// fallback set.
pub fn collect_and_resolve_font_chains(
    styled_dom: &StyledDom,
    fc_cache: &FcFontCache,
    platform: &azul_css::system::Platform,
) -> ResolvedFontChains {
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);
    resolve_font_chains(&collected, fc_cache, None)
}

/// Legacy wrapper: register only. Prefer `collect_and_resolve_font_chains_with_registration`.
pub fn register_embedded_fonts_from_styled_dom<T: crate::font_traits::ParsedFontTrait>(
    styled_dom: &StyledDom,
    font_manager: &crate::text3::cache::FontManager<T>,
    platform: &azul_css::system::Platform,
) {
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);
    for (_ptr, font_ref) in &collected.font_refs {
        font_manager.register_embedded_font(font_ref);
    }
}

// Font Loading Functions

use std::collections::HashSet;

use rust_fontconfig::FontId;

/// Extract all unique FontIds from resolved font chains
///
/// This function collects all FontIds that are referenced in the font chains,
/// which represents the complete set of fonts that may be needed for rendering.
pub fn collect_font_ids_from_chains(chains: &ResolvedFontChains) -> HashSet<FontId> {
    let mut font_ids = HashSet::new();

    // M12.7: hashbrown's RawIterRange (the .values() iterator below) mis-lifts
    // to wasm and loops forever on an empty map; is_empty() is len-based, so
    // bail out before iterating when there are no chains (web bare-body case).
    if chains.chains.is_empty() {
        return font_ids;
    }

    for chain in chains.chains.values() {
        // Collect from CSS fallbacks
        for group in &chain.css_fallbacks {
            for font in &group.fonts {
                font_ids.insert(font.id);
            }
        }

        // Collect from Unicode fallbacks
        for font in &chain.unicode_fallbacks {
            font_ids.insert(font.id);
        }
    }

    font_ids
}

/// Compute which fonts need to be loaded (diff with already loaded fonts)
///
/// # Arguments
/// * `required_fonts` - Set of FontIds that are needed
/// * `already_loaded` - Set of FontIds that are already loaded
///
/// # Returns
/// Set of FontIds that need to be loaded
pub fn compute_fonts_to_load(
    required_fonts: &HashSet<FontId>,
    already_loaded: &HashSet<FontId>,
) -> HashSet<FontId> {
    // M12.7: `.difference()` drives hashbrown's RawIterRange, which mis-lifts
    // to wasm and loops on an empty map. Nothing required → nothing to load.
    if required_fonts.is_empty() {
        return HashSet::new();
    }
    required_fonts.difference(already_loaded).cloned().collect()
}

/// Result of loading fonts
#[derive(Debug)]
pub struct FontLoadResult<T> {
    /// Successfully loaded fonts
    pub loaded: HashMap<FontId, T>,
    /// FontIds that failed to load, with error messages
    pub failed: Vec<(FontId, String)>,
}

/// Load fonts from disk using the provided loader function
///
/// This is a generic function that works with any font loading implementation.
/// The `load_fn` parameter should be a function that takes font bytes and an index,
/// and returns a parsed font or an error.
///
/// # Arguments
/// * `font_ids` - Set of FontIds to load
/// * `fc_cache` - The fontconfig cache to get font paths from
/// * `load_fn` - Function to load and parse font bytes
///
/// # Returns
/// A `FontLoadResult` containing successfully loaded fonts and any failures
pub fn load_fonts_from_disk<T, F>(
    font_ids: &HashSet<FontId>,
    fc_cache: &FcFontCache,
    load_fn: F,
) -> FontLoadResult<T>
where
    // Bytes come in as `Arc<FontBytes>` so the loader can retain
    // them cheaply (one `Arc::clone` per retained copy). On disk the
    // backing is an mmap, so untouched glyf/CFF pages don't count
    // toward RSS — the layout shaper only faults in pages it reads.
    F: Fn(std::sync::Arc<rust_fontconfig::FontBytes>, usize) -> Result<T, crate::text3::cache::LayoutError>,
{
    let mut loaded = HashMap::new();
    let mut failed = Vec::new();

    for font_id in font_ids {
        // Get font bytes from fc_cache as a shared mmap. Faces backed
        // by the same .ttc all observe the same `Arc<FontBytes>` via
        // rust_fontconfig's `shared_bytes` dedup.
        let font_bytes = match fc_cache.get_font_bytes(font_id) {
            Some(bytes) => bytes,
            None => {
                failed.push((
                    *font_id,
                    format!("Could not get font bytes for {:?}", font_id),
                ));
                continue;
            }
        };

        // Get font index (for font collections like .ttc files)
        let font_index = fc_cache
            .get_font_by_id(font_id)
            .and_then(|source| match source {
                rust_fontconfig::OwnedFontSource::Disk(path) => Some(path.font_index),
                rust_fontconfig::OwnedFontSource::Memory(font) => Some(font.font_index),
            })
            .unwrap_or(0) as usize;

        // Load the font using the provided function
        match load_fn(font_bytes, font_index) {
            Ok(font) => {
                loaded.insert(*font_id, font);
            }
            Err(e) => {
                failed.push((
                    *font_id,
                    format!("Failed to parse font {:?}: {:?}", font_id, e),
                ));
            }
        }
    }

    FontLoadResult { loaded, failed }
}

/// Convenience function to load all required fonts for a styled DOM
///
/// This function:
/// 1. Collects all font stacks from the DOM
/// 2. Resolves them to font chains
/// 3. Extracts all required FontIds
/// 4. Computes which fonts need to be loaded (diff with already loaded)
/// 5. Loads the missing fonts
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font requirements from
/// * `fc_cache` - The fontconfig cache
/// * `already_loaded` - Set of FontIds that are already loaded
/// * `load_fn` - Function to load and parse font bytes
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A tuple of (ResolvedFontChains, FontLoadResult)
pub fn resolve_and_load_fonts<T, F>(
    styled_dom: &StyledDom,
    fc_cache: &FcFontCache,
    already_loaded: &HashSet<FontId>,
    load_fn: F,
    platform: &azul_css::system::Platform,
) -> (ResolvedFontChains, FontLoadResult<T>)
where
    F: Fn(std::sync::Arc<rust_fontconfig::FontBytes>, usize) -> Result<T, crate::text3::cache::LayoutError>,
{
    // Step 1-2: Collect and resolve font chains
    let chains = collect_and_resolve_font_chains(styled_dom, fc_cache, platform);

    // Step 3: Extract all required FontIds
    let required_fonts = collect_font_ids_from_chains(&chains);

    // Step 4: Compute diff
    let fonts_to_load = compute_fonts_to_load(&required_fonts, already_loaded);

    // Step 5: Load missing fonts
    let load_result = load_fonts_from_disk(&fonts_to_load, fc_cache, load_fn);

    (chains, load_result)
}

// ============================================================================
// Scrollbar Style Getters
// ============================================================================

use azul_css::props::style::scrollbar::{
    LayoutScrollbarWidth, ScrollbarVisibilityMode,
    StyleScrollbarColor,
};

/// Computed scrollbar style for a node.
///
/// All visual defaults (colors, width) come from the UA CSS conditional rules
/// in `core/src/ua_css.rs` — individual `CssPropertyWithConditions` entries for
/// `scrollbar-color` and `scrollbar-width`, keyed on `@os` / `@theme`.
///
/// Overlay behaviour (fade timing, visibility, clip) is derived from the
/// resolved `scrollbar-width` mode:
///   - `thin`  → overlay:  fade 500/200 ms, `WhenScrolling`, clip = true
///   - `auto`  → classic:  no fade, `Always`, clip = false
///   - `none`  → hidden:   no fade, `Always`, clip = false
///
/// Per-node CSS overrides (in priority order):
///   1. `-azul-scrollbar-style`  (full `ScrollbarInfo` override)
///   2. `scrollbar-width`        (overrides width + overlay mode)
///   3. `scrollbar-color`        (overrides thumb / track colours)
#[derive(Debug, Clone)]
pub struct ComputedScrollbarStyle {
    /// The scrollbar width mode (auto/thin/none)
    pub width_mode: LayoutScrollbarWidth,
    /// Visual width in pixels — used for rendering track + thumb.
    /// Non-zero even for overlay scrollbars.
    pub visual_width_px: f32,
    /// Reserve width in pixels — layout space subtracted from content area.
    /// 0 for overlay scrollbars, equal to `visual_width_px` for legacy.
    pub reserve_width_px: f32,
    /// Thumb color
    pub thumb_color: ColorU,
    /// Track color
    pub track_color: ColorU,
    /// Button color (for scroll arrows)
    pub button_color: ColorU,
    /// Corner color (where scrollbars meet)
    pub corner_color: ColorU,
    /// Whether to clip the scrollbar to the container's border-radius
    pub clip_to_container_border: bool,
    /// Delay in ms before scrollbar starts fading out (0 = never fade)
    pub fade_delay_ms: u32,
    /// Duration of fade-out animation in ms (0 = instant)
    pub fade_duration_ms: u32,
    /// Scrollbar visibility mode (always / when-scrolling / auto)
    pub visibility: ScrollbarVisibilityMode,
    /// Whether to show top/bottom (or left/right) arrow buttons.
    /// When false, the track spans the entire scrollbar length.
    pub show_scroll_buttons: bool,
    /// Size of each arrow button in px (square: width = height).
    /// Only used when `show_scroll_buttons == true`.
    pub scroll_button_size_px: f32,
    /// Whether to show the corner rect where V and H scrollbars meet.
    pub show_corner_rect: bool,
    /// Thumb color when hovered (None = use thumb_color)
    pub thumb_color_hover: Option<ColorU>,
    /// Thumb color when pressed/active (None = use thumb_color)
    pub thumb_color_active: Option<ColorU>,
    /// Track color when hovered (None = use track_color)
    pub track_color_hover: Option<ColorU>,
    /// Visual width when hovered (None = use visual_width_px)
    pub visual_width_px_hover: Option<f32>,
    /// Visual width when pressed (None = use visual_width_px)
    pub visual_width_px_active: Option<f32>,
}

impl Default for ComputedScrollbarStyle {
    fn default() -> Self {
        // Evaluate UA CSS rules with a default context (no OS info).
        // Picks the unconditional fallback: classic light, auto width.
        let ctx = azul_css::dynamic_selector::DynamicSelectorContext::default();
        let ua = azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx);
        Self::from_ua_resolved(&ua)
    }
}

impl ComputedScrollbarStyle {
    /// Build from resolved UA scrollbar CSS properties.
    ///
    /// Each property is read individually from the resolved UA CSS.
    fn from_ua_resolved(ua: &azul_core::ua_css::ResolvedUaScrollbar) -> Self {
        let width_mode = ua.width;
        let visibility = ua.visibility;
        let fade_delay_ms = ua.fade_delay.ms;
        let fade_duration_ms = ua.fade_duration.ms;

        let visual_width_px = match width_mode {
            LayoutScrollbarWidth::Thin => 8.0,
            LayoutScrollbarWidth::Auto => 12.0,
            LayoutScrollbarWidth::None => 0.0,
        };

        // Overlay scrollbars don't reserve layout space.
        let reserve_width_px = if visibility == ScrollbarVisibilityMode::WhenScrolling {
            0.0
        } else {
            visual_width_px
        };

        let clip = visibility == ScrollbarVisibilityMode::WhenScrolling;

        // Overlay scrollbars hide buttons and corner by default.
        let is_overlay = visibility == ScrollbarVisibilityMode::WhenScrolling;
        let show_scroll_buttons = !is_overlay;
        let scroll_button_size_px = if is_overlay { 0.0 } else { visual_width_px };
        let show_corner_rect = !is_overlay;

        let (thumb_color, track_color) = match ua.color {
            StyleScrollbarColor::Custom(c) => (c.thumb, c.track),
            _ => (ColorU::TRANSPARENT, ColorU::TRANSPARENT),
        };

        // Compute hover / active variants:
        // Hover: lighten thumb by ~20%, widen by +4px
        // Active: darken thumb by ~10%, widen by +4px
        let thumb_hover = ColorU {
            r: thumb_color.r.saturating_add(30),
            g: thumb_color.g.saturating_add(30),
            b: thumb_color.b.saturating_add(30),
            a: thumb_color.a.saturating_add(40).min(255),
        };
        let thumb_active = ColorU {
            r: thumb_color.r.saturating_sub(15),
            g: thumb_color.g.saturating_sub(15),
            b: thumb_color.b.saturating_sub(15),
            a: 255,  // fully opaque when pressed
        };
        let track_hover = ColorU {
            r: track_color.r,
            g: track_color.g,
            b: track_color.b,
            a: track_color.a.saturating_add(40).min(255),
        };
        let hover_width = visual_width_px + 4.0;
        let active_width = visual_width_px + 4.0;

        Self {
            width_mode,
            visual_width_px,
            reserve_width_px,
            thumb_color,
            track_color,
            button_color: ColorU::TRANSPARENT,
            corner_color: ColorU::TRANSPARENT,
            clip_to_container_border: clip,
            fade_delay_ms,
            fade_duration_ms,
            visibility,
            show_scroll_buttons,
            scroll_button_size_px,
            show_corner_rect,
            thumb_color_hover: Some(thumb_hover),
            thumb_color_active: Some(thumb_active),
            track_color_hover: Some(track_hover),
            visual_width_px_hover: Some(hover_width),
            visual_width_px_active: Some(active_width),
        }
    }
}

/// Get the computed scrollbar style for a node.
///
/// Resolution order (later wins):
///   1. UA scrollbar CSS (`CssPropertyWithConditions` in `ua_css.rs`,
///      evaluated via `@os` / `@theme` conditions)
///   2. CSS `-azul-scrollbar-style` (full `ScrollbarInfo` customisation)
///   3. CSS `scrollbar-width`  (overrides width only)
///   4. CSS `scrollbar-color`  (overrides thumb / track colours)
///   5. CSS `-azul-scrollbar-visibility` (overrides visibility + clip)
///   6. CSS `-azul-scrollbar-fade-delay` (overrides fade delay)
///   7. CSS `-azul-scrollbar-fade-duration` (overrides fade duration)
///
/// When `system_style` is `None`, falls back to the unconditional UA rule
/// (classic light scrollbar).
pub fn get_scrollbar_style(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
    system_style: Option<&azul_css::system::SystemStyle>,
) -> ComputedScrollbarStyle {
    let node_data = &styled_dom.node_data.as_container()[node_id];

    // Step 1: Evaluate UA scrollbar CSS using the DynamicSelector system.
    let ctx = match system_style {
        Some(sys) => {
            azul_css::dynamic_selector::DynamicSelectorContext::from_system_style(sys)
        }
        None => azul_css::dynamic_selector::DynamicSelectorContext::default(),
    };
    let ua = azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx);
    let result = ComputedScrollbarStyle::from_ua_resolved(&ua);

    // FAST PATH: 99% of nodes have no scrollbar CSS. Bail before walking 8 × cascade.
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_scrollbar_css(node_id.index()) {
                return result;
            }
        }
    }
    let mut result = result;

    // Step 2: Check individual scrollbar part backgrounds
    if let Some(track) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_track(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.track_color = extract_color_from_background(track);
    }
    if let Some(thumb) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_thumb(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.thumb_color = extract_color_from_background(thumb);
    }
    if let Some(button) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_button(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.button_color = extract_color_from_background(button);
    }
    if let Some(corner) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_corner(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.corner_color = extract_color_from_background(corner);
    }

    // Step 3: Check for scrollbar-width (overrides width only, not overlay)
    if let Some(scrollbar_width) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_width(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.width_mode = *scrollbar_width;
        let w = match scrollbar_width {
            LayoutScrollbarWidth::Auto => 12.0,
            LayoutScrollbarWidth::Thin => 8.0,
            LayoutScrollbarWidth::None => 0.0,
        };
        result.visual_width_px = w;
        if result.visibility != ScrollbarVisibilityMode::WhenScrolling {
            result.reserve_width_px = w;
        }
    }

    // Step 4: Check for scrollbar-color (overrides thumb/track colors)
    if let Some(scrollbar_color) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_color(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        match scrollbar_color {
            StyleScrollbarColor::Auto => { /* keep */ }
            StyleScrollbarColor::Custom(custom) => {
                result.thumb_color = custom.thumb;
                result.track_color = custom.track;
            }
        }
    }

    // Step 5: Check for -azul-scrollbar-visibility
    if let Some(vis) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_visibility(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.visibility = *vis;
        result.clip_to_container_border = *vis == ScrollbarVisibilityMode::WhenScrolling;
        // Overlay mode: no reserved layout space, hide buttons and corner
        let is_overlay = *vis == ScrollbarVisibilityMode::WhenScrolling;
        if is_overlay {
            result.reserve_width_px = 0.0;
            result.show_scroll_buttons = false;
            result.scroll_button_size_px = 0.0;
            result.show_corner_rect = false;
        } else {
            result.reserve_width_px = result.visual_width_px;
        }
    }

    // Step 6: Check for -azul-scrollbar-fade-delay
    if let Some(delay) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_fade_delay(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.fade_delay_ms = delay.ms;
    }

    // Step 7: Check for -azul-scrollbar-fade-duration
    if let Some(dur) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_fade_duration(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        result.fade_duration_ms = dur.ms;
    }

    result
}

/// Cached wrapper for [`get_scrollbar_style`] that reuses the
/// memo stored on `LayoutContext`. The underlying call performs
/// 9 cascade walks per node (track/thumb/button/corner/width/
/// color/visibility/fade-delay/fade-duration). The BFC, Taffy,
/// and display-list callers all hit the same node many times
/// inside a single layout pass, so caching turns ~21 rebuilds per
/// node into one.
///
/// Falls back to the uncached `get_scrollbar_style` when no ctx
/// is available (shouldn't happen in the current code paths).
pub fn get_scrollbar_style_cached<T: crate::font_traits::ParsedFontTrait>(
    ctx: &crate::solver3::LayoutContext<'_, T>,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> ComputedScrollbarStyle {
    if let Some(s) = ctx.scrollbar_style_cache.borrow().get(&node_id) {
        return s.clone();
    }
    let style = get_scrollbar_style(
        ctx.styled_dom,
        node_id,
        node_state,
        ctx.system_style.as_deref(),
    );
    ctx.scrollbar_style_cache.borrow_mut().insert(node_id, style.clone());
    style
}

/// Helper to extract a solid color from a StyleBackgroundContent
fn extract_color_from_background(
    bg: &azul_css::props::style::background::StyleBackgroundContent,
) -> ColorU {
    use azul_css::props::style::background::StyleBackgroundContent;
    match bg {
        StyleBackgroundContent::Color(c) => *c,
        _ => ColorU::TRANSPARENT,
    }
}

/// Check if a node should clip its scrollbar to the container's border-radius
pub fn should_clip_scrollbar_to_border(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> bool {
    let style = get_scrollbar_style(styled_dom, node_id, node_state, None);
    style.clip_to_container_border
}

/// Get the scrollbar visual width in pixels for a node (used for rendering)
pub fn get_scrollbar_width_px(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    let style = get_scrollbar_style(styled_dom, node_id, node_state, None);
    style.visual_width_px
}

/// Checks if text in a node is selectable based on CSS `user-select` property.
///
/// Returns `true` if the text can be selected (default behavior),
/// `false` if `user-select: none` is set.
pub fn is_text_selectable(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> bool {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    
    styled_dom
        .css_property_cache
        .ptr
        .get_user_select(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|us| *us != StyleUserSelect::None)
        .unwrap_or(true) // Default: text is selectable
}

/// Checks if a node has the `contenteditable` attribute set directly.
///
/// Returns `true` if:
/// - The node has `contenteditable: true` set via `.set_contenteditable(true)`
/// - OR the node has `contenteditable` attribute set to `true`
///
/// This does NOT check inheritance - use `is_node_contenteditable_inherited` for that.
pub fn is_node_contenteditable(styled_dom: &StyledDom, node_id: NodeId) -> bool {
    use azul_core::dom::AttributeType;
    
    let node_data = &styled_dom.node_data.as_container()[node_id];
    
    // First check the direct contenteditable field (primary method)
    if node_data.is_contenteditable() {
        return true;
    }
    
    // Also check the attribute for backwards compatibility
    // Only return true if the attribute value is explicitly true
    node_data.attributes().as_ref().iter().any(|attr| {
        matches!(attr, AttributeType::ContentEditable(true))
    })
}
// =============================================================================
// Additional ExtractPropertyValue impls (not in compact cache tier 1/2)
// =============================================================================

use azul_css::props::layout::text::LayoutTextJustify;
use azul_css::props::layout::table::{LayoutTableLayout, StyleBorderCollapse, StyleCaptionSide, StyleEmptyCells};
use azul_css::props::style::text::StyleHyphens;
use azul_css::props::style::text::StyleWordBreak;
use azul_css::props::style::text::StyleOverflowWrap;
use azul_css::props::style::text::StyleLineBreak;
use azul_css::props::style::text::StyleTextAlignLast;
use azul_css::props::style::effects::StyleCursor;
use azul_css::props::style::effects::StyleObjectFit;
use azul_css::props::style::effects::StyleObjectPosition;
use azul_css::props::style::effects::StyleAspectRatio;
use azul_css::props::style::effects::StyleTextOrientation;

impl ExtractPropertyValue<LayoutTextJustify> for CssProperty {
    fn extract(&self) -> Option<LayoutTextJustify> {
        match self {
            Self::TextJustify(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleHyphens> for CssProperty {
    fn extract(&self) -> Option<StyleHyphens> {
        match self {
            Self::Hyphens(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleWordBreak> for CssProperty {
    fn extract(&self) -> Option<StyleWordBreak> {
        match self {
            Self::WordBreak(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleOverflowWrap> for CssProperty {
    fn extract(&self) -> Option<StyleOverflowWrap> {
        match self {
            Self::OverflowWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleLineBreak> for CssProperty {
    fn extract(&self) -> Option<StyleLineBreak> {
        match self {
            Self::LineBreak(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleTextAlignLast> for CssProperty {
    fn extract(&self) -> Option<StyleTextAlignLast> {
        match self {
            Self::TextAlignLast(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleObjectFit> for CssProperty {
    fn extract(&self) -> Option<StyleObjectFit> {
        match self {
            Self::ObjectFit(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleTextOrientation> for CssProperty {
    fn extract(&self) -> Option<StyleTextOrientation> {
        match self {
            Self::TextOrientation(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleObjectPosition> for CssProperty {
    fn extract(&self) -> Option<StyleObjectPosition> {
        match self {
            Self::ObjectPosition(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleAspectRatio> for CssProperty {
    fn extract(&self) -> Option<StyleAspectRatio> {
        match self {
            Self::AspectRatio(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<LayoutTableLayout> for CssProperty {
    fn extract(&self) -> Option<LayoutTableLayout> {
        match self {
            Self::TableLayout(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleBorderCollapse> for CssProperty {
    fn extract(&self) -> Option<StyleBorderCollapse> {
        match self {
            Self::BorderCollapse(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleCaptionSide> for CssProperty {
    fn extract(&self) -> Option<StyleCaptionSide> {
        match self {
            Self::CaptionSide(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleEmptyCells> for CssProperty {
    fn extract(&self) -> Option<StyleEmptyCells> {
        match self {
            Self::EmptyCells(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}

impl ExtractPropertyValue<StyleCursor> for CssProperty {
    fn extract(&self) -> Option<StyleCursor> {
        match self {
            Self::Cursor(CssPropertyValue::Exact(v)) => Some(v.clone()),
            _ => None,
        }
    }
}

// =============================================================================
// Additional macro-based getters (not covered by compact cache fast-path getters)
// =============================================================================

get_css_property!(
    get_text_justify,
    get_text_justify,
    LayoutTextJustify,
    CssPropertyType::TextJustify
);

get_css_property!(
    get_hyphens,
    get_hyphens,
    StyleHyphens,
    CssPropertyType::Hyphens
);

get_css_property!(
    get_word_break,
    get_word_break,
    StyleWordBreak,
    CssPropertyType::WordBreak
);

get_css_property!(
    get_overflow_wrap,
    get_overflow_wrap,
    StyleOverflowWrap,
    CssPropertyType::OverflowWrap
);

get_css_property!(
    get_line_break,
    get_line_break,
    StyleLineBreak,
    CssPropertyType::LineBreak
);

get_css_property!(
    get_text_align_last,
    get_text_align_last,
    StyleTextAlignLast,
    CssPropertyType::TextAlignLast
);

get_css_property!(
    get_table_layout,
    get_table_layout,
    LayoutTableLayout,
    CssPropertyType::TableLayout
);

get_css_property!(
    get_border_collapse,
    get_border_collapse,
    StyleBorderCollapse,
    CssPropertyType::BorderCollapse,
    compact = get_border_collapse
);

get_css_property!(
    get_caption_side,
    get_caption_side,
    StyleCaptionSide,
    CssPropertyType::CaptionSide
);

get_css_property!(
    get_empty_cells,
    get_empty_cells,
    StyleEmptyCells,
    CssPropertyType::EmptyCells
);

get_css_property!(
    get_cursor_property,
    get_cursor,
    StyleCursor,
    CssPropertyType::Cursor
);

// =============================================================================
// Handwritten getters (Option<T>, special logic, or non-standard returns)
// =============================================================================

/// Get height property value for IFC text layout height reference.
pub fn get_height_value(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<LayoutHeight> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_height(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get shape-inside property. Returns Option<ShapeInside> (cloned).
pub fn get_shape_inside(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::layout::shape::ShapeInside> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_shape_inside(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get shape-outside property. Returns Option<ShapeOutside> (cloned).
pub fn get_shape_outside(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::layout::shape::ShapeOutside> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_shape_outside(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get line-height as the full StyleLineHeight value for caller resolution.
pub fn get_line_height_value(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleLineHeight> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_line_height(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get text-indent as the full StyleTextIndent value for caller resolution.
pub fn get_text_indent_value(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleTextIndent> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_text_indent(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get column-count property. Returns Option<ColumnCount>.
pub fn get_column_count(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::layout::column::ColumnCount> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_column_count(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get initial-letter property. Returns Option<StyleInitialLetter>.
pub fn get_initial_letter(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleInitialLetter> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_initial_letter(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get line-clamp property. Returns Option<StyleLineClamp>.
pub fn get_line_clamp(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleLineClamp> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_line_clamp(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get hanging-punctuation property. Returns Option<StyleHangingPunctuation>.
pub fn get_hanging_punctuation(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleHangingPunctuation> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_hanging_punctuation(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get text-combine-upright property. Returns Option<StyleTextCombineUpright>.
pub fn get_text_combine_upright(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::text::StyleTextCombineUpright> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_text_combine_upright(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get exclusion-margin value. Returns f32 (default 0.0).
pub fn get_exclusion_margin(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_exclusion_margin(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| v.inner.get() as f32)
        .unwrap_or(0.0)
}

/// Get hyphenation-language property. Returns Option<StyleHyphenationLanguage>.
pub fn get_hyphenation_language(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::azul_exclusion::StyleHyphenationLanguage> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_hyphenation_language(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get border-spacing property.
pub fn get_border_spacing(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> azul_css::props::layout::table::LayoutBorderSpacing {
    use azul_css::props::basic::pixel::PixelValue;

    // FAST PATH: compact cache for normal state
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let h_raw = cc.get_border_spacing_h_raw(node_id.index());
            let v_raw = cc.get_border_spacing_v_raw(node_id.index());
            // Both 0 means no border-spacing set (default)
            // Sentinel means non-px unit → slow path
            if h_raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD
                && v_raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD
            {
                return azul_css::props::layout::table::LayoutBorderSpacing {
                    horizontal: PixelValue::px(h_raw as f32 / 10.0),
                    vertical: PixelValue::px(v_raw as f32 / 10.0),
                };
            }
        }
    }

    // SLOW PATH
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_border_spacing(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
        .unwrap_or_default()
}

/// Get opacity value. Returns f32 (default 1.0).
///
/// GPU fast path: the compact cache encodes opacity as a u8 (0-254, 255 = unset).
/// Avoids the 4-pseudo-state × 6-layer cascade walk for animations reading opacity
/// across every node each frame.
pub fn get_opacity(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    // FAST PATH: compact cache for normal state
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            let raw = cc.get_opacity_raw(node_id.index());
            if raw == azul_css::compact_cache::OPACITY_SENTINEL {
                return 1.0;
            }
            return (raw as f32) / 254.0;
        }
    }
    // SLOW PATH: fall back to cascade walk (state != normal, or no compact cache)
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_opacity(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| v.inner.normalized())
        .unwrap_or(1.0)
}

/// Get filter property. Returns Option with cloned filter list.
pub fn get_filter(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::filter::StyleFilterVec> {
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_filter(node_id.index()) { return None; }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_filter(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get backdrop-filter property. Returns Option with cloned filter list.
pub fn get_backdrop_filter(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::filter::StyleFilterVec> {
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_backdrop_filter(node_id.index()) { return None; }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_backdrop_filter(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Compact-cache negative fast path for all 4 box-shadow sides.
/// Most nodes have no shadow; cheap to check one bit vs. 4 cascade walks.
#[inline]
fn box_shadow_fast_bail(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> bool {
    if !node_state.is_normal() { return false; }
    if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
        return !cc.has_box_shadow(node_id.index());
    }
    false
}

/// Get box-shadow for left side. Returns Option<StyleBoxShadow> (cloned).
pub fn get_box_shadow_left(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
    if box_shadow_fast_bail(styled_dom, node_id, node_state) { return None; }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_box_shadow_left(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| (**v).clone())
}

/// Get box-shadow for right side. Returns Option<StyleBoxShadow> (cloned).
pub fn get_box_shadow_right(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
    if box_shadow_fast_bail(styled_dom, node_id, node_state) { return None; }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_box_shadow_right(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| (**v).clone())
}

/// Get box-shadow for top side. Returns Option<StyleBoxShadow> (cloned).
pub fn get_box_shadow_top(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
    if box_shadow_fast_bail(styled_dom, node_id, node_state) { return None; }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_box_shadow_top(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| (**v).clone())
}

/// Get box-shadow for bottom side. Returns Option<StyleBoxShadow> (cloned).
pub fn get_box_shadow_bottom(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
    if box_shadow_fast_bail(styled_dom, node_id, node_state) { return None; }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_box_shadow_bottom(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| (**v).clone())
}

/// Get text-shadow property. Returns Option<StyleBoxShadow> (cloned).
pub fn get_text_shadow(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_text_shadow(node_id.index()) { return None; }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_text_shadow(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .map(|v| (**v).clone())
}

/// Get transform property. Returns Option (non-empty transform list, cloned).
///
/// GPU fast path: the compact cache keeps a `has_transform` flag. If unset,
/// skips the cascade walk entirely — which is the overwhelming case since most
/// nodes have no transform. Only nodes that actually have a transform pay the
/// slow-walk cost to retrieve the parsed value.
pub fn get_transform(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::transform::StyleTransformVec> {
    // FAST PATH: bit check in compact cache
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_transform(node_id.index()) {
                return None;
            }
            // has_transform set → fall through to cascade walk for the value
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_transform(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get counter-reset property. Returns Option<CounterReset> (cloned).
pub fn get_counter_reset(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::content::CounterReset> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_counter_reset(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// Get counter-increment property. Returns Option<CounterIncrement> (cloned).
pub fn get_counter_increment(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::content::CounterIncrement> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_counter_increment(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}

/// W3C-conformant contenteditable inheritance check.
///
/// In the W3C model, the `contenteditable` attribute is **inherited**:
/// - A node is editable if it has `contenteditable="true"` set directly
/// - OR if its parent has `isContentEditable` as true
/// - UNLESS the node explicitly sets `contenteditable="false"`
///
/// This function traverses up the DOM tree to determine editability.
///
/// # Returns
///
/// - `true` if the node is editable (either directly or via inheritance)
/// - `false` if the node is not editable or has `contenteditable="false"`
///
/// # Example
///
/// ```html
/// <div contenteditable="true">
///   A                              <!-- editable (inherited) -->
///   <div contenteditable="false">
///     B                            <!-- NOT editable (explicitly false) -->
///   </div>
///   C                              <!-- editable (inherited) -->
/// </div>
/// ```
pub fn is_node_contenteditable_inherited(styled_dom: &StyledDom, node_id: NodeId) -> bool {
    use azul_core::dom::AttributeType;
    
    let node_data_container = styled_dom.node_data.as_container();
    let hierarchy = styled_dom.node_hierarchy.as_container();
    
    let mut current_node_id = Some(node_id);
    
    while let Some(nid) = current_node_id {
        let node_data = &node_data_container[nid];
        
        // First check the direct contenteditable field (set via set_contenteditable())
        // This takes precedence as it's the API-level setting
        if node_data.is_contenteditable() {
            return true;
        }
        
        // Then check for explicit contenteditable attribute on this node
        // This handles HTML-style contenteditable="true" or contenteditable="false"
        for attr in node_data.attributes().as_ref().iter() {
            if let AttributeType::ContentEditable(is_editable) = attr {
                // If explicitly set to true, node is editable
                // If explicitly set to false, node is NOT editable (blocks inheritance)
                return *is_editable;
            }
        }
        
        // No explicit setting on this node, check parent for inheritance
        current_node_id = hierarchy.get(nid).and_then(|h| h.parent_id());
    }
    
    // Reached root without finding contenteditable - not editable
    false
}

/// Find the contenteditable ancestor of a node.
///
/// When focus lands on a text node inside a contenteditable container,
/// we need to find the actual container that has the `contenteditable` attribute.
///
/// # Returns
///
/// - `Some(node_id)` of the contenteditable ancestor (may be the node itself)
/// - `None` if no contenteditable ancestor exists
pub fn find_contenteditable_ancestor(styled_dom: &StyledDom, node_id: NodeId) -> Option<NodeId> {
    use azul_core::dom::AttributeType;
    
    let node_data_container = styled_dom.node_data.as_container();
    let hierarchy = styled_dom.node_hierarchy.as_container();
    
    let mut current_node_id = Some(node_id);
    
    while let Some(nid) = current_node_id {
        let node_data = &node_data_container[nid];
        
        // First check the direct contenteditable field (set via set_contenteditable())
        if node_data.is_contenteditable() {
            return Some(nid);
        }
        
        // Then check for contenteditable attribute on this node
        for attr in node_data.attributes().as_ref().iter() {
            if let AttributeType::ContentEditable(is_editable) = attr {
                if *is_editable {
                    return Some(nid);
                } else {
                    // Explicitly not editable - stop search
                    return None;
                }
            }
        }
        
        // Check parent
        current_node_id = hierarchy.get(nid).and_then(|h| h.parent_id());
    }
    
    None
}

// --- Taffy bridge property getters ---
//
// These getters return `Option<CssPropertyValue<T>>` (cloned from cache) for use
// by taffy_bridge.rs. The conversion from CssPropertyValue to taffy types is done
// in taffy_bridge.rs itself. Routing access through these functions centralizes
// all CSS property lookups for future cache optimizations (e.g., FxHash migration).

macro_rules! get_css_property_value {
    ($fn_name:ident, $cache_method:ident, $ret_type:ty) => {
        pub fn $fn_name(
            styled_dom: &StyledDom,
            node_id: NodeId,
            node_state: &StyledNodeState,
        ) -> Option<$ret_type> {
            let node_data = &styled_dom.node_data.as_container()[node_id];
            styled_dom
                .css_property_cache
                .ptr
                .$cache_method(node_data, &node_id, node_state)
                .cloned()
        }
    };
}

// Flexbox properties
get_css_property_value!(get_flex_direction_prop, get_flex_direction, LayoutFlexDirectionValue);
get_css_property_value!(get_flex_wrap_prop, get_flex_wrap, LayoutFlexWrapValue);
get_css_property_value!(get_flex_grow_prop, get_flex_grow, LayoutFlexGrowValue);
get_css_property_value!(get_flex_shrink_prop, get_flex_shrink, LayoutFlexShrinkValue);
get_css_property_value!(get_flex_basis_prop, get_flex_basis, LayoutFlexBasisValue);

// Alignment properties
get_css_property_value!(get_align_items_prop, get_align_items, LayoutAlignItemsValue);
get_css_property_value!(get_align_self_prop, get_align_self, LayoutAlignSelfValue);
get_css_property_value!(get_align_content_prop, get_align_content, LayoutAlignContentValue);
get_css_property_value!(get_justify_content_prop, get_justify_content, LayoutJustifyContentValue);
get_css_property_value!(get_justify_items_prop, get_justify_items, LayoutJustifyItemsValue);
get_css_property_value!(get_justify_self_prop, get_justify_self, LayoutJustifySelfValue);

// Gap
get_css_property_value!(get_gap_prop, get_gap, LayoutGapValue);

// Grid properties
get_css_property_value!(get_grid_template_rows_prop, get_grid_template_rows, LayoutGridTemplateRowsValue);
get_css_property_value!(get_grid_template_columns_prop, get_grid_template_columns, LayoutGridTemplateColumnsValue);
get_css_property_value!(get_grid_auto_rows_prop, get_grid_auto_rows, LayoutGridAutoRowsValue);
get_css_property_value!(get_grid_auto_columns_prop, get_grid_auto_columns, LayoutGridAutoColumnsValue);
get_css_property_value!(get_grid_auto_flow_prop, get_grid_auto_flow, LayoutGridAutoFlowValue);
get_css_property_value!(get_grid_column_prop, get_grid_column, LayoutGridColumnValue);
get_css_property_value!(get_grid_row_prop, get_grid_row, LayoutGridRowValue);

/// Get grid-template-areas property.
/// Uses the generic `get_property()` since CssPropertyCache lacks a specific getter.
/// Returns the inner `GridTemplateAreas` value (already unwrapped from CssPropertyValue).
pub fn get_grid_template_areas_prop(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<GridTemplateAreas> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom
        .css_property_cache
        .ptr
        .get_property(node_data, &node_id, node_state, &CssPropertyType::GridTemplateAreas)
        .and_then(|p| {
            if let CssProperty::GridTemplateAreas(v) = p {
                v.get_property().cloned()
            } else {
                None
            }
        })
}

/// Get clip-path property. Returns the ClipPath value for the node.
///
/// CSS Masking Module Level 1, section 3:
/// The clip-path property creates a clipping region that determines which parts
/// of an element are visible. Returns None for `clip-path: none` (default).
pub fn get_clip_path(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::layout::shape::ClipPath> {
    // Negative fast path: most nodes have `clip-path: none`.
    if node_state.is_normal() {
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
            if !cc.has_clip_path(node_id.index()) {
                return None;
            }
        }
    }
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_clip_path(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
        .cloned()
}