azul-layout 0.0.7

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
//! Getter functions for CSS properties from the styled DOM
//!
//! This module provides clean, consistent access to CSS properties with proper
//! fallbacks and type conversions.

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,
            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,
        },
    },
};

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
pub fn get_element_font_size(
    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;

    // Try to get from dependency chain first (proper resolution)
    let cached_font_size = cache
        .dependency_chains
        .get(dom_id.index())
        .and_then(|chains| chains.get(&azul_css::props::property::CssPropertyType::FontSize))
        .and_then(|chain| chain.cached_pixels);

    if let Some(cached) = cached_font_size {
        return cached;
    }

    // Fallback: get from property cache and resolve manually
    let parent_font_size = styled_dom
        .node_hierarchy
        .as_container()
        .get(dom_id)
        .and_then(|node| node.parent_id())
        .and_then(|parent_id| {
            // Check parent's dependency chain first (avoids recursion)
            cache
                .dependency_chains
                .get(parent_id.index())
                .and_then(|chains| {
                    chains.get(&azul_css::props::property::CssPropertyType::FontSize)
                })
                .and_then(|chain| chain.cached_pixels)
        })
        .unwrap_or(DEFAULT_FONT_SIZE);

    // Get root font-size (avoid recursion by checking cache first)
    let root_font_size = {
        let root_id = NodeId::new(0);
        cache
            .dependency_chains
            .get(root_id.index())
            .and_then(|chains| chains.get(&azul_css::props::property::CssPropertyType::FontSize))
            .and_then(|chain| chain.cached_pixels)
            .unwrap_or(DEFAULT_FONT_SIZE)
    };

    // Resolve font-size with proper context
    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, // Not used for FontSize property
                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), // Not used for font-size resolution
            };

            v.inner
                .resolve_with_context(&context, PropertyContext::FontSize)
        })
        .unwrap_or(DEFAULT_FONT_SIZE)
}

/// Helper function to get parent's computed font-size
pub fn get_parent_font_size(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    node_state: &StyledNodeState,
) -> f32 {
    styled_dom
        .node_hierarchy
        .as_container()
        .get(dom_id)
        .and_then(|node| node.parent_id())
        .map(|parent_id| get_element_font_size(styled_dom, parent_id, node_state))
        .unwrap_or(azul_css::props::basic::pixel::DEFAULT_FONT_SIZE)
}

/// Helper function to get root element's font-size
pub fn get_root_font_size(styled_dom: &StyledDom, node_state: &StyledNodeState) -> f32 {
    // Root is always NodeId(0) in Azul
    get_element_font_size(styled_dom, NodeId::new(0), node_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_visible_or_clip(&self) -> bool {
        matches!(
            self,
            MultiValue::Exact(LayoutOverflow::Visible | LayoutOverflow::Clip)
        )
    }
}

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

            // FIX: 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)
            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),
            _ => 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<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
);

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
);

get_css_property!(
    get_direction_property,
    get_direction,
    StyleDirection,
    azul_css::props::property::CssPropertyType::Direction,
    compact = get_direction
);

get_css_property!(
    get_vertical_align_property,
    get_vertical_align,
    StyleVerticalAlign,
    azul_css::props::property::CssPropertyType::VerticalAlign,
    compact = get_vertical_align
);
// 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 {
    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};

    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),
    }
}

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

// 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];

    // Fast path: Get this node's background
    let get_node_bg = |node_id: NodeId, node_data: &azul_core::dom::NodeData| {
        styled_dom
            .css_property_cache
            .ptr
            .get_background_content(node_data, &node_id, node_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);

    // 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)
    get_node_bg(first_child, first_child_data).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];

    // Helper to get backgrounds for a node
    let get_node_backgrounds =
        |nid: NodeId, ndata: &azul_core::dom::NodeData| -> Vec<StyleBackgroundContent> {
            styled_dom
                .css_property_cache
                .ptr
                .get_background_content(ndata, &nid, node_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);

    // 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)
    get_node_backgrounds(first_child, first_child_data)
}

/// 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::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 (already have compact path via i16)
            let node_data = &styled_dom.node_data.as_container()[node_id];
            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(),
            };

            // 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) => {
                use azul_css::props::basic::SizeMetric;
                match pv.metric {
                    SizeMetric::Px => pv.number.get(),
                    SizeMetric::Pt => pv.number.get() * 1.333333,
                    SizeMetric::Em | SizeMetric::Rem => pv.number.get() * 16.0,
                    _ => 0.0,
                }
            }
            _ => 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;
    }

    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,
    })
}

// 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)) // 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, Default)]
pub struct CaretStyle {
    pub color: ColorU,
    pub width: f32,
    pub animation_duration: u32,
}

/// 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 {
            r: 255,
            g: 255,
            b: 255,
            a: 255, // White caret by default
        });

    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 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.
///
/// 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 {
    use azul_css::props::style::scrollbar::LayoutScrollbarWidth;

    // Check OS-level preference: overlay scrollbars reserve no layout space.
    if let Some(ref sys) = ctx.system_style {
        use azul_css::system::ScrollbarVisibility;
        match sys.scrollbar_preferences.visibility {
            ScrollbarVisibility::WhenScrolling => return 0.0, // overlay
            ScrollbarVisibility::Always | ScrollbarVisibility::Automatic => {}
        }
    }

    // Per-node CSS resolution
    get_scrollbar_width_px(ctx.styled_dom, dom_id, styled_node_state)
}

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

/// Reads the CSS `vertical-align` property for a DOM node and converts it to
/// the text3 `VerticalAlign` enum used during inline layout.
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,
    }
}

pub fn get_style_properties(
    styled_dom: &StyledDom,
    dom_id: NodeId,
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
) -> 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;

    // NEW: Get ALL fonts from CSS font-family, not just first
    use azul_css::props::basic::font::{StyleFontFamily, StyleFontFamilyVec};

    let font_families = cache
        .get_font_family(node_data, &dom_id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or_else(|| {
            // Default to serif (same as browser default)
            StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
        });

    // Get parent's font-size for proper em resolution in font-size property
    let parent_font_size = styled_dom
        .node_hierarchy
        .as_container()
        .get(dom_id)
        .and_then(|node| {
            let parent_id = CoreNodeId::from_usize(node.parent)?;
            // Recursively get parent's font-size
            cache
                .get_font_size(
                    &styled_dom.node_data.as_container()[parent_id],
                    &parent_id,
                    &styled_dom.styled_nodes.as_container()[parent_id].styled_node_state,
                )
                .and_then(|v| v.get_property().cloned())
                .map(|v| {
                    // If parent also has em/rem, we'd need to recurse, but for now use fallback
                    use azul_css::props::basic::pixel::DEFAULT_FONT_SIZE;
                    v.inner.to_pixels_internal(0.0, DEFAULT_FONT_SIZE)
                })
        })
        .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 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: PhysicalSize::new(0.0, 0.0), // TODO: Pass viewport from LayoutContext
    };

    // 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
        let mut fast_font_size = None;
        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
                {
                    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,
                        ));
                    }
                }
            }
        }
        fast_font_size.unwrap_or_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)
        })
    };

    // Use system text color as fallback (respects dark/light mode)
    let system_text_color = system_style
        .and_then(|ss| ss.colors.text.as_option().copied())
        .unwrap_or(ColorU::BLACK); // Ultimate fallback if no system style
    
    let color = color_from_cache.unwrap_or(system_text_color);

    let line_height = {
        // FAST PATH: compact cache for line-height (stored as normalized × 1000 i16)
        let mut fast_lh = None;
        if node_state.is_normal() {
            if let Some(ref cc) = cache.compact_cache {
                if let Some(normalized) = cc.get_line_height(dom_id.index()) {
                    // normalized is the raw i16 / 1000.0 value from decode_resolved_px_i16
                    // But line_height encoding is special: percentage × 10 as i16
                    // decode: i16 / 10.0 → raw percentage value (not /100!)
                    // Wait - get_line_height uses decode_resolved_px_i16 which does val / 10.0
                    // Builder stores: normalized() * 1000.0 as i16
                    // So decoded = i16 / 10.0 = normalized() * 100.0
                    // We need normalized() * font_size, so: decoded / 100.0 * font_size
                    fast_lh = Some(normalized / 100.0 * font_size);
                }
            }
        }
        fast_lh.unwrap_or_else(|| {
            cache
                .get_line_height(node_data, &dom_id, node_state)
                .and_then(|v| v.get_property().cloned())
                .map(|v| v.inner.normalized() * font_size)
                .unwrap_or(font_size * 1.2)
        })
    };

    // 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.
    use azul_css::props::layout::LayoutDisplay;
    let display = cache
        .get_display(node_data, &dom_id, node_state)
        .and_then(|v| v.get_property().cloned())
        .unwrap_or(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
    let text_decoration = 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
    let tab_size = {
        // FAST PATH: compact cache for tab-size (i16 resolved px × 10)
        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);
                }
            }
        }
        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_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_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_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_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};

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 {
    let mut font_stacks = Vec::new();
    let mut hash_to_index: HashMap<u64, usize> = HashMap::new();
    let mut seen_hashes = std::collections::HashSet::new();
    let mut font_refs: HashMap<usize, azul_css::props::basic::font::FontRef> = HashMap::new();

    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes_container = styled_dom.styled_nodes.as_container();
    let cache = &styled_dom.css_property_cache.ptr;

    // Iterate over all nodes
    for (node_idx, node_data) in node_data_container.internal.iter().enumerate() {
        // Only process text nodes (they are the ones that need fonts)
        if !matches!(node_data.node_type, NodeType::Text(_)) {
            continue;
        }

        let dom_id = match NodeId::from_usize(node_idx) {
            Some(id) => id,
            None => continue,
        };

        let node_state = &styled_nodes_container[dom_id].styled_node_state;

        // Get font families from CSS
        let font_families = 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())])
            });

        // Check if the first font family is a FontRef (direct embedded font)
        // If so, we don't need to go through fontconfig - just collect the 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;
                if !font_refs.contains_key(&ptr) {
                    font_refs.insert(ptr, font_ref.clone());
                }
                // Skip the normal font stack processing for FontRef
                continue;
            }
        }

        // Get font weight and style
        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,
        };

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

        // Build font stack (only for non-Ref font families)
        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();
            // Skip FontRef entries in the stack - they're handled separately
            if matches!(family, StyleFontFamily::Ref(_)) {
                continue;
            }
            
            // Handle SystemFontType specially - resolve to actual font names
            // and apply the font weight/style from the system font type
            if let StyleFontFamily::SystemType(system_type) = family {
                // Get platform-specific font names using the provided platform
                let font_names = system_type.get_fallback_chain(platform);
                
                // Override weight/style based on system font type
                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
                };
                
                // Add each font name from the fallback chain
                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
        let generic_fallbacks = ["sans-serif", "serif", "monospace"];
        for fallback in &generic_fallbacks {
            if !font_stack
                .iter()
                .any(|f| f.family.to_lowercase() == fallback.to_lowercase())
            {
                font_stack.push(FontSelector {
                    family: fallback.to_string(),
                    weight: FcWeight::Normal,
                    style: FontStyle::Normal,
                    unicode_ranges: Vec::new(),
                });
            }
        }

        // Skip empty font stacks (can happen if all families were FontRefs)
        if font_stack.is_empty() {
            continue;
        }

        // Compute hash for deduplication
        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()
        };

        // Only add if not seen before
        if !seen_hashes.contains(&hash) {
            seen_hashes.insert(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
pub fn resolve_font_chains(
    collected: &CollectedFontStacks,
    fc_cache: &FcFontCache,
) -> 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
        };

        let mut trace = Vec::new();
        let chain =
            fc_cache.resolve_font_chain(&font_families, weight, italic, oblique, &mut trace);

        chains.insert(cache_key, chain);
    }

    // Create single-font chains for direct FontRefs
    // These bypass fontconfig and cover the entire Unicode range
    // NOTE: FontRefs are handled differently - they don't go through fontconfig at all.
    // The shaping code checks style.font_stack for FontStack::Ref and uses the font directly.
    // We just need to record that we have these font refs for font loading purposes.
    for (ptr, _font_ref) in &collected.font_refs {
        let cache_key = FontChainKeyOrRef::Ref(*ptr);
        
        // For FontRef, we create an empty pattern that will be handled specially
        // during shaping. The font data is already available via the FontRef pointer.
        // We don't insert anything - the shaping code handles FontStack::Ref directly.
        let _ = cache_key; // Mark as used
    }

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

/// Register all embedded FontRefs from the styled DOM in the FontManager
/// 
/// This must be called BEFORE layout so that the fonts are available
/// for WebRender resource registration after layout.
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();

    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> {
    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
    F: Fn(&[u8], 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
        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::FontSource::Disk(path) => Some(path.font_index),
                rust_fontconfig::FontSource::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(&[u8], 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, ScrollbarColorCustom, ScrollbarInfo, StyleScrollbarColor,
    SCROLLBAR_CLASSIC_LIGHT,
};

/// Computed scrollbar style for a node, combining CSS properties
#[derive(Debug, Clone)]
pub struct ComputedScrollbarStyle {
    /// The scrollbar width mode (auto/thin/none)
    pub width_mode: LayoutScrollbarWidth,
    /// Actual width in pixels (resolved from width_mode or scrollbar-style)
    pub 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,
}

impl Default for ComputedScrollbarStyle {
    fn default() -> Self {
        Self {
            width_mode: LayoutScrollbarWidth::Auto,
            width_px: 16.0, // Standard scrollbar width
            // Debug colors - bright magenta thumb, orange track
            thumb_color: ColorU::new(255, 0, 255, 255), // Magenta
            track_color: ColorU::new(255, 165, 0, 255), // Orange
            button_color: ColorU::new(0, 255, 0, 255),  // Green
            corner_color: ColorU::new(0, 0, 255, 255),  // Blue
            clip_to_container_border: false,
        }
    }
}

/// Get the computed scrollbar style for a node
///
/// This combines:
/// - `scrollbar-width` property (auto/thin/none)
/// - `scrollbar-color` property (thumb and track colors)
/// - `-azul-scrollbar-style` property (full scrollbar customization)
pub fn get_scrollbar_style(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> ComputedScrollbarStyle {
    let node_data = &styled_dom.node_data.as_container()[node_id];

    // Start with defaults
    let mut result = ComputedScrollbarStyle::default();

    // Check for -azul-scrollbar-style (full customization)
    if let Some(scrollbar_style) = styled_dom
        .css_property_cache
        .ptr
        .get_scrollbar_style(node_data, &node_id, node_state)
        .and_then(|v| v.get_property())
    {
        // Use the detailed scrollbar info
        result.width_px = match scrollbar_style.horizontal.width {
            azul_css::props::layout::dimensions::LayoutWidth::Px(px) => {
                // Use to_pixels_internal with 100% = 16px and 1em = 16px as reasonable defaults
                px.to_pixels_internal(16.0, 16.0)
            }
            _ => 16.0,
        };
        result.thumb_color = extract_color_from_background(&scrollbar_style.horizontal.thumb);
        result.track_color = extract_color_from_background(&scrollbar_style.horizontal.track);
        result.button_color = extract_color_from_background(&scrollbar_style.horizontal.button);
        result.corner_color = extract_color_from_background(&scrollbar_style.horizontal.corner);
        result.clip_to_container_border = scrollbar_style.horizontal.clip_to_container_border;
    }

    // Check for scrollbar-width (overrides width)
    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;
        result.width_px = match scrollbar_width {
            LayoutScrollbarWidth::Auto => 16.0,
            LayoutScrollbarWidth::Thin => 8.0,
            LayoutScrollbarWidth::None => 0.0,
        };
    }

    // 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 default colors
            }
            StyleScrollbarColor::Custom(custom) => {
                result.thumb_color = custom.thumb;
                result.track_color = custom.track;
            }
        }
    }

    result
}

/// 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);
    style.clip_to_container_border
}

/// Get the scrollbar width in pixels for a node
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);
    style.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};
use azul_css::props::style::text::StyleHyphens;
use azul_css::props::style::effects::StyleCursor;

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<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<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_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_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 column-gap as PixelValue. Returns Option.
pub fn get_column_gap_value(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::layout::spacing::LayoutColumnGap> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_column_gap(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).
pub fn get_opacity(
    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_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> {
    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> {
    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()
}

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

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

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

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

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

/// Get transform property. Returns Option (non-empty transform list, cloned).
pub fn get_transform(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<azul_css::props::style::transform::StyleTransformVec> {
    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 display property (raw). Returns Option<LayoutDisplay>.
pub fn get_display_raw(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> Option<LayoutDisplay> {
    let node_data = &styled_dom.node_data.as_container()[node_id];
    styled_dom.css_property_cache.ptr
        .get_display(node_data, &node_id, node_state)
        .and_then(|v| v.get_property().copied())
}

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