azul-core 0.0.16

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
//! XML and XHTML parsing for declarative UI definitions.
//!
//! This module provides comprehensive XML parsing and manipulation for Azul's XML-based
//! UI format (`.azul` files). It supports:
//!
//! - **XHTML parsing**: Parse HTML-like syntax into DOM structures
//! - **CSS extraction**: Extract `<style>` blocks and inline styles
//! - **Component system**: Define reusable UI components with arguments
//! - **Hot reload**: Track file changes and rebuild UI incrementally
//! - **Error reporting**: Detailed syntax error messages with line/column info
//!
//! # Examples
//!
//! ```rust,no_run,ignore
//! use azul_core::xml::{XmlNode, XmlParseOptions};
//!
//! let xml = "<div>Hello</div>";
//! // let node = XmlNode::parse(xml)?;
//! ```

use alloc::{
    boxed::Box,
    collections::BTreeMap,
    string::{String, ToString},
    vec::Vec,
};
use core::{fmt, fmt::Write, hash::Hash};

use azul_css::{
    codegen::format::VecContents,
    css::{
        Css, CssDeclaration, CssPath, CssPathPseudoSelector, CssPathSelector, CssRuleBlock,
        NodeTypeTag,
    },
    parser2::{CssParseErrorOwned, ErrorLocation},
    props::{
        basic::{ColorU, StyleFontFamilyVec},
        property::CssProperty,
        style::{
            NormalizedLinearColorStopVec, NormalizedRadialColorStopVec, StyleBackgroundContentVec,
            StyleBackgroundPositionVec, StyleBackgroundRepeatVec, StyleBackgroundSizeVec,
            StyleTransformVec,
        },
    },
    AzString, OptionString, StringVec, U8Vec,
};

use crate::{
    dom::{Dom, NodeType, OptionNodeType},
    styled_dom::StyledDom,
    window::{AzStringPair, StringPairVec},
};

/// Error that can occur during XML parsing or hot-reload.
///
/// Stringified for error reporting; not part of the public API.
pub type SyntaxError = String;

/// Tag of an XML node, such as the "button" in `<button>Hello</button>`.
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct XmlTagName {
    pub inner: AzString,
}

impl From<AzString> for XmlTagName {
    fn from(s: AzString) -> Self {
        Self { inner: s }
    }
}

impl From<String> for XmlTagName {
    fn from(s: String) -> Self {
        Self { inner: s.into() }
    }
}

impl From<&str> for XmlTagName {
    fn from(s: &str) -> Self {
        Self { inner: s.into() }
    }
}

impl core::ops::Deref for XmlTagName {
    type Target = AzString;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// (Unparsed) text content of an XML node, such as the "Hello" in `<button>Hello</button>`.
pub type XmlTextContent = OptionString;

/// Attributes of an XML node, such as `["color" => "blue"]` in `<button color="blue" />`.
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct XmlAttributeMap {
    pub inner: StringPairVec,
}

impl From<StringPairVec> for XmlAttributeMap {
    fn from(v: StringPairVec) -> Self {
        Self { inner: v }
    }
}

impl core::ops::Deref for XmlAttributeMap {
    type Target = StringPairVec;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl core::ops::DerefMut for XmlAttributeMap {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// Name of a component argument (e.g. `"text"`, `"href"`).
type ComponentArgumentName = String;
/// Type of a component argument as a string (e.g. `"String"`, `"bool"`).
type ComponentArgumentType = String;
/// Zero-based position of an argument in the component's argument list.
type ComponentArgumentOrder = usize;

/// FFI-safe replacement for `(ComponentArgumentName, ComponentArgumentType)` tuple.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentArgument {
    pub name: AzString,
    pub arg_type: AzString,
}

impl_vec!(
    ComponentArgument,
    ComponentArgumentVec,
    ComponentArgumentVecDestructor,
    ComponentArgumentVecDestructorType,
    ComponentArgumentVecSlice,
    OptionComponentArgument
);
impl_option!(
    ComponentArgument,
    OptionComponentArgument,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_vec_debug!(ComponentArgument, ComponentArgumentVec);
impl_vec_partialeq!(ComponentArgument, ComponentArgumentVec);
impl_vec_eq!(ComponentArgument, ComponentArgumentVec);
impl_vec_partialord!(ComponentArgument, ComponentArgumentVec);
impl_vec_ord!(ComponentArgument, ComponentArgumentVec);
impl_vec_hash!(ComponentArgument, ComponentArgumentVec);
impl_vec_clone!(
    ComponentArgument,
    ComponentArgumentVec,
    ComponentArgumentVecDestructor
);
impl_vec_mut!(ComponentArgument, ComponentArgumentVec);

/// Holds the list of arguments and whether the component accepts text content.
/// Used by the compile pipeline to generate Rust function signatures.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ComponentArguments {
    pub args: ComponentArgumentVec,
    pub accepts_text: bool,
}

/// Name of an XML/HTML component (e.g. `"button"`, `"my-widget"`).
type ComponentName = String;
/// Compiled source code string for a component.
type CompiledComponent = String;

/// Universal HTML attribute names that are handled by the framework
/// and should not be passed through to component-specific argument lists.
const DEFAULT_ARGS: [&str; 8] = [
    "id",
    "class",
    "tabindex",
    "focusable",
    "accepts_text",
    "name",
    "style",
    "args",
];

/// Opaque void type for FFI pointers. Uses a custom definition instead of
/// `core::ffi::c_void` for `#[repr(C)]` compatibility in the generated API.
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)]
pub enum c_void {}

/// Type of an XML node in the parsed tree.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub enum XmlNodeType {
    Root,
    Element,
    PI,
    Comment,
    Text,
}

/// A namespace-qualified XML name (e.g. `svg:rect` has namespace `"svg"` and local name `"rect"`).
#[repr(C)]
#[derive(Debug)]
pub struct XmlQualifiedName {
    pub local_name: AzString,
    pub namespace: OptionString,
}

/// Classification of an external resource referenced in HTML/XML
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ExternalResourceKind {
    /// Image resource (img src, background-image, etc.)
    Image,
    /// Font resource (@font-face src, link rel="preload" as="font")
    Font,
    /// Stylesheet (link rel="stylesheet", @import)
    Stylesheet,
    /// Script (script src)
    Script,
    /// Favicon or icon
    Icon,
    /// Video source
    Video,
    /// Audio source
    Audio,
    /// Generic link or unknown resource type
    Unknown,
}

/// MIME type hint for an external resource
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct MimeTypeHint {
    pub inner: AzString,
}

impl MimeTypeHint {
    #[must_use]
    pub fn new(s: &str) -> Self {
        Self {
            inner: AzString::from(s),
        }
    }

    #[must_use]
    pub fn from_extension(ext: &str) -> Self {
        let mime = match ext.to_lowercase().as_str() {
            // Images
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "webp" => "image/webp",
            "svg" => "image/svg+xml",
            "ico" => "image/x-icon",
            "bmp" => "image/bmp",
            "avif" => "image/avif",
            // Fonts
            "ttf" => "font/ttf",
            "otf" => "font/otf",
            "woff" => "font/woff",
            "woff2" => "font/woff2",
            "eot" => "application/vnd.ms-fontobject",
            // Stylesheets
            "css" => "text/css",
            // Scripts
            "js" | "mjs" => "application/javascript",
            // Video
            "mp4" => "video/mp4",
            "webm" => "video/webm",
            "ogg" => "video/ogg",
            // Audio
            "mp3" => "audio/mpeg",
            "wav" => "audio/wav",
            "flac" => "audio/flac",
            // Default
            _ => "application/octet-stream",
        };
        Self {
            inner: AzString::from(mime),
        }
    }
}

impl_option!(
    MimeTypeHint,
    OptionMimeTypeHint,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

/// An external resource URL found in an XML/HTML document
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ExternalResource {
    /// The URL as found in the document (may be relative or absolute)
    pub url: AzString,
    /// Classification of the resource type
    pub kind: ExternalResourceKind,
    /// MIME type hint (from type attribute, file extension, or heuristics)
    pub mime_type: OptionMimeTypeHint,
    /// The HTML element that referenced this resource (e.g., "img", "link", "script")
    pub source_element: AzString,
    /// The attribute that contained the URL (e.g., "src", "href")
    pub source_attribute: AzString,
}

impl_option!(
    ExternalResource,
    OptionExternalResource,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl_vec!(
    ExternalResource,
    ExternalResourceVec,
    ExternalResourceVecDestructor,
    ExternalResourceVecDestructorType,
    ExternalResourceVecSlice,
    OptionExternalResource
);
impl_vec_mut!(ExternalResource, ExternalResourceVec);
impl_vec_debug!(ExternalResource, ExternalResourceVec);
impl_vec_partialeq!(ExternalResource, ExternalResourceVec);
impl_vec_eq!(ExternalResource, ExternalResourceVec);
impl_vec_partialord!(ExternalResource, ExternalResourceVec);
impl_vec_ord!(ExternalResource, ExternalResourceVec);
impl_vec_hash!(ExternalResource, ExternalResourceVec);
impl_vec_clone!(
    ExternalResource,
    ExternalResourceVec,
    ExternalResourceVecDestructor
);

/// AUDIT 2026-07-08: maximum XML/HTML nesting depth handled by the recursive
/// DOM-build (`xml_node_to_dom_fast`, `xml_node_to_fast_dom`), resource-scan
/// (iterative worklist in `scan_external_resources`) and `<body>`-lookup
/// (`find_body_recursive`) passes. These bound descent per nesting level, so a pathologically deep
/// document (e.g. tens of thousands of nested `<div>`s) would overflow the native
/// stack. Beyond this depth, deeper children are ignored rather than crashing.
/// 512 is far past any realistic hand-authored markup while staying comfortably
/// inside the default thread stack.
const MAX_XML_NESTING_DEPTH: usize = 512;

/// AUDIT 2026-07-08: maximum recursion depth for [`ComponentFieldType::parse`],
/// which recurses through `Option<..>` / `Vec<..>` wrappers. Caps attacker
/// strings such as `"Option<".repeat(100_000)` that would otherwise overflow the
/// stack. 64 nested type wrappers is far beyond any real field type.
const MAX_TYPE_PARSE_DEPTH: usize = 64;

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct Xml {
    pub root: XmlNodeChildVec,
}

impl Xml {
    /// Scan the XML/HTML document for external resource URLs.
    ///
    /// This function traverses the entire document tree and extracts URLs from:
    /// - `<img src="...">` - Images
    /// - `<link href="...">` - Stylesheets, icons, fonts
    /// - `<script src="...">` - Scripts
    /// - `<video src="...">`, `<source src="...">` - Video
    /// - `<audio src="...">` - Audio
    /// - `<a href="...">` - Links (classified as Unknown)
    /// - CSS `url()` in style attributes
    /// - `<style>` blocks with @import or `url()`
    #[must_use]
    pub fn scan_external_resources(&self) -> ExternalResourceVec {
        let mut resources = Vec::new();

        // AUDIT 2026-07-08: iterative DFS with an explicit worklist. The old
        // per-node recursion overflowed the stack on pathologically deep markup
        // (a single-purpose scan frame is large: string lowercasing + closure +
        // wide match). An explicit stack keeps memory on the heap; `depth` still
        // bounds how deep we descend so unbounded input can't grow the worklist
        // without limit.
        let mut stack: Vec<(&XmlNodeChild, usize)> = Vec::new();
        for child in self.root.as_ref() {
            stack.push((child, 0));
        }
        while let Some((child, depth)) = stack.pop() {
            match child {
                XmlNodeChild::Text(text) => {
                    // CSS @import / url() in text content (inside <style> tags).
                    Self::extract_css_urls(text.as_str(), &mut resources);
                }
                XmlNodeChild::Element(node) => {
                    if depth > MAX_XML_NESTING_DEPTH {
                        // Deeper subtrees are simply not scanned.
                        continue;
                    }
                    Self::scan_node(node, &mut resources);
                    for c in node.children.as_ref() {
                        stack.push((c, depth + 1));
                    }
                }
            }
        }

        resources.into()
    }

    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
    fn scan_node(node: &XmlNode, resources: &mut Vec<ExternalResource>) {
        let tag_name = node.node_type.inner.as_str().to_lowercase();

        // Get attribute lookup helper
        let get_attr = |name: &str| -> Option<String> {
            node.attributes
                .inner
                .as_ref()
                .iter()
                .find(|pair| pair.key.as_str().eq_ignore_ascii_case(name))
                .map(|pair| pair.value.as_str().to_string())
        };

        match tag_name.as_str() {
            "img" => {
                if let Some(src) = get_attr("src") {
                    let mime = Self::guess_mime_from_url(&src, "image");
                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind: ExternalResourceKind::Image,
                        mime_type: mime.into(),
                        source_element: AzString::from("img"),
                        source_attribute: AzString::from("src"),
                    });
                }
                // Also check srcset
                if let Some(srcset) = get_attr("srcset") {
                    for src in Self::parse_srcset(&srcset) {
                        let mime = Self::guess_mime_from_url(&src, "image");
                        resources.push(ExternalResource {
                            url: AzString::from(src),
                            kind: ExternalResourceKind::Image,
                            mime_type: mime.into(),
                            source_element: AzString::from("img"),
                            source_attribute: AzString::from("srcset"),
                        });
                    }
                }
            }
            "link" => {
                if let Some(href) = get_attr("href") {
                    let rel = get_attr("rel").unwrap_or_default().to_lowercase();
                    let type_attr = get_attr("type");
                    let as_attr = get_attr("as").unwrap_or_default().to_lowercase();

                    let (kind, category) = if rel.contains("stylesheet") {
                        (ExternalResourceKind::Stylesheet, "stylesheet")
                    } else if rel.contains("icon") || rel.contains("apple-touch-icon") {
                        (ExternalResourceKind::Icon, "image")
                    } else if as_attr == "font" {
                        (ExternalResourceKind::Font, "font")
                    } else if as_attr == "script" {
                        (ExternalResourceKind::Script, "script")
                    } else if as_attr == "image" {
                        (ExternalResourceKind::Image, "image")
                    } else {
                        (ExternalResourceKind::Unknown, "")
                    };

                    let mime = type_attr
                        .map(|t| MimeTypeHint::new(&t))
                        .or_else(|| Self::guess_mime_from_url(&href, category));

                    resources.push(ExternalResource {
                        url: AzString::from(href),
                        kind,
                        mime_type: mime.into(),
                        source_element: AzString::from("link"),
                        source_attribute: AzString::from("href"),
                    });
                }
            }
            "script" => {
                if let Some(src) = get_attr("src") {
                    let type_attr = get_attr("type");
                    let mime = type_attr
                        .map(|t| MimeTypeHint::new(&t))
                        .or_else(|| Some(MimeTypeHint::new("application/javascript")));

                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind: ExternalResourceKind::Script,
                        mime_type: mime.into(),
                        source_element: AzString::from("script"),
                        source_attribute: AzString::from("src"),
                    });
                }
            }
            "video" => {
                if let Some(src) = get_attr("src") {
                    let mime = Self::guess_mime_from_url(&src, "video");
                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind: ExternalResourceKind::Video,
                        mime_type: mime.into(),
                        source_element: AzString::from("video"),
                        source_attribute: AzString::from("src"),
                    });
                }
                if let Some(poster) = get_attr("poster") {
                    let mime = Self::guess_mime_from_url(&poster, "image");
                    resources.push(ExternalResource {
                        url: AzString::from(poster),
                        kind: ExternalResourceKind::Image,
                        mime_type: mime.into(),
                        source_element: AzString::from("video"),
                        source_attribute: AzString::from("poster"),
                    });
                }
            }
            "audio" => {
                if let Some(src) = get_attr("src") {
                    let mime = Self::guess_mime_from_url(&src, "audio");
                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind: ExternalResourceKind::Audio,
                        mime_type: mime.into(),
                        source_element: AzString::from("audio"),
                        source_attribute: AzString::from("src"),
                    });
                }
            }
            "source" => {
                if let Some(src) = get_attr("src") {
                    let type_attr = get_attr("type");
                    // Determine kind based on type or parent (heuristic: assume video)
                    let kind = if type_attr.as_ref().is_some_and(|t| t.starts_with("audio")) {
                        ExternalResourceKind::Audio
                    } else {
                        ExternalResourceKind::Video
                    };
                    let mime = type_attr.map(|t| MimeTypeHint::new(&t)).or_else(|| {
                        Self::guess_mime_from_url(
                            &src,
                            if kind == ExternalResourceKind::Audio {
                                "audio"
                            } else {
                                "video"
                            },
                        )
                    });

                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind,
                        mime_type: mime.into(),
                        source_element: AzString::from("source"),
                        source_attribute: AzString::from("src"),
                    });
                }
                // Also handle srcset for picture elements
                if let Some(srcset) = get_attr("srcset") {
                    for src in Self::parse_srcset(&srcset) {
                        let mime = Self::guess_mime_from_url(&src, "image");
                        resources.push(ExternalResource {
                            url: AzString::from(src),
                            kind: ExternalResourceKind::Image,
                            mime_type: mime.into(),
                            source_element: AzString::from("source"),
                            source_attribute: AzString::from("srcset"),
                        });
                    }
                }
            }
            "a" => {
                if let Some(href) = get_attr("href") {
                    // Only include if it looks like a resource, not a page link
                    if Self::looks_like_resource(&href) {
                        let mime = Self::guess_mime_from_url(&href, "");
                        resources.push(ExternalResource {
                            url: AzString::from(href),
                            kind: ExternalResourceKind::Unknown,
                            mime_type: mime.into(),
                            source_element: AzString::from("a"),
                            source_attribute: AzString::from("href"),
                        });
                    }
                }
            }
            "virtualized-view" | "embed" | "object" => {
                let src_attr = if tag_name == "object" { "data" } else { "src" };
                if let Some(src) = get_attr(src_attr) {
                    resources.push(ExternalResource {
                        url: AzString::from(src),
                        kind: ExternalResourceKind::Unknown,
                        mime_type: OptionMimeTypeHint::None,
                        source_element: AzString::from(tag_name.clone()),
                        source_attribute: AzString::from(src_attr),
                    });
                }
            }
            "style" => {
                // Scan text content for CSS URLs
                for child in node.children.as_ref() {
                    if let XmlNodeChild::Text(text) = child {
                        Self::extract_css_urls(text.as_str(), resources);
                    }
                }
            }
            _ => {}
        }

        // Check inline style attribute for url()
        if let Some(style) = get_attr("style") {
            Self::extract_css_urls(&style, resources);
        }

        // Check for background attribute (deprecated but still used)
        if let Some(bg) = get_attr("background") {
            let mime = Self::guess_mime_from_url(&bg, "image");
            resources.push(ExternalResource {
                url: AzString::from(bg),
                kind: ExternalResourceKind::Image,
                mime_type: mime.into(),
                source_element: AzString::from(tag_name),
                source_attribute: AzString::from("background"),
            });
        }

        // Children are walked by the iterative driver in `scan_external_resources`.
    }

    /// Extract URLs from CSS content (handles `url()` and @import)
    fn extract_css_urls(css: &str, resources: &mut Vec<ExternalResource>) {
        // AUDIT 2026-07-08: fold to lowercase ONCE using ASCII-only folding.
        // `to_ascii_lowercase` never changes a string's byte length (only A-Z are
        // touched, multi-byte code points are left verbatim), so every byte offset
        // into `lower` maps 1:1 onto `css`. The old code called `to_lowercase()`
        // every iteration (O(n^2)) and then sliced the ORIGINAL `css` with an
        // offset computed in the lowercased temporary -- for characters whose
        // lowercase changes byte length (e.g. 'İ' U+0130, 2 bytes -> 3 bytes) that
        // offset landed off a char boundary and panicked. Searching in `lower` and
        // slicing `css` at the same offset also makes the `url(` / `@import` scans
        // case-insensitive for free.
        let lower = css.to_ascii_lowercase();

        // url(...) scan (case-insensitive)
        let mut search_from = 0;
        while let Some(rel) = lower[search_from..].find("url(") {
            let url_start = search_from + rel;
            let after = url_start + 4;
            // Skip a `url(` that is the argument of an `@import` — the @import scan
            // below emits it, correctly tagged as a Stylesheet. Without this guard the
            // same URL is pushed twice (once here, mistagged "url()").
            if lower[..url_start].trim_end().ends_with("@import") {
                search_from = after;
                continue;
            }
            let after_url = &css[after..];
            if let Some(url) = Self::extract_url_value(after_url) {
                let mime = Self::guess_mime_from_url(&url, "");
                let kind = Self::guess_kind_from_url(&url);
                resources.push(ExternalResource {
                    url: AzString::from(url),
                    kind,
                    mime_type: mime.into(),
                    source_element: AzString::from("style"),
                    source_attribute: AzString::from("url()"),
                });
            }
            search_from = after;
        }

        // Handle @import "url" or @import url(...) (case-insensitive)
        let mut search_from = 0;
        while let Some(rel) = lower[search_from..].find("@import") {
            let after = search_from + rel + 7;
            let after_import = &css[after..];
            let trimmed = after_import.trim_start();

            // Match `url(` case-insensitively without allocating. `get(..4)`
            // returns `None` if byte 4 is not a char boundary, so the slice below
            // can never panic on multi-byte input.
            let import_url = if trimmed
                .get(..4)
                .is_some_and(|p| p.eq_ignore_ascii_case("url("))
            {
                Self::extract_url_value(&trimmed[4..])
            } else {
                Self::extract_quoted_string(trimmed)
            };

            if let Some(url) = import_url {
                resources.push(ExternalResource {
                    url: AzString::from(url),
                    kind: ExternalResourceKind::Stylesheet,
                    mime_type: Some(MimeTypeHint::new("text/css")).into(),
                    source_element: AzString::from("style"),
                    source_attribute: AzString::from("@import"),
                });
            }

            search_from = after;
        }
    }

    /// Extract value from url(...) - handles quoted and unquoted URLs
    fn extract_url_value(s: &str) -> Option<String> {
        let trimmed = s.trim_start();
        if trimmed.starts_with('"') {
            Self::extract_quoted_string(trimmed)
        } else if let Some(rest) = trimmed.strip_prefix('\'') {
            let end = rest.find('\'')?;
            Some(rest[..end].to_string())
        } else {
            let end = trimmed.find(')')?;
            Some(trimmed[..end].trim().to_string())
        }
    }

    /// Extract a quoted string value
    fn extract_quoted_string(s: &str) -> Option<String> {
        if let Some(rest) = s.strip_prefix('"') {
            let end = rest.find('"')?;
            Some(rest[..end].to_string())
        } else if let Some(rest) = s.strip_prefix('\'') {
            let end = rest.find('\'')?;
            Some(rest[..end].to_string())
        } else {
            None
        }
    }

    /// Parse srcset attribute into individual URLs
    fn parse_srcset(srcset: &str) -> Vec<String> {
        srcset
            .split(',')
            .filter_map(|entry| {
                let trimmed = entry.trim();
                // srcset format: "url 1x" or "url 100w"
                trimmed
                    .split_whitespace()
                    .next()
                    .map(alloc::string::ToString::to_string)
            })
            .filter(|url| !url.is_empty())
            .collect()
    }

    /// Check if a URL looks like a downloadable resource (not a page)
    fn looks_like_resource(url: &str) -> bool {
        let lower = url.to_lowercase();
        // Check for common resource extensions
        let resource_exts = [
            ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".bmp", ".ttf", ".otf",
            ".woff", ".woff2", ".eot", ".css", ".js", ".mp4", ".webm", ".ogg", ".mp3", ".wav",
            ".pdf", ".zip", ".tar", ".gz",
        ];
        resource_exts.iter().any(|ext| lower.ends_with(ext))
    }

    /// Guess the resource kind from URL based on file extension.
    // `url` is lowercased into `path` below, so these literal `.ext` checks are
    // already case-insensitive — the lint can't see the runtime lowercasing.
    #[allow(clippy::case_sensitive_file_extension_comparisons)]
    fn guess_kind_from_url(url: &str) -> ExternalResourceKind {
        let lower = url.to_lowercase();
        // Strip query string before checking extension
        let path = lower.split('?').next().unwrap_or(&lower);
        if path.ends_with(".png")
            || path.ends_with(".jpg")
            || path.ends_with(".jpeg")
            || path.ends_with(".gif")
            || path.ends_with(".webp")
            || path.ends_with(".svg")
            || path.ends_with(".bmp")
            || path.ends_with(".avif")
        {
            ExternalResourceKind::Image
        } else if path.ends_with(".ttf")
            || path.ends_with(".otf")
            || path.ends_with(".woff")
            || path.ends_with(".woff2")
            || path.ends_with(".eot")
        {
            ExternalResourceKind::Font
        } else if path.ends_with(".css") {
            ExternalResourceKind::Stylesheet
        } else if path.ends_with(".js") || path.ends_with(".mjs") {
            ExternalResourceKind::Script
        } else if path.ends_with(".mp4") || path.ends_with(".webm") || path.ends_with(".ogg") {
            ExternalResourceKind::Video
        } else if path.ends_with(".mp3") || path.ends_with(".wav") || path.ends_with(".flac") {
            ExternalResourceKind::Audio
        } else if path.ends_with(".ico") {
            ExternalResourceKind::Icon
        } else {
            ExternalResourceKind::Unknown
        }
    }

    /// Guess MIME type from URL based on extension
    fn guess_mime_from_url(url: &str, category: &str) -> Option<MimeTypeHint> {
        let lower = url.to_lowercase();
        // Find extension
        let ext = lower.rsplit('.').next()?;
        // Remove query string if present
        let ext = ext.split('?').next()?;

        // Check if it's a valid extension
        let valid_exts = [
            "png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", "avif", "ttf", "otf", "woff",
            "woff2", "eot", "css", "js", "mjs", "mp4", "webm", "ogg", "mp3", "wav", "flac",
        ];

        if valid_exts.contains(&ext) {
            Some(MimeTypeHint::from_extension(ext))
        } else if !category.is_empty() {
            // Use category hint for default
            match category {
                "image" => Some(MimeTypeHint::new("image/*")),
                "font" => Some(MimeTypeHint::new("font/*")),
                "stylesheet" => Some(MimeTypeHint::new("text/css")),
                "script" => Some(MimeTypeHint::new("application/javascript")),
                "video" => Some(MimeTypeHint::new("video/*")),
                "audio" => Some(MimeTypeHint::new("audio/*")),
                _ => None,
            }
        } else {
            None
        }
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
#[repr(C)]
pub struct NonXmlCharError {
    pub ch: u32, /* u32 = char, but ABI stable */
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
#[repr(C)]
pub struct InvalidCharError {
    pub expected: u8,
    pub got: u8,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct InvalidCharMultipleError {
    pub expected: u8,
    pub got: U8Vec,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
#[repr(C)]
pub struct InvalidQuoteError {
    pub got: u8,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
#[repr(C)]
pub struct InvalidSpaceError {
    pub got: u8,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct InvalidStringError {
    pub got: AzString,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C, u8)]
pub enum XmlStreamError {
    UnexpectedEndOfStream,
    InvalidName,
    NonXmlChar(NonXmlCharError),
    InvalidChar(InvalidCharError),
    InvalidCharMultiple(InvalidCharMultipleError),
    InvalidQuote(InvalidQuoteError),
    InvalidSpace(InvalidSpaceError),
    InvalidString(InvalidStringError),
    InvalidReference,
    InvalidExternalID,
    InvalidCommentData,
    InvalidCommentEnd,
    InvalidCharacterData,
}

impl fmt::Display for XmlStreamError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::XmlStreamError::{
            InvalidChar, InvalidCharMultiple, InvalidCharacterData, InvalidCommentData,
            InvalidCommentEnd, InvalidExternalID, InvalidName, InvalidQuote, InvalidReference,
            InvalidSpace, InvalidString, NonXmlChar, UnexpectedEndOfStream,
        };
        match self {
            UnexpectedEndOfStream => write!(f, "Unexpected end of stream"),
            InvalidName => write!(f, "Invalid name"),
            NonXmlChar(nx) => write!(
                f,
                "Non-XML character: {:?} at {}",
                core::char::from_u32(nx.ch),
                nx.pos
            ),
            InvalidChar(ic) => write!(
                f,
                "Invalid character: expected: {}, got: {} at {}",
                ic.expected as char, ic.got as char, ic.pos
            ),
            InvalidCharMultiple(imc) => write!(
                f,
                "Multiple invalid characters: expected: {}, got: {:?} at {}",
                imc.expected,
                imc.got.as_ref(),
                imc.pos
            ),
            InvalidQuote(iq) => write!(f, "Invalid quote: got {} at {}", iq.got as char, iq.pos),
            InvalidSpace(is) => write!(f, "Invalid space: got {} at {}", is.got as char, is.pos),
            InvalidString(ise) => write!(
                f,
                "Invalid string: got \"{}\" at {}",
                ise.got.as_str(),
                ise.pos
            ),
            InvalidReference => write!(f, "Invalid reference"),
            InvalidExternalID => write!(f, "Invalid external ID"),
            InvalidCommentData => write!(f, "Invalid comment data"),
            InvalidCommentEnd => write!(f, "Invalid comment end"),
            InvalidCharacterData => write!(f, "Invalid character data"),
        }
    }
}

#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Ord, Hash, Eq)]
#[repr(C)]
pub struct XmlTextPos {
    pub row: u32,
    pub col: u32,
}

impl fmt::Display for XmlTextPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {}:{}", self.row, self.col)
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct XmlTextError {
    pub stream_error: XmlStreamError,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C, u8)]
pub enum XmlParseError {
    InvalidDeclaration(XmlTextError),
    InvalidComment(XmlTextError),
    InvalidPI(XmlTextError),
    InvalidDoctype(XmlTextError),
    InvalidEntity(XmlTextError),
    InvalidElement(XmlTextError),
    InvalidAttribute(XmlTextError),
    InvalidCdata(XmlTextError),
    InvalidCharData(XmlTextError),
    UnknownToken(XmlTextPos),
}

impl fmt::Display for XmlParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::XmlParseError::{
            InvalidAttribute, InvalidCdata, InvalidCharData, InvalidComment, InvalidDeclaration,
            InvalidDoctype, InvalidElement, InvalidEntity, InvalidPI, UnknownToken,
        };
        match self {
            InvalidDeclaration(e) => {
                write!(f, "Invalid declaration: {} at {}", e.stream_error, e.pos)
            }
            InvalidComment(e) => write!(f, "Invalid comment: {} at {}", e.stream_error, e.pos),
            InvalidPI(e) => write!(
                f,
                "Invalid processing instruction: {} at {}",
                e.stream_error, e.pos
            ),
            InvalidDoctype(e) => write!(f, "Invalid doctype: {} at {}", e.stream_error, e.pos),
            InvalidEntity(e) => write!(f, "Invalid entity: {} at {}", e.stream_error, e.pos),
            InvalidElement(e) => write!(f, "Invalid element: {} at {}", e.stream_error, e.pos),
            InvalidAttribute(e) => write!(f, "Invalid attribute: {} at {}", e.stream_error, e.pos),
            InvalidCdata(e) => write!(f, "Invalid CDATA: {} at {}", e.stream_error, e.pos),
            InvalidCharData(e) => write!(f, "Invalid char data: {} at {}", e.stream_error, e.pos),
            UnknownToken(e) => write!(f, "Unknown token at {e}"),
        }
    }
}

impl_result!(
    Xml,
    XmlError,
    ResultXmlXmlError,
    copy = false,
    [Debug, PartialEq, Eq, PartialOrd, Clone]
);

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct DuplicatedNamespaceError {
    pub ns: AzString,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnknownNamespaceError {
    pub ns: AzString,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnexpectedCloseTagError {
    pub expected: AzString,
    pub actual: AzString,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct UnknownEntityReferenceError {
    pub entity: AzString,
    pub pos: XmlTextPos,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct DuplicatedAttributeError {
    pub attribute: AzString,
    pub pos: XmlTextPos,
}

/// Error for mismatched open/close tags in XML hierarchy
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C)]
pub struct MalformedHierarchyError {
    /// The tag that was expected (from the opening tag)
    pub expected: AzString,
    /// The tag that was actually found (the closing tag)
    pub got: AzString,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
#[repr(C, u8)]
pub enum XmlError {
    NoParserAvailable,
    InvalidXmlPrefixUri(XmlTextPos),
    UnexpectedXmlUri(XmlTextPos),
    UnexpectedXmlnsUri(XmlTextPos),
    InvalidElementNamePrefix(XmlTextPos),
    DuplicatedNamespace(DuplicatedNamespaceError),
    UnknownNamespace(UnknownNamespaceError),
    UnexpectedCloseTag(UnexpectedCloseTagError),
    UnexpectedEntityCloseTag(XmlTextPos),
    UnknownEntityReference(UnknownEntityReferenceError),
    MalformedEntityReference(XmlTextPos),
    EntityReferenceLoop(XmlTextPos),
    InvalidAttributeValue(XmlTextPos),
    DuplicatedAttribute(DuplicatedAttributeError),
    NoRootNode,
    SizeLimit,
    DtdDetected,
    /// Invalid hierarchy close tags, i.e `<app></p></app>`
    MalformedHierarchy(MalformedHierarchyError),
    ParserError(XmlParseError),
    UnclosedRootNode,
    UnexpectedDeclaration(XmlTextPos),
    NodesLimitReached,
    AttributesLimitReached,
    NamespacesLimitReached,
    InvalidName(XmlTextPos),
    NonXmlChar(XmlTextPos),
    InvalidChar(XmlTextPos),
    InvalidChar2(XmlTextPos),
    InvalidString(XmlTextPos),
    InvalidExternalID(XmlTextPos),
    InvalidComment(XmlTextPos),
    InvalidCharacterData(XmlTextPos),
    UnknownToken(XmlTextPos),
    UnexpectedEndOfStream,
}

impl fmt::Display for XmlError {
    #[allow(clippy::too_many_lines)] // large but cohesive: one arm per variant
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::XmlError::{
            AttributesLimitReached, DtdDetected, DuplicatedAttribute, DuplicatedNamespace,
            EntityReferenceLoop, InvalidAttributeValue, InvalidChar, InvalidChar2,
            InvalidCharacterData, InvalidComment, InvalidElementNamePrefix, InvalidExternalID,
            InvalidName, InvalidString, InvalidXmlPrefixUri, MalformedEntityReference,
            MalformedHierarchy, NamespacesLimitReached, NoParserAvailable, NoRootNode,
            NodesLimitReached, NonXmlChar, ParserError, SizeLimit, UnclosedRootNode,
            UnexpectedCloseTag, UnexpectedDeclaration, UnexpectedEndOfStream,
            UnexpectedEntityCloseTag, UnexpectedXmlUri, UnexpectedXmlnsUri, UnknownEntityReference,
            UnknownNamespace, UnknownToken,
        };
        match self {
            NoParserAvailable => write!(
                f,
                "Library was compiled without XML parser (XML parser not available)"
            ),
            InvalidXmlPrefixUri(pos) => {
                write!(f, "Invalid XML Prefix URI at line {}:{}", pos.row, pos.col)
            }
            UnexpectedXmlUri(pos) => {
                write!(f, "Unexpected XML URI at line {}:{}", pos.row, pos.col)
            }
            UnexpectedXmlnsUri(pos) => write!(
                f,
                "Unexpected XML namespace URI at line {}:{}",
                pos.row, pos.col
            ),
            InvalidElementNamePrefix(pos) => write!(
                f,
                "Invalid element name prefix at line {}:{}",
                pos.row, pos.col
            ),
            DuplicatedNamespace(ns) => write!(
                f,
                "Duplicated namespace: \"{}\" at {}",
                ns.ns.as_str(),
                ns.pos
            ),
            UnknownNamespace(uns) => write!(
                f,
                "Unknown namespace: \"{}\" at {}",
                uns.ns.as_str(),
                uns.pos
            ),
            UnexpectedCloseTag(ct) => write!(
                f,
                "Unexpected close tag: expected \"{}\", got \"{}\" at {}",
                ct.expected.as_str(),
                ct.actual.as_str(),
                ct.pos
            ),
            UnexpectedEntityCloseTag(pos) => write!(
                f,
                "Unexpected entity close tag at line {}:{}",
                pos.row, pos.col
            ),
            UnknownEntityReference(uer) => write!(
                f,
                "Unexpected entity reference: \"{}\" at {}",
                uer.entity, uer.pos
            ),
            MalformedEntityReference(pos) => write!(
                f,
                "Malformed entity reference at line {}:{}",
                pos.row, pos.col
            ),
            EntityReferenceLoop(pos) => write!(
                f,
                "Entity reference loop (recursive entity reference) at line {}:{}",
                pos.row, pos.col
            ),
            InvalidAttributeValue(pos) => {
                write!(f, "Invalid attribute value at line {}:{}", pos.row, pos.col)
            }
            DuplicatedAttribute(ae) => write!(
                f,
                "Duplicated attribute \"{}\" at line {}:{}",
                ae.attribute.as_str(),
                ae.pos.row,
                ae.pos.col
            ),
            NoRootNode => write!(f, "No root node found"),
            SizeLimit => write!(f, "XML file too large (size limit reached)"),
            DtdDetected => write!(f, "Document type descriptor detected"),
            MalformedHierarchy(e) => write!(
                f,
                "Malformed hierarchy: expected <{}/> closing tag, got <{}/>",
                e.expected.as_str(),
                e.got.as_str()
            ),
            ParserError(p) => write!(f, "{p}"),
            UnclosedRootNode => write!(f, "unclosed root node"),
            UnexpectedDeclaration(tp) => write!(f, "unexpected declaration at {tp}"),
            NodesLimitReached => write!(f, "nodes limit reached"),
            AttributesLimitReached => write!(f, "attributes limit reached"),
            NamespacesLimitReached => write!(f, "namespaces limit reached"),
            InvalidName(tp) => write!(f, "invalid name at {tp}"),
            NonXmlChar(tp) => write!(f, "non xml char at {tp}"),
            InvalidChar(tp) => write!(f, "invalid char at {tp}"),
            InvalidChar2(tp) => write!(f, "invalid char2 at {tp}"),
            InvalidString(tp) => write!(f, "invalid string at {tp}"),
            InvalidExternalID(tp) => write!(f, "invalid externalid at {tp}"),
            InvalidComment(tp) => write!(f, "invalid comment at {tp}"),
            InvalidCharacterData(tp) => write!(f, "invalid character data at {tp}"),
            UnknownToken(tp) => write!(f, "unknown token at {tp}"),
            UnexpectedEndOfStream => write!(f, "unexpected end of stream"),
        }
    }
}

// ============================================================================
// New repr(C) component system
// ============================================================================

/// Identifies a component within a library collection.
/// e.g. collection="builtin", name="div" for the `<div>` element,
/// or collection="shadcn", name="avatar" for a custom component.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentId {
    /// Library / collection name: "builtin", "shadcn", "myproject"
    pub collection: AzString,
    /// Component name within the collection: "div", "avatar", "card"
    pub name: AzString,
}

impl ComponentId {
    #[must_use]
    pub fn builtin(name: &str) -> Self {
        Self {
            collection: AzString::from_const_str("builtin"),
            name: AzString::from(name),
        }
    }

    #[must_use]
    pub fn new(collection: &str, name: &str) -> Self {
        Self {
            collection: AzString::from(collection),
            name: AzString::from(name),
        }
    }

    /// Returns "collection:name" format string
    #[must_use]
    pub fn qualified_name(&self) -> String {
        format!("{}:{}", self.collection.as_str(), self.name.as_str())
    }
}

// ============================================================================
// Component type system — rich type descriptors for component fields
// ============================================================================

/// A single argument in a callback signature.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentCallbackArg {
    /// Argument name, e.g. "`button_id`"
    pub name: AzString,
    /// Argument type
    pub arg_type: ComponentFieldType,
}

impl_vec!(
    ComponentCallbackArg,
    ComponentCallbackArgVec,
    ComponentCallbackArgVecDestructor,
    ComponentCallbackArgVecDestructorType,
    ComponentCallbackArgVecSlice,
    OptionComponentCallbackArg
);
impl_option!(
    ComponentCallbackArg,
    OptionComponentCallbackArg,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_vec_debug!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_partialeq!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_eq!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_partialord!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_ord!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_hash!(ComponentCallbackArg, ComponentCallbackArgVec);
impl_vec_clone!(
    ComponentCallbackArg,
    ComponentCallbackArgVec,
    ComponentCallbackArgVecDestructor
);

/// Callback signature: return type + argument list.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ComponentCallbackSignature {
    /// Return type name, e.g. "Update"
    pub return_type: AzString,
    /// Callback arguments (excluding the implicit `&mut RefAny` and `&mut CallbackInfo`)
    pub args: ComponentCallbackArgVec,
}

/// Heap-allocated box for recursive `ComponentFieldType` (e.g. `Option<String>`).
/// Uses raw pointer indirection to break the infinite size.
#[repr(C)]
pub struct ComponentFieldTypeBox {
    pub ptr: *mut ComponentFieldType,
}

impl ComponentFieldTypeBox {
    #[must_use]
    pub fn new(t: ComponentFieldType) -> Self {
        Self {
            ptr: Box::into_raw(Box::new(t)),
        }
    }

    #[must_use]
    pub fn as_ref(&self) -> &ComponentFieldType {
        unsafe { &*self.ptr }
    }
}

impl Clone for ComponentFieldTypeBox {
    fn clone(&self) -> Self {
        Self::new(unsafe { (*self.ptr).clone() })
    }
}

impl Drop for ComponentFieldTypeBox {
    fn drop(&mut self) {
        // Null the pointer as we free it, so a *second* drop is a no-op instead
        // of a double free. This type is a by-value payload of the
        // `ComponentFieldType` enum, whose codegen FFI mirror gets
        // `impl Drop { _delete }` (= drop_in_place of the real type) AND Rust
        // field drop-glue — dropping each by-value field twice. Without this
        // take-and-null the second drop would `Box::from_raw` a dangling pointer.
        let ptr = core::mem::replace(&mut self.ptr, core::ptr::null_mut());
        if !ptr.is_null() {
            unsafe {
                drop(Box::from_raw(ptr));
            }
        }
    }
}

impl fmt::Debug for ComponentFieldTypeBox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ptr.is_null() {
            write!(f, "ComponentFieldTypeBox(null)")
        } else {
            write!(f, "ComponentFieldTypeBox({:?})", unsafe { &*self.ptr })
        }
    }
}

impl PartialEq for ComponentFieldTypeBox {
    fn eq(&self, other: &Self) -> bool {
        if self.ptr.is_null() && other.ptr.is_null() {
            return true;
        }
        if self.ptr.is_null() || other.ptr.is_null() {
            return false;
        }
        unsafe { *self.ptr == *other.ptr }
    }
}

impl Eq for ComponentFieldTypeBox {}

impl PartialOrd for ComponentFieldTypeBox {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ComponentFieldTypeBox {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        match (self.ptr.is_null(), other.ptr.is_null()) {
            (true, true) => core::cmp::Ordering::Equal,
            (true, false) => core::cmp::Ordering::Less,
            (false, true) => core::cmp::Ordering::Greater,
            (false, false) => unsafe { (*self.ptr).cmp(&*other.ptr) },
        }
    }
}

impl Hash for ComponentFieldTypeBox {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        if !self.ptr.is_null() {
            unsafe {
                (*self.ptr).hash(state);
            }
        }
    }
}

/// Heap-allocated box for recursive `ComponentFieldValue` (e.g. `Some(value)`).
/// Uses raw pointer indirection to break the infinite size.
#[repr(C)]
pub struct ComponentFieldValueBox {
    pub ptr: *mut ComponentFieldValue,
}

impl ComponentFieldValueBox {
    #[must_use]
    pub fn new(v: ComponentFieldValue) -> Self {
        Self {
            ptr: Box::into_raw(Box::new(v)),
        }
    }

    #[must_use]
    pub fn as_ref(&self) -> &ComponentFieldValue {
        unsafe { &*self.ptr }
    }
}

impl Clone for ComponentFieldValueBox {
    fn clone(&self) -> Self {
        Self::new(unsafe { (*self.ptr).clone() })
    }
}

impl Drop for ComponentFieldValueBox {
    fn drop(&mut self) {
        // Take-and-null so a second drop (codegen FFI double-drop of a by-value
        // field, see `ComponentFieldTypeBox`) is a no-op, not a double free.
        let ptr = core::mem::replace(&mut self.ptr, core::ptr::null_mut());
        if !ptr.is_null() {
            unsafe {
                drop(Box::from_raw(ptr));
            }
        }
    }
}

impl fmt::Debug for ComponentFieldValueBox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ptr.is_null() {
            write!(f, "ComponentFieldValueBox(null)")
        } else {
            write!(f, "ComponentFieldValueBox({:?})", unsafe { &*self.ptr })
        }
    }
}

impl PartialEq for ComponentFieldValueBox {
    fn eq(&self, other: &Self) -> bool {
        if self.ptr.is_null() && other.ptr.is_null() {
            return true;
        }
        if self.ptr.is_null() || other.ptr.is_null() {
            return false;
        }
        unsafe { *self.ptr == *other.ptr }
    }
}

/// Rich type descriptor for a component field.
/// Replaces the old `AzString` type names ("String", "bool", etc.) with
/// a structured enum that the debugger can use for type-aware editing.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum ComponentFieldType {
    String,
    Bool,
    I32,
    I64,
    U32,
    U64,
    Usize,
    F32,
    F64,
    ColorU,
    CssProperty,
    ImageRef,
    FontRef,
    /// `StyledDom` slot — field name = slot name
    StyledDom,
    /// Callback with typed signature
    Callback(ComponentCallbackSignature),
    /// `RefAny` data binding with type hint
    RefAny(AzString),
    /// Optional value (recursive via Box)
    OptionType(ComponentFieldTypeBox),
    /// Vec of values (recursive via Box)
    VecType(ComponentFieldTypeBox),
    /// Reference to a struct defined in the same library
    StructRef(AzString),
    /// Reference to an enum defined in the same library
    EnumRef(AzString),
}

impl ComponentFieldType {
    /// Parse a field type string like "String", "Option<Bool>", "Vec<I32>",
    /// "Callback(fn(LayoutCallbackInfo) -> Dom)", "StructRef(MyStruct)" etc.
    /// Returns `None` if the string cannot be parsed.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Self::parse_depth(s, 0)
    }

    /// Depth-bounded implementation of [`parse`](Self::parse).
    ///
    /// AUDIT 2026-07-08: `Option<..>` / `Vec<..>` wrappers recurse once per level,
    /// so an attacker string like `"Option<".repeat(100_000)` (with matching `>`)
    /// overflowed the stack. Recursion is capped at [`MAX_TYPE_PARSE_DEPTH`];
    /// beyond it, parsing fails (`None`) instead of crashing.
    fn parse_depth(s: &str, depth: usize) -> Option<Self> {
        if depth > MAX_TYPE_PARSE_DEPTH {
            return None;
        }
        let s = s.trim();
        match s {
            "String" | "string" => return Some(Self::String),
            "Bool" | "bool" => return Some(Self::Bool),
            "I32" | "i32" => return Some(Self::I32),
            "I64" | "i64" => return Some(Self::I64),
            "U32" | "u32" => return Some(Self::U32),
            "U64" | "u64" => return Some(Self::U64),
            "Usize" | "usize" => return Some(Self::Usize),
            "F32" | "f32" => return Some(Self::F32),
            "F64" | "f64" => return Some(Self::F64),
            "ColorU" => return Some(Self::ColorU),
            "CssProperty" => return Some(Self::CssProperty),
            "ImageRef" => return Some(Self::ImageRef),
            "FontRef" => return Some(Self::FontRef),
            "StyledDom" => return Some(Self::StyledDom),
            "RefAny" => return Some(Self::RefAny(AzString::from(""))),
            _ => {}
        }

        // Option<T>
        if let Some(inner) = s.strip_prefix("Option<").and_then(|r| r.strip_suffix('>')) {
            let inner_type = Self::parse_depth(inner, depth + 1)?;
            return Some(Self::OptionType(ComponentFieldTypeBox::new(inner_type)));
        }

        // Vec<T>
        if let Some(inner) = s.strip_prefix("Vec<").and_then(|r| r.strip_suffix('>')) {
            let inner_type = Self::parse_depth(inner, depth + 1)?;
            return Some(Self::VecType(ComponentFieldTypeBox::new(inner_type)));
        }

        // Callback(signature)
        if let Some(sig) = s
            .strip_prefix("Callback(")
            .and_then(|r| r.strip_suffix(')'))
        {
            return Some(Self::Callback(ComponentCallbackSignature {
                return_type: AzString::from(sig),
                args: Vec::new().into(),
            }));
        }

        // RefAny(TypeHint)
        if let Some(hint) = s.strip_prefix("RefAny(").and_then(|r| r.strip_suffix(')')) {
            return Some(Self::RefAny(AzString::from(hint)));
        }

        // EnumRef(Name) — explicit
        if let Some(name) = s.strip_prefix("EnumRef(").and_then(|r| r.strip_suffix(')')) {
            return Some(Self::EnumRef(AzString::from(name)));
        }

        // StructRef(Name) — explicit
        if let Some(name) = s
            .strip_prefix("StructRef(")
            .and_then(|r| r.strip_suffix(')'))
        {
            return Some(Self::StructRef(AzString::from(name)));
        }

        // If starts with uppercase, treat as StructRef
        if s.chars().next().is_some_and(char::is_uppercase) {
            return Some(Self::StructRef(AzString::from(s)));
        }

        None
    }

    /// Format this field type to its canonical string representation.
    /// This is the inverse of `parse`.
    #[must_use]
    pub fn format(&self) -> String {
        match self {
            Self::String => "String".to_string(),
            Self::Bool => "Bool".to_string(),
            Self::I32 => "I32".to_string(),
            Self::I64 => "I64".to_string(),
            Self::U32 => "U32".to_string(),
            Self::U64 => "U64".to_string(),
            Self::Usize => "Usize".to_string(),
            Self::F32 => "F32".to_string(),
            Self::F64 => "F64".to_string(),
            Self::ColorU => "ColorU".to_string(),
            Self::CssProperty => "CssProperty".to_string(),
            Self::ImageRef => "ImageRef".to_string(),
            Self::FontRef => "FontRef".to_string(),
            Self::StyledDom => "StyledDom".to_string(),
            Self::Callback(sig) => format!("Callback({})", sig.return_type.as_str()),
            Self::RefAny(hint) => {
                if hint.as_str().is_empty() {
                    "RefAny".to_string()
                } else {
                    format!("RefAny({})", hint.as_str())
                }
            }
            Self::OptionType(inner) => format!("Option<{}>", inner.as_ref().format()),
            Self::VecType(inner) => format!("Vec<{}>", inner.as_ref().format()),
            Self::StructRef(name) | Self::EnumRef(name) => name.as_str().to_string(),
        }
    }
}

impl fmt::Display for ComponentFieldType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.format())
    }
}

/// A single variant in a component enum model.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentEnumVariant {
    /// Variant name, e.g. "Admin", "Editor", "Viewer"
    pub name: AzString,
    /// Human-readable description for this variant
    pub description: AzString,
    /// Optional associated fields for this variant
    pub fields: ComponentDataFieldVec,
}

impl_vec!(
    ComponentEnumVariant,
    ComponentEnumVariantVec,
    ComponentEnumVariantVecDestructor,
    ComponentEnumVariantVecDestructorType,
    ComponentEnumVariantVecSlice,
    OptionComponentEnumVariant
);
impl_option!(
    ComponentEnumVariant,
    OptionComponentEnumVariant,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentEnumVariant, ComponentEnumVariantVec);
impl_vec_partialeq!(ComponentEnumVariant, ComponentEnumVariantVec);
impl_vec_clone!(
    ComponentEnumVariant,
    ComponentEnumVariantVec,
    ComponentEnumVariantVecDestructor
);

/// A named enum model for code generation.
/// Stored in `ComponentLibrary::enum_models`.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentEnumModel {
    /// Enum name, e.g. "`UserRole`"
    pub name: AzString,
    /// Human-readable description
    pub description: AzString,
    /// Variants
    pub variants: ComponentEnumVariantVec,
}

impl_vec!(
    ComponentEnumModel,
    ComponentEnumModelVec,
    ComponentEnumModelVecDestructor,
    ComponentEnumModelVecDestructorType,
    ComponentEnumModelVecSlice,
    OptionComponentEnumModel
);
impl_option!(
    ComponentEnumModel,
    OptionComponentEnumModel,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentEnumModel, ComponentEnumModelVec);
impl_vec_partialeq!(ComponentEnumModel, ComponentEnumModelVec);
impl_vec_clone!(
    ComponentEnumModel,
    ComponentEnumModelVec,
    ComponentEnumModelVecDestructor
);

/// Default value for a component field.
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum ComponentDefaultValue {
    /// No default value (field is required)
    None,
    /// String literal default
    String(AzString),
    /// Boolean default
    Bool(bool),
    /// i32 default
    I32(i32),
    /// i64 default
    I64(i64),
    /// u32 default
    U32(u32),
    /// u64 default
    U64(u64),
    /// usize default
    Usize(usize),
    /// f32 default
    F32(f32),
    /// f64 default
    F64(f64),
    /// `ColorU` default
    ColorU(ColorU),
    /// Default is an instance of another component
    ComponentInstance(ComponentInstanceDefault),
    /// Default callback function pointer name
    CallbackFnPointer(AzString),
    /// JSON string representing a complex default value
    Json(AzString),
}

impl_option!(
    ComponentDefaultValue,
    OptionComponentDefaultValue,
    copy = false,
    [Debug, Clone, PartialEq]
);

/// Default component instance for a `StyledDom` slot.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentInstanceDefault {
    /// Library name, e.g. "builtin"
    pub library: AzString,
    /// Component tag, e.g. "a"
    pub component: AzString,
    /// Field overrides for this instance
    pub field_overrides: ComponentFieldOverrideVec,
}

/// An override for a single field in a component instance.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct ComponentFieldOverride {
    /// Field name to override
    pub field_name: AzString,
    /// Value source for this override
    pub source: ComponentFieldValueSource,
}

impl_vec!(
    ComponentFieldOverride,
    ComponentFieldOverrideVec,
    ComponentFieldOverrideVecDestructor,
    ComponentFieldOverrideVecDestructorType,
    ComponentFieldOverrideVecSlice,
    OptionComponentFieldOverride
);
impl_option!(
    ComponentFieldOverride,
    OptionComponentFieldOverride,
    copy = false,
    [Debug, Clone, PartialEq, Eq]
);
impl_vec_debug!(ComponentFieldOverride, ComponentFieldOverrideVec);
impl_vec_partialeq!(ComponentFieldOverride, ComponentFieldOverrideVec);
impl_vec_clone!(
    ComponentFieldOverride,
    ComponentFieldOverrideVec,
    ComponentFieldOverrideVecDestructor
);

/// How a field value is sourced at the instance level.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C, u8)]
pub enum ComponentFieldValueSource {
    /// Use the component's default value
    Default,
    /// Hardcoded literal value (as string, parsed at runtime)
    Literal(AzString),
    /// Bound to an app state path (e.g. "`app_state.user.name`")
    Binding(AzString),
}
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size disparity accepted
/// Runtime value for a component field — the "instance" counterpart
/// to `ComponentFieldType` (which is the "class" / type descriptor).
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
#[allow(clippy::large_enum_variant)] // #[repr(C,u8)] FFI enum: boxing a variant changes the C ABI/api.json
pub enum ComponentFieldValue {
    String(AzString),
    Bool(bool),
    I32(i32),
    I64(i64),
    U32(u32),
    U64(u64),
    Usize(usize),
    F32(f32),
    F64(f64),
    ColorU(ColorU),
    /// Option<T> with no value
    None,
    /// Option<T> with a value
    Some(ComponentFieldValueBox),
    /// Vec of values
    Vec(ComponentFieldValueVec),
    /// `StyledDom` slot content
    StyledDom(StyledDom),
    /// Struct fields, in order
    Struct(ComponentFieldNamedValueVec),
    /// Enum variant
    Enum {
        variant: AzString,
        fields: ComponentFieldNamedValueVec,
    },
    /// Callback function reference (function name as string)
    Callback(AzString),
    /// Opaque reference-counted data
    RefAny(crate::refany::RefAny),
}

/// Named field value: (`field_name`, value) pair.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentFieldNamedValue {
    pub name: AzString,
    pub value: ComponentFieldValue,
}

impl_vec!(
    ComponentFieldNamedValue,
    ComponentFieldNamedValueVec,
    ComponentFieldNamedValueVecDestructor,
    ComponentFieldNamedValueVecDestructorType,
    ComponentFieldNamedValueVecSlice,
    OptionComponentFieldNamedValue
);
impl_option!(
    ComponentFieldNamedValue,
    OptionComponentFieldNamedValue,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentFieldNamedValue, ComponentFieldNamedValueVec);
impl_vec_partialeq!(ComponentFieldNamedValue, ComponentFieldNamedValueVec);
impl_vec_clone!(
    ComponentFieldNamedValue,
    ComponentFieldNamedValueVec,
    ComponentFieldNamedValueVecDestructor
);

impl ComponentFieldNamedValueVec {
    /// Look up a field by name, return a reference to its value.
    #[must_use]
    pub fn get_field(&self, name: &str) -> Option<&ComponentFieldValue> {
        self.as_ref().iter().find_map(|v| {
            if v.name.as_str() == name {
                Some(&v.value)
            } else {
                None
            }
        })
    }

    /// Convenience: get a field as `&str` if it is `ComponentFieldValue::String`.
    #[must_use]
    pub fn get_string(&self, name: &str) -> Option<&AzString> {
        match self.get_field(name) {
            Some(ComponentFieldValue::String(s)) => Some(s),
            _ => None,
        }
    }
}

impl_vec!(
    ComponentFieldValue,
    ComponentFieldValueVec,
    ComponentFieldValueVecDestructor,
    ComponentFieldValueVecDestructorType,
    ComponentFieldValueVecSlice,
    OptionComponentFieldValue
);
impl_option!(
    ComponentFieldValue,
    OptionComponentFieldValue,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentFieldValue, ComponentFieldValueVec);
impl_vec_partialeq!(ComponentFieldValue, ComponentFieldValueVec);
impl_vec_clone!(
    ComponentFieldValue,
    ComponentFieldValueVec,
    ComponentFieldValueVecDestructor
);

/// A field in the component's internal data model.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct ComponentDataField {
    /// Field name, e.g. "counter", "text", "number"
    pub name: AzString,
    /// Rich type descriptor for this field
    pub field_type: ComponentFieldType,
    /// Typed default value, or None if the field is required
    pub default_value: OptionComponentDefaultValue,
    /// Whether this field is required (must be provided by the parent)
    pub required: bool,
    /// Human-readable description
    pub description: AzString,
}

impl_vec!(
    ComponentDataField,
    ComponentDataFieldVec,
    ComponentDataFieldVecDestructor,
    ComponentDataFieldVecDestructorType,
    ComponentDataFieldVecSlice,
    OptionComponentDataField
);
impl_option!(
    ComponentDataField,
    OptionComponentDataField,
    copy = false,
    [Debug, Clone, PartialEq]
);
impl_vec_debug!(ComponentDataField, ComponentDataFieldVec);
impl_vec_partialeq!(ComponentDataField, ComponentDataFieldVec);
impl_vec_clone!(
    ComponentDataField,
    ComponentDataFieldVec,
    ComponentDataFieldVecDestructor
);

/// A named data model (struct definition) for code generation.
///
/// Stored in `ComponentLibrary::data_models`. Components reference these
/// by name in `ComponentDataField::field_type`, enabling nested/structured
/// data models. For example, a `UserCard` component might have a field
/// `user: UserProfile` where `UserProfile` is a `ComponentDataModel`.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentDataModel {
    /// Type name, e.g. "`UserProfile`", "`TodoItem`"
    pub name: AzString,
    /// Human-readable description
    pub description: AzString,
    /// Fields in this struct
    pub fields: ComponentDataFieldVec,
}

impl ComponentDataModel {
    /// Look up a field by name.
    #[must_use]
    pub fn get_field(&self, name: &str) -> Option<&ComponentDataField> {
        self.fields
            .as_ref()
            .iter()
            .find(|f| f.name.as_str() == name)
    }

    /// Look up a field's default value as a string, if it exists and is a String variant.
    #[must_use]
    pub fn get_default_string(&self, name: &str) -> Option<&AzString> {
        self.get_field(name).and_then(|f| match &f.default_value {
            OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => Some(s),
            _ => None,
        })
    }

    /// Clone this data model, overriding the default value for a field by name.
    /// If the field is not found, the data model is returned unchanged.
    #[must_use]
    pub fn with_default(mut self, name: &str, value: ComponentDefaultValue) -> Self {
        let mut fields_vec = core::mem::replace(
            &mut self.fields,
            ComponentDataFieldVec::from_const_slice(&[]),
        )
        .into_library_owned_vec();
        for f in &mut fields_vec {
            if f.name.as_str() == name {
                f.default_value = OptionComponentDefaultValue::Some(value);
                break;
            }
        }
        self.fields = ComponentDataFieldVec::from_vec(fields_vec);
        self
    }
}

impl_vec!(
    ComponentDataModel,
    ComponentDataModelVec,
    ComponentDataModelVecDestructor,
    ComponentDataModelVecDestructorType,
    ComponentDataModelVecSlice,
    OptionComponentDataModel
);
impl_option!(
    ComponentDataModel,
    OptionComponentDataModel,
    copy = false,
    [Debug, Clone]
);
impl_vec_debug!(ComponentDataModel, ComponentDataModelVec);
impl_vec_clone!(
    ComponentDataModel,
    ComponentDataModelVec,
    ComponentDataModelVecDestructor
);
impl_vec_mut!(ComponentDataModel, ComponentDataModelVec);

// ============================================================================
// Serde support for ComponentDataModel (feature-gated)
// ============================================================================

#[cfg(feature = "serde-json")]
mod serde_impl {
    #[allow(clippy::wildcard_imports)] // serde impl module mirrors the parent surface
    use super::*;
    use serde::ser::SerializeStruct;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    // --- AzString helpers ---

    fn ser_azstring<S: Serializer>(s: &AzString, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(s.as_str())
    }

    fn de_azstring<'de, D: Deserializer<'de>>(deserializer: D) -> Result<AzString, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(AzString::from(s.as_str()))
    }

    // --- ComponentFieldType ---

    impl Serialize for ComponentFieldType {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(&field_type_to_string(self))
        }
    }

    impl<'de> Deserialize<'de> for ComponentFieldType {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let s = String::deserialize(deserializer)?;
            Ok(string_to_field_type(&s))
        }
    }

    fn field_type_to_string(ft: &ComponentFieldType) -> String {
        match ft {
            ComponentFieldType::String => "String".into(),
            ComponentFieldType::Bool => "bool".into(),
            ComponentFieldType::I32 => "i32".into(),
            ComponentFieldType::I64 => "i64".into(),
            ComponentFieldType::U32 => "u32".into(),
            ComponentFieldType::U64 => "u64".into(),
            ComponentFieldType::Usize => "usize".into(),
            ComponentFieldType::F32 => "f32".into(),
            ComponentFieldType::F64 => "f64".into(),
            ComponentFieldType::ColorU => "ColorU".into(),
            ComponentFieldType::CssProperty => "CssProperty".into(),
            ComponentFieldType::ImageRef => "ImageRef".into(),
            ComponentFieldType::FontRef => "FontRef".into(),
            ComponentFieldType::StyledDom => "Dom".into(),
            ComponentFieldType::Callback(sig) => {
                alloc::format!("Callback({})", sig.return_type.as_str())
            }
            ComponentFieldType::RefAny(hint) => alloc::format!("RefAny({})", hint.as_str()),
            ComponentFieldType::OptionType(inner) => {
                alloc::format!("Option<{}>", field_type_to_string(inner.as_ref()))
            }
            ComponentFieldType::VecType(inner) => {
                alloc::format!("Vec<{}>", field_type_to_string(inner.as_ref()))
            }
            ComponentFieldType::StructRef(name) => alloc::format!("struct:{}", name.as_str()),
            ComponentFieldType::EnumRef(name) => alloc::format!("enum:{}", name.as_str()),
        }
    }

    // A 5-arm strip_prefix dispatch ladder. `option_if_let_else` (nursery)
    // wants `map_or_else` here, which would nest five closures inside each
    // other's else-branch — strictly less readable than the ladder.
    #[allow(clippy::option_if_let_else)]
    fn string_to_field_type(s: &str) -> ComponentFieldType {
        match s {
            "String" | "string" => ComponentFieldType::String,
            "bool" | "Bool" => ComponentFieldType::Bool,
            "i32" | "I32" => ComponentFieldType::I32,
            "i64" | "I64" => ComponentFieldType::I64,
            "u32" | "U32" => ComponentFieldType::U32,
            "u64" | "U64" => ComponentFieldType::U64,
            "usize" | "Usize" => ComponentFieldType::Usize,
            "f32" | "F32" => ComponentFieldType::F32,
            "f64" | "F64" => ComponentFieldType::F64,
            "ColorU" | "Color" | "color" => ComponentFieldType::ColorU,
            "CssProperty" => ComponentFieldType::CssProperty,
            "ImageRef" | "Image" => ComponentFieldType::ImageRef,
            "FontRef" | "Font" => ComponentFieldType::FontRef,
            "Dom" | "StyledDom" | "Children" => ComponentFieldType::StyledDom,
            other => {
                if let Some(inner) = other
                    .strip_prefix("Option<")
                    .and_then(|s| s.strip_suffix('>'))
                {
                    ComponentFieldType::OptionType(ComponentFieldTypeBox::new(
                        string_to_field_type(inner),
                    ))
                } else if let Some(inner) =
                    other.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>'))
                {
                    ComponentFieldType::VecType(ComponentFieldTypeBox::new(string_to_field_type(
                        inner,
                    )))
                } else if let Some(name) = other.strip_prefix("struct:") {
                    ComponentFieldType::StructRef(AzString::from(name))
                } else if let Some(name) = other.strip_prefix("enum:") {
                    ComponentFieldType::EnumRef(AzString::from(name))
                } else if other.starts_with("Callback") {
                    let ret = other
                        .strip_prefix("Callback(")
                        .and_then(|s| s.strip_suffix(')'))
                        .unwrap_or("()");
                    ComponentFieldType::Callback(ComponentCallbackSignature {
                        return_type: AzString::from(ret),
                        args: ComponentCallbackArgVec::from_const_slice(&[]),
                    })
                } else if other.starts_with("RefAny") {
                    let hint = other
                        .strip_prefix("RefAny(")
                        .and_then(|s| s.strip_suffix(')'))
                        .unwrap_or("");
                    ComponentFieldType::RefAny(AzString::from(hint))
                } else {
                    ComponentFieldType::String // fallback
                }
            }
        }
    }

    // --- ComponentDefaultValue ---

    impl Serialize for ComponentDefaultValue {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            use serde::ser::SerializeMap;
            match self {
                Self::None => serializer.serialize_none(),
                Self::String(s) => serializer.serialize_str(s.as_str()),
                Self::Bool(b) => serializer.serialize_bool(*b),
                Self::I32(v) => serializer.serialize_i32(*v),
                Self::I64(v) => serializer.serialize_i64(*v),
                Self::U32(v) => serializer.serialize_u32(*v),
                Self::U64(v) => serializer.serialize_u64(*v),
                Self::Usize(v) => serializer.serialize_u64(*v as u64),
                Self::F32(v) => serializer.serialize_f32(*v),
                Self::F64(v) => serializer.serialize_f64(*v),
                Self::ColorU(c) => serializer.serialize_str(&alloc::format!(
                    "#{:02x}{:02x}{:02x}{:02x}",
                    c.r,
                    c.g,
                    c.b,
                    c.a
                )),
                Self::ComponentInstance(ci) => {
                    let mut map = serializer.serialize_map(Some(2))?;
                    map.serialize_entry("library", ci.library.as_str())?;
                    map.serialize_entry("component", ci.component.as_str())?;
                    map.end()
                }
                Self::CallbackFnPointer(name) => serializer.serialize_str(name.as_str()),
                Self::Json(json_str) => {
                    // Serialize raw JSON string as-is by parsing and re-emitting
                    match serde_json::from_str::<serde_json::Value>(json_str.as_str()) {
                        Ok(v) => v.serialize(serializer),
                        Err(_) => serializer.serialize_str(json_str.as_str()),
                    }
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for ComponentDefaultValue {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let val = serde_json::Value::deserialize(deserializer)?;
            // NOTE: `Value::Null` is deliberately NOT its own arm — it maps to
            // `Self::None`, which is exactly what the catch-all below produces.
            Ok(match val {
                serde_json::Value::Bool(b) => Self::Bool(b),
                serde_json::Value::Number(n) => n.as_i64().map_or_else(
                    || n.as_f64().map_or(Self::None, Self::F64),
                    |i| i32::try_from(i).map_or(Self::I64(i), Self::I32),
                ),
                serde_json::Value::String(s) => Self::String(AzString::from(s.as_str())),
                _ => Self::None,
            })
        }
    }

    // --- OptionComponentDefaultValue ---

    impl Serialize for OptionComponentDefaultValue {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            match self {
                Self::Some(v) => v.serialize(serializer),
                Self::None => serializer.serialize_none(),
            }
        }
    }

    impl<'de> Deserialize<'de> for OptionComponentDefaultValue {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let val = Option::<ComponentDefaultValue>::deserialize(deserializer)?;
            Ok(val.map_or(Self::None, Self::Some))
        }
    }

    // --- ComponentDataField ---

    impl Serialize for ComponentDataField {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut s = serializer.serialize_struct("ComponentDataField", 5)?;
            s.serialize_field("name", self.name.as_str())?;
            s.serialize_field("type", &self.field_type)?;
            s.serialize_field("default", &self.default_value)?;
            s.serialize_field("required", &self.required)?;
            s.serialize_field("description", self.description.as_str())?;
            s.end()
        }
    }

    impl<'de> Deserialize<'de> for ComponentDataField {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            #[derive(Deserialize)]
            struct Helper {
                name: String,
                #[serde(rename = "type", default = "default_type")]
                field_type: ComponentFieldType,
                #[serde(default)]
                default: OptionComponentDefaultValue,
                #[serde(default)]
                required: bool,
                #[serde(default)]
                description: String,
            }
            const fn default_type() -> ComponentFieldType {
                ComponentFieldType::String
            }

            let h = Helper::deserialize(deserializer)?;
            Ok(Self {
                name: AzString::from(h.name.as_str()),
                field_type: h.field_type,
                default_value: h.default,
                required: h.required,
                description: AzString::from(h.description.as_str()),
            })
        }
    }

    // --- ComponentDataModel ---

    impl Serialize for ComponentDataModel {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut s = serializer.serialize_struct("ComponentDataModel", 3)?;
            s.serialize_field("name", self.name.as_str())?;
            s.serialize_field("description", self.description.as_str())?;
            let fields: Vec<&ComponentDataField> = self.fields.as_ref().iter().collect();
            s.serialize_field("fields", &fields)?;
            s.end()
        }
    }

    impl<'de> Deserialize<'de> for ComponentDataModel {
        /// A data model is a JSON **object**. This deliberately drives the
        /// deserializer with `deserialize_map` instead of `deserialize_struct`:
        /// the struct hint makes serde accept a *sequence* as well (the
        /// positional encoding used by compact formats), so `from_json("[]")`
        /// used to succeed and hand back a nameless, field-less model instead of
        /// reporting that the input is not a data model at all. Every key stays
        /// optional, so `{}` still deserializes to the empty model.
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            use serde::de::{IgnoredAny, MapAccess, Visitor};

            struct ModelVisitor;

            impl<'de> Visitor<'de> for ModelVisitor {
                type Value = ComponentDataModel;

                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.write_str("a data model object with `name`, `description` and `fields`")
                }

                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                    let mut name: Option<String> = None;
                    let mut description: Option<String> = None;
                    let mut fields: Option<Vec<ComponentDataField>> = None;

                    while let Some(key) = map.next_key::<String>()? {
                        match key.as_str() {
                            "name" => name = Some(map.next_value()?),
                            "description" => description = Some(map.next_value()?),
                            "fields" => fields = Some(map.next_value()?),
                            // Unknown keys are ignored (forward compatibility),
                            // but their values must still be consumed.
                            _ => {
                                map.next_value::<IgnoredAny>()?;
                            }
                        }
                    }

                    Ok(ComponentDataModel {
                        name: AzString::from(name.unwrap_or_default().as_str()),
                        description: AzString::from(description.unwrap_or_default().as_str()),
                        fields: ComponentDataFieldVec::from_vec(fields.unwrap_or_default()),
                    })
                }
            }

            deserializer.deserialize_map(ModelVisitor)
        }
    }
}

// NOTE: no `pub use serde_impl::*` — the module holds only private helpers and
// trait impls, and trait impls are in scope crate-wide (and for downstream
// users) regardless of the defining module's visibility.

#[cfg(feature = "serde-json")]
impl ComponentDataModel {
    /// Serialize this data model to a JSON string.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error message if the model cannot be
    /// represented as JSON.
    pub fn to_json(&self) -> Result<String, String> {
        serde_json::to_string_pretty(self).map_err(|e| alloc::format!("{e}"))
    }

    /// Deserialize a data model from a JSON string.
    ///
    /// # Errors
    ///
    /// Returns the parser's error message if `json` is malformed or does not
    /// match the data-model shape.
    pub fn from_json(json: &str) -> Result<Self, String> {
        serde_json::from_str(json).map_err(|e| alloc::format!("{e}"))
    }
}

/// Source of a component definition — determines whether it can be exported
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
#[derive(Default)]
pub enum ComponentSource {
    /// Built into the DLL (HTML elements). Never exported.
    Builtin,
    /// Compiled Rust widget (Button, `TextInput`, etc.). Never exported.
    Compiled,
    /// Defined via JSON/XML at runtime. Can be exported.
    #[default]
    UserDefined,
}

impl ComponentSource {
    #[must_use]
    pub fn create() -> Self {
        Self::default()
    }
}

/// The target language for code compilation
// Threaded by reference through the codegen call graph; kept non-Copy so
// deriving Copy doesn't force trivially_copy_pass_by_ref churn across the many
// &CompileTarget codegen callers for a perf-neutral change.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum CompileTarget {
    Rust,
    C,
    Cpp,
    Python,
}

impl_result!(
    StyledDom,
    RenderDomError,
    ResultStyledDomRenderDomError,
    copy = false,
    [Debug, Clone, PartialEq]
);

impl_result!(
    AzString,
    CompileError,
    ResultStringCompileError,
    copy = false,
    [Debug, Clone, PartialEq]
);

/// Render function type: takes component definition + data model (with current values
/// in `default_value` fields) + component map for recursive sub-component instantiation,
/// returns `StyledDom`.
///
/// The `data` parameter is typically `def.data_model` cloned and with caller-provided
/// values substituted into the `default_value` fields.
pub type ComponentRenderFn =
    fn(&ComponentDef, &ComponentDataModel, &ComponentMap) -> ResultStyledDomRenderDomError;

/// Compile function type: takes component definition + target language + data model, returns source code.
pub type ComponentCompileFn = fn(
    &ComponentDef,
    &CompileTarget,
    &ComponentDataModel,
    indent: usize,
) -> ResultStringCompileError;

/// Raw function pointer type that returns a single `ComponentDef` when called.
/// Used as the `cb` field in `RegisterComponentFn`.
pub type RegisterComponentFnType = extern "C" fn() -> ComponentDef;

/// Callback struct for registering individual components at startup.
///
/// In C: pass a bare `extern "C" fn() -> ComponentDef` function pointer —
/// it converts automatically via `From<RegisterComponentFnType>`.
///
/// In Python: construct this struct with `cb` set to a trampoline and
/// `ctx` set to `Some(RefAny(...))` wrapping the Python callable.
#[repr(C)]
pub struct RegisterComponentFn {
    pub cb: RegisterComponentFnType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`).
    /// Native Rust/C code sets this to None.
    pub ctx: crate::refany::OptionRefAny,
}

impl_callback!(RegisterComponentFn, RegisterComponentFnType);

/// Raw function pointer type that returns a complete `ComponentLibrary` when called.
/// Used as the `cb` field in `RegisterComponentLibraryFn`.
pub type RegisterComponentLibraryFnType = extern "C" fn() -> ComponentLibrary;

/// Callback struct for registering entire component libraries at startup.
///
/// In C: pass a bare `extern "C" fn() -> ComponentLibrary` function pointer —
/// it converts automatically via `From<RegisterComponentLibraryFnType>`.
///
/// In Python: construct this struct with `cb` set to a trampoline and
/// `ctx` set to `Some(RefAny(...))` wrapping the Python callable.
#[repr(C)]
pub struct RegisterComponentLibraryFn {
    pub cb: RegisterComponentLibraryFnType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`).
    /// Native Rust/C code sets this to None.
    pub ctx: crate::refany::OptionRefAny,
}

impl_callback!(RegisterComponentLibraryFn, RegisterComponentLibraryFnType);

/// A component definition — the "class" / "template" of a component.
/// Can come from Rust builtins, compiled widgets, JSON, or user creation in debugger.
///
#[derive(Clone)]
#[repr(C)]
pub struct ComponentDef {
    /// Collection + name, e.g. builtin:div, shadcn:avatar
    pub id: ComponentId,
    /// Human-readable display name, e.g. "Link" for builtin:a, "Avatar" for shadcn:avatar
    pub display_name: AzString,
    /// Markdown documentation for the component
    pub description: AzString,
    /// The component's CSS
    pub css: AzString,
    /// Where this component was defined (determines exportability)
    pub source: ComponentSource,
    /// Unified data model: all value fields, callback slots, and child slots
    /// in a single named struct. Code gen uses `data_model.name` as the
    /// input struct type name (e.g. "`ButtonData`").
    /// The `default_value` on each field doubles as the "current value" for
    /// preview rendering — callers override defaults before calling `render_fn`.
    pub data_model: ComponentDataModel,
    /// Render to live DOM
    pub render_fn: ComponentRenderFn,
    /// Compile to source code in target language
    pub compile_fn: ComponentCompileFn,
    /// Source code for `render_fn` (user-defined components only)
    pub render_fn_source: OptionString,
    /// Source code for `compile_fn` (user-defined components only)
    pub compile_fn_source: OptionString,
}

impl fmt::Debug for ComponentDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ComponentDef")
            .field("id", &self.id)
            .field("display_name", &self.display_name)
            .field("source", &self.source)
            .field("data_model", &self.data_model.name)
            .finish_non_exhaustive()
    }
}

impl_vec!(
    ComponentDef,
    ComponentDefVec,
    ComponentDefVecDestructor,
    ComponentDefVecDestructorType,
    ComponentDefVecSlice,
    OptionComponentDef
);
impl_option!(ComponentDef, OptionComponentDef, copy = false, [Clone]);
impl_vec_debug!(ComponentDef, ComponentDefVec);
impl_vec_clone!(ComponentDef, ComponentDefVec, ComponentDefVecDestructor);
impl_vec_mut!(ComponentDef, ComponentDefVec);

/// A named collection of component definitions
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentLibrary {
    /// Library identifier, e.g. "builtin", "shadcn", "myproject"
    pub name: AzString,
    /// Version string
    pub version: AzString,
    /// Human-readable description
    pub description: AzString,
    /// The components in this library
    pub components: ComponentDefVec,
    /// Whether this library can be exported (false for builtin/compiled)
    pub exportable: bool,
    /// Whether this library can be modified by the user (add/remove/edit components).
    /// False for builtin and compiled libraries. True for user-created libraries.
    pub modifiable: bool,
    /// Named data model types defined by this library.
    /// Components reference these by name in their `field_type`.
    pub data_models: ComponentDataModelVec,
    /// Named enum types defined by this library.
    /// Components reference these via `ComponentFieldType::EnumRef(name)`.
    pub enum_models: ComponentEnumModelVec,
}

impl_vec!(
    ComponentLibrary,
    ComponentLibraryVec,
    ComponentLibraryVecDestructor,
    ComponentLibraryVecDestructorType,
    ComponentLibraryVecSlice,
    OptionComponentLibrary
);
impl_option!(
    ComponentLibrary,
    OptionComponentLibrary,
    copy = false,
    [Debug, Clone]
);
impl_vec_debug!(ComponentLibrary, ComponentLibraryVec);
impl_vec_clone!(
    ComponentLibrary,
    ComponentLibraryVec,
    ComponentLibraryVecDestructor
);
impl_vec_mut!(ComponentLibrary, ComponentLibraryVec);

/// The component map — holds libraries with namespaced components.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct ComponentMap {
    /// Libraries indexed by name. "builtin" is always present.
    pub libraries: ComponentLibraryVec,
}

impl ComponentMap {
    /// Qualified lookup: "shadcn:avatar" -> finds library "shadcn", component "avatar"
    #[must_use]
    pub fn get(&self, collection: &str, name: &str) -> Option<&ComponentDef> {
        self.libraries
            .iter()
            .find(|lib| lib.name.as_str() == collection)
            .and_then(|lib| lib.components.iter().find(|c| c.id.name.as_str() == name))
    }

    /// Unqualified lookup: "div" -> searches ONLY the "builtin" library.
    #[must_use]
    pub fn get_unqualified(&self, name: &str) -> Option<&ComponentDef> {
        self.get("builtin", name)
    }

    /// Parse a "collection:name" string into a lookup
    #[must_use]
    pub fn get_by_qualified_name(&self, qualified: &str) -> Option<&ComponentDef> {
        if let Some((collection, name)) = qualified.split_once(':') {
            self.get(collection, name)
        } else {
            self.get_unqualified(qualified)
        }
    }

    /// Get all libraries that can be exported (user-defined only)
    #[must_use]
    pub fn get_exportable_libraries(&self) -> Vec<&ComponentLibrary> {
        self.libraries.iter().filter(|lib| lib.exportable).collect()
    }

    /// Get all component definitions across all libraries
    #[must_use]
    pub fn all_components(&self) -> Vec<&ComponentDef> {
        self.libraries
            .iter()
            .flat_map(|lib| lib.components.iter())
            .collect()
    }
}

// ============================================================================
// Builtin component bridge — wraps existing render/compile into ComponentDef
// ============================================================================

/// Single source of truth mapping HTML/SVG tag names to node variants.
///
/// Each `"tag" => Variant` entry expands to **both** a `NodeType::Variant` arm in
/// [`tag_to_node_type`] and a `NodeTypeTag::Variant` arm in [`tag_to_node_type_tag`],
/// so the two lookups can never drift apart. Tags whose two enums diverge —
/// `img`, `image`, `icon` — are handled as explicit special cases inside each
/// generated function and are intentionally absent from this table.
macro_rules! html_tag_node_types {
    ($($tag:literal => $variant:ident),* $(,)?) => {
        /// Map a builtin tag name to its corresponding `NodeType`.
        /// Falls back to `NodeType::Div` for unknown tags.
        #[must_use] pub fn tag_to_node_type(tag: &str) -> NodeType {
            match tag {
                // `<img>` becomes a replaced `NodeType::Image`. The `src` attribute is not
                // available here, so a placeholder `NullImage` (0x0, empty tag) is created;
                // `xml_node_to_dom_fast` overrides it with a `NullImage` whose `tag` carries
                // the `src` bytes so a renderer (e.g. printpdf) can resolve the actual image.
                "img" => NodeType::Image(azul_css::css::BoxOrStatic::heap(
                    crate::resources::ImageRef::null_image(
                        0,
                        0,
                        crate::resources::RawImageFormat::RGBA8,
                        alloc::vec::Vec::new(),
                    ),
                )),
                // `<icon>content_copy</icon>` becomes an un-named `NodeType::Icon`;
                // the icon SPEC is its text content, consumed by the icon
                // resolution pass (`resolve_icons_in_styled_dom`) against the
                // registered icon packs — exactly like a ligature icon font
                // turns glyph text into an icon. The builders stay generic.
                "icon" => NodeType::Icon(azul_css::css::BoxOrStatic::heap(
                    azul_css::AzString::from_const_str(""),
                )),
                // `<transient-window>` starts CLOSED with every default; the
                // parser applies `open=` / `anchor=` / `dismiss=` / `size=` /
                // `tearoff=` onto this config afterwards (see
                // `apply_transient_window_attrs`). Carrying the config inline is
                // what lets a closed popup cost nothing.
                "transient-window" => NodeType::TransientWindow(
                    crate::transient::TransientWindowConfig::closed(),
                ),
                $($tag => NodeType::$variant,)*
                _ => NodeType::Div,
            }
        }

        /// Map a tag name to its CSS `NodeTypeTag` for CSS matching in the compile pipeline.
        /// Falls back to `NodeTypeTag::Div` for unknown tags.
        fn tag_to_node_type_tag(tag: &str) -> NodeTypeTag {
            match tag {
                // `img`/`image`/`icon` have no 1:1 `NodeType` equivalent (see
                // `tag_to_node_type`), so they map to dedicated `NodeTypeTag` variants.
                "img" | "image" => NodeTypeTag::Img,
                "icon" => NodeTypeTag::Icon,
                "transient-window" => NodeTypeTag::TransientWindow,
                $($tag => NodeTypeTag::$variant,)*
                _ => NodeTypeTag::Div,
            }
        }
    };
}

html_tag_node_types! {
    // Document structure
    "html" => Html,
    "head" => Head,
    "title" => Title,
    "body" => Body,
    // Block-level
    "div" => Div,
    "header" => Header,
    "footer" => Footer,
    "section" => Section,
    "article" => Article,
    "aside" => Aside,
    "nav" => Nav,
    "main" => Main,
    "figure" => Figure,
    "figcaption" => FigCaption,
    "address" => Address,
    "details" => Details,
    "summary" => Summary,
    "dialog" => Dialog,
    // Headings
    "h1" => H1,
    "h2" => H2,
    "h3" => H3,
    "h4" => H4,
    "h5" => H5,
    "h6" => H6,
    // Text content
    "p" => P,
    "span" => Span,
    "pre" => Pre,
    "code" => Code,
    "blockquote" => BlockQuote,
    "br" => Br,
    "hr" => Hr,
    "pagebreak" => PageBreak,
    // Lists
    "ul" => Ul,
    "ol" => Ol,
    "li" => Li,
    "dl" => Dl,
    "dt" => Dt,
    "dd" => Dd,
    "menu" => Menu,
    "menuitem" => MenuItem,
    "dir" => Dir,
    // Tables
    "table" => Table,
    "caption" => Caption,
    "thead" => THead,
    "tbody" => TBody,
    "tfoot" => TFoot,
    "tr" => Tr,
    "th" => Th,
    "td" => Td,
    "colgroup" => ColGroup,
    "col" => Col,
    // Forms
    "form" => Form,
    "fieldset" => FieldSet,
    "legend" => Legend,
    "label" => Label,
    "input" => Input,
    "button" => Button,
    "select" => Select,
    "optgroup" => OptGroup,
    "option" => SelectOption,
    "textarea" => TextArea,
    "output" => Output,
    "progress" => Progress,
    "meter" => Meter,
    "datalist" => DataList,
    // Inline
    "a" => A,
    "strong" => Strong,
    "em" => Em,
    "b" => B,
    "i" => I,
    "u" => U,
    "s" => S,
    "small" => Small,
    "mark" => Mark,
    "del" => Del,
    "ins" => Ins,
    "samp" => Samp,
    "kbd" => Kbd,
    "var" => Var,
    "cite" => Cite,
    "dfn" => Dfn,
    "abbr" => Abbr,
    "acronym" => Acronym,
    "q" => Q,
    "time" => Time,
    "sub" => Sub,
    "sup" => Sup,
    "big" => Big,
    "bdo" => Bdo,
    "bdi" => Bdi,
    "wbr" => Wbr,
    "ruby" => Ruby,
    "rt" => Rt,
    "rtc" => Rtc,
    "rp" => Rp,
    "data" => Data,
    // Embedded content (`img` is a special case in the generated fns)
    "canvas" => Canvas,
    "object" => Object,
    "param" => Param,
    "embed" => Embed,
    "audio" => Audio,
    "video" => Video,
    "source" => Source,
    "track" => Track,
    "map" => Map,
    "area" => Area,
    // SVG elements
    "svg" => Svg,
    "g" => SvgG,
    "defs" => SvgDefs,
    "symbol" => SvgSymbol,
    "use" => SvgUse,
    "switch" => SvgSwitch,
    "path" => SvgPath,
    "circle" => SvgCircle,
    "rect" => SvgRect,
    "ellipse" => SvgEllipse,
    "line" => SvgLine,
    "polygon" => SvgPolygon,
    "polyline" => SvgPolyline,
    "tspan" => SvgTspan,
    "textpath" => SvgTextPath,
    "lineargradient" => SvgLinearGradient,
    "radialgradient" => SvgRadialGradient,
    "stop" => SvgStop,
    "pattern" => SvgPattern,
    "clippath" => SvgClipPathElement,
    "mask" => SvgMask,
    "filter" => SvgFilter,
    "feblend" => SvgFeBlend,
    "fecolormatrix" => SvgFeColorMatrix,
    "fecomponenttransfer" => SvgFeComponentTransfer,
    "fecomposite" => SvgFeComposite,
    "feconvolvematrix" => SvgFeConvolveMatrix,
    "fediffuselighting" => SvgFeDiffuseLighting,
    "fedisplacementmap" => SvgFeDisplacementMap,
    "fedistantlight" => SvgFeDistantLight,
    "fedropshadow" => SvgFeDropShadow,
    "feflood" => SvgFeFlood,
    "fefuncr" => SvgFeFuncR,
    "fefuncg" => SvgFeFuncG,
    "fefuncb" => SvgFeFuncB,
    "fefunca" => SvgFeFuncA,
    "fegaussianblur" => SvgFeGaussianBlur,
    "feimage" => SvgFeImage,
    "femerge" => SvgFeMerge,
    "femergenode" => SvgFeMergeNode,
    "femorphology" => SvgFeMorphology,
    "feoffset" => SvgFeOffset,
    "fepointlight" => SvgFePointLight,
    "fespecularlighting" => SvgFeSpecularLighting,
    "fespotlight" => SvgFeSpotLight,
    "fetile" => SvgFeTile,
    "feturbulence" => SvgFeTurbulence,
    "foreignobject" => SvgForeignObject,
    "desc" => SvgDesc,
    "view" => SvgView,
    "animate" => SvgAnimate,
    "animatemotion" => SvgAnimateMotion,
    "animatetransform" => SvgAnimateTransform,
    "set" => SvgSet,
    "mpath" => SvgMpath,
    // Metadata
    "meta" => Meta,
    "link" => Link,
    "script" => Script,
    "style" => Style,
    "base" => Base,
}

/// Default render function for builtin HTML elements.
/// Delegates to creating a DOM node of the appropriate `NodeType`.
fn builtin_render_fn(
    def: &ComponentDef,
    data: &ComponentDataModel,
    _component_map: &ComponentMap,
) -> ResultStyledDomRenderDomError {
    let node_type = tag_to_node_type(def.id.name.as_str());
    let mut dom = Dom::create_node(node_type);
    if let Some(text_str) = data.get_default_string("text") {
        let prepared = prepare_string(text_str);
        if !prepared.is_empty() {
            dom = dom.with_children(
                alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
                    prepared
                )]
                .into(),
            );
        }
    }
    let r: Result<StyledDom, RenderDomError> = Ok(StyledDom::create(&mut dom, Css::empty()));
    r.into()
}

/// Default compile function for builtin HTML elements.
/// Generates `Dom::create_node(NodeType::Div)` style code for the target language.
fn builtin_compile_fn(
    def: &ComponentDef,
    target: &CompileTarget,
    data: &ComponentDataModel,
    indent: usize,
) -> ResultStringCompileError {
    let node_type = tag_to_node_type(def.id.name.as_str());
    let type_name = format!("{node_type:?}"); // "Div", "Body", "P", etc.
    let text = data.get_default_string("text");

    let r: Result<AzString, CompileError> = match target {
        CompileTarget::Rust => {
            text.map_or_else(|| Ok(format!("Dom::create_node(NodeType::{type_name})").into()), |text_str| Ok(format!(
                    "Dom::create_node(NodeType::{}).with_children(vec![Dom::create_text_do_not_use_without_block_level_wrapper(\"{}\")])",
                    type_name,
                    text_str.as_str().replace('\\', "\\\\").replace('"', "\\\"")
                ).into()))
        }
        CompileTarget::C => {
            text.map_or_else(|| Ok(format!("AzDom_create{type_name}()").into()), |text_str| Ok(format!(
                    "AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{}\"))",
                    text_str
                        .as_str()
                        .replace('\\', "\\\\")
                        .replace('"', "\\\"")
                )
                .into()))
        }
        CompileTarget::Cpp => Ok(format!("Dom::create_{}()", type_name.to_lowercase()).into()),
        CompileTarget::Python => Ok(format!("Dom.create_{}()", type_name.to_lowercase()).into()),
    };
    r.into()
}

/// Pushes a `<div>` containing `"field_name: value"` text into the children list.
fn push_scalar_field(children: &mut Vec<Dom>, field_name: &str, value: &dyn fmt::Display) {
    use crate::dom::{Dom, NodeType};
    let text = alloc::format!("{field_name}: {value}");
    children.push(
        Dom::create_node(NodeType::Div).with_children(
            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
                text
            )]
            .into(),
        ),
    );
}

/// Default render function for user-defined (JSON-imported) components.
///
/// Interprets the `ComponentDef` structure generically:
/// 1. Creates a wrapper `<div>` with the component's CSS class
/// 2. For each data field, renders content based on type:
///    - String fields → text node with current value
///    - Bool fields → conditional display
///    - `StyledDom` fields → embeds the child DOM subtree
///    - StructRef/EnumRef → recursively renders sub-components if found in `ComponentMap`
///    - Other scalar fields → text display of the value
/// 3. Applies the component's scoped CSS
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
pub fn user_defined_render_fn(
    def: &ComponentDef,
    data: &ComponentDataModel,
    component_map: &ComponentMap,
) -> ResultStyledDomRenderDomError {
    use crate::dom::{Dom, NodeType};
    use azul_css::css::Css;

    let mut children: Vec<Dom> = Vec::new();

    for field in data.fields.as_ref() {
        let field_name = field.name.as_str();

        // Get the current value from default_value
        match &field.default_value {
            OptionComponentDefaultValue::None => {
                // Required field with no value — skip in preview
            }
            OptionComponentDefaultValue::Some(default_val) => {
                match default_val {
                    ComponentDefaultValue::String(s) => {
                        let text = s.as_str().trim();
                        if !text.is_empty() {
                            let label_dom = Dom::create_node(NodeType::Div).with_children(
                                alloc::vec![
                                    Dom::create_text_do_not_use_without_block_level_wrapper(
                                        text.to_string()
                                    )
                                ]
                                .into(),
                            );
                            children.push(label_dom);
                        }
                    }
                    ComponentDefaultValue::Bool(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::I32(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::I64(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::U32(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::U64(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::Usize(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::F32(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::F64(v) => {
                        push_scalar_field(&mut children, field_name, v);
                    }
                    ComponentDefaultValue::ColorU(c) => {
                        let text = alloc::format!(
                            "{}: #{:02x}{:02x}{:02x}{:02x}",
                            field_name,
                            c.r,
                            c.g,
                            c.b,
                            c.a
                        );
                        children.push(
                            Dom::create_node(NodeType::Div).with_children(
                                alloc::vec![
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
                                ]
                                .into(),
                            ),
                        );
                    }
                    ComponentDefaultValue::ComponentInstance(ci) => {
                        // Recursively instantiate sub-component from ComponentMap
                        if let Some(sub_comp) =
                            component_map.get(ci.library.as_str(), ci.component.as_str())
                        {
                            let sub_data = sub_comp.data_model.clone();
                            match (sub_comp.render_fn)(sub_comp, &sub_data, component_map) {
                                ResultStyledDomRenderDomError::Ok(_styled_dom) => {
                                    // Sub-component rendered successfully — add a placeholder
                                    // (StyledDom cannot be directly converted back to Dom)
                                    let text = alloc::format!(
                                        "[{}:{}]",
                                        ci.library.as_str(),
                                        ci.component.as_str()
                                    );
                                    children.push(
                                        Dom::create_node(NodeType::Div).with_children(
                                            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(text)].into(),
                                        ),
                                    );
                                }
                                ResultStyledDomRenderDomError::Err(_) => {
                                    // On error, show a placeholder
                                    let text = alloc::format!(
                                        "[Error rendering {}:{}]",
                                        ci.library.as_str(),
                                        ci.component.as_str()
                                    );
                                    children.push(
                                        Dom::create_node(NodeType::Div).with_children(
                                            alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(text)].into(),
                                        ),
                                    );
                                }
                            }
                        } else {
                            let text = alloc::format!(
                                "[Unknown component {}:{}]",
                                ci.library.as_str(),
                                ci.component.as_str()
                            );
                            children.push(
                                Dom::create_node(NodeType::Div).with_children(
                                    alloc::vec![
                                        Dom::create_text_do_not_use_without_block_level_wrapper(
                                            text
                                        )
                                    ]
                                    .into(),
                                ),
                            );
                        }
                    }
                    ComponentDefaultValue::CallbackFnPointer(name) => {
                        // Callbacks are not rendered, just acknowledged
                        let text = alloc::format!("{}: fn({})", field_name, name.as_str());
                        children.push(
                            Dom::create_node(NodeType::Div).with_children(
                                alloc::vec![
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
                                ]
                                .into(),
                            ),
                        );
                    }
                    ComponentDefaultValue::Json(json_str) => {
                        let text = alloc::format!("{}: {}", field_name, json_str.as_str());
                        children.push(
                            Dom::create_node(NodeType::Div).with_children(
                                alloc::vec![
                                    Dom::create_text_do_not_use_without_block_level_wrapper(text)
                                ]
                                .into(),
                            ),
                        );
                    }
                    ComponentDefaultValue::None => {
                        // No default, skip
                    }
                }
            }
        }
    }

    let mut wrapper = Dom::create_node(NodeType::Div);
    if !children.is_empty() {
        wrapper = wrapper.with_children(children.into());
    }

    // Apply component CSS
    let css = if def.css.as_str().is_empty() {
        Css::empty()
    } else {
        Css::from_string(def.css.clone())
    };

    let r: Result<StyledDom, RenderDomError> = Ok(StyledDom::create(&mut wrapper, css));
    r.into()
}

/// Default compile function for user-defined (JSON-imported) components.
///
/// Generates source code that creates the component's DOM structure for the
/// target language. For each data field, emits the appropriate code:
/// - String fields → text node creation
/// - Scalar fields → formatted display
/// - `ComponentInstance` → function call to sub-component's render function
/// - `StyledDom` slots → child parameter pass-through
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
pub fn user_defined_compile_fn(
    def: &ComponentDef,
    target: &CompileTarget,
    data: &ComponentDataModel,
    indent: usize,
) -> ResultStringCompileError {
    let tag = def.id.name.as_str();
    let indent_str = " ".repeat(indent * 4);
    let inner_indent = " ".repeat((indent + 1) * 4);

    let r: Result<AzString, CompileError> = match target {
        CompileTarget::Rust => {
            let mut lines = Vec::new();
            lines.push(alloc::format!("{indent_str}// Component: {tag}"));
            lines.push(alloc::format!(
                "{indent_str}let mut children: Vec<Dom> = Vec::new();"
            ));

            for field in data.fields.as_ref() {
                let fname = field.name.as_str();
                match &field.default_value {
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
                        lines.push(alloc::format!(
                            "{inner_indent}children.push(Dom::create_text_do_not_use_without_block_level_wrapper(\"{escaped}\"));"
                        ));
                    }
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::Bool(b)) => {
                        lines.push(alloc::format!(
                            "{inner_indent}children.push(Dom::create_text_do_not_use_without_block_level_wrapper(format!(\"{{}}: {{}}\", \"{fname}\", {b}).as_str()));"
                        ));
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{}children.push({}()); // sub-component {}:{}",
                            inner_indent,
                            fn_name,
                            ci.library.as_str(),
                            ci.component.as_str()
                        ));
                    }
                    _ => {
                        // For other types, generate a placeholder comment
                        lines.push(alloc::format!(
                            "{}// field '{}': {:?}",
                            inner_indent,
                            fname,
                            field.field_type
                        ));
                    }
                }
            }

            lines.push(alloc::format!(
                "{indent_str}Dom::create_node(NodeType::Div).with_children(children.into())"
            ));
            Ok(lines.join("\n").into())
        }
        CompileTarget::C => {
            let mut lines = Vec::new();
            lines.push(alloc::format!("{indent_str}/* Component: {tag} */"));
            lines.push(alloc::format!(
                "{indent_str}AzDom root = AzDom_createDiv();"
            ));

            for field in data.fields.as_ref() {
                let fname = field.name.as_str();
                match &field.default_value {
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
                        lines.push(alloc::format!(
                            "{inner_indent}AzDom_addChild(&root, AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{escaped}\")));"
                        ));
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{inner_indent}AzDom_addChild(&root, {fn_name}());"
                        ));
                    }
                    _ => {
                        lines.push(alloc::format!("{inner_indent}/* field '{fname}' */"));
                    }
                }
            }

            lines.push(alloc::format!("{indent_str}return root;"));
            Ok(lines.join("\n").into())
        }
        CompileTarget::Cpp => {
            let mut lines = Vec::new();
            lines.push(alloc::format!("{indent_str}// Component: {tag}"));
            lines.push(alloc::format!("{indent_str}auto root = Dom::create_div();"));

            for field in data.fields.as_ref() {
                let fname = field.name.as_str();
                match &field.default_value {
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
                        let escaped = s.as_str().replace('\\', "\\\\").replace('"', "\\\"");
                        lines.push(alloc::format!(
                            "{inner_indent}root.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(String(\"{escaped}\")));"
                        ));
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!("{inner_indent}root.add_child({fn_name}());"));
                    }
                    _ => {
                        lines.push(alloc::format!("{inner_indent}// field '{fname}'"));
                    }
                }
            }

            lines.push(alloc::format!("{indent_str}return root;"));
            Ok(lines.join("\n").into())
        }
        CompileTarget::Python => {
            let mut lines = Vec::new();
            lines.push(alloc::format!("{indent_str}# Component: {tag}"));
            lines.push(alloc::format!("{indent_str}root = Dom.create_div()"));

            for field in data.fields.as_ref() {
                let fname = field.name.as_str();
                match &field.default_value {
                    OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
                        let escaped = s
                            .as_str()
                            .replace('\\', "\\\\")
                            .replace('"', "\\\"")
                            .replace('\'', "\\'");
                        lines.push(alloc::format!(
                            "{inner_indent}root = root.with_child(Dom.create_text_do_not_use_without_block_level_wrapper(\"{escaped}\"))"
                        ));
                    }
                    OptionComponentDefaultValue::Some(
                        ComponentDefaultValue::ComponentInstance(ci),
                    ) => {
                        let fn_name =
                            alloc::format!("render_{}", ci.component.as_str().replace('-', "_"));
                        lines.push(alloc::format!(
                            "{inner_indent}root = root.with_child({fn_name}())"
                        ));
                    }
                    _ => {
                        lines.push(alloc::format!("{inner_indent}# field '{fname}'"));
                    }
                }
            }

            lines.push(alloc::format!("{indent_str}return root"));
            Ok(lines.join("\n").into())
        }
    };
    r.into()
}

/// Create a `ComponentDef` for a builtin HTML element.
///
/// # Arguments
/// * `tag` - HTML tag name (e.g. "button", "div")
/// * `display_name` - Human-readable name (e.g. "Button", "Div")
/// * `default_text` - Default text content for the preview, or `None` if the element has no text.
///   Pass `Some("Button text")` for `<button>`, `Some("")` for text elements like `<span>` that
///   accept text but have no meaningful default.
/// * `css` - Component-level CSS string. For most builtin elements this is `""` because
///   styling comes from `ua_css.rs` and the `SystemStyle`. Components that need extra
///   styling (e.g. a future high-level button widget) can pass CSS here.
fn builtin_component_def(
    tag: &str,
    display_name: &str,
    default_text: Option<&str>,
    css: &str,
) -> ComponentDef {
    let mut fields = builtin_data_model(tag);
    // If a default_text is provided, this element accepts text content
    if let Some(text) = default_text {
        fields.push(data_field(
            "text",
            ComponentFieldType::String,
            Some(ComponentDefaultValue::String(AzString::from(text))),
            "Text content of the element",
        ));
    }
    let model_name = format!("{display_name}Data");
    ComponentDef {
        id: ComponentId::builtin(tag),
        display_name: AzString::from(display_name),
        description: AzString::from(format!("HTML <{tag}> element").as_str()),
        css: AzString::from(css),
        source: ComponentSource::Builtin,
        data_model: ComponentDataModel {
            name: AzString::from(model_name.as_str()),
            description: AzString::from(format!("Data model for <{tag}>").as_str()),
            fields: fields.into(),
        },
        render_fn: builtin_render_fn,
        compile_fn: builtin_compile_fn,
        render_fn_source: None.into(),
        compile_fn_source: None.into(),
    }
}

/// Helper to create a `ComponentDataField` with a rich type
fn data_field(
    name: &str,
    ft: ComponentFieldType,
    default: Option<ComponentDefaultValue>,
    description: &str,
) -> ComponentDataField {
    let required = default.is_none();
    ComponentDataField {
        name: AzString::from(name),
        field_type: ft,
        default_value: default.map_or_else(
            || OptionComponentDefaultValue::None,
            OptionComponentDefaultValue::Some,
        ),
        required,
        description: AzString::from(description),
    }
}

/// Returns the tag-specific data model fields for builtin HTML elements.
/// These are the component's "main data model" — the attributes that define
/// what the component needs as configuration (e.g., `href` for `<a>`,
/// `src` for `<img>`). Universal HTML attributes (id, class, style, etc.)
/// are NOT included here — they are added separately by the debug server.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
fn builtin_data_model(tag: &str) -> Vec<ComponentDataField> {
    use ComponentDefaultValue as D;
    use ComponentFieldType::{Bool, String, I32};
    match tag {
        "a" => alloc::vec![
            data_field(
                "href",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL the link points to"
            ),
            data_field(
                "target",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Where to open the linked document (_blank, _self, _parent, _top)"
            ),
            data_field(
                "rel",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Relationship between current and linked document"
            ),
        ],
        "img" | "image" => alloc::vec![
            data_field("src", String, None, "URL of the image"),
            data_field(
                "alt",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Alternative text for the image"
            ),
            data_field(
                "width",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Width of the image"
            ),
            data_field(
                "height",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Height of the image"
            ),
        ],
        "form" => alloc::vec![
            data_field(
                "action",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL where form data is submitted"
            ),
            data_field(
                "method",
                String,
                Some(D::String(AzString::from_const_str("GET"))),
                "HTTP method for form submission (GET or POST)"
            ),
        ],
        "label" => alloc::vec![data_field(
            "for",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "ID of the form element this label is for"
        ),],
        "button" => alloc::vec![
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str("button"))),
                "Button type (button, submit, reset)"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether the button is disabled"
            ),
        ],
        "td" | "th" => alloc::vec![
            data_field(
                "colspan",
                I32,
                Some(D::I32(1)),
                "Number of columns the cell spans"
            ),
            data_field(
                "rowspan",
                I32,
                Some(D::I32(1)),
                "Number of rows the cell spans"
            ),
        ],
        "icon" => alloc::vec![data_field(
            "name",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "Icon name"
        ),],
        "ol" => alloc::vec![
            data_field(
                "start",
                I32,
                Some(D::I32(1)),
                "Start value for the ordered list"
            ),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str("1"))),
                "Numbering type (1, A, a, I, i)"
            ),
        ],
        // Form controls
        "input" => alloc::vec![
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str("text"))),
                "Input type (text, password, email, number, checkbox, radio, etc.)"
            ),
            data_field(
                "name",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Name of the input for form submission"
            ),
            data_field(
                "value",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Current value of the input"
            ),
            data_field(
                "placeholder",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Placeholder text"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether the input is disabled"
            ),
            data_field(
                "required",
                Bool,
                Some(D::Bool(false)),
                "Whether the input is required"
            ),
            data_field(
                "readonly",
                Bool,
                Some(D::Bool(false)),
                "Whether the input is read-only"
            ),
            data_field(
                "checked",
                Bool,
                Some(D::Bool(false)),
                "Whether the checkbox/radio is checked"
            ),
            data_field(
                "min",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Minimum value (for number, range, date)"
            ),
            data_field(
                "max",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Maximum value (for number, range, date)"
            ),
            data_field(
                "step",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Step increment (for number, range)"
            ),
            data_field(
                "pattern",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Regex pattern for validation"
            ),
            data_field(
                "maxlength",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Maximum number of characters"
            ),
        ],
        "select" => alloc::vec![
            data_field(
                "name",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Name for form submission"
            ),
            data_field(
                "multiple",
                Bool,
                Some(D::Bool(false)),
                "Whether multiple options can be selected"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether the select is disabled"
            ),
            data_field(
                "required",
                Bool,
                Some(D::Bool(false)),
                "Whether selection is required"
            ),
            data_field(
                "size",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Number of visible options"
            ),
        ],
        "option" => alloc::vec![
            data_field(
                "value",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Value submitted with the form"
            ),
            data_field(
                "selected",
                Bool,
                Some(D::Bool(false)),
                "Whether this option is selected"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether this option is disabled"
            ),
        ],
        "optgroup" => alloc::vec![
            data_field(
                "label",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Label for the option group"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether the group is disabled"
            ),
        ],
        "textarea" => alloc::vec![
            data_field(
                "name",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Name for form submission"
            ),
            data_field(
                "placeholder",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Placeholder text"
            ),
            data_field("rows", I32, Some(D::I32(2)), "Number of visible text lines"),
            data_field(
                "cols",
                I32,
                Some(D::I32(20)),
                "Visible width in average character widths"
            ),
            data_field(
                "disabled",
                Bool,
                Some(D::Bool(false)),
                "Whether the textarea is disabled"
            ),
            data_field(
                "required",
                Bool,
                Some(D::Bool(false)),
                "Whether content is required"
            ),
            data_field(
                "readonly",
                Bool,
                Some(D::Bool(false)),
                "Whether the textarea is read-only"
            ),
            data_field(
                "maxlength",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Maximum number of characters"
            ),
        ],
        "fieldset" => alloc::vec![data_field(
            "disabled",
            Bool,
            Some(D::Bool(false)),
            "Whether all controls in the fieldset are disabled"
        ),],
        "output" => alloc::vec![
            data_field(
                "for",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "IDs of elements that contributed to the output"
            ),
            data_field(
                "name",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Name for form submission"
            ),
        ],
        "progress" => alloc::vec![
            data_field(
                "value",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Current progress value"
            ),
            data_field(
                "max",
                String,
                Some(D::String(AzString::from_const_str("1"))),
                "Maximum value"
            ),
        ],
        "meter" => alloc::vec![
            data_field(
                "value",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Current value"
            ),
            data_field(
                "min",
                String,
                Some(D::String(AzString::from_const_str("0"))),
                "Minimum value"
            ),
            data_field(
                "max",
                String,
                Some(D::String(AzString::from_const_str("1"))),
                "Maximum value"
            ),
            data_field(
                "low",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Low threshold"
            ),
            data_field(
                "high",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "High threshold"
            ),
            data_field(
                "optimum",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Optimum value"
            ),
        ],
        // Interactive
        "details" => alloc::vec![data_field(
            "open",
            Bool,
            Some(D::Bool(false)),
            "Whether the details are visible"
        ),],
        "dialog" => alloc::vec![data_field(
            "open",
            Bool,
            Some(D::Bool(false)),
            "Whether the dialog is active and can be interacted with"
        ),],
        // Embedded content
        "audio" | "video" => alloc::vec![
            data_field(
                "src",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL of the media resource"
            ),
            data_field(
                "controls",
                Bool,
                Some(D::Bool(false)),
                "Whether to show playback controls"
            ),
            data_field(
                "autoplay",
                Bool,
                Some(D::Bool(false)),
                "Whether to start playing automatically"
            ),
            data_field(
                "loop",
                Bool,
                Some(D::Bool(false)),
                "Whether to loop playback"
            ),
            data_field(
                "muted",
                Bool,
                Some(D::Bool(false)),
                "Whether audio is muted"
            ),
            data_field(
                "preload",
                String,
                Some(D::String(AzString::from_const_str("auto"))),
                "Preload hint (none, metadata, auto)"
            ),
        ],
        "source" => alloc::vec![
            data_field("src", String, None, "URL of the media resource"),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "MIME type of the resource"
            ),
        ],
        "track" => alloc::vec![
            data_field("src", String, None, "URL of the track file"),
            data_field(
                "kind",
                String,
                Some(D::String(AzString::from_const_str("subtitles"))),
                "Kind of text track (subtitles, captions, descriptions, chapters, metadata)"
            ),
            data_field(
                "srclang",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Language of the track text"
            ),
            data_field(
                "label",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "User-readable title for the track"
            ),
            data_field(
                "default",
                Bool,
                Some(D::Bool(false)),
                "Whether this is the default track"
            ),
        ],
        "canvas" => alloc::vec![
            data_field(
                "width",
                String,
                Some(D::String(AzString::from_const_str("300"))),
                "Width of the canvas in pixels"
            ),
            data_field(
                "height",
                String,
                Some(D::String(AzString::from_const_str("150"))),
                "Height of the canvas in pixels"
            ),
        ],
        "embed" => alloc::vec![
            data_field("src", String, None, "URL of the resource to embed"),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "MIME type of the embedded content"
            ),
            data_field(
                "width",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Width"
            ),
            data_field(
                "height",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Height"
            ),
        ],
        "object" => alloc::vec![
            data_field(
                "data",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL of the resource"
            ),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "MIME type of the resource"
            ),
            data_field(
                "width",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Width"
            ),
            data_field(
                "height",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Height"
            ),
        ],
        "param" => alloc::vec![
            data_field("name", String, None, "Name of the parameter"),
            data_field(
                "value",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Value of the parameter"
            ),
        ],
        "area" => alloc::vec![
            data_field(
                "shape",
                String,
                Some(D::String(AzString::from_const_str("default"))),
                "Shape of the area (default, rect, circle, poly)"
            ),
            data_field(
                "coords",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Coordinates of the area"
            ),
            data_field(
                "href",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL for the area link"
            ),
            data_field(
                "alt",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Alternative text"
            ),
            data_field(
                "target",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Where to open the linked document"
            ),
        ],
        "map" => alloc::vec![data_field(
            "name",
            String,
            None,
            "Name of the image map (referenced by usemap)"
        ),],
        // Inline semantics with special attributes
        "time" => alloc::vec![data_field(
            "datetime",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "Machine-readable date/time value"
        ),],
        "data" => alloc::vec![data_field(
            "value",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "Machine-readable value"
        ),],
        "abbr" | "acronym" | "dfn" => alloc::vec![data_field(
            "title",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "Full expansion or definition"
        ),],
        "q" | "blockquote" => alloc::vec![data_field(
            "cite",
            String,
            Some(D::String(AzString::from_const_str(""))),
            "URL of the source of the quotation"
        ),],
        "del" | "ins" => alloc::vec![
            data_field(
                "cite",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL explaining the change"
            ),
            data_field(
                "datetime",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Date/time of the change"
            ),
        ],
        "bdo" => alloc::vec![data_field(
            "dir",
            String,
            Some(D::String(AzString::from_const_str("ltr"))),
            "Text direction (ltr, rtl)"
        ),],
        "col" | "colgroup" => alloc::vec![data_field(
            "span",
            I32,
            Some(D::I32(1)),
            "Number of columns the element spans"
        ),],
        // Metadata
        "meta" => alloc::vec![
            data_field(
                "name",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Metadata name"
            ),
            data_field(
                "content",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Metadata value"
            ),
            data_field(
                "charset",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Character encoding"
            ),
            data_field(
                "http-equiv",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "HTTP header equivalent"
            ),
        ],
        "link" => alloc::vec![
            data_field("rel", String, None, "Relationship type"),
            data_field(
                "href",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL of the linked resource"
            ),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "MIME type of the linked resource"
            ),
        ],
        "script" => alloc::vec![
            data_field(
                "src",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "URL of external script"
            ),
            data_field(
                "type",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "MIME type or module"
            ),
            data_field(
                "async",
                Bool,
                Some(D::Bool(false)),
                "Execute asynchronously"
            ),
            data_field(
                "defer",
                Bool,
                Some(D::Bool(false)),
                "Defer execution until page load"
            ),
        ],
        "style" => alloc::vec![data_field(
            "type",
            String,
            Some(D::String(AzString::from_const_str("text/css"))),
            "MIME type of the style sheet"
        ),],
        "base" => alloc::vec![
            data_field(
                "href",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Base URL for relative URLs"
            ),
            data_field(
                "target",
                String,
                Some(D::String(AzString::from_const_str(""))),
                "Default target for hyperlinks"
            ),
        ],
        _ => alloc::vec![],
    }
}

impl Default for ComponentMap {
    /// Returns an empty `ComponentMap` with no libraries.
    ///
    /// Use `AppConfig::create()` (which registers the 52 builtins via
    /// `register_builtin_components`) followed by `ComponentMap::from_libraries()`
    /// to get a fully-populated map.
    fn default() -> Self {
        Self {
            libraries: ComponentLibraryVec::from_const_slice(&[]),
        }
    }
}

impl ComponentMap {
    #[must_use]
    pub fn create() -> Self {
        Self::default()
    }

    /// Create a `ComponentMap` with the 52 built-in HTML element components pre-registered.
    #[must_use]
    pub fn with_builtin() -> Self {
        Self {
            libraries: alloc::vec![register_builtin_components()].into(),
        }
    }

    /// Build a `ComponentMap` from the libraries stored in an `AppConfig`.
    ///
    /// The `component_libraries` field already contains builtins (registered in
    /// `AppConfig::create()`) plus any user-added libraries.  No merging needed —
    /// `add_component_library` / `add_component` handle insertion at registration time.
    #[must_use]
    pub fn from_libraries(libs: &ComponentLibraryVec) -> Self {
        Self {
            libraries: libs.clone(),
        }
    }
}

/// Convert XML attributes to a `ComponentDataModel` by cloning the component's
/// base data model and overriding field defaults with values from the XML attributes.
///
/// This is the bridge between the XML parsing layer (key-value string pairs)
/// and the typed component data model. For each field in the base model,
/// if a matching XML attribute exists, its string value is set as the new default.
///
/// # Arguments
/// * `base_model` - The component's data model template (from `ComponentDef::data_model`)
/// * `xml_attributes` - The XML node's attribute map
/// * `text_content` - Optional text content from child text nodes
///
/// # Returns
/// A cloned `ComponentDataModel` with overridden defaults
fn xml_attrs_to_data_model(
    base_model: &ComponentDataModel,
    xml_attributes: &XmlAttributeMap,
    text_content: Option<&str>,
) -> ComponentDataModel {
    let mut model = base_model.clone();

    // Override defaults from XML attributes
    let mut fields_vec = core::mem::replace(
        &mut model.fields,
        ComponentDataFieldVec::from_const_slice(&[]),
    )
    .into_library_owned_vec();

    for field in &mut fields_vec {
        if let Some(attr_value) = xml_attributes.get_key(field.name.as_str()) {
            // Override the default_value with the XML attribute's string value
            field.default_value = OptionComponentDefaultValue::Some(ComponentDefaultValue::String(
                attr_value.clone(),
            ));
        }
    }

    model.fields = ComponentDataFieldVec::from_vec(fields_vec);

    // Handle text content — set the "text" field if present
    if let Some(text) = text_content {
        let prepared = prepare_string(text);
        if !prepared.is_empty() {
            model = model.with_default(
                "text",
                ComponentDefaultValue::String(AzString::from(prepared.as_str())),
            );
        }
    }

    model
}

// ============================================================================
// Structural builtin components: if, for, map
// ============================================================================

/// `builtin:if` — conditional rendering.
/// Takes `condition: Bool`, `then: StyledDom`, and optionally `else: StyledDom`.
fn builtin_if_component() -> ComponentDef {
    ComponentDef {
        id: ComponentId::builtin("if"),
        display_name: AzString::from_const_str("If"),
        description: AzString::from_const_str("Conditional rendering: shows 'then' if condition is true, else shows 'else' (if provided)."),
        css: AzString::from_const_str(""),
        source: ComponentSource::Builtin,
        data_model: ComponentDataModel {
            name: AzString::from_const_str("IfData"),
            description: AzString::from_const_str("Data for conditional rendering"),
            fields: alloc::vec![
                data_field("condition", ComponentFieldType::Bool, Some(ComponentDefaultValue::Bool(false)), "The boolean condition to evaluate"),
            ].into(),
        },
        render_fn: builtin_if_render_fn,
        compile_fn: builtin_if_compile_fn,
        render_fn_source: None.into(),
        compile_fn_source: None.into(),
    }
}

fn builtin_if_render_fn(
    _comp: &ComponentDef,
    data_model: &ComponentDataModel,
    _component_map: &ComponentMap,
) -> ResultStyledDomRenderDomError {
    // Evaluate the condition field
    let condition = data_model
        .fields
        .iter()
        .find(|f| f.name.as_str() == "condition")
        .and_then(|f| match &f.default_value {
            OptionComponentDefaultValue::Some(ComponentDefaultValue::Bool(b)) => Some(*b),
            _ => None,
        })
        .unwrap_or(false);

    let label = if condition {
        "if: true (then branch)"
    } else {
        "if: false (else branch)"
    };
    let mut dom = Dom::create_node(NodeType::Div).with_children(
        alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
            label
        )]
        .into(),
    );
    let css = Css::empty();
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
}

fn builtin_if_compile_fn(
    _comp: &ComponentDef,
    target: &CompileTarget,
    _data: &ComponentDataModel,
    _indent: usize,
) -> ResultStringCompileError {
    match target {
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
            "if data.condition {\n    // then branch\n    Dom::create_div()\n} else {\n    // else branch\n    Dom::create_div()\n}"
        )),
        CompileTarget::C => ResultStringCompileError::Ok(AzString::from(
            "if (data.condition) {\n    // then branch\n    AzDom_createDiv();\n} else {\n    // else branch\n    AzDom_createDiv();\n}"
        )),
        CompileTarget::Cpp => ResultStringCompileError::Ok(AzString::from(
            "if (data.condition) {\n    // then branch\n    Dom::create_div();\n} else {\n    // else branch\n    Dom::create_div();\n}"
        )),
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
            "if data.condition:\n    # then branch\n    Dom.create_div()\nelse:\n    # else branch\n    Dom.create_div()"
        )),
    }
}

/// `builtin:for` — iterative rendering.
/// Takes `count: U32` (number of iterations), renders children N times.
fn builtin_for_component() -> ComponentDef {
    ComponentDef {
        id: ComponentId::builtin("for"),
        display_name: AzString::from_const_str("For Loop"),
        description: AzString::from_const_str(
            "Iterative rendering: repeats children 'count' times.",
        ),
        css: AzString::from_const_str(""),
        source: ComponentSource::Builtin,
        data_model: ComponentDataModel {
            name: AzString::from_const_str("ForData"),
            description: AzString::from_const_str("Data for iterative rendering"),
            fields: alloc::vec![data_field(
                "count",
                ComponentFieldType::U32,
                Some(ComponentDefaultValue::U32(3)),
                "Number of iterations"
            ),]
            .into(),
        },
        render_fn: builtin_for_render_fn,
        compile_fn: builtin_for_compile_fn,
        render_fn_source: None.into(),
        compile_fn_source: None.into(),
    }
}

fn builtin_for_render_fn(
    _comp: &ComponentDef,
    data_model: &ComponentDataModel,
    _component_map: &ComponentMap,
) -> ResultStyledDomRenderDomError {
    let count = data_model
        .fields
        .iter()
        .find(|f| f.name.as_str() == "count")
        .and_then(|f| match &f.default_value {
            OptionComponentDefaultValue::Some(ComponentDefaultValue::U32(n)) => Some(*n),
            _ => None,
        })
        .unwrap_or(3);

    let mut items: Vec<Dom> = Vec::new();
    for i in 0..count {
        items.push(
            Dom::create_node(NodeType::Div).with_children(
                alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
                    alloc::format!("Item {i}")
                )]
                .into(),
            ),
        );
    }
    let mut dom = Dom::create_node(NodeType::Div).with_children(items.into());
    let css = Css::empty();
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
}

fn builtin_for_compile_fn(
    _comp: &ComponentDef,
    target: &CompileTarget,
    _data: &ComponentDataModel,
    _indent: usize,
) -> ResultStringCompileError {
    match target {
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
            "let mut children = Vec::new();\nfor i in 0..data.count {\n    children.push(Dom::create_div());\n}\nDom::create_div().with_children(children)"
        )),
        CompileTarget::C => ResultStringCompileError::Ok(AzString::from(
            "AzDom container = AzDom_createDiv();\nfor (uint32_t i = 0; i < data.count; i++) {\n    AzDom_addChild(&container, AzDom_createDiv());\n}"
        )),
        CompileTarget::Cpp => ResultStringCompileError::Ok(AzString::from(
            "auto container = Dom::create_div();\nfor (uint32_t i = 0; i < data.count; i++) {\n    container.add_child(Dom::create_div());\n}"
        )),
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
            "container = Dom.create_div()\nfor i in range(data.count):\n    container = container.with_child(Dom.create_div())"
        )),
    }
}

/// `builtin:map` — map data to DOM.
/// Takes `data_json: String` (JSON array) + maps each element.
fn builtin_map_component() -> ComponentDef {
    ComponentDef {
        id: ComponentId::builtin("map"),
        display_name: AzString::from_const_str("Map"),
        description: AzString::from_const_str(
            "Map data to DOM: applies a template to each item in a collection.",
        ),
        css: AzString::from_const_str(""),
        source: ComponentSource::Builtin,
        data_model: ComponentDataModel {
            name: AzString::from_const_str("MapData"),
            description: AzString::from_const_str("Data for map rendering"),
            fields: alloc::vec![data_field(
                "data_json",
                ComponentFieldType::String,
                Some(ComponentDefaultValue::String(AzString::from_const_str(
                    "[]"
                ))),
                "JSON array of items to map over"
            ),]
            .into(),
        },
        render_fn: builtin_map_render_fn,
        compile_fn: builtin_map_compile_fn,
        render_fn_source: None.into(),
        compile_fn_source: None.into(),
    }
}

fn builtin_map_render_fn(
    _comp: &ComponentDef,
    data_model: &ComponentDataModel,
    _component_map: &ComponentMap,
) -> ResultStyledDomRenderDomError {
    // For now, render a placeholder — actual mapping requires callback support
    let data_str = data_model
        .fields
        .iter()
        .find(|f| f.name.as_str() == "data_json")
        .and_then(|f| match &f.default_value {
            OptionComponentDefaultValue::Some(ComponentDefaultValue::String(s)) => {
                Some(s.as_str().to_string())
            }
            _ => None,
        })
        .unwrap_or_else(|| "[]".to_string());

    let label = alloc::format!("map: data_json={data_str}");
    let mut dom = Dom::create_node(NodeType::Div).with_children(
        alloc::vec![Dom::create_text_do_not_use_without_block_level_wrapper(
            label
        )]
        .into(),
    );
    let css = Css::empty();
    ResultStyledDomRenderDomError::Ok(StyledDom::create(&mut dom, css))
}

fn builtin_map_compile_fn(
    _comp: &ComponentDef,
    target: &CompileTarget,
    _data: &ComponentDataModel,
    _indent: usize,
) -> ResultStringCompileError {
    match target {
        CompileTarget::Rust => ResultStringCompileError::Ok(AzString::from(
            "let items: Vec<serde_json::Value> = serde_json::from_str(&data.data_json).unwrap_or_default();\nlet children: Vec<Dom> = items.iter().map(|item| {\n    Dom::create_div() // map template\n}).collect();\nDom::create_div().with_children(children)"
        )),
        CompileTarget::C => ResultStringCompileError::Ok(AzString::from(
            "// Parse data.data_json and map each item\nAzDom container = AzDom_createDiv();\n// TODO: iterate parsed JSON array"
        )),
        CompileTarget::Cpp => ResultStringCompileError::Ok(AzString::from(
            "// Parse data.data_json and map each item\nauto container = Dom::create_div();\n// TODO: iterate parsed JSON array"
        )),
        CompileTarget::Python => ResultStringCompileError::Ok(AzString::from(
            "import json\nitems = json.loads(data.data_json)\ncontainer = Dom.create_div()\nfor item in items:\n    container = container.with_child(Dom.create_div())"
        )),
    }
}

/// Register the 52 built-in HTML element components.
///
/// This is an `extern "C"` function pointer compatible with
/// `RegisterComponentLibraryFnType`, so it can be passed directly to
/// `AppConfig::add_component_library()`.
///
/// Called once during `AppConfig::create()` — the framework dogfoods
/// its own component registration system for builtins.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
#[must_use]
pub extern "C" fn register_builtin_components() -> ComponentLibrary {
    ComponentLibrary {
        name: AzString::from_const_str("builtin"),
        version: AzString::from_const_str("1.0.0"),
        description: AzString::from_const_str("Built-in HTML elements"),
        exportable: false,
        modifiable: false,
        data_models: Vec::new().into(),
        enum_models: Vec::new().into(),
        components: alloc::vec![
            // Structural
            builtin_component_def("html", "HTML", None, ""),
            builtin_component_def("head", "Head", None, ""),
            builtin_component_def("title", "Title", Some(""), ""),
            builtin_component_def("body", "Body", None, ""),
            // Block-level
            builtin_component_def("div", "Div", None, ""),
            builtin_component_def("header", "Header", None, ""),
            builtin_component_def("footer", "Footer", None, ""),
            builtin_component_def("section", "Section", None, ""),
            builtin_component_def("article", "Article", None, ""),
            builtin_component_def("aside", "Aside", None, ""),
            builtin_component_def("nav", "Nav", None, ""),
            builtin_component_def("main", "Main", None, ""),
            builtin_component_def("figure", "Figure", None, ""),
            builtin_component_def("figcaption", "Figure Caption", Some(""), ""),
            builtin_component_def("address", "Address", Some(""), ""),
            builtin_component_def("details", "Details", None, ""),
            builtin_component_def("summary", "Summary", Some("Details"), ""),
            builtin_component_def("dialog", "Dialog", None, ""),
            // Headings — default text is the heading level name so preview is visible
            builtin_component_def("h1", "Heading 1", Some("Heading 1"), ""),
            builtin_component_def("h2", "Heading 2", Some("Heading 2"), ""),
            builtin_component_def("h3", "Heading 3", Some("Heading 3"), ""),
            builtin_component_def("h4", "Heading 4", Some("Heading 4"), ""),
            builtin_component_def("h5", "Heading 5", Some("Heading 5"), ""),
            builtin_component_def("h6", "Heading 6", Some("Heading 6"), ""),
            // Text content
            builtin_component_def("p", "Paragraph", Some("Paragraph text"), ""),
            builtin_component_def("span", "Span", Some(""), ""),
            builtin_component_def("pre", "Preformatted", Some(""), ""),
            builtin_component_def("code", "Code", Some(""), ""),
            builtin_component_def("blockquote", "Blockquote", Some(""), ""),
            builtin_component_def("br", "Line Break", None, ""),
            builtin_component_def("hr", "Horizontal Rule", None, ""),
            builtin_component_def("pagebreak", "Page Break", None, ""),
            builtin_component_def("icon", "Icon", Some(""), ""),
            // Lists
            builtin_component_def("ul", "Unordered List", None, ""),
            builtin_component_def("ol", "Ordered List", None, ""),
            builtin_component_def("li", "List Item", Some("List item"), ""),
            builtin_component_def("dl", "Description List", None, ""),
            builtin_component_def("dt", "Description Term", Some(""), ""),
            builtin_component_def("dd", "Description Details", Some(""), ""),
            builtin_component_def("menu", "Menu", None, ""),
            builtin_component_def("menuitem", "Menu Item", Some(""), ""),
            builtin_component_def("dir", "Directory List", None, ""),
            // Tables
            builtin_component_def("table", "Table", None, ""),
            builtin_component_def("caption", "Table Caption", Some(""), ""),
            builtin_component_def("thead", "Table Head", None, ""),
            builtin_component_def("tbody", "Table Body", None, ""),
            builtin_component_def("tfoot", "Table Foot", None, ""),
            builtin_component_def("tr", "Table Row", None, ""),
            builtin_component_def("th", "Table Header Cell", Some("Header"), ""),
            builtin_component_def("td", "Table Data Cell", Some(""), ""),
            builtin_component_def("colgroup", "Column Group", None, ""),
            builtin_component_def("col", "Column", None, ""),
            // Inline
            builtin_component_def("a", "Link", Some("Link text"), ""),
            builtin_component_def("strong", "Strong", Some(""), ""),
            builtin_component_def("em", "Emphasis", Some(""), ""),
            builtin_component_def("b", "Bold", Some(""), ""),
            builtin_component_def("i", "Italic", Some(""), ""),
            builtin_component_def("u", "Underline", Some(""), ""),
            builtin_component_def("s", "Strikethrough", Some(""), ""),
            builtin_component_def("small", "Small", Some(""), ""),
            builtin_component_def("mark", "Mark", Some(""), ""),
            builtin_component_def("del", "Deleted Text", Some(""), ""),
            builtin_component_def("ins", "Inserted Text", Some(""), ""),
            builtin_component_def("sub", "Subscript", Some(""), ""),
            builtin_component_def("sup", "Superscript", Some(""), ""),
            builtin_component_def("samp", "Sample Output", Some(""), ""),
            builtin_component_def("kbd", "Keyboard Input", Some(""), ""),
            builtin_component_def("var", "Variable", Some(""), ""),
            builtin_component_def("cite", "Citation", Some(""), ""),
            builtin_component_def("dfn", "Definition", Some(""), ""),
            builtin_component_def("abbr", "Abbreviation", Some(""), ""),
            builtin_component_def("acronym", "Acronym", Some(""), ""),
            builtin_component_def("q", "Inline Quote", Some(""), ""),
            builtin_component_def("time", "Time", Some(""), ""),
            builtin_component_def("big", "Big", Some(""), ""),
            builtin_component_def("bdo", "BiDi Override", Some(""), ""),
            builtin_component_def("bdi", "BiDi Isolate", Some(""), ""),
            builtin_component_def("wbr", "Word Break Opportunity", None, ""),
            builtin_component_def("ruby", "Ruby Annotation", None, ""),
            builtin_component_def("rt", "Ruby Text", Some(""), ""),
            builtin_component_def("rtc", "Ruby Text Container", None, ""),
            builtin_component_def("rp", "Ruby Parenthesis", Some(""), ""),
            builtin_component_def("data", "Data", Some(""), ""),
            // Forms
            builtin_component_def("form", "Form", None, ""),
            builtin_component_def("fieldset", "Field Set", None, ""),
            builtin_component_def("legend", "Legend", Some("Legend"), ""),
            builtin_component_def("label", "Label", Some("Label"), ""),
            builtin_component_def("input", "Input", None, ""),
            builtin_component_def("button", "Button", Some("Button text"), ""),
            builtin_component_def("select", "Select", None, ""),
            builtin_component_def("optgroup", "Option Group", None, ""),
            builtin_component_def("option", "Option", Some(""), ""),
            builtin_component_def("textarea", "Text Area", Some(""), ""),
            builtin_component_def("output", "Output", Some(""), ""),
            builtin_component_def("progress", "Progress", None, ""),
            builtin_component_def("meter", "Meter", None, ""),
            builtin_component_def("datalist", "Data List", None, ""),
            // Embedded content
            builtin_component_def("canvas", "Canvas", None, ""),
            builtin_component_def("object", "Object", None, ""),
            builtin_component_def("param", "Parameter", None, ""),
            builtin_component_def("embed", "Embed", None, ""),
            builtin_component_def("audio", "Audio", None, ""),
            builtin_component_def("video", "Video", None, ""),
            builtin_component_def("source", "Source", None, ""),
            builtin_component_def("track", "Track", None, ""),
            builtin_component_def("map", "Image Map", None, ""),
            builtin_component_def("area", "Map Area", None, ""),
            builtin_component_def("svg", "SVG", None, ""),
            // Metadata
            builtin_component_def("meta", "Meta", None, ""),
            builtin_component_def("link", "Link (Resource)", None, ""),
            builtin_component_def("script", "Script", Some(""), ""),
            builtin_component_def("style", "Style", Some(""), ""),
            builtin_component_def("base", "Base URL", None, ""),
            // Structural control-flow builtins (F1-F3)
            builtin_if_component(),
            builtin_for_component(),
            builtin_map_component(),
        ]
        .into(),
    }
}

// ============================================================================
// End new component system types
// ============================================================================

/// Wrapper for the XML parser - necessary to easily create a Dom from
/// XML without putting an XML solver into `azul-core`.
#[derive(Debug, Default)]
pub struct DomXml {
    pub parsed_dom: StyledDom,
}

impl DomXml {
    /// Convenience function, only available in tests, useful for quickly writing UI tests.
    /// Wraps the XML string in the required `<app></app>` braces, panics if the XML couldn't be
    /// parsed.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// # use azul::dom::Dom;
    /// # use azul::xml::DomXml;
    /// let dom = DomXml::mock("<div id='test' />");
    /// dom.assert_eq(Dom::create_div().with_id("test"));
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the rendered DOM does not equal `other` (this is a test-only
    /// assertion helper).
    #[cfg(test)]
    pub fn assert_eq(self, other: StyledDom) {
        let mut body = Dom::create_body();
        let mut fixed = StyledDom::create(&mut body, Css::empty());
        fixed.append_child(other);
        assert!(
            !(self.parsed_dom != fixed),
            "\r\nExpected DOM did not match:\r\n\r\nexpected: ----------\r\n{}\r\ngot: \
                 ----------\r\n{}\r\n",
            self.parsed_dom.get_html_string("", "", true),
            fixed.get_html_string("", "", true)
        );
    }

    #[must_use]
    pub fn into_styled_dom(self) -> StyledDom {
        self.into()
    }
}

impl From<DomXml> for StyledDom {
    fn from(val: DomXml) -> Self {
        val.parsed_dom
    }
}

/// Represents a child of an XML node - either an element or text
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum XmlNodeChild {
    /// A text node
    Text(AzString),
    /// An element node
    Element(XmlNode),
}

impl_option!(
    XmlNodeChild,
    OptionXmlNodeChild,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl XmlNodeChild {
    /// Get the text content if this is a text node
    #[must_use]
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(s) => Some(s.as_str()),
            Self::Element(_) => None,
        }
    }

    /// Get the element if this is an element node
    #[must_use]
    pub const fn as_element(&self) -> Option<&XmlNode> {
        match self {
            Self::Text(_) => None,
            Self::Element(node) => Some(node),
        }
    }

    /// Get the element mutably if this is an element node
    pub const fn as_element_mut(&mut self) -> Option<&mut XmlNode> {
        match self {
            Self::Text(_) => None,
            Self::Element(node) => Some(node),
        }
    }
}

impl_vec!(
    XmlNodeChild,
    XmlNodeChildVec,
    XmlNodeChildVecDestructor,
    XmlNodeChildVecDestructorType,
    XmlNodeChildVecSlice,
    OptionXmlNodeChild
);
impl_vec_mut!(XmlNodeChild, XmlNodeChildVec);
impl_vec_debug!(XmlNodeChild, XmlNodeChildVec);
impl_vec_partialeq!(XmlNodeChild, XmlNodeChildVec);
impl_vec_eq!(XmlNodeChild, XmlNodeChildVec);
impl_vec_partialord!(XmlNodeChild, XmlNodeChildVec);
impl_vec_ord!(XmlNodeChild, XmlNodeChildVec);
impl_vec_hash!(XmlNodeChild, XmlNodeChildVec);
impl_vec_clone!(XmlNodeChild, XmlNodeChildVec, XmlNodeChildVecDestructor);

/// Represents one XML node tag
#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct XmlNode {
    /// Type of the node
    pub node_type: XmlTagName,
    /// Attributes of an XML node (note: not yet filtered and / or broken into function arguments!)
    pub attributes: XmlAttributeMap,
    /// Direct children of this node (can be text or element nodes)
    pub children: XmlNodeChildVec,
}

impl_option!(
    XmlNode,
    OptionXmlNode,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl XmlNode {
    pub fn create<I: Into<XmlTagName>>(node_type: I) -> Self {
        Self {
            node_type: node_type.into(),
            ..Default::default()
        }
    }
    #[must_use]
    pub fn with_children(mut self, v: Vec<XmlNodeChild>) -> Self {
        Self {
            children: v.into(),
            ..self
        }
    }

    /// Get all text content concatenated from direct children
    #[must_use]
    pub fn get_text_content(&self) -> String {
        self.children
            .as_ref()
            .iter()
            .filter_map(|child| child.as_text())
            .collect::<Vec<_>>()
            .join("")
    }

    /// Check if this node has only text children (no element children)
    #[must_use]
    pub fn has_only_text_children(&self) -> bool {
        self.children
            .as_ref()
            .iter()
            .all(|child| matches!(child, XmlNodeChild::Text(_)))
    }
}

impl_vec!(
    XmlNode,
    XmlNodeVec,
    XmlNodeVecDestructor,
    XmlNodeVecDestructorType,
    XmlNodeVecSlice,
    OptionXmlNode
);
impl_vec_mut!(XmlNode, XmlNodeVec);
impl_vec_debug!(XmlNode, XmlNodeVec);
impl_vec_partialeq!(XmlNode, XmlNodeVec);
impl_vec_eq!(XmlNode, XmlNodeVec);
impl_vec_partialord!(XmlNode, XmlNodeVec);
impl_vec_ord!(XmlNode, XmlNodeVec);
impl_vec_hash!(XmlNode, XmlNodeVec);
impl_vec_clone!(XmlNode, XmlNodeVec, XmlNodeVecDestructor);

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum DomXmlParseError {
    /// No `<html></html>` node component present
    NoHtmlNode,
    /// Multiple `<html>` nodes
    MultipleHtmlRootNodes,
    /// No ´<body></body>´ node in the root HTML
    NoBodyInHtml,
    /// The DOM can only have one <body> node, not multiple.
    MultipleBodyNodes,
    /// Note: Sadly, the error type can only be a string because xmlparser
    /// returns all errors as strings. There is an open PR to fix
    /// this deficiency, but since the XML parsing is only needed for
    /// hot-reloading and compiling, it doesn't matter that much.
    Xml(XmlError),
    /// Invalid hierarchy close tags, i.e `<app></p></app>`
    MalformedHierarchy(MalformedHierarchyError),
    /// A component raised an error while rendering the DOM - holds the component name + error
    /// string
    RenderDom(RenderDomError),
    /// Something went wrong while parsing an XML component
    Component(ComponentParseError),
    /// Error parsing global CSS in head node
    Css(CssParseErrorOwned),
}

impl From<XmlError> for DomXmlParseError {
    fn from(e: XmlError) -> Self {
        Self::Xml(e)
    }
}

impl From<ComponentParseError> for DomXmlParseError {
    fn from(e: ComponentParseError) -> Self {
        Self::Component(e)
    }
}

impl From<RenderDomError> for DomXmlParseError {
    fn from(e: RenderDomError) -> Self {
        Self::RenderDom(e)
    }
}

impl From<CssParseErrorOwned> for DomXmlParseError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::Css(e)
    }
}

/// Error that can happen from the translation from XML code to Rust code -
/// stringified, since it is only used for printing and is not exposed in the public API
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum CompileError {
    Dom(RenderDomError),
    Xml(DomXmlParseError),
    Css(CssParseErrorOwned),
}

impl From<ComponentError> for CompileError {
    fn from(e: ComponentError) -> Self {
        Self::Dom(RenderDomError::Component(e))
    }
}

impl From<CssParseErrorOwned> for CompileError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::Css(e)
    }
}

impl fmt::Display for CompileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::CompileError::{Css, Dom, Xml};
        match self {
            Dom(d) => write!(f, "{d}"),
            Xml(s) => write!(f, "{s}"),
            Css(s) => write!(f, "{}", s.to_shared()),
        }
    }
}

impl From<RenderDomError> for CompileError {
    fn from(e: RenderDomError) -> Self {
        Self::Dom(e)
    }
}

impl From<DomXmlParseError> for CompileError {
    fn from(e: DomXmlParseError) -> Self {
        Self::Xml(e)
    }
}

/// Wrapper for `UselessFunctionArgument` error data.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct UselessFunctionArgumentError {
    pub component_name: AzString,
    pub argument_name: AzString,
    pub valid_args: StringVec,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum ComponentError {
    /// While instantiating a component, a function argument
    /// was encountered that the component won't use or react to.
    UselessFunctionArgument(UselessFunctionArgumentError),
    /// A certain node type can't be rendered, because the
    /// renderer for this node is not available isn't available
    ///
    /// `UnknownComponent(component_name)`
    UnknownComponent(AzString),
}

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum RenderDomError {
    Component(ComponentError),
    /// Error parsing the CSS on the component style
    CssError(CssParseErrorOwned),
}

impl From<ComponentError> for RenderDomError {
    fn from(e: ComponentError) -> Self {
        Self::Component(e)
    }
}

impl From<CssParseErrorOwned> for RenderDomError {
    fn from(e: CssParseErrorOwned) -> Self {
        Self::CssError(e)
    }
}

/// Wrapper for `MissingType` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct MissingTypeError {
    pub arg_pos: usize,
    pub arg_name: AzString,
}

/// Wrapper for `WhiteSpaceInComponentName` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct WhiteSpaceInComponentNameError {
    pub arg_pos: usize,
    pub arg_name: AzString,
}

/// Wrapper for `WhiteSpaceInComponentType` error data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct WhiteSpaceInComponentTypeError {
    pub arg_pos: usize,
    pub arg_name: AzString,
    pub arg_type: AzString,
}

#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum ComponentParseError {
    /// Given `XmlNode` is not a `<component />` node.
    NotAComponent,
    /// A `<component>` node does not have a `name` attribute.
    UnnamedComponent,
    /// Argument at position `usize` is either empty or has no name
    MissingName(usize),
    /// Argument at position `usize` with the name
    /// `String` doesn't have a `: type`
    MissingType(MissingTypeError),
    /// Component name may not contain a whitespace
    /// (probably missing a `:` between the name and the type)
    WhiteSpaceInComponentName(WhiteSpaceInComponentNameError),
    /// Component type may not contain a whitespace
    /// (probably missing a `,` between the type and the next name)
    WhiteSpaceInComponentType(WhiteSpaceInComponentTypeError),
    /// Error parsing the <style> tag / CSS
    CssError(CssParseErrorOwned),
}

impl fmt::Display for DomXmlParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::DomXmlParseError::{
            Component, Css, MalformedHierarchy, MultipleBodyNodes, MultipleHtmlRootNodes,
            NoBodyInHtml, NoHtmlNode, RenderDom, Xml,
        };
        match self {
            NoHtmlNode => write!(
                f,
                "No <html> node found as the root of the file - empty file?"
            ),
            MultipleHtmlRootNodes => write!(
                f,
                "Multiple <html> nodes found as the root of the file - only one root node allowed"
            ),
            NoBodyInHtml => write!(
                f,
                "No <body> node found as a direct child of an <html> node - malformed DOM \
                 hierarchy?"
            ),
            MultipleBodyNodes => write!(
                f,
                "Multiple <body> nodes present, only one <body> node is allowed"
            ),
            Xml(e) => write!(f, "Error parsing XML: {e}"),
            MalformedHierarchy(e) => write!(
                f,
                "Invalid </{}> tag: expected </{}>",
                e.got.as_str(),
                e.expected.as_str()
            ),
            RenderDom(e) => write!(f, "Error rendering DOM: {e}"),
            Component(c) => write!(f, "Error parsing component in <head> node:\r\n{c}"),
            Css(c) => write!(f, "Error parsing CSS in <head> node:\r\n{}", c.to_shared()),
        }
    }
}

impl fmt::Display for ComponentParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::ComponentParseError::{
            CssError, MissingName, MissingType, NotAComponent, UnnamedComponent,
            WhiteSpaceInComponentName, WhiteSpaceInComponentType,
        };
        match self {
            NotAComponent => write!(f, "Expected <component/> node, found no such node"),
            UnnamedComponent => write!(
                f,
                "Found <component/> tag with out a \"name\" attribute, component must have a name"
            ),
            MissingName(arg_pos) => write!(
                f,
                "Argument at position {arg_pos} is either empty or has no name"
            ),
            MissingType(e) => write!(
                f,
                "Argument \"{}\" at position {} doesn't have a `: type`",
                e.arg_name, e.arg_pos
            ),
            WhiteSpaceInComponentName(e) => {
                write!(
                    f,
                    "Missing `:` between the name and the type in argument {} (around \"{}\")",
                    e.arg_pos, e.arg_name
                )
            }
            WhiteSpaceInComponentType(e) => {
                write!(
                    f,
                    "Missing `,` between two arguments (in argument {}, position {}, around \
                     \"{}\")",
                    e.arg_name, e.arg_pos, e.arg_type
                )
            }
            CssError(lsf) => write!(f, "Error parsing <style> tag: {}", lsf.to_shared()),
        }
    }
}

impl fmt::Display for ComponentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::ComponentError::{UnknownComponent, UselessFunctionArgument};
        match self {
            UselessFunctionArgument(e) => {
                write!(
                    f,
                    "Useless component argument \"{}\": \"{}\" - available args are: {:#?}",
                    e.component_name, e.argument_name, e.valid_args
                )
            }
            UnknownComponent(name) => write!(f, "Unknown component: \"{name}\""),
        }
    }
}

impl fmt::Display for RenderDomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use self::RenderDomError::{Component, CssError};
        match self {
            Component(c) => write!(f, "{c}"),
            CssError(e) => write!(f, "Error parsing CSS in component: {}", e.to_shared()),
        }
    }
}

/// Find the one and only `<body>` node, return error if
/// there is no app node or there are multiple app nodes
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the document has no `<html>` root node.
/// Every `<head><style>` block's text, concatenated in document order.
///
/// ALL of them, not the first: a document may state its stylesheet in several
/// blocks (a reset, then the page's own rules), and browsers apply each in
/// turn. Reading only the first silently dropped everything after it - and it
/// is silent in the worst way, because the page still renders, just with some
/// rules missing and nothing to say which.
fn head_style_text(html_node: &XmlNode) -> String {
    let Some(head) = find_node_by_type(html_node.children.as_ref(), "head") else {
        return String::new();
    };
    let mut out = String::new();
    for child in head.children.as_ref() {
        let XmlNodeChild::Element(element) = child else {
            continue;
        };
        if !element.node_type.as_str().eq_ignore_ascii_case("style") {
            continue;
        }
        let text = element.get_text_content();
        if !text.is_empty() {
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(&text);
        }
    }
    out
}

pub fn get_html_node(
    root_nodes: &[XmlNodeChild],
) -> Result<alloc::borrow::Cow<'_, XmlNode>, DomXmlParseError> {
    use alloc::borrow::Cow;

    let mut html_node_iterator = root_nodes.iter().filter_map(|child| {
        if let XmlNodeChild::Element(node) = child {
            // HTML element names are case-insensitive (ASCII). NOT normalize_casing:
            // that inserts '_' before each uppercase letter for component-name
            // canonicalisation, so "HTML" would become "h_t_m_l" and never match.
            if node.node_type.as_str().eq_ignore_ascii_case("html") {
                Some(node)
            } else {
                None
            }
        } else {
            None
        }
    });

    if let Some(html_node) = html_node_iterator.next() {
        return if html_node_iterator.next().is_some() {
            Err(DomXmlParseError::MultipleHtmlRootNodes)
        } else {
            Ok(Cow::Borrowed(html_node))
        };
    }

    // NO <html> ROOT: synthesise one, the way a browser does.
    //
    // Requiring the wrapper made a perfectly good fragment - `<svg>…</svg>`,
    // `<div>hi</div>`, an icon file straight off the disk - parse into the
    // TEXT "No <html> node found as the root of the file", which then lays
    // out and paints like any other text. The failure was silent and looked
    // exactly like a rendering bug: a caller measuring pixels saw an error
    // message it never asked for and no sign of what happened.
    //
    // A root `<body>`/`<head>` is ADOPTED rather than nested (again like a
    // browser): wrapping `<body>` inside a fresh `<body>` would give the
    // document two, which is its own error.
    let has_structural_root = root_nodes.iter().any(|child| match child {
        XmlNodeChild::Element(node) => {
            let tag = node.node_type.as_str();
            tag.eq_ignore_ascii_case("body") || tag.eq_ignore_ascii_case("head")
        }
        XmlNodeChild::Text(_) => false,
    });
    if has_structural_root {
        return Ok(Cow::Owned(
            XmlNode::create("html").with_children(root_nodes.to_vec()),
        ));
    }

    // METADATA GOES TO THE HEAD, content to the body - the same split a
    // browser makes. A `<style>` left in the body is not looked at by
    // `str_to_dom_unstyled` (it reads `<head><style>`), so a fragment that
    // brought its own stylesheet would render unstyled and give no hint why.
    let (head_children, body_children): (Vec<_>, Vec<_>) =
        root_nodes.iter().cloned().partition(|child| match child {
            XmlNodeChild::Element(node) => {
                let tag = node.node_type.as_str();
                tag.eq_ignore_ascii_case("style")
                    || tag.eq_ignore_ascii_case("link")
                    || tag.eq_ignore_ascii_case("meta")
                    || tag.eq_ignore_ascii_case("title")
                    || tag.eq_ignore_ascii_case("base")
            }
            XmlNodeChild::Text(_) => false,
        });

    let mut html_children = Vec::new();
    if !head_children.is_empty() {
        html_children.push(XmlNodeChild::Element(
            XmlNode::create("head").with_children(head_children),
        ));
    }
    html_children.push(XmlNodeChild::Element(
        XmlNode::create("body").with_children(body_children),
    ));
    Ok(Cow::Owned(XmlNode::create("html").with_children(html_children)))
}

/// Find the one and only `<body>` node, return error if
/// there is no app node or there are multiple app nodes
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the document has no `<body>` node.
pub fn get_body_node(root_nodes: &[XmlNodeChild]) -> Result<&XmlNode, DomXmlParseError> {
    fn find_body_recursive(nodes: &[XmlNodeChild], depth: usize) -> Option<&XmlNode> {
        // AUDIT 2026-07-08: bound recursion depth to avoid a stack overflow on
        // pathologically deep markup while hunting for the <body> element.
        if depth > MAX_XML_NESTING_DEPTH {
            return None;
        }
        for child in nodes {
            if let XmlNodeChild::Element(node) = child {
                // case-insensitive ASCII tag match; see get_html_node.
                if node.node_type.as_str().eq_ignore_ascii_case("body") {
                    return Some(node);
                }
                // Recurse into children
                if let Some(found) = find_body_recursive(node.children.as_ref(), depth + 1) {
                    return Some(found);
                }
            }
        }
        None
    }

    // First try to find body as a direct child (proper HTML structure)
    let direct_body = root_nodes.iter().find_map(|child| {
        if let XmlNodeChild::Element(node) = child {
            // case-insensitive ASCII tag match; see get_html_node.
            if node.node_type.as_str().eq_ignore_ascii_case("body") {
                Some(node)
            } else {
                None
            }
        } else {
            None
        }
    });

    if let Some(body) = direct_body {
        return Ok(body);
    }

    // If not found as direct child, search recursively (for malformed HTML like example.com)
    // where <body> might be nested inside <head> due to missing </head> tag
    find_body_recursive(root_nodes, 0).ok_or(DomXmlParseError::NoBodyInHtml)
}

/// Searches in the the `root_nodes` for a `node_type`, convenience function in order to
/// for example find the first <blah /> node in all these nodes.
/// This function searches recursively through the entire tree.
fn find_node_by_type<'a>(root_nodes: &'a [XmlNodeChild], node_type: &str) -> Option<&'a XmlNode> {
    // First check direct children
    for child in root_nodes {
        if let XmlNodeChild::Element(node) = child {
            // case-insensitive ASCII tag match; see get_html_node.
            if node.node_type.as_str().eq_ignore_ascii_case(node_type) {
                return Some(node);
            }
        }
    }

    // If not found, search recursively (for malformed HTML)
    for child in root_nodes {
        if let XmlNodeChild::Element(node) = child {
            if let Some(found) = find_node_by_type(node.children.as_ref(), node_type) {
                return Some(found);
            }
        }
    }

    None
}

#[must_use]
pub fn find_attribute<'a>(node: &'a XmlNode, attribute: &str) -> Option<&'a AzString> {
    node.attributes
        .iter()
        .find(|n| normalize_casing(n.key.as_str()).as_str() == attribute)
        .map(|s| &s.value)
}

/// Normalizes input such as `abcDef`, `AbcDef`, `abc-def` to the normalized form of `abc_def`
#[must_use]
pub fn normalize_casing(input: &str) -> String {
    let mut words: Vec<String> = Vec::new();
    let mut cur_str = Vec::new();

    for ch in input.chars() {
        if ch.is_uppercase() || ch == '_' || ch == '-' {
            if !cur_str.is_empty() {
                words.push(cur_str.iter().collect());
                cur_str.clear();
            }
            if ch.is_uppercase() {
                cur_str.extend(ch.to_lowercase());
            }
        } else {
            cur_str.extend(ch.to_lowercase());
        }
    }

    if !cur_str.is_empty() {
        words.push(cur_str.iter().collect());
        cur_str.clear();
    }

    words.join("_")
}

/// Given a root node, traverses along the hierarchy, and returns a
/// mutable reference to the last child node of the root node
#[allow(trivial_casts)]
pub fn get_item<'a>(hierarchy: &[usize], root_node: &'a mut XmlNode) -> Option<&'a mut XmlNode> {
    let mut hierarchy = hierarchy.to_vec();
    hierarchy.reverse();
    let Some(item) = hierarchy.pop() else {
        return Some(root_node);
    };
    let child = root_node.children.as_mut().get_mut(item)?;
    match child {
        XmlNodeChild::Element(node) => get_item_internal(&mut hierarchy, node),
        XmlNodeChild::Text(_) => None, // Can't traverse into text nodes
    }
}

fn get_item_internal<'a>(
    hierarchy: &mut Vec<usize>,
    root_node: &'a mut XmlNode,
) -> Option<&'a mut XmlNode> {
    if hierarchy.is_empty() {
        return Some(root_node);
    }
    let Some(cur_item) = hierarchy.pop() else {
        return Some(root_node);
    };
    let child = root_node.children.as_mut().get_mut(cur_item)?;
    match child {
        XmlNodeChild::Element(node) => get_item_internal(hierarchy, node),
        XmlNodeChild::Text(_) => None, // Can't traverse into text nodes
    }
}

/// Parses an XML string and returns a `StyledDom` with the components instantiated in the
/// `<app></app>`
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed into a DOM (malformed markup or an unknown component).
pub fn str_to_dom<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
    max_width: Option<f32>,
) -> Result<StyledDom, DomXmlParseError> {
    // Delegate to the fast path (Dom::Fast / CompactDom arena).
    str_to_dom_fast(root_nodes, component_map, max_width)
}

/// Parse XML to `StyledDom` via arena-based `FastDom` (no tree intermediary).
///
/// **Note**: `str_to_dom()` now delegates to this function, so you can use
/// either one. This function is kept for backward compatibility.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
fn str_to_dom_fast<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
    max_width: Option<f32>,
) -> Result<StyledDom, DomXmlParseError> {
    let html_node = get_html_node(root_nodes)?;
    let body_node = get_body_node(html_node.children.as_ref())?;

    let style_text = head_style_text(&html_node);
    let global_style = if style_text.is_empty() {
        None
    } else {
        Some(Css::from_string(style_text.into()))
    };

    render_dom_from_body_node_fast(body_node, global_style, component_map, max_width)
        .map_err(Into::into)
}

/// Parses XML nodes and returns a `Dom` with CSS stylesheets attached (but not applied).
///
/// Unlike `str_to_dom` which returns a fully styled `StyledDom`, this function
/// returns an unstyled `Dom` whose `css` field carries the parsed `<style>` rules.
/// The layout framework will apply the CSS during the cascade pass.
///
/// This is the correct function for building a `Dom` from XML in layout callbacks
/// (which must return `Dom`, not `StyledDom`).
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed into a DOM (malformed markup or an unknown component).
pub fn str_to_dom_unstyled<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
) -> Result<Dom, DomXmlParseError> {
    let html_node = get_html_node(root_nodes)?;
    let body_node = get_body_node(html_node.children.as_ref())?;

    let style_text = head_style_text(&html_node);
    let global_style = if style_text.is_empty() {
        None
    } else {
        Some(Css::from_string(style_text.into()))
    };

    // Build the DOM tree from the body node
    let body_dom =
        xml_node_to_dom_fast(body_node, component_map, false, 0).map_err(DomXmlParseError::from)?;

    // Wrap in proper HTML structure (NodeType is imported at module top)
    let root_node_type = body_dom.root.node_type.clone();

    let mut full_dom = match root_node_type {
        NodeType::Html => body_dom,
        NodeType::Body => Dom::create_html().with_child(body_dom),
        _ => {
            let body_wrapper = Dom::create_body().with_child(body_dom);
            Dom::create_html().with_child(body_wrapper)
        }
    };

    // Attach CSS to the Dom's css field instead of applying it immediately
    if let Some(css) = global_style {
        full_dom.css = alloc::vec![css].into();
    }

    Ok(full_dom)
}

/// Parses an XML string and returns a `String`, which contains the Rust source code
/// (i.e. it compiles the XML to valid Rust)
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to Rust code.
pub fn str_to_rust_code<'a>(
    root_nodes: &'a [XmlNodeChild],
    imports: &str,
    component_map: &'a ComponentMap,
) -> Result<String, CompileError> {
    let html_node = get_html_node(root_nodes)?;
    let body_node = get_body_node(html_node.children.as_ref())?;
    let style_text = head_style_text(&html_node);
    let mut global_style = if style_text.is_empty() {
        Css::empty()
    } else {
        azul_css::parser2::new_from_str(&style_text).0
    };

    global_style.sort_by_specificity();

    let mut css_blocks = BTreeMap::new();
    let mut extra_blocks = VecContents::default();
    let app_source = compile_body_node_to_rust_code(
        body_node,
        component_map,
        &mut extra_blocks,
        &mut css_blocks,
        &global_style,
        CssMatcher {
            path: Vec::new(),
            indices_in_parent: vec![0],
            children_length: vec![body_node.children.as_ref().len()],
        },
    )?;

    let app_source = app_source
        .lines()
        .map(|l| format!("        {l}"))
        .collect::<Vec<String>>()
        .join("\r\n");

    // NOTE: `css_blocks` / `extra_blocks` are no longer emitted — per-node styles
    // are now inlined as `.with_css("..")` strings (public API) rather than as
    // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` blocks (that API was
    // removed in 32d44ed8a). The maps stay in the signatures for compatibility.
    let _ = (&css_blocks, &extra_blocks);

    let main_func = "

use azul::{
    app::{App, AppConfig},
    dom::Dom,
    callbacks::{RefAny, LayoutCallbackInfo},
    window::WindowCreateOptions,
};

struct Data { }

extern \"C\" fn render(_: RefAny, _: LayoutCallbackInfo) -> Dom {
    crate::ui::render()
}

fn main() {
    let config = AppConfig::create();
    let app = App::create(RefAny::new(Data { }), config);
    let window = WindowCreateOptions::create(render);
    app.run(window);
}";

    let ui_module = format!(
        "#[allow(unused_imports)]\r\npub mod ui {{

    use azul::prelude::*;
    use azul::dom::{{NodeType, TabIndex, SmallAriaInfo}};
    use azul::str::String as AzString;

    pub fn render() -> Dom {{\r\n{app_source}\r\n    }}\r\n}}"
    );
    let source_code = format!(
        "#![windows_subsystem = \"windows\"]\r\n//! Auto-generated UI source \
         code\r\n{}\r\n{}\r\n\r\n{}{}",
        imports,
        compile_components(Vec::new()), // no user-defined components to compile
        ui_module,
        main_func,
    );

    Ok(source_code)
}

// Compile all components to source code
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API / ownership-transfer convention)
fn compile_components(
    components: Vec<(
        ComponentName,
        CompiledComponent,
        ComponentArguments,
        BTreeMap<String, String>,
    )>,
) -> String {
    let cs = components
        .iter()
        .map(|(name, function_body, function_args, css_blocks)| {
            let name = &normalize_casing(name);
            let f = compile_component(name, function_args, function_body)
                .lines()
                .map(|l| format!("    {l}"))
                .collect::<Vec<String>>()
                .join("\r\n");

            // let css_blocks = ...

            format!(
                "#[allow(unused_imports)]\r\npub mod {name} {{\r\n    use azul::dom::Dom;\r\n    use \
                 azul::str::String as AzString;\r\n{f}\r\n}}"
            )
        })
        .collect::<Vec<String>>()
        .join("\r\n\r\n");

    let cs = cs
        .lines()
        .map(|l| format!("    {l}"))
        .collect::<Vec<String>>()
        .join("\r\n");

    if cs.is_empty() {
        cs
    } else {
        format!("pub mod components {{\r\n{cs}\r\n}}")
    }
}

fn format_component_args(component_args: &ComponentArgumentVec) -> String {
    let mut args = component_args
        .iter()
        .map(|a| format!("{}: {}", a.name, a.arg_type))
        .collect::<Vec<String>>();

    args.sort_by(|a, b| b.cmp(a));

    args.join(", ")
}

#[must_use]
pub fn compile_component(
    component_name: &str,
    component_args: &ComponentArguments,
    component_function_body: &str,
) -> String {
    let component_name = &normalize_casing(component_name);
    let function_args = format_component_args(&component_args.args);
    let component_function_body = component_function_body
        .lines()
        .map(|l| format!("    {l}"))
        .collect::<Vec<String>>()
        .join("\r\n");
    let should_inline = component_function_body.lines().count() == 1;
    format!(
        "{}pub fn render({}{}{}) -> Dom {{\r\n{}\r\n}}",
        if should_inline { "#[inline]\r\n" } else { "" },
        // pass the text content as the first
        if component_args.accepts_text {
            "text: AzString"
        } else {
            ""
        },
        if function_args.is_empty() || !component_args.accepts_text {
            ""
        } else {
            ", "
        },
        function_args,
        component_function_body,
    )
}

/// Parse an SVG numeric attribute value to f32.
///
/// STRICT: a geometry attribute (`cx`, `r`, `x1`, ...) is a USER UNIT, and
/// `cx="10px"` is not valid SVG. The `<svg>` element's own `width`/`height`
/// are CSS lengths and a different thing entirely - see [`parse_svg_length`].
fn parse_svg_float(attr: Option<&AzString>) -> Option<f32> {
    attr?.as_str().trim().parse::<f32>().ok()
}

/// Parse the `<svg>` element's own `width`/`height`, which - unlike the
/// geometry attributes - are CSS LENGTHS.
///
/// A bare `px` is accepted because `width="16px"` is as common in the wild as
/// `width="16"`. A relative unit (`%`, `em`) is REJECTED rather than guessed
/// at: the caller then falls back to the viewBox, which is a real answer,
/// instead of resolving a percentage against nothing.
fn parse_svg_length(attr: Option<&AzString>) -> Option<f32> {
    let raw = attr?.as_str().trim();
    let number = raw.strip_suffix("px").unwrap_or(raw).trim();
    number.parse::<f32>().ok()
}

/// Parse an SVG `viewBox` into `(min_x, min_y, width, height)`.
///
/// Space- or comma-separated, per the spec; exactly four numbers, because
/// three or five is a malformed viewBox and silently taking the first four
/// would place the art somewhere nobody asked for.
fn parse_svg_view_box(value: &str) -> Option<(f32, f32, f32, f32)> {
    let nums: Vec<f32> = value
        .split(|c: char| c == ',' || c.is_ascii_whitespace())
        .filter(|s| !s.is_empty())
        .map(str::parse::<f32>)
        .collect::<Result<Vec<_>, _>>()
        .ok()?;
    match nums[..] {
        [min_x, min_y, width, height] if width > 0.0 && height > 0.0 => {
            Some((min_x, min_y, width, height))
        }
        _ => None,
    }
}

/// Parse an SVG `points` attribute (used by `<polygon>` and `<polyline>`).
fn parse_svg_points(pts: &str, close: bool) -> Option<crate::svg::SvgMultiPolygon> {
    let nums: Vec<f32> = pts
        .split(|c: char| c == ',' || c.is_ascii_whitespace())
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse::<f32>().ok())
        .collect();
    if nums.len() < 4 || !nums.len().is_multiple_of(2) {
        return None;
    }
    let mut elements = Vec::new();
    let points: Vec<azul_css::props::basic::SvgPoint> = nums
        .chunks_exact(2)
        .map(|c| azul_css::props::basic::SvgPoint { x: c[0], y: c[1] })
        .collect();
    for w in points.windows(2) {
        elements.push(crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
            w[0], w[1],
        )));
    }
    if close && points.len() >= 2 {
        let first = points[0];
        let last = *points.last().unwrap();
        if (first.x - last.x).abs() > 0.001 || (first.y - last.y).abs() > 0.001 {
            elements.push(crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
                last, first,
            )));
        }
    }
    Some(crate::svg::SvgMultiPolygon {
        rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
            items: crate::svg::SvgPathElementVec::from_vec(elements),
        }]),
    })
}

/// Fast XML to Dom conversion that builds Dom tree directly without intermediate `StyledDom`
/// This is O(n) instead of O(n²) for large documents
/// Apply the shared set of XML attributes onto a single [`NodeData`] node.
///
/// Handles `<img src>` rebuild, `id`/`class`, `focusable`, `tabindex`, inline
/// `style`, and SVG-shape geometry — the block that was previously duplicated
/// verbatim between [`xml_node_to_dom_fast`] (operating on `dom.root`) and
/// [`xml_node_to_fast_dom`] (operating on the arena `NodeData`). `component_name`
/// must already be normalized (lowercased); the caller computes `child_inside_svg`.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
fn apply_xml_node_attributes(
    node: &mut crate::dom::NodeData,
    xml_node: &XmlNode,
    component_name: &str,
    inside_svg: bool,
) {
    use crate::dom::{IdOrClass, NodeType, TabIndex};

    // `<img src="...">`: rebuild the placeholder Image node so its `NullImage`
    // carries the `src` string (as UTF-8 bytes in `tag`). The bytes are NOT
    // resolved here — a downstream renderer (printpdf, the compositor, ...) uses
    // the tag to look up and embed the actual image. Optional `width`/`height`
    // attributes set the intrinsic size used for layout (CSS still overrides).
    if component_name == "img" {
        if let Some(src) = xml_node.attributes.get_key("src") {
            let width = xml_node
                .attributes
                .get_key("width")
                .and_then(|w| {
                    w.as_str()
                        .trim()
                        .trim_end_matches("px")
                        .trim()
                        .parse::<usize>()
                        .ok()
                })
                .unwrap_or(0);
            let height = xml_node
                .attributes
                .get_key("height")
                .and_then(|h| {
                    h.as_str()
                        .trim()
                        .trim_end_matches("px")
                        .trim()
                        .parse::<usize>()
                        .ok()
                })
                .unwrap_or(0);
            let image_ref = crate::resources::ImageRef::null_image(
                width,
                height,
                crate::resources::RawImageFormat::RGBA8,
                src.as_str().as_bytes().to_vec(),
            );
            node.set_node_type(NodeType::Image(azul_css::css::BoxOrStatic::heap(image_ref)));
        }
    }

    // Set id and class attributes
    let mut ids_and_classes = Vec::new();
    if let Some(id_str) = xml_node.attributes.get_key("id") {
        for id in id_str.split_whitespace() {
            ids_and_classes.push(IdOrClass::Id(id.into()));
        }
    }
    if let Some(class_str) = xml_node.attributes.get_key("class") {
        for class in class_str.split_whitespace() {
            ids_and_classes.push(IdOrClass::Class(class.into()));
        }
    }
    if !ids_and_classes.is_empty() {
        node.set_ids_and_classes(ids_and_classes.into());
    }

    // Handle focusable attribute
    if let Some(focusable) = xml_node
        .attributes
        .get_key("focusable")
        .and_then(|f| parse_bool(f.as_str()))
    {
        if focusable {
            node.set_tab_index(TabIndex::Auto);
        } else {
            node.set_tab_index(TabIndex::NoKeyboardFocus);
        }
    }

    // Handle tabindex attribute
    if let Some(tab_index) = xml_node
        .attributes
        .get_key("tabindex")
        .and_then(|val| val.parse::<isize>().ok())
    {
        match tab_index {
            0 => node.set_tab_index(TabIndex::Auto),
            i if i > 0 => node.set_tab_index(TabIndex::OverrideInParent(
                u32::try_from(i).unwrap_or(u32::MAX),
            )),
            _ => node.set_tab_index(TabIndex::NoKeyboardFocus),
        }
    }

    // Table cell span attributes (`colspan` / `rowspan`).
    apply_cell_span_attributes(node, xml_node);

    // HTML `dir` attribute → the `direction` CSS property (dir="rtl"/"ltr"). Without
    // this, dir="rtl" (the common way to set RTL in HTML) had no effect. Appended
    // BEFORE the inline `style` below so author style still wins on equal specificity.
    let dir_prop = xml_node.attributes.get_key("dir").and_then(|d| {
        let v = d.as_str().trim();
        if v.eq_ignore_ascii_case("rtl") {
            Some(azul_css::props::style::StyleDirection::Rtl)
        } else if v.eq_ignore_ascii_case("ltr") {
            Some(azul_css::props::style::StyleDirection::Ltr)
        } else {
            None
        }
    });

    // `<svg>`: its own viewport. Two things have to come off the element, and
    // both were being dropped.
    //
    //   * the `viewBox`, which is the element's USER-SPACE coordinate system.
    //     `SvgNodeData::ViewBox` existed as a variant but nothing ever produced
    //     one, so a parsed `<svg>` had no record of what coordinate space its
    //     children were drawn in.
    //   * an INTRINSIC SIZE. An `<svg>` is a replaced element: it is as big as
    //     `width`/`height` say, and failing that as big as its viewBox (SVG's
    //     own default sizing rule). Without one the element lays out 0x0 and
    //     takes no space at all - which is what an icon parsed straight from a
    //     theme file did, and why it came out blank.
    //
    // These are INTRINSIC dimensions, not a demand: they are pushed ahead of
    // the inline `style` below, so a call site that says how big it wants the
    // thing still wins.
    let mut intrinsic_props: Vec<azul_css::dynamic_selector::CssPropertyWithConditions> =
        Vec::new();
    if component_name == "svg" {
        let view_box = xml_node
            .attributes
            .get_key("viewBox")
            .or_else(|| xml_node.attributes.get_key("viewbox"))
            .and_then(|v| parse_svg_view_box(v.as_str()));
        if let Some((min_x, min_y, width, height)) = view_box {
            node.set_svg_data(crate::dom::SvgNodeData::ViewBox {
                min_x,
                min_y,
                width,
                height,
            });
        }
        let stated = |key: &str| parse_svg_length(xml_node.attributes.get_key(key));
        let usable = |v: f32| v.is_finite() && v > 0.0;
        if let Some(w) = stated("width")
            .or(view_box.map(|(_, _, w, _)| w))
            .filter(|w| usable(*w))
        {
            intrinsic_props.push(
                azul_css::dynamic_selector::CssPropertyWithConditions::simple(
                    azul_css::props::property::CssProperty::width(
                        azul_css::props::layout::LayoutWidth::px(w),
                    ),
                ),
            );
        }
        if let Some(h) = stated("height")
            .or(view_box.map(|(_, _, _, h)| h))
            .filter(|h| usable(*h))
        {
            intrinsic_props.push(
                azul_css::dynamic_selector::CssPropertyWithConditions::simple(
                    azul_css::props::property::CssProperty::height(
                        azul_css::props::layout::LayoutHeight::px(h),
                    ),
                ),
            );
        }
    }

    // An SVG SHAPE is painted by filling its own box and clipping that box to
    // its geometry (`SvgNodeData::*`, pushed as a clip mask by the display
    // list). Two things make that work, and both are ordinary CSS:
    //
    //   * the box has to BE the `<svg>`'s viewport - the clip mask is
    //     rasterised into the node's paint rect, so a shape that laid out as
    //     an ordinary in-flow block would be clipped against the wrong
    //     rectangle (and, being empty, would be 0-high anyway);
    //   * `fill` has to reach the cascade. The presentation ATTRIBUTE is
    //     translated here; `style="fill:…"` and a stylesheet rule need nothing,
    //     because `fill` is an accepted spelling of `background-color`
    //     (`COMBINED_CSS_PROPERTIES_KEY_MAP`).
    //
    // `fill="none"` deliberately emits NOTHING rather than a transparent
    // background: it must not shadow a stylesheet rule that does set a fill.
    if inside_svg
        && matches!(
            component_name,
            "path" | "circle" | "rect" | "ellipse" | "line" | "polygon" | "polyline"
        )
    {
        use azul_css::props::{
            layout::{
                LayoutInsetBottom, LayoutLeft, LayoutPosition, LayoutRight, LayoutTop,
            },
            property::CssProperty,
        };
        let simple = azul_css::dynamic_selector::CssPropertyWithConditions::simple;
        intrinsic_props.push(simple(CssProperty::const_position(LayoutPosition::Absolute)));
        intrinsic_props.push(simple(CssProperty::const_left(LayoutLeft::const_px(0))));
        intrinsic_props.push(simple(CssProperty::const_top(LayoutTop::const_px(0))));
        intrinsic_props.push(simple(CssProperty::const_right(LayoutRight::const_px(0))));
        intrinsic_props.push(simple(CssProperty::const_bottom(LayoutInsetBottom::const_px(
            0,
        ))));

        if let Some(fill) = xml_node.attributes.get_key("fill") {
            let fill = fill.as_str().trim();
            if fill != "none" {
                if let Ok(color) = azul_css::props::basic::color::parse_css_color(fill) {
                    intrinsic_props.push(simple(CssProperty::const_background_content(
                        azul_css::props::style::StyleBackgroundContentVec::from_vec(vec![
                            azul_css::props::style::StyleBackgroundContent::Color(color),
                        ]),
                    )));
                }
            }
        }

        // The STROKE, as the box's border - the display list turns it into a
        // stroked path rather than a rectangle. Both halves are translated
        // here only for the presentation ATTRIBUTE; `style="stroke:…"` and a
        // stylesheet rule need nothing, because `stroke`/`stroke-width` are
        // accepted spellings of `border-color`/`border-width`.
        if let Some(stroke) = xml_node.attributes.get_key("stroke") {
            let stroke = stroke.as_str().trim();
            if stroke != "none" {
                if let Ok(color) = azul_css::props::basic::color::parse_css_color(stroke) {
                    use azul_css::props::style::{
                        StyleBorderBottomColor, StyleBorderLeftColor, StyleBorderRightColor,
                        StyleBorderTopColor,
                    };
                    intrinsic_props.push(simple(CssProperty::const_border_top_color(
                        StyleBorderTopColor { inner: color },
                    )));
                    intrinsic_props.push(simple(CssProperty::const_border_right_color(
                        StyleBorderRightColor { inner: color },
                    )));
                    intrinsic_props.push(simple(CssProperty::const_border_bottom_color(
                        StyleBorderBottomColor { inner: color },
                    )));
                    intrinsic_props.push(simple(CssProperty::const_border_left_color(
                        StyleBorderLeftColor { inner: color },
                    )));
                }
            }
        }
        // `stroke-width` is in USER UNITS, like every other geometry
        // attribute - not a CSS length.
        if let Some(width) = parse_svg_float(xml_node.attributes.get_key("stroke-width")) {
            if width.is_finite() && width > 0.0 {
                use azul_css::props::style::{
                    LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
                    LayoutBorderTopWidth,
                };
                let px = azul_css::props::basic::PixelValue::px(width);
                intrinsic_props.push(simple(CssProperty::const_border_top_width(
                    LayoutBorderTopWidth { inner: px },
                )));
                intrinsic_props.push(simple(CssProperty::const_border_right_width(
                    LayoutBorderRightWidth { inner: px },
                )));
                intrinsic_props.push(simple(CssProperty::const_border_bottom_width(
                    LayoutBorderBottomWidth { inner: px },
                )));
                intrinsic_props.push(simple(CssProperty::const_border_left_width(
                    LayoutBorderLeftWidth { inner: px },
                )));
            }
        }
    }

    // `<svg>` is the positioning context its shapes resolve against.
    if component_name == "svg" {
        intrinsic_props.push(
            azul_css::dynamic_selector::CssPropertyWithConditions::simple(
                azul_css::props::property::CssProperty::const_position(
                    azul_css::props::layout::LayoutPosition::Relative,
                ),
            ),
        );
    }

    // Handle inline style attribute (and the mapped `dir` attribute above)
    let style_attr = xml_node.attributes.get_key("style");
    if style_attr.is_some() || dir_prop.is_some() || !intrinsic_props.is_empty() {
        use azul_css::dynamic_selector::CssPropertyWithConditions;
        let css_key_map = azul_css::props::property::get_css_key_map();
        let mut props: Vec<CssPropertyWithConditions> = intrinsic_props;
        if let Some(dir) = dir_prop {
            props.push(CssPropertyWithConditions::simple(
                azul_css::props::property::CssProperty::Direction(
                    azul_css::css::CssPropertyValue::Exact(dir),
                ),
            ));
        }
        if let Some(style) = style_attr {
            let mut attributes = Vec::new();
            for s in style.as_str().split(';') {
                let mut s = s.split(':');
                let Some(key) = s.next() else {
                    continue;
                };
                let Some(value) = s.next() else {
                    continue;
                };
                // Called for its side effect (writes parsed props into `attributes`);
                // the returned value is intentionally discarded.
                drop(azul_css::parser2::parse_css_declaration(
                    key.trim(),
                    value.trim(),
                    azul_css::parser2::ErrorLocationRange::default(),
                    &css_key_map,
                    &mut Vec::new(),
                    &mut attributes,
                ));
            }
            props.extend(attributes.into_iter().filter_map(|s| match s {
                CssDeclaration::Static(s) => Some(CssPropertyWithConditions::simple(s)),
                CssDeclaration::Dynamic(_) => None,
            }));
        }
        if !props.is_empty() {
            node.set_css_props(props.into());
        }
    }

    // Handle SVG shape elements when inside an <svg> context
    let tag = component_name;
    let is_svg_shape = inside_svg
        && matches!(
            tag,
            "path" | "circle" | "rect" | "ellipse" | "line" | "polygon" | "polyline"
        );

    if is_svg_shape {
        let clip = match tag {
            "path" => xml_node
                .attributes
                .get_key("d")
                .and_then(|d| crate::path_parser::parse_svg_path_d(d.as_str()).ok()),
            "circle" => {
                let cx = parse_svg_float(xml_node.attributes.get_key("cx")).unwrap_or(0.0);
                let cy = parse_svg_float(xml_node.attributes.get_key("cy")).unwrap_or(0.0);
                let r = parse_svg_float(xml_node.attributes.get_key("r")).unwrap_or(0.0);
                if r > 0.0 {
                    Some(crate::svg::SvgMultiPolygon {
                        rings: crate::svg::SvgPathVec::from_vec(vec![
                            crate::path_parser::svg_circle_to_paths(cx, cy, r),
                        ]),
                    })
                } else {
                    None
                }
            }
            "rect" => {
                let x = parse_svg_float(xml_node.attributes.get_key("x")).unwrap_or(0.0);
                let y = parse_svg_float(xml_node.attributes.get_key("y")).unwrap_or(0.0);
                let w = parse_svg_float(xml_node.attributes.get_key("width")).unwrap_or(0.0);
                let h = parse_svg_float(xml_node.attributes.get_key("height")).unwrap_or(0.0);
                let rx = parse_svg_float(xml_node.attributes.get_key("rx")).unwrap_or(0.0);
                let ry = parse_svg_float(xml_node.attributes.get_key("ry")).unwrap_or(rx);
                if w > 0.0 && h > 0.0 {
                    Some(crate::svg::SvgMultiPolygon {
                        rings: crate::svg::SvgPathVec::from_vec(vec![
                            crate::path_parser::svg_rect_to_path(x, y, w, h, rx, ry),
                        ]),
                    })
                } else {
                    None
                }
            }
            "ellipse" => {
                let cx = parse_svg_float(xml_node.attributes.get_key("cx")).unwrap_or(0.0);
                let cy = parse_svg_float(xml_node.attributes.get_key("cy")).unwrap_or(0.0);
                let rx = parse_svg_float(xml_node.attributes.get_key("rx")).unwrap_or(0.0);
                let ry = parse_svg_float(xml_node.attributes.get_key("ry")).unwrap_or(0.0);
                if rx > 0.0 && ry > 0.0 {
                    // Approximate ellipse with 4 cubic beziers (using rx for x-kappa, ry for y-kappa)
                    use azul_css::props::basic::{SvgCubicCurve, SvgPoint};
                    const KAPPA: f32 = 0.552_284_8;
                    let kx = rx * KAPPA;
                    let ky = ry * KAPPA;
                    let elements = vec![
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
                            start: SvgPoint { x: cx, y: cy - ry },
                            ctrl_1: SvgPoint {
                                x: cx + kx,
                                y: cy - ry,
                            },
                            ctrl_2: SvgPoint {
                                x: cx + rx,
                                y: cy - ky,
                            },
                            end: SvgPoint { x: cx + rx, y: cy },
                        }),
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
                            start: SvgPoint { x: cx + rx, y: cy },
                            ctrl_1: SvgPoint {
                                x: cx + rx,
                                y: cy + ky,
                            },
                            ctrl_2: SvgPoint {
                                x: cx + kx,
                                y: cy + ry,
                            },
                            end: SvgPoint { x: cx, y: cy + ry },
                        }),
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
                            start: SvgPoint { x: cx, y: cy + ry },
                            ctrl_1: SvgPoint {
                                x: cx - kx,
                                y: cy + ry,
                            },
                            ctrl_2: SvgPoint {
                                x: cx - rx,
                                y: cy + ky,
                            },
                            end: SvgPoint { x: cx - rx, y: cy },
                        }),
                        crate::svg::SvgPathElement::CubicCurve(SvgCubicCurve {
                            start: SvgPoint { x: cx - rx, y: cy },
                            ctrl_1: SvgPoint {
                                x: cx - rx,
                                y: cy - ky,
                            },
                            ctrl_2: SvgPoint {
                                x: cx - kx,
                                y: cy - ry,
                            },
                            end: SvgPoint { x: cx, y: cy - ry },
                        }),
                    ];
                    Some(crate::svg::SvgMultiPolygon {
                        rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
                            items: crate::svg::SvgPathElementVec::from_vec(elements),
                        }]),
                    })
                } else {
                    None
                }
            }
            "line" => {
                let x1 = parse_svg_float(xml_node.attributes.get_key("x1")).unwrap_or(0.0);
                let y1 = parse_svg_float(xml_node.attributes.get_key("y1")).unwrap_or(0.0);
                let x2 = parse_svg_float(xml_node.attributes.get_key("x2")).unwrap_or(0.0);
                let y2 = parse_svg_float(xml_node.attributes.get_key("y2")).unwrap_or(0.0);
                Some(crate::svg::SvgMultiPolygon {
                    rings: crate::svg::SvgPathVec::from_vec(vec![crate::svg::SvgPath {
                        items: crate::svg::SvgPathElementVec::from_vec(vec![
                            crate::svg::SvgPathElement::Line(crate::svg::SvgLine::new(
                                azul_css::props::basic::SvgPoint { x: x1, y: y1 },
                                azul_css::props::basic::SvgPoint { x: x2, y: y2 },
                            )),
                        ]),
                    }]),
                })
            }
            "polygon" | "polyline" => xml_node
                .attributes
                .get_key("points")
                .and_then(|pts| parse_svg_points(pts.as_str(), tag == "polygon")),
            _ => None,
        };

        if let Some(mp) = clip {
            node.set_svg_data(crate::dom::SvgNodeData::Path(mp));
        }
    }
}

/// Parse the HTML `colspan` / `rowspan` presentational attributes into
/// `AttributeType`s on the node. The table layout reads them back via
/// `get_cell_spans`. Without this the XML→DOM conversion dropped them and every
/// cell defaulted to span 1, so `<th colspan="2">` only covered one column.
/// Parsed unconditionally — non-cell elements simply don't carry these attributes.
fn apply_cell_span_attributes(node: &mut crate::dom::NodeData, xml_node: &XmlNode) {
    let mut spans = Vec::new();
    if let Some(n) = xml_node
        .attributes
        .get_key("colspan")
        .and_then(|v| v.as_str().trim().parse::<i32>().ok())
    {
        spans.push(crate::dom::AttributeType::ColSpan(n));
    }
    if let Some(n) = xml_node
        .attributes
        .get_key("rowspan")
        .and_then(|v| v.as_str().trim().parse::<i32>().ok())
    {
        spans.push(crate::dom::AttributeType::RowSpan(n));
    }
    if !spans.is_empty() {
        let mut v = node.attributes().clone().into_library_owned_vec();
        v.extend(spans);
        node.set_attributes(v.into());
    }
}

#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// component_map is threaded through the whole fast-DOM pipeline for parity with the
// component-expanding interpreter path (see ~xml.rs:2845); this fast path never expands
// components, so it only forwards the map into recursive calls. Removing it here would
// cascade unused-param removals up the entire pipeline.
#[allow(clippy::only_used_in_recursion)]
/// Every `<style>` element's text in this subtree, in document order.
///
/// Depth-bounded for the same reason the DOM conversion is: this reads files
/// nothing in this build produced.
fn collect_style_text(node: &XmlNode, out: &mut Vec<String>, depth: usize) {
    if depth >= MAX_XML_NESTING_DEPTH {
        return;
    }
    for child in node.children.as_ref() {
        let XmlNodeChild::Element(element) = child else {
            continue;
        };
        if normalize_casing(&element.node_type) == "style" {
            let text = element.get_text_content();
            if !text.is_empty() {
                out.push(text);
            }
        } else {
            collect_style_text(element, out, depth + 1);
        }
    }
}

fn xml_node_to_dom_fast<'a>(
    xml_node: &'a XmlNode,
    component_map: &'a ComponentMap,
    inside_svg: bool,
    depth: usize,
) -> Result<Dom, RenderDomError> {
    use crate::dom::Dom;

    let component_name = normalize_casing(&xml_node.node_type);

    // Look up the component definition
    let node_type = tag_to_node_type(&component_name);
    let mut dom = Dom::create_node(node_type);

    apply_xml_node_attributes(&mut dom.root, xml_node, &component_name, inside_svg);

    let child_inside_svg = inside_svg || component_name == "svg";

    // AUDIT 2026-07-08: bound recursion depth to avoid a native stack overflow on
    // pathologically deep markup. At the cap, this node is emitted without its
    // children (truncation) rather than crashing the process.
    // AUDIT-TODO: a worklist-based iterative builder would preserve deep subtrees.
    if depth >= MAX_XML_NESTING_DEPTH {
        return Ok(dom);
    }

    // Recursively convert children
    let mut children = Vec::new();
    // A `<style>` found INSIDE the tree - an SVG's own `<defs><style>`, above
    // all - is a stylesheet, not content. In azul a stylesheet is an ATTRIBUTE
    // of a node (`Dom.css`, scoped to that subtree by `scope_inline_css`)
    // rather than a node of its own, so it has to be recognised HERE, at the
    // input, and hung on the element that contains it. Leaving it as a node
    // rendered the CSS source as visible text.
    //
    // Scoping to the subtree is exactly right for the case that motivates it:
    // an icon's `.ColorScheme-Text { color:… }` is meant for that icon, and
    // must not reach the rest of the document.
    let mut scoped_css: Vec<Css> = Vec::new();
    // An `<svg>`'s stylesheet is SVG-GLOBAL: it is nearly always written in
    // `<defs><style>`, and `<defs>` is a definition container that draws
    // nothing - attaching the sheet there would scope it to a subtree with no
    // shapes in it. Collected from the whole subtree and hung on the `<svg>`,
    // which is as global as it should ever get.
    if component_name == "svg" {
        let mut texts = Vec::new();
        collect_style_text(xml_node, &mut texts, 0);
        for text in texts {
            scoped_css.push(Css::from_string(text.into()));
        }
    }
    for child in xml_node.children.as_ref() {
        match child {
            XmlNodeChild::Element(child_node)
                if normalize_casing(&child_node.node_type) == "style" =>
            {
                // Never a rendered node. Inside an `<svg>` it was already
                // hoisted above; elsewhere it scopes to THIS element.
                if component_name != "svg" {
                    let text = child_node.get_text_content();
                    if !text.is_empty() {
                        scoped_css.push(Css::from_string(text.into()));
                    }
                }
            }
            XmlNodeChild::Element(child_node) => {
                let child_dom =
                    xml_node_to_dom_fast(child_node, component_map, child_inside_svg, depth + 1)?;
                children.push(child_dom);
            }
            XmlNodeChild::Text(text) => {
                let text_dom = Dom::create_text_do_not_use_without_block_level_wrapper(
                    AzString::from(text.as_str()),
                );
                children.push(text_dom);
            }
        }
    }

    if !children.is_empty() {
        dom = dom.with_children(children.into());
    }

    for css in scoped_css {
        dom.add_component_css(css);
    }

    Ok(dom)
}

/// Builder for arena-based DOM construction (`FastDom`).
/// Builds two parallel Vecs (hierarchy + `node_data`) in a single DFS pass.
#[derive(Debug)]
pub struct CompactDomBuilder {
    hierarchy: Vec<crate::styled_dom::NodeHierarchyItem>,
    node_data: Vec<crate::dom::NodeData>,
    css: Vec<crate::dom::CssWithNodeId>,
    /// Stack of (`node_index`, `previous_child_index`) for open elements
    stack: Vec<(usize, Option<usize>)>,
}

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

impl CompactDomBuilder {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            hierarchy: Vec::new(),
            node_data: Vec::new(),
            css: Vec::new(),
            stack: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            hierarchy: Vec::with_capacity(cap),
            node_data: Vec::with_capacity(cap),
            css: Vec::new(),
            stack: Vec::new(),
        }
    }

    /// Open a new element node. Must be paired with `close_node()`.
    pub fn open_node(&mut self, node_data: crate::dom::NodeData) {
        use crate::id::NodeId;
        use crate::styled_dom::NodeHierarchyItem;

        let idx = self.hierarchy.len();

        // Determine parent from stack
        let parent_raw = if let Some(&(parent_idx, _)) = self.stack.last() {
            NodeId::into_raw(&Some(NodeId::new(parent_idx)))
        } else {
            0 // No parent (root)
        };

        // Determine previous sibling from parent's last child tracking
        let prev_sibling_raw = if let Some(&(_, prev_child)) = self.stack.last() {
            prev_child.map_or(0, |pi| NodeId::into_raw(&Some(NodeId::new(pi))))
        } else {
            0
        };

        // If there's a previous sibling, set its next_sibling to us
        if let Some(&(_, Some(prev_idx))) = self.stack.last() {
            self.hierarchy[prev_idx].next_sibling = NodeId::into_raw(&Some(NodeId::new(idx)));
        }

        // Update parent's "last seen child" to us
        if let Some(parent) = self.stack.last_mut() {
            parent.1 = Some(idx);
        }

        // Push the hierarchy item (last_child will be set in close_node)
        self.hierarchy.push(NodeHierarchyItem {
            parent: parent_raw,
            previous_sibling: prev_sibling_raw,
            next_sibling: 0, // Will be set by next sibling's open_node
            last_child: 0,   // Will be set in close_node
        });
        self.node_data.push(node_data);

        // Push onto stack: this node is now the "open" element, no children yet
        self.stack.push((idx, None));
    }

    /// Close the current element. Sets the `last_child` pointer.
    pub fn close_node(&mut self) {
        use crate::id::NodeId;

        if let Some((idx, last_child_idx)) = self.stack.pop() {
            // Set last_child on this node's hierarchy item
            self.hierarchy[idx].last_child =
                last_child_idx.map_or(0, |lc| NodeId::into_raw(&Some(NodeId::new(lc))));
        }
    }

    /// Add a leaf node (text, br, hr, etc.) that has no children.
    pub fn add_leaf(&mut self, node_data: crate::dom::NodeData) {
        self.open_node(node_data);
        self.close_node();
    }

    /// Add a CSS stylesheet scoped to a node ID.
    pub fn add_css(&mut self, node_id: usize, css: Css) {
        self.css.push(crate::dom::CssWithNodeId { node_id, css });
    }

    /// Finish building and produce a `FastDom`.
    #[must_use]
    pub fn finish(self) -> crate::dom::FastDom {
        crate::dom::FastDom {
            node_hierarchy: self.hierarchy.into(),
            node_data: self.node_data.into(),
            css: self.css.into(),
        }
    }
}

/// Convert an XML node tree into a `FastDom` (arena-based) in a single DFS pass.
/// This is the fast path equivalent of `xml_node_to_dom_fast`.
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// See xml_node_to_dom_fast: component_map is forwarded for pipeline parity, not read here.
#[allow(clippy::only_used_in_recursion)]
fn xml_node_to_fast_dom<'a>(
    xml_node: &'a XmlNode,
    component_map: &'a ComponentMap,
    inside_svg: bool,
    builder: &mut CompactDomBuilder,
    depth: usize,
) -> Result<(), RenderDomError> {
    use crate::dom::NodeData;

    let component_name = normalize_casing(&xml_node.node_type);
    let node_type = tag_to_node_type(&component_name);
    let mut node_data = NodeData::create_node(node_type);

    apply_xml_node_attributes(&mut node_data, xml_node, &component_name, inside_svg);

    let child_inside_svg = inside_svg || component_name == "svg";

    // Open this node in the builder
    builder.open_node(node_data);

    // AUDIT 2026-07-08: bound recursion depth to avoid a native stack overflow on
    // pathologically deep markup. At the cap, children are dropped (the node is
    // still opened+closed) rather than crashing the process.
    // AUDIT-TODO: a worklist-based iterative builder would preserve deep subtrees.
    if depth < MAX_XML_NESTING_DEPTH {
        // Recursively convert children
        for child in xml_node.children.as_ref() {
            match child {
                XmlNodeChild::Element(child_node) => {
                    xml_node_to_fast_dom(
                        child_node,
                        component_map,
                        child_inside_svg,
                        builder,
                        depth + 1,
                    )?;
                }
                XmlNodeChild::Text(text) => {
                    builder.add_leaf(
                        NodeData::create_text_do_not_use_without_block_level_wrapper(
                            AzString::from(text.as_str()),
                        ),
                    );
                }
            }
        }
    }

    // Close this node
    builder.close_node();

    Ok(())
}

/// Render a DOM from an XML body node using the fast arena-based path.
/// Builds a `FastDom` directly (no tree intermediary), then creates `StyledDom`.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
fn render_dom_from_body_node_fast<'a>(
    body_node: &'a XmlNode,
    mut global_css: Option<Css>,
    component_map: &'a ComponentMap,
    max_width: Option<f32>,
) -> Result<StyledDom, RenderDomError> {
    use crate::dom::{NodeData, NodeType};

    let mut builder = CompactDomBuilder::new();

    // Build the HTML > Body wrapper + body content in one pass
    // Open <html>
    builder.open_node(NodeData::create_node(NodeType::Html));
    // Open <body> (the body_node content goes inside)
    xml_node_to_fast_dom(body_node, component_map, false, &mut builder, 0)?;
    // Close <html>
    builder.close_node();

    // Collect CSS rules from each source.
    let mut combined_rules: Vec<CssRuleBlock> = Vec::new();
    if let Some(max_width) = max_width {
        let max_width_css =
            Css::from_string(format!("html {{ max-width: {max_width}px; }}").into());
        combined_rules.extend(max_width_css.rules.into_library_owned_vec());
    }
    let mut combined_keyframes = Vec::new();
    if let Some(css) = global_css.take() {
        combined_rules.extend(css.rules.into_library_owned_vec());
        combined_keyframes.extend(css.keyframes.into_library_owned_vec());
    }
    let mut combined_css = Css::new(combined_rules);
    combined_css.keyframes = combined_keyframes.into();

    // Add CSS to the FastDom
    let mut fast_dom = builder.finish();
    fast_dom.css = vec![crate::dom::CssWithNodeId {
        node_id: 0, // Global scope (root)
        css: combined_css,
    }]
    .into();

    // Create StyledDom via the fast path (no tree→arena conversion)
    let styled = StyledDom::create_from_fast_dom(fast_dom);
    Ok(styled)
}

// render_dom_from_body_node() removed — use render_dom_from_body_node_fast() or str_to_dom()

fn set_stringified_attributes(
    dom_string: &mut String,
    xml_attributes: &XmlAttributeMap,
    filtered_xml_attributes: &ComponentArgumentVec,
    tabs: usize,
) {
    let t0 = String::from("    ").repeat(tabs);
    let t = String::from("    ").repeat(tabs + 1);

    // push ids and classes as chained `.with_id("..")` / `.with_class("..")`
    // calls (public builder API; both take `Into<AzString>`, so bare &str works).
    let _ = &t;
    for id in xml_attributes
        .get_key("id")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default()
    {
        let _ = write!(
            dom_string,
            "\r\n{}.with_id(\"{}\")",
            t0,
            format_args_dynamic(id, filtered_xml_attributes)
        );
    }

    for class in xml_attributes
        .get_key("class")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default()
    {
        let _ = write!(
            dom_string,
            "\r\n{}.with_class(\"{}\")",
            t0,
            format_args_dynamic(class, filtered_xml_attributes)
        );
    }

    if let Some(focusable) = xml_attributes
        .get_key("focusable")
        .map(|f| format_args_dynamic(f, filtered_xml_attributes))
        .and_then(|f| parse_bool(&f))
    {
        if focusable {
            let _ = write!(dom_string, "\r\n{t}.with_tab_index(TabIndex::Auto)");
        } else {
            let _ = write!(
                dom_string,
                "\r\n{t}.with_tab_index(TabIndex::NoKeyboardFocus)"
            );
        }
    }

    if let Some(tab_index) = xml_attributes
        .get_key("tabindex")
        .map(|val| format_args_dynamic(val, filtered_xml_attributes))
        .and_then(|val| val.parse::<isize>().ok())
    {
        match tab_index {
            0 => {
                let _ = write!(dom_string, "\r\n{t}.with_tab_index(TabIndex::Auto)");
            }
            i if i > 0 => {
                let _ = write!(
                    dom_string,
                    "\r\n{}.with_tab_index(TabIndex::OverrideInParent({}))",
                    t,
                    usize::try_from(i).unwrap_or(0)
                );
            }
            _ => {
                let _ = write!(
                    dom_string,
                    "\r\n{t}.with_tab_index(TabIndex::NoKeyboardFocus)"
                );
            }
        }
    }
}

/// Item of a split string - either a variable name (with optional format spec) or a string
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum DynamicItem {
    /// A variable reference, e.g. {counter} or {counter:?} or {price:.2}
    Var {
        name: String,
        /// Optional format specifier after the colon: "?" for debug, ".2" for precision, etc.
        format_spec: Option<String>,
    },
    Str(String),
}

/// Splits a string into formatting arguments, supporting format specifiers like `{var:?}`
/// ```rust
/// # use azul_core::xml::DynamicItem::*;
/// # use azul_core::xml::split_dynamic_string;
/// let s = "hello {a}, {b}{{ {c} }}";
/// let split = split_dynamic_string(s);
/// let output = vec![
///     Str("hello ".to_string()),
///     Var { name: "a".to_string(), format_spec: None },
///     Str(", ".to_string()),
///     Var { name: "b".to_string(), format_spec: None },
///     Str("{ ".to_string()),
///     Var { name: "c".to_string(), format_spec: None },
///     Str(" }".to_string()),
/// ];
/// assert_eq!(output, split);
/// ```
#[must_use]
pub fn split_dynamic_string(input: &str) -> Vec<DynamicItem> {
    use self::DynamicItem::{Str, Var};

    let input: Vec<char> = input.chars().collect();
    let input_chars_len = input.len();

    let mut items = Vec::new();
    let mut current_idx = 0;
    let mut last_idx = 0;

    while current_idx < input_chars_len {
        let c = input[current_idx];
        match c {
            '{' if input.get(current_idx + 1).copied() != Some('{') => {
                // variable start, search until next closing brace or whitespace or end of string
                let mut start_offset = 1;
                let mut has_found_variable = false;
                while let Some(c) = input.get(current_idx + start_offset) {
                    if c.is_whitespace() {
                        break;
                    }
                    if *c == '}' && input.get(current_idx + start_offset + 1).copied() != Some('}')
                    {
                        start_offset += 1;
                        has_found_variable = true;
                        break;
                    }
                    start_offset += 1;
                }

                // advance current_idx accordingly
                // on fail, set cursor to end
                // set last_idx accordingly
                if has_found_variable {
                    if last_idx != current_idx {
                        items.push(Str(input[last_idx..current_idx].iter().collect()));
                    }

                    // subtract 1 from start for opening brace, one from end for closing brace
                    let var_content: String = input
                        [(current_idx + 1)..(current_idx + start_offset - 1)]
                        .iter()
                        .collect();
                    // Split on first ':' to separate variable name from format specifier
                    let (var_name, format_spec) = if let Some(colon_pos) = var_content.find(':') {
                        let name = var_content[..colon_pos].to_string();
                        let spec = var_content[(colon_pos + 1)..].to_string();
                        (name, Some(spec))
                    } else {
                        (var_content, None)
                    };
                    items.push(Var {
                        name: var_name,
                        format_spec,
                    });
                    current_idx += start_offset;
                    last_idx = current_idx;
                } else {
                    current_idx += start_offset;
                }
            }
            _ => {
                current_idx += 1;
            }
        }
    }

    if current_idx != last_idx {
        items.push(Str(input[last_idx..].iter().collect()));
    }

    for item in &mut items {
        // replace {{ with { in strings
        if let Str(s) = item {
            *s = s.replace("{{", "{").replace("}}", "}");
        }
    }

    items
}

/// Combines the split string back into its original form while replacing the variables with their
/// values
///
/// let variables = btreemap!{ "a" => "value1", "b" => "value2" };
/// [Str("hello "), Var("a"), Str(", "), Var("b"), Str("{ "), Var("c"), Str(" }}")]
/// => "hello value1, valuec{ {c} }"
fn combine_and_replace_dynamic_items(
    input: &[DynamicItem],
    variables: &ComponentArgumentVec,
) -> String {
    let mut s = String::new();

    for item in input {
        match item {
            DynamicItem::Var { name, format_spec } => {
                let variable_name = normalize_casing(name.trim());
                if let Some(resolved_var) = variables
                    .iter()
                    .find(|s| s.name.as_str() == variable_name)
                    .map(|q| &q.arg_type)
                {
                    // Format specifiers are applied at compile time, not at runtime replacement
                    s.push_str(resolved_var);
                } else {
                    s.push('{');
                    s.push_str(name);
                    if let Some(spec) = format_spec {
                        s.push(':');
                        s.push_str(spec);
                    }
                    s.push('}');
                }
            }
            DynamicItem::Str(dynamic_str) => {
                s.push_str(dynamic_str);
            }
        }
    }

    s
}

/// Given a string and a key => value mapping, replaces parts of the string with the value, i.e.:
///
/// ```rust
/// # use azul_core::xml::{format_args_dynamic, ComponentArgument, ComponentArgumentVec};
/// # use azul_css::AzString;
/// let variables: ComponentArgumentVec = vec![
///     ComponentArgument { name: AzString::from("a"), arg_type: AzString::from("value1") },
///     ComponentArgument { name: AzString::from("b"), arg_type: AzString::from("value2") },
/// ].into();
///
/// let initial = "hello {a}, {b}{{ {c} }}";
/// let expected = "hello value1, value2{ {c} }".to_string();
/// assert_eq!(format_args_dynamic(initial, &variables), expected);
/// ```
///
/// Note: the number (0, 1, etc.) is the order of the argument, it is irrelevant for
/// runtime formatting, only important for keeping the component / function arguments
/// in order when compiling the arguments to Rust code
#[must_use]
pub fn format_args_dynamic(input: &str, variables: &ComponentArgumentVec) -> String {
    let dynamic_str_items = split_dynamic_string(input);
    combine_and_replace_dynamic_items(&dynamic_str_items, variables)
}

/// Decode a numeric character reference body (the part between `&` and `;`),
/// e.g. `"#65"` -> `'A'`, `"#x41"` -> `'A'`. Returns `None` if it is not a valid
/// numeric reference.
fn decode_numeric_entity(entity: &str) -> Option<char> {
    let num = entity.strip_prefix('#')?;
    let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
        u32::from_str_radix(hex, 16).ok()?
    } else {
        num.parse::<u32>().ok()?
    };
    char::from_u32(code)
}

/// Decode the common HTML/XML entities in a single left-to-right pass.
///
/// Handles `&lt;` `&gt;` `&amp;` `&quot;` `&apos;` and numeric references
/// (`&#NN;` / `&#xHH;`). `&nbsp;` and any unrecognized `&...;` sequence are left
/// verbatim. The single pass guarantees `&amp;` never double-decodes a following
/// entity. See [`prepare_string`] for why `&nbsp;` is deliberately preserved.
fn decode_entities(input: &str) -> String {
    // Longest handled entity body is a hex numeric ref like `#x10FFFF` (8 bytes);
    // cap the `;` search window so a stray `&` far from a `;` stays cheap.
    const MAX_ENTITY_BODY: usize = 12;

    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    while i < input.len() {
        if bytes[i] == b'&' {
            if let Some(semi_rel) = input[i + 1..].find(';') {
                if semi_rel <= MAX_ENTITY_BODY {
                    let body = &input[i + 1..i + 1 + semi_rel];
                    let end = i + 1 + semi_rel; // index of ';'
                                                // Leave &nbsp; for the per-line pass in prepare_string.
                    if body.eq_ignore_ascii_case("nbsp") {
                        out.push_str(&input[i..=end]);
                        i = end + 1;
                        continue;
                    }
                    let decoded = match body {
                        "lt" => Some('<'),
                        "gt" => Some('>'),
                        "amp" => Some('&'),
                        "quot" => Some('"'),
                        "apos" => Some('\''),
                        _ => decode_numeric_entity(body),
                    };
                    if let Some(c) = decoded {
                        out.push(c);
                        i = end + 1;
                        continue;
                    }
                }
            }
            // Not a recognized entity: emit the '&' literally.
            out.push('&');
            i += 1;
        } else {
            // Copy one whole UTF-8 char (i is always on a char boundary here).
            let ch = input[i..].chars().next().unwrap_or('\u{FFFD}');
            out.push(ch);
            i += ch.len_utf8();
        }
    }
    out
}

// NOTE: Two sequential returns count as a single return, while single returns get ignored.
#[must_use]
pub fn prepare_string(input: &str) -> String {
    const SPACE: &str = " ";
    const RETURN: &str = "\n";

    let input = input.trim();

    if input.is_empty() {
        return String::new();
    }

    // AUDIT 2026-07-08: previously only `&lt;`/`&gt;` were decoded. Decode the full
    // common named-entity set (`&lt;` `&gt;` `&amp;` `&quot;` `&apos;`) plus numeric
    // references (`&#NN;` decimal and `&#xHH;` hex) in a single left-to-right pass.
    // A single pass is used deliberately so `&amp;` cannot double-decode a following
    // entity (e.g. "&amp;lt;" -> literal "&lt;", not "<"). `&nbsp;` is intentionally
    // left untouched here so the per-line pass below (which runs AFTER trimming) can
    // still turn it into a space that survives leading/trailing trim.
    let input = decode_entities(input);

    let input_len = input.len();
    let mut final_lines: Vec<String> = Vec::new();
    let mut last_line_was_empty = false;

    for line in input.lines() {
        let line = line.trim();
        let line = line.replace("&nbsp;", " ");
        let current_line_is_empty = line.is_empty();

        if !current_line_is_empty {
            if last_line_was_empty {
                final_lines.push(format!("{RETURN}{line}"));
            } else {
                final_lines.push(line.to_string());
            }
        }

        last_line_was_empty = current_line_is_empty;
    }

    let mut target = String::with_capacity(input_len);
    for (line_idx, line) in final_lines.iter().enumerate() {
        // A joining space goes before every line EXCEPT the first (idx 0) and a
        // paragraph break (RETURN-prefixed). The old code also skipped the LAST line,
        // which dropped the word boundary for a soft-wrapped final line
        // ("Hello\nworld" -> "Helloworld").
        if !(line.starts_with(RETURN) || line_idx == 0) {
            target.push_str(SPACE);
        }
        target.push_str(line);
    }
    target
}

/// Parses a string ("true" or "false")
#[must_use]
pub fn parse_bool(input: &str) -> Option<bool> {
    match input {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    }
}

#[derive(Debug, Clone)]
pub struct CssMatcher {
    path: Vec<CssPathSelector>,
    indices_in_parent: Vec<usize>,
    children_length: Vec<usize>,
}

impl CssMatcher {
    fn get_hash(&self) -> u64 {
        use core::hash::Hash;

        use core::hash::Hasher;

        let mut hasher = crate::hash::DefaultHasher::new();
        for p in &self.path {
            p.hash(&mut hasher);
        }
        hasher.finish()
    }
}

impl CssMatcher {
    fn matches(&self, path: &CssPath) -> bool {
        use azul_css::css::CssPathSelector::*;

        use crate::style::{CssGroupIterator, CssGroupSplitReason};

        if self.path.is_empty() {
            return false;
        }
        if path.selectors.as_ref().is_empty() {
            return false;
        }

        // self_matcher is only ever going to contain "Children" selectors, never "DirectChildren"
        let mut path_groups = CssGroupIterator::new(path.selectors.as_ref()).collect::<Vec<_>>();
        path_groups.reverse();

        if path_groups.is_empty() {
            return false;
        }
        let mut self_groups = CssGroupIterator::new(self.path.as_ref()).collect::<Vec<_>>();
        self_groups.reverse();
        if self_groups.is_empty() {
            return false;
        }

        if self.indices_in_parent.len() != self_groups.len() {
            return false;
        }
        if self.children_length.len() != self_groups.len() {
            return false;
        }

        // self_groups = [ // HTML
        //     "body",
        //     "div.__azul_native-ribbon-container"
        //     "div.__azul_native-ribbon-tabs"
        //     "p.home"
        // ]
        //
        // path_groups = [ // CSS
        //     ".__azul_native-ribbon-tabs"
        //     "div.after-tabs"
        // ]

        // get the first path group and see if it matches anywhere in the self group
        let mut cur_selfgroup_scan = 0;
        let mut cur_pathgroup_scan = 0;
        let mut valid = false;
        let mut path_group = path_groups[cur_pathgroup_scan].clone();

        while cur_selfgroup_scan < self_groups.len() {
            let mut advance = None;

            // scan all remaining path groups
            for (id, cg) in self_groups[cur_selfgroup_scan..].iter().enumerate() {
                let gm = group_matches(
                    &path_group.0,
                    &self_groups[cur_selfgroup_scan + id].0,
                    self.indices_in_parent[cur_selfgroup_scan + id],
                    self.children_length[cur_selfgroup_scan + id],
                );

                if gm {
                    // ok: ".__azul_native-ribbon-tabs" was found within self_groups
                    // advance the self_groups by n
                    advance = Some(id);
                    break;
                }
            }

            match advance {
                Some(n) => {
                    // group was found in remaining items
                    // advance cur_pathgroup_scan by 1 and cur_selfgroup_scan by n
                    if cur_pathgroup_scan == path_groups.len() - 1 {
                        // last path group
                        return cur_selfgroup_scan + n == self_groups.len() - 1;
                    }
                    cur_pathgroup_scan += 1;
                    cur_selfgroup_scan += n;
                    path_group = path_groups[cur_pathgroup_scan].clone();
                }
                None => return false, // group was not found in remaining items
            }
        }

        // only return true if all path_groups matched
        cur_pathgroup_scan == path_groups.len() - 1
    }
}

// does p.home match div.after-tabs?
// a: div.after-tabs
fn group_matches(
    a: &[&CssPathSelector],
    b: &[&CssPathSelector],
    idx_in_parent: usize,
    parent_children: usize,
) -> bool {
    use azul_css::css::{
        CssNthChildSelector, CssPathPseudoSelector,
        CssPathSelector::{Class, Global, Id, PseudoSelector, Type},
    };

    for selector in a {
        match selector {
            // always matches
            Global
            | PseudoSelector(
                CssPathPseudoSelector::Hover
                | CssPathPseudoSelector::Active
                | CssPathPseudoSelector::Focus
                | CssPathPseudoSelector::SeatFocus,
            ) => {}

            Type(tag) => {
                if !b.iter().any(|t| **t == Type(*tag)) {
                    return false;
                }
            }
            Class(class) => {
                if !b.iter().any(|t| **t == Class(class.clone())) {
                    return false;
                }
            }
            Id(id) => {
                if !b.iter().any(|t| **t == Id(id.clone())) {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::First) => {
                if idx_in_parent != 0 {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::Last) => {
                if idx_in_parent != parent_children.saturating_sub(1) {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Number(i))) => {
                if idx_in_parent != *i as usize {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Even)) => {
                if !idx_in_parent.is_multiple_of(2) {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Odd)) => {
                if idx_in_parent.is_multiple_of(2) {
                    return false;
                }
            }
            PseudoSelector(CssPathPseudoSelector::NthChild(CssNthChildSelector::Pattern(p))) => {
                if !idx_in_parent
                    .saturating_sub(p.offset as usize)
                    .is_multiple_of(p.pattern_repeat as usize)
                {
                    return false;
                }
            }

            _ => return false, // can't happen
        }
    }

    true
}

struct CssBlock {
    ending: Option<CssPathPseudoSelector>,
    block: CssRuleBlock,
}

#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the body node cannot be compiled to Rust code.
pub fn compile_body_node_to_rust_code<'a>(
    body_node: &'a XmlNode,
    component_map: &'a ComponentMap,
    extra_blocks: &mut VecContents,
    css_blocks: &mut BTreeMap<String, String>,
    css: &Css,
    mut matcher: CssMatcher,
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;

    let t = "";
    let t2 = "    ";
    let mut dom_string = String::from("Dom::create_body()");
    let node_type = CssPathSelector::Type(NodeTypeTag::Body);
    matcher.path.push(node_type);

    let ids = body_node
        .attributes
        .get_key("id")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default();
    matcher.path.extend(
        ids.into_iter()
            .map(|id| CssPathSelector::Id(id.to_string().into())),
    );
    let classes = body_node
        .attributes
        .get_key("class")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default();
    matcher.path.extend(
        classes
            .into_iter()
            .map(|class| CssPathSelector::Class(class.to_string().into())),
    );

    let matcher_hash = matcher.get_hash();
    let css_blocks_for_this_node = get_css_blocks(css, &matcher);
    if !css_blocks_for_this_node.is_empty() {
        // Track property types for the helper-const machinery, then emit the
        // matched declarations as an inline CSS string. (The old path emitted a
        // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` + `.with_inline_css_props`,
        // but that API was removed in 32d44ed8a; `.with_css(<str>)` is the
        // current equivalent and parses pseudo blocks too.)
        for css_block in &css_blocks_for_this_node {
            for declaration in css_block.block.declarations.as_ref() {
                let prop = match declaration {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(d) => &d.default_value,
                };
                extra_blocks.insert_from_css_property(prop);
            }
        }

        let inline_css = css_blocks_to_inline_string(&css_blocks_for_this_node);
        if !inline_css.is_empty() {
            let escaped = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = write!(dom_string, "\r\n{t2}.with_css(\"{escaped}\")");
        }
        let _ = (&mut *css_blocks, matcher_hash); // retained for signature compat
    }

    if !body_node.children.as_ref().is_empty() {
        use azul_css::codegen::format::GetHash;
        let children_hash = body_node.children.as_ref().get_hash();
        dom_string.push_str("\r\n.with_children(vec![\r\n");

        for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
            match child {
                XmlNodeChild::Element(child_node) => {
                    let mut matcher = matcher.clone();
                    matcher.path.push(CssPathSelector::Children);
                    matcher.indices_in_parent.push(child_idx);
                    matcher.children_length.push(body_node.children.len());

                    let _ = write!(
                        dom_string,
                        "{}{},\r\n",
                        t,
                        compile_node_to_rust_code_inner(
                            child_node,
                            component_map,
                            1,
                            extra_blocks,
                            css_blocks,
                            css,
                            matcher,
                        )?
                    );
                }
                XmlNodeChild::Text(text) => {
                    let text = text.trim();
                    if !text.is_empty() {
                        let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
                        let _ = write!(dom_string,
                            "{t}Dom::create_text_do_not_use_without_block_level_wrapper(\"{escaped}\"),\r\n"
                        );
                    }
                }
            }
        }
        let _ = write!(dom_string, "\r\n{t}])");
    }

    let dom_string = dom_string.trim();
    Ok(dom_string.to_string())
}

/// Serialize the CSS blocks matched for a node into one inline CSS string for
/// `Dom::with_css(...)`. `with_css` parses via `Css::parse_inline`, which runs
/// the full selector+nesting machinery, so `:hover`/`:active`/`:focus` are
/// emitted as nested pseudo blocks and round-trip faithfully; plain rules are
/// emitted flat as `key: value;` (via `CssProperty::key()` / `value()`).
fn css_blocks_to_inline_string(blocks: &[CssBlock]) -> String {
    fn decls_of(block: &CssBlock) -> Vec<String> {
        block
            .block
            .declarations
            .as_ref()
            .iter()
            .map(|d| {
                let prop = match d {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(dy) => &dy.default_value,
                };
                format!("{}: {};", prop.key(), prop.value())
            })
            .collect()
    }

    let mut normal: Vec<String> = Vec::new();
    let mut pseudo: Vec<String> = Vec::new();
    for block in blocks {
        let pseudo_sel = match block.ending {
            Some(CssPathPseudoSelector::Hover) => Some(":hover"),
            Some(CssPathPseudoSelector::Active) => Some(":active"),
            Some(CssPathPseudoSelector::Focus) => Some(":focus"),
            Some(CssPathPseudoSelector::SeatFocus) => Some(":seat-focus"),
            _ => None,
        };
        match pseudo_sel {
            None => normal.extend(decls_of(block)),
            Some(sel) => pseudo.push(format!("{} {{ {} }}", sel, decls_of(block).join(" "))),
        }
    }

    let mut parts = normal;
    parts.extend(pseudo);
    parts.join(" ")
}

fn get_css_blocks(css: &Css, matcher: &CssMatcher) -> Vec<CssBlock> {
    let mut blocks = Vec::new();

    for css_block in css.rules.as_ref() {
        if matcher.matches(&css_block.path) {
            let ending = match css_block.path.selectors.as_ref().last() {
                Some(CssPathSelector::PseudoSelector(p)) => Some(p.clone()),
                _ => None,
            };

            blocks.push(CssBlock {
                ending,
                block: css_block.clone(),
            });
        }
    }

    blocks
}

fn compile_and_format_dynamic_items(input: &[DynamicItem]) -> String {
    use self::DynamicItem::{Str, Var};
    if input.is_empty() {
        String::from("AzString::from_const_str(\"\")")
    } else if input.len() == 1 {
        // common: there is only one "dynamic item" - skip the "format!()" macro
        match &input[0] {
            Var { name, format_spec } => {
                let var_name = normalize_casing(name.trim());
                if let Some(spec) = format_spec {
                    format!("format!(\"{{:{spec}}}\", {var_name}).into()")
                } else {
                    var_name
                }
            }
            Str(s) => format!("AzString::from_const_str(\"{s}\")"),
        }
    } else {
        // build a "format!("{var}, blah", var)" string
        let mut formatted_str = String::from("format!(\"");
        let mut variables = Vec::new();
        for item in input {
            match item {
                Var { name, format_spec } => {
                    let variable_name = normalize_casing(name.trim());
                    if let Some(spec) = format_spec {
                        let _ = write!(formatted_str, "{{{variable_name}:{spec}}}");
                    } else {
                        let _ = write!(formatted_str, "{{{variable_name}}}");
                    }
                    variables.push(variable_name.clone());
                }
                Str(s) => {
                    let s = s.replace('"', "\\\"");
                    formatted_str.push_str(&s);
                }
            }
        }

        formatted_str.push('\"');
        if !variables.is_empty() {
            formatted_str.push_str(", ");
        }

        formatted_str.push_str(&variables.join(", "));
        formatted_str.push_str(").into()");
        formatted_str
    }
}

fn format_args_for_rust_code(input: &str) -> String {
    let dynamic_str_items = split_dynamic_string(input);
    compile_and_format_dynamic_items(&dynamic_str_items)
}

#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// component_map is forwarded through the codegen recursion for parity with the
// component-expanding path; this Rust-codegen path only threads it into recursive calls.
#[allow(clippy::only_used_in_recursion)]
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
fn compile_node_to_rust_code_inner(
    node: &XmlNode,
    component_map: &ComponentMap,
    tabs: usize,
    extra_blocks: &mut VecContents,
    css_blocks: &mut BTreeMap<String, String>,
    css: &Css,
    mut matcher: CssMatcher,
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;

    let t = String::from("    ").repeat(tabs - 1);
    let t2 = String::from("    ").repeat(tabs);

    let component_name = normalize_casing(&node.node_type);

    // Look up the CSS NodeTypeTag
    let node_type_tag = tag_to_node_type_tag(&component_name);
    let node_type = CssPathSelector::Type(node_type_tag);

    // Emit a plain `create_node(<Tag>)` for the base node. Do NOT route through
    // the component `compile_fn`: its Rust arm bakes inline text into a
    // `.with_children(..)`, which the child-walk below would then OVERWRITE with
    // a second `.with_children(..)` — silently dropping the text on any node
    // that has BOTH text and element children. The child-walk handles ALL
    // children (text + elements) in order, so the base node must stay childless.
    // Interactive/data tags (Button/Input/…) whose NodeType carries data fall
    // back to `div`, matching the C/C++/Python walkers (`safe_container_tag`).
    let ctor = analyze_node_ctor(&component_name, node);
    let mut dom_string = ctor.render_rust().map_or_else(
        || {
            let tag = safe_container_tag(&format!("{:?}", tag_to_node_type(&component_name)));
            format!("{t2}Dom::create_node(NodeType::{tag})")
        },
        |expr| format!("{t2}{expr}"),
    );

    matcher.path.push(node_type);
    let ids = node
        .attributes
        .get_key("id")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default();

    matcher.path.extend(
        ids.into_iter()
            .map(|id| CssPathSelector::Id(id.to_string().into())),
    );

    let classes = node
        .attributes
        .get_key("class")
        .map(|s| s.split_whitespace().collect::<Vec<_>>())
        .unwrap_or_default();

    matcher.path.extend(
        classes
            .into_iter()
            .map(|class| CssPathSelector::Class(class.to_string().into())),
    );

    let matcher_hash = matcher.get_hash();
    let css_blocks_for_this_node = get_css_blocks(css, &matcher);
    if !css_blocks_for_this_node.is_empty() {
        // Track property types for the helper-const machinery, then emit the
        // matched declarations as an inline CSS string. (The old path emitted a
        // `const CSS_MATCH_*: NodeDataInlineCssPropertyVec` + `.with_inline_css_props`,
        // but that API was removed in 32d44ed8a; `.with_css(<str>)` is the
        // current equivalent and parses pseudo blocks too.)
        for css_block in &css_blocks_for_this_node {
            for declaration in css_block.block.declarations.as_ref() {
                let prop = match declaration {
                    CssDeclaration::Static(s) => s,
                    CssDeclaration::Dynamic(d) => &d.default_value,
                };
                extra_blocks.insert_from_css_property(prop);
            }
        }

        let inline_css = css_blocks_to_inline_string(&css_blocks_for_this_node);
        if !inline_css.is_empty() {
            let escaped = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = write!(dom_string, "\r\n{t2}.with_css(\"{escaped}\")");
        }
        let _ = (&mut *css_blocks, matcher_hash); // retained for signature compat
    }

    set_stringified_attributes(
        &mut dom_string,
        &node.attributes,
        &ComponentArgumentVec::new(),
        tabs,
    );

    // Text folded into the ctor (Tier A/C) is skipped, as is a `<caption>`
    // already injected by `create_table`.
    let mut caption_skipped = false;
    let mut children_string = node
        .children
        .as_ref()
        .iter()
        .enumerate()
        .filter_map(|(child_idx, c)| match c {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    return None;
                }
                let mut matcher = matcher.clone();
                matcher.path.push(CssPathSelector::Children);
                matcher.indices_in_parent.push(child_idx);
                matcher.children_length.push(node.children.len());

                Some(compile_node_to_rust_code_inner(
                    child_node,
                    component_map,
                    tabs + 1,
                    extra_blocks,
                    css_blocks,
                    css,
                    matcher,
                ))
            }
            XmlNodeChild::Text(text) => {
                if ctor.consumes_text() {
                    return None;
                }
                let text = text.trim();
                if text.is_empty() {
                    None
                } else {
                    let t2 = String::from("    ").repeat(tabs);
                    let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
                    Some(Ok(format!(
                        "{t2}Dom::create_text_do_not_use_without_block_level_wrapper(\"{escaped}\")"
                    )))
                }
            }
        })
        .collect::<Result<Vec<_>, _>>()?
        .join(",\r\n");

    if !children_string.is_empty() {
        let _ = write!(
            dom_string,
            "\r\n{t2}.with_children(vec![\r\n{children_string}\r\n{t2}])"
        );
    }

    Ok(dom_string)
}

// ───────────────────────────────────────────────────────────────────────────
// Generic FLUENT DOM-builder emitter (C++ / Python).
//
// Rust has its own dedicated walker above (`compile_*_to_rust_code`). C++ and
// Python share this generic walker because their builder APIs are also fluent
// (`Dom::create_*().with_css(..).with_child(..)`); only the surface tokens
// differ, captured in `FluentSyntax`. Plain C is imperative and has its own
// walker (`compile_*_to_c_code`).
// ───────────────────────────────────────────────────────────────────────────

/// Tags with a zero-arg per-tag creator (`create_<tag>()` / `AzDom_create<Tag>()`
/// / `create_node(NodeType::<Tag>)`). Interactive / data elements (Button, Input,
/// Img, Select, Textarea, Label, A, Table, …) take constructor arguments, so an
/// exported page maps them to a plain `div` container (structure preserved; the
/// user re-wires behavior). Keep these CamelCase to match `NodeTypeTag` debug names.
const SAFE_CONTAINER_TAGS: &[&str] = &[
    // These must match the real `NodeType` Debug names exactly (the lookup below is a
    // string compare against `{:?}`). Six used to be mis-cased — "Blockquote",
    // "Colgroup", "Figcaption", "Tbody", "Tfoot", "Thead" — so those tags silently
    // degraded to "Div".
    "Abbr",
    "Acronym",
    "Address",
    "Article",
    "Aside",
    "B",
    "Bdi",
    "Bdo",
    "Big",
    "BlockQuote",
    "Body",
    "Br",
    "Caption",
    "Cite",
    "Code",
    "ColGroup",
    "Dd",
    "Del",
    "Dfn",
    "Dir",
    "Div",
    "Dl",
    "Dt",
    "Em",
    "Embed",
    "FigCaption",
    "Figure",
    "Footer",
    "H1",
    "H2",
    "H3",
    "H4",
    "H5",
    "H6",
    "Head",
    "Header",
    "Hr",
    "Html",
    "I",
    "Ins",
    "Kbd",
    "Li",
    "Link",
    "Main",
    "Map",
    "Mark",
    "Meta",
    "Nav",
    "Object",
    "Ol",
    "P",
    "Pre",
    "Q",
    "Rp",
    "Rt",
    "Rtc",
    "Ruby",
    "S",
    "Samp",
    "Script",
    "Section",
    "Small",
    "Span",
    "Strong",
    "Style",
    "Sub",
    "Sup",
    "Svg",
    "TBody",
    "Td",
    "TFoot",
    "Th",
    "THead",
    "Title",
    "Tr",
    "U",
    "Ul",
    "Var",
    "Wbr",
];

/// The CamelCase tag to actually emit a creator for: the tag itself if it has a
/// zero-arg creator, else `"Div"`.
fn safe_container_tag(tag_dbg: &str) -> &'static str {
    SAFE_CONTAINER_TAGS
        .iter()
        .copied()
        .find(|t| *t == tag_dbg)
        .unwrap_or("Div")
}

// ───────────────────────────────────────────────────────────────────────────
// Semantic / accessibility-aware constructor selection.
//
// Instead of mapping every element to a plain `div`, an exported live page
// picks the *most specific* Azul constructor so the generated app keeps the
// page's semantics + accessibility tree:
//
//   • Tier A  `create_<tag>_with_text(text)` — a tag with a single text child
//             and no element children (P, Span, H1-H6, Li, Td, Code, …).
//   • Tier B  aria-only / void widgets (Details, Summary, Form, Canvas, Area,
//             …) — `create_<tag>(SmallAriaInfo::label(..))` when `aria-label`
//             is present, else `create_<tag>_no_a11y()`.
//   • Tier C  multi-arg widgets (Button, A, Label, Input, Select, Option,
//             Optgroup, Textarea, Table) — args pulled from HTML attributes.
//   • Tier D  scalar-driven widgets (Progress, Meter, Dialog) — the `*_no_a11y`
//             form with extracted numeric args (the full aria structs are
//             complex; the NoA11y form is simplest + correct).
//
// Every symbol emitted here is verified to exist in `target/codegen/azul.h` (C)
// and `azul20.hpp` (C++); anything else falls back to `safe_container_tag`
// (`div`). The four walkers share `analyze_node_ctor` and each renders the
// result with its own surface tokens.
// ───────────────────────────────────────────────────────────────────────────

/// A single positional argument of a semantic constructor. String payloads are
/// RAW — escaping happens at render time (matching the walkers).
#[derive(Debug, Clone)]
enum CtorArg {
    /// Plain string literal (`AzString` / `String` / `"…"`).
    Str(String),
    /// `SmallAriaInfo` built from an accessible label.
    Aria(String),
    /// `f32` numeric literal.
    Float(f32),
    /// `OptionString::Some(text)`.
    OptSome(String),
    /// `OptionString::None`.
    OptNone,
}

/// The constructor chosen for an element node.
enum NodeCtor {
    /// Plain container — keep each walker's existing `create_<tag>()` path.
    Plain,
    /// A specific semantic constructor.
    Semantic {
        /// Canonical CamelCase suffix after `create` / `AzDom_create`
        /// (e.g. `Button`, `ButtonNoA11y`, `PWithText`, `A`, `ANoA11y`).
        suffix: String,
        args: Vec<CtorArg>,
        /// The node's direct text is folded into the ctor — skip text children
        /// in the walk so it isn't emitted twice.
        consumes_text: bool,
        /// The table aria form injects its own `<caption>` child — drop the
        /// first literal `<caption>` element so it isn't duplicated.
        skip_caption: bool,
    },
}

/// Uppercase the first character (`button` → `Button`, `h1` → `H1`). HTML tags
/// are single lowercase tokens, so this yields the exact `AzDom_create<Suffix>`
/// spelling.
fn cap_first(tag: &str) -> String {
    let mut c = tag.chars();
    c.next().map_or_else(String::new, |f| {
        f.to_uppercase().collect::<String>() + c.as_str()
    })
}

/// CamelCase → `snake_case` for the C++/Python/Rust method names
/// (`ButtonNoA11y` → `button_no_a11y`, `PWithText` → `p_with_text`,
/// `ANoA11y` → `a_no_a11y`, `H1WithText` → `h1_with_text`).
fn camel_to_snake(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::new();
    for (i, &ch) in chars.iter().enumerate() {
        if ch.is_ascii_uppercase() && i > 0 {
            let prev = chars[i - 1];
            let next_lower = chars.get(i + 1).is_some_and(char::is_ascii_lowercase);
            if prev.is_ascii_lowercase()
                || prev.is_ascii_digit()
                || (prev.is_ascii_uppercase() && next_lower)
            {
                out.push('_');
            }
        }
        out.extend(ch.to_lowercase());
    }
    out
}

/// Escape `\` and `"` for a double-quoted string literal.
fn esc_lit(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Format an `f32` as a valid float literal with a decimal point (`1` → `1.0`).
fn fmt_f32_lit(f: f32) -> String {
    let s = format!("{f}");
    if s.contains('.') || s.contains('e') || s.contains("inf") || s.contains("NaN") {
        s
    } else {
        format!("{s}.0")
    }
}

/// Joined, trimmed text of a node's *direct* text children (`"  Go  "` → `"Go"`).
fn node_direct_text(node: &XmlNode) -> String {
    node.children
        .as_ref()
        .iter()
        .filter_map(|c| match c {
            XmlNodeChild::Text(t) => {
                let t = t.trim();
                if t.is_empty() {
                    None
                } else {
                    Some(t.to_string())
                }
            }
            XmlNodeChild::Element(_) => None,
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Non-empty `aria-label` attribute value, if present.
fn node_aria_label(node: &XmlNode) -> Option<String> {
    node.attributes.get_key("aria-label").and_then(|v| {
        let v = v.as_str().trim();
        if v.is_empty() {
            None
        } else {
            Some(v.to_string())
        }
    })
}

/// Attribute value, or `default` when absent.
fn node_attr_or(node: &XmlNode, key: &str, default: &str) -> String {
    node.attributes
        .get_key(key)
        .map_or_else(|| default.to_string(), |v| v.as_str().to_string())
}

/// Attribute parsed as `f32`, or `default` when absent / unparsable.
fn node_attr_f32(node: &XmlNode, key: &str, default: f32) -> f32 {
    node.attributes
        .get_key(key)
        .and_then(|v| v.as_str().trim().parse::<f32>().ok())
        .unwrap_or(default)
}

/// Text of the node's first `<caption>` element child, if any (non-empty).
fn first_caption_text(node: &XmlNode) -> Option<String> {
    node.children.as_ref().iter().find_map(|c| match c {
        XmlNodeChild::Element(e) if e.node_type.as_str().eq_ignore_ascii_case("caption") => {
            let t = e.get_text_content();
            let t = t.trim();
            if t.is_empty() {
                None
            } else {
                Some(t.to_string())
            }
        }
        _ => None,
    })
}

/// Tags with a single-arg `create_<tag>_with_text(text)` constructor (Tier A).
const WITH_TEXT_TAGS: &[&str] = &[
    "acronym",
    "b",
    "bdi",
    "bdo",
    "big",
    "blockquote",
    "cite",
    "code",
    "del",
    "dfn",
    "em",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "i",
    "ins",
    "kbd",
    "li",
    "mark",
    "p",
    "pre",
    "rp",
    "rt",
    "s",
    "samp",
    "small",
    "span",
    "strong",
    "style",
    "sub",
    "sup",
    "td",
    "th",
    "title",
    "u",
    "var",
];

/// Pick the semantic constructor for `tag` (lowercase HTML tag) + `node`.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
fn analyze_node_ctor(tag: &str, node: &XmlNode) -> NodeCtor {
    // Helper for the common "no caption skip" case.
    fn sem(suffix: impl Into<String>, args: Vec<CtorArg>, consumes_text: bool) -> NodeCtor {
        NodeCtor::Semantic {
            suffix: suffix.into(),
            args,
            consumes_text,
            skip_caption: false,
        }
    }

    let aria = node_aria_label(node);
    let has_aria = aria.is_some();
    let label = aria.unwrap_or_default();
    // `has_only_text_children()` is also true for childless nodes; pair it with
    // `has_text` so empty elements stay plain containers.
    let pure_text = node.has_only_text_children();
    let text = node_direct_text(node);
    let has_text = !text.is_empty();
    let cap = cap_first(tag);

    // Tier A — *_with_text (single text child, no element children).
    if WITH_TEXT_TAGS.contains(&tag) {
        if pure_text && has_text {
            return sem(format!("{cap}WithText"), vec![CtorArg::Str(text)], true);
        }
        return NodeCtor::Plain;
    }

    match tag {
        // Tier B — aria-only / void widgets.
        "details" | "form" | "fieldset" | "legend" | "menu" | "output" | "datalist" | "canvas"
        | "audio" | "video" | "area" => {
            if has_aria {
                sem(cap, vec![CtorArg::Aria(label)], false)
            } else {
                sem(format!("{cap}NoA11y"), vec![], false)
            }
        }
        // Summary is Tier B but also has a WithText form for a single text child.
        "summary" => {
            if pure_text && has_text {
                if has_aria {
                    sem(
                        "SummaryWithText",
                        vec![CtorArg::Str(text), CtorArg::Aria(label)],
                        true,
                    )
                } else {
                    sem("SummaryWithTextNoA11y", vec![CtorArg::Str(text)], true)
                }
            } else if has_aria {
                sem("Summary", vec![CtorArg::Aria(label)], false)
            } else {
                sem("SummaryNoA11y", vec![], false)
            }
        }

        // Tier C — multi-arg widgets (args from HTML attributes).
        "button" => {
            if has_aria {
                sem(
                    "Button",
                    vec![CtorArg::Str(text), CtorArg::Aria(label)],
                    true,
                )
            } else {
                sem("ButtonNoA11y", vec![CtorArg::Str(text)], true)
            }
        }
        "a" => {
            let href = node_attr_or(node, "href", "");
            if has_aria {
                sem(
                    "A",
                    vec![CtorArg::Str(href), CtorArg::Str(text), CtorArg::Aria(label)],
                    true,
                )
            } else {
                let lbl = if has_text {
                    CtorArg::OptSome(text)
                } else {
                    CtorArg::OptNone
                };
                sem("ANoA11y", vec![CtorArg::Str(href), lbl], true)
            }
        }
        "label" => {
            let for_id = node_attr_or(node, "for", "");
            if has_aria {
                sem(
                    "Label",
                    vec![
                        CtorArg::Str(for_id),
                        CtorArg::Str(text),
                        CtorArg::Aria(label),
                    ],
                    true,
                )
            } else {
                sem(
                    "LabelNoA11y",
                    vec![CtorArg::Str(for_id), CtorArg::Str(text)],
                    true,
                )
            }
        }
        "input" => {
            let ty = node_attr_or(node, "type", "text");
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Input",
                    vec![
                        CtorArg::Str(ty),
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "InputNoA11y",
                    vec![CtorArg::Str(ty), CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
        "textarea" => {
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Textarea",
                    vec![
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "TextareaNoA11y",
                    vec![CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
        "select" => {
            let name = node_attr_or(node, "name", "");
            if has_aria {
                sem(
                    "Select",
                    vec![
                        CtorArg::Str(name),
                        CtorArg::Str(label.clone()),
                        CtorArg::Aria(label),
                    ],
                    false,
                )
            } else {
                sem(
                    "SelectNoA11y",
                    vec![CtorArg::Str(name), CtorArg::Str(label)],
                    false,
                )
            }
        }
        "option" => {
            let value = node_attr_or(node, "value", "");
            if has_aria {
                sem(
                    "Option",
                    vec![
                        CtorArg::Str(value),
                        CtorArg::Str(text),
                        CtorArg::Aria(label),
                    ],
                    true,
                )
            } else {
                sem(
                    "OptionNoA11y",
                    vec![CtorArg::Str(value), CtorArg::Str(text)],
                    true,
                )
            }
        }
        "optgroup" => {
            let lbl = node_attr_or(node, "label", "");
            if has_aria {
                sem(
                    "Optgroup",
                    vec![CtorArg::Str(lbl), CtorArg::Aria(label)],
                    false,
                )
            } else {
                sem("OptgroupNoA11y", vec![CtorArg::Str(lbl)], false)
            }
        }
        "table" => {
            if has_aria {
                // The aria form injects a caption child, so take the caption from
                // the literal <caption> (or the aria label) and drop the literal.
                let caption = first_caption_text(node).unwrap_or_else(|| label.clone());
                NodeCtor::Semantic {
                    suffix: "Table".to_string(),
                    args: vec![CtorArg::Str(caption), CtorArg::Aria(label)],
                    consumes_text: false,
                    skip_caption: true,
                }
            } else {
                sem("TableNoA11y", vec![], false)
            }
        }

        // Tier D — scalar-driven widgets (NoA11y form with extracted numbers).
        "progress" => sem(
            "ProgressNoA11y",
            vec![
                CtorArg::Float(node_attr_f32(node, "value", 0.0)),
                CtorArg::Float(node_attr_f32(node, "max", 1.0)),
            ],
            false,
        ),
        "meter" => sem(
            "MeterNoA11y",
            vec![
                CtorArg::Float(node_attr_f32(node, "value", 0.0)),
                CtorArg::Float(node_attr_f32(node, "min", 0.0)),
                CtorArg::Float(node_attr_f32(node, "max", 1.0)),
            ],
            false,
        ),
        "dialog" => sem("DialogNoA11y", vec![], false),

        _ => NodeCtor::Plain,
    }
}

impl CtorArg {
    /// Rust expression for this argument (`AzString::from(..)` works for both the
    /// `Into<AzString>` and the concrete `AzString` parameter forms).
    fn render_rust(&self) -> String {
        match self {
            Self::Str(s) => format!("AzString::from(\"{}\")", esc_lit(s)),
            Self::Aria(s) => format!("SmallAriaInfo::label(AzString::from(\"{}\"))", esc_lit(s)),
            Self::Float(f) => fmt_f32_lit(*f),
            Self::OptSome(s) => format!("OptionString::Some(AzString::from(\"{}\"))", esc_lit(s)),
            Self::OptNone => "OptionString::None".to_string(),
        }
    }
    fn render_c(&self) -> String {
        match self {
            Self::Str(s) => format!("AZ_STR(\"{}\")", esc_lit(s)),
            Self::Aria(s) => format!("AzSmallAriaInfo_label(AZ_STR(\"{}\"))", esc_lit(s)),
            Self::Float(f) => format!("{}f", fmt_f32_lit(*f)),
            Self::OptSome(s) => format!("AzOptionString_some(AZ_STR(\"{}\"))", esc_lit(s)),
            Self::OptNone => "AzOptionString_none()".to_string(),
        }
    }
    fn render_cpp(&self) -> String {
        match self {
            Self::Str(s) => format!("String(\"{}\")", esc_lit(s)),
            Self::Aria(s) => format!("SmallAriaInfo::label(String(\"{}\"))", esc_lit(s)),
            Self::Float(f) => format!("{}f", fmt_f32_lit(*f)),
            Self::OptSome(s) => format!("OptionString::some(String(\"{}\"))", esc_lit(s)),
            Self::OptNone => "OptionString::none()".to_string(),
        }
    }
    fn render_python(&self) -> String {
        match self {
            Self::Str(s) => format!("\"{}\"", esc_lit(s)),
            Self::Aria(s) => format!("azul.SmallAriaInfo.label(\"{}\")", esc_lit(s)),
            Self::Float(f) => fmt_f32_lit(*f),
            Self::OptSome(s) => format!("azul.OptionString.some(\"{}\")", esc_lit(s)),
            Self::OptNone => "azul.OptionString.none()".to_string(),
        }
    }
}

impl NodeCtor {
    const fn consumes_text(&self) -> bool {
        matches!(
            self,
            Self::Semantic {
                consumes_text: true,
                ..
            }
        )
    }
    const fn skip_caption(&self) -> bool {
        matches!(
            self,
            Self::Semantic {
                skip_caption: true,
                ..
            }
        )
    }
    /// `Dom::create_…(args)` for Rust, or `None` for a plain container.
    fn render_rust(&self) -> Option<String> {
        match self {
            Self::Plain => None,
            Self::Semantic { suffix, args, .. } => Some(format!(
                "Dom::create_{}({})",
                camel_to_snake(suffix),
                args.iter()
                    .map(CtorArg::render_rust)
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
        }
    }
    /// `AzDom_create…(args)` for C, or `None` for a plain container.
    fn render_c(&self) -> Option<String> {
        match self {
            Self::Plain => None,
            Self::Semantic { suffix, args, .. } => Some(format!(
                "AzDom_create{}({})",
                suffix,
                args.iter()
                    .map(CtorArg::render_c)
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
        }
    }
    /// Fluent `Dom::create_…` (C++) / `azul.Dom.create_…` (Python), or `None`.
    fn render_fluent(&self, target: &CompileTarget) -> Option<String> {
        match self {
            Self::Plain => None,
            Self::Semantic { suffix, args, .. } => {
                let snake = camel_to_snake(suffix);
                let (prefix, rendered) = match target {
                    CompileTarget::Cpp => (
                        format!("Dom::create_{snake}"),
                        args.iter().map(CtorArg::render_cpp).collect::<Vec<_>>(),
                    ),
                    CompileTarget::Python => (
                        format!("azul.Dom.create_{snake}"),
                        args.iter().map(CtorArg::render_python).collect::<Vec<_>>(),
                    ),
                    _ => return None,
                };
                Some(format!("{}({})", prefix, rendered.join(", ")))
            }
        }
    }
}

/// Per-language token hooks for the fluent walker. The `&str` args are already
/// escaped for a double-quoted string literal.
struct FluentSyntax {
    target: CompileTarget,
    /// tag debug-name (e.g. "Div") -> full create expression
    create_node: fn(&str) -> String,
    /// escaped text -> create-text expression
    create_text: fn(&str) -> String,
    /// escaped css -> `.with_css(..)` call
    with_css: fn(&str) -> String,
    /// escaped class -> `.with_class(..)` call
    with_class: fn(&str) -> String,
    /// escaped id -> `.with_id(..)` call
    with_id: fn(&str) -> String,
    /// escaped child expression -> `.with_child(..)` call (children are chained)
    with_child: fn(&str) -> String,
}

const CPP_SYNTAX: FluentSyntax = FluentSyntax {
    target: CompileTarget::Cpp,
    // Use per-tag creators (Dom::create_div(), create_p(), create_body(), …)
    // — `NodeType` is a tagged union, so `create_node` would need union
    // construction; the per-tag creators exist for every common HTML element.
    create_node: |tag| alloc::format!("Dom::create_{}()", tag.to_lowercase()),
    create_text: |s| {
        alloc::format!("Dom::create_text_do_not_use_without_block_level_wrapper(String(\"{s}\"))")
    },
    with_css: |s| alloc::format!(".with_css(String(\"{s}\"))"),
    with_class: |s| alloc::format!(".with_class(String(\"{s}\"))"),
    with_id: |s| alloc::format!(".with_id(String(\"{s}\"))"),
    with_child: |c| alloc::format!(".with_child({c})"),
};

const PYTHON_SYNTAX: FluentSyntax = FluentSyntax {
    target: CompileTarget::Python,
    // Per-tag creators (azul.Dom.create_div(), …) — see CPP_SYNTAX note.
    create_node: |tag| alloc::format!("azul.Dom.create_{}()", tag.to_lowercase()),
    create_text: |s| {
        alloc::format!("azul.Dom.create_text_do_not_use_without_block_level_wrapper(\"{s}\")")
    },
    with_css: |s| alloc::format!(".with_css(\"{s}\")"),
    with_class: |s| alloc::format!(".with_class(\"{s}\")"),
    with_id: |s| alloc::format!(".with_id(\"{s}\")"),
    with_child: |c| alloc::format!(".with_child({c})"),
};

/// Walk one element node, emitting a fluent create-expression for `syntax`'s
/// language. Mirrors `compile_node_to_rust_code_inner` but token-parameterized.
#[allow(clippy::result_large_err)]
// returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
// See compile_node_to_rust_code_inner: component_map is forwarded for codegen-path parity.
#[allow(clippy::only_used_in_recursion)]
fn compile_node_fluent(
    node: &XmlNode,
    syntax: &FluentSyntax,
    component_map: &ComponentMap,
    css: &Css,
    mut matcher: CssMatcher,
) -> Result<String, CompileError> {
    use azul_css::css::CssDeclaration;

    let component_name = normalize_casing(&node.node_type);
    let node_type_tag = tag_to_node_type_tag(&component_name);
    let tag_dbg = alloc::format!("{:?}", tag_to_node_type(&component_name));

    // Base create-expression. For an exported live page every node is a plain
    // HTML element, so emit a per-tag creator directly via the language hooks
    // (universal + verified) rather than the per-component `compile_fn`, whose
    // C++/Python arms emit stale placeholder syntax (`Dom.div()` etc.).
    // Interactive/data tags (whose creators need args) fall back to `div`. Any
    // element text shows up as a Text child below and is handled there.
    let ctor = analyze_node_ctor(&component_name, node);
    let mut s = ctor.render_fluent(&syntax.target).map_or_else(
        || (syntax.create_node)(safe_container_tag(&tag_dbg)),
        |expr| expr,
    );

    matcher.path.push(CssPathSelector::Type(node_type_tag));
    let ids: Vec<String> = node
        .attributes
        .get_key("id")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher
        .path
        .extend(ids.iter().map(|id| CssPathSelector::Id(id.clone().into())));
    let classes: Vec<String> = node
        .attributes
        .get_key("class")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher.path.extend(
        classes
            .iter()
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );

    // Inline CSS (matched rules -> `.with_css("..")`, pseudo blocks included).
    let blocks = get_css_blocks(css, &matcher);
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            s.push_str(&(syntax.with_css)(&esc));
        }
    }
    for id in &ids {
        s.push_str(&(syntax.with_id)(
            &id.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }
    for class in &classes {
        s.push_str(&(syntax.with_class)(
            &class.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }

    // Children (chained `.with_child(..)`). Text folded into the ctor (Tier A/C)
    // is skipped here, as is a `<caption>` already injected by `create_table`.
    let mut caption_skipped = false;
    for (child_idx, child) in node.children.as_ref().iter().enumerate() {
        match child {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    continue;
                }
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(node.children.len());
                let child_src = compile_node_fluent(child_node, syntax, component_map, css, m)?;
                s.push_str(&(syntax.with_child)(&child_src));
            }
            XmlNodeChild::Text(text) => {
                if ctor.consumes_text() {
                    continue;
                }
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    s.push_str(&(syntax.with_child)(&(syntax.create_text)(&esc)));
                }
            }
        }
    }

    Ok(s)
}

/// Build the `<body>` render-expression for `syntax`'s language.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
fn compile_body_fluent<'a>(
    body_node: &'a XmlNode,
    syntax: &FluentSyntax,
    component_map: &'a ComponentMap,
    css: &Css,
    mut matcher: CssMatcher,
) -> Result<String, CompileError> {
    let mut s = (syntax.create_node)("Body");
    matcher.path.push(CssPathSelector::Type(NodeTypeTag::Body));
    let classes: Vec<String> = body_node
        .attributes
        .get_key("class")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher.path.extend(
        classes
            .iter()
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );

    let blocks = get_css_blocks(css, &matcher);
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            s.push_str(&(syntax.with_css)(&esc));
        }
    }
    for class in &classes {
        s.push_str(&(syntax.with_class)(
            &class.replace('\\', "\\\\").replace('"', "\\\""),
        ));
    }

    for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
        match child {
            XmlNodeChild::Element(child_node) => {
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(body_node.children.len());
                let child_src = compile_node_fluent(child_node, syntax, component_map, css, m)?;
                s.push_str(&(syntax.with_child)(&child_src));
            }
            XmlNodeChild::Text(text) => {
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    s.push_str(&(syntax.with_child)(&(syntax.create_text)(&esc)));
                }
            }
        }
    }
    Ok(s)
}

/// Parse the page's `<style>` and seed a matcher rooted at `<body>`. Shared by
/// the C++/Python/C entry points (mirrors the head of `str_to_rust_code`).
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// Returns the body by VALUE: `get_html_node` may have synthesised the `<html>`
/// wrapper (a fragment with no root of its own), and a reference into a node
/// this function owns cannot outlive it. Codegen, not a hot path - one clone
/// of the body subtree per compile.
fn parse_page_style_and_body(root_nodes: &[XmlNodeChild]) -> Result<(Css, XmlNode), CompileError> {
    let html_node = get_html_node(root_nodes)?;
    let body_node = get_body_node(html_node.children.as_ref())?.clone();
    let mut global_style = Css::empty();
    if let Some(head_node) = find_node_by_type(html_node.children.as_ref(), "head") {
        if let Some(style_node) = find_node_by_type(head_node.children.as_ref(), "style") {
            let text = style_node.get_text_content();
            if !text.is_empty() {
                global_style = azul_css::parser2::new_from_str(&text).0;
            }
        }
    }
    global_style.sort_by_specificity();
    Ok((global_style, body_node))
}

fn body_matcher(body_node: &XmlNode) -> CssMatcher {
    CssMatcher {
        path: Vec::new(),
        indices_in_parent: vec![0],
        children_length: vec![body_node.children.as_ref().len()],
    }
}

/// Compile a full HTML page to a compilable **C++** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to C++ code.
pub fn str_to_cpp_code<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
) -> Result<String, CompileError> {
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
    let body_node = &body_node;
    let render = compile_body_fluent(
        body_node,
        &CPP_SYNTAX,
        component_map,
        &global_style,
        body_matcher(body_node),
    )?;
    Ok(alloc::format!(
        "// Auto-generated UI source code (C++). Build:\n\
         //   clang++ -std=c++20 -I <azul>/target/codegen main.cpp -lazul\n\
         #include \"azul20.hpp\"\n\
         using namespace azul;\n\n\
         struct Data {{}};\n\n\
         AzDom render(AzRefAny data, AzLayoutCallbackInfo info) {{\n    \
         return {render};\n}}\n\n\
         int main() {{\n    \
         RefAny data = RefAny::create(Data{{}});\n    \
         WindowCreateOptions window = WindowCreateOptions::create(render);\n    \
         App app = App::create(std::move(data), AppConfig::default_());\n    \
         app.run(std::move(window));\n    \
         return 0;\n}}\n"
    ))
}

/// Compile a full HTML page to a compilable **Python** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to Python code.
pub fn str_to_python_code<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
) -> Result<String, CompileError> {
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
    let body_node = &body_node;
    let render = compile_body_fluent(
        body_node,
        &PYTHON_SYNTAX,
        component_map,
        &global_style,
        body_matcher(body_node),
    )?;
    Ok(alloc::format!(
        "# Auto-generated UI source code (Python). Run: python3 main.py\n\
         import azul\n\n\
         class Data:\n    pass\n\n\
         def render(data, info):\n    return (\n        {}\n    )\n\n\
         def main():\n    \
         app = azul.App.create(Data(), azul.AppConfig.create())\n    \
         window = azul.WindowCreateOptions.create(render)\n    \
         app.run(window)\n\n\
         if __name__ == \"__main__\":\n    main()\n",
        render.replace("\r\n", "\n        ")
    ))
}

// ───────────────────────────────────────────────────────────────────────────
// Imperative C emitter. C has no fluent builder: each node is a statement that
// creates an `AzDom` local, applies css/class (by-value, returns), and pushes
// children via `AzDom_addChild(&parent, child)`. A recursive walk emits the
// statements bottom-up and returns the variable name holding each node.
// ───────────────────────────────────────────────────────────────────────────

/// C per-tag creator suffix: `NodeTypeTag` debug name with first char kept and
/// the rest lowercased (`Div`->`Div`, `BlockQuote`->`Blockquote`, `H1`->`H1`),
/// matching `AzDom_create<Suffix>` in azul.h.
fn c_creator_suffix(tag_dbg: &str) -> String {
    let mut chars = tag_dbg.chars();
    chars.next().map_or_else(
        || "Div".to_string(),
        |first| {
            let rest: String = chars.as_str().to_lowercase();
            alloc::format!("{first}{rest}")
        },
    )
}

#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
#[allow(clippy::too_many_lines)] // large but cohesive: one branch per node kind
fn compile_node_c(
    node: &XmlNode,
    component_map: &ComponentMap,
    css: &Css,
    mut matcher: CssMatcher,
    counter: &mut usize,
    out: &mut String,
) -> Result<String, CompileError> {
    let _ = component_map;
    let component_name = normalize_casing(&node.node_type);
    let node_type_tag = tag_to_node_type_tag(&component_name);
    let tag_dbg = alloc::format!("{:?}", tag_to_node_type(&component_name));

    let var = alloc::format!("n{}", *counter);
    *counter += 1;
    let ctor = analyze_node_ctor(&component_name, node);
    match ctor.render_c() {
        Some(expr) => {
            let _ = writeln!(out, "    AzDom {var} = {expr};");
        }
        None => {
            let _ = writeln!(
                out,
                "    AzDom {} = AzDom_create{}();",
                var,
                c_creator_suffix(safe_container_tag(&tag_dbg))
            );
        }
    }

    matcher.path.push(CssPathSelector::Type(node_type_tag));
    let ids: Vec<String> = node
        .attributes
        .get_key("id")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher
        .path
        .extend(ids.iter().map(|id| CssPathSelector::Id(id.clone().into())));
    let classes: Vec<String> = node
        .attributes
        .get_key("class")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher.path.extend(
        classes
            .iter()
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );

    let blocks = get_css_blocks(css, &matcher);
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = writeln!(out, "    {var} = AzDom_withCss({var}, AZ_STR(\"{esc}\"));");
        }
    }
    for id in &ids {
        let esc = id.replace('\\', "\\\\").replace('"', "\\\"");
        let _ = writeln!(out, "    {var} = AzDom_withId({var}, AZ_STR(\"{esc}\"));");
    }
    for class in &classes {
        let esc = class.replace('\\', "\\\\").replace('"', "\\\"");
        let _ = writeln!(
            out,
            "    {var} = AzDom_withClass({var}, AZ_STR(\"{esc}\"));"
        );
    }

    let mut caption_skipped = false;
    for (child_idx, child) in node.children.as_ref().iter().enumerate() {
        match child {
            XmlNodeChild::Element(child_node) => {
                if ctor.skip_caption()
                    && !caption_skipped
                    && child_node
                        .node_type
                        .as_str()
                        .eq_ignore_ascii_case("caption")
                {
                    caption_skipped = true;
                    continue;
                }
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(node.children.len());
                let child_var = compile_node_c(child_node, component_map, css, m, counter, out)?;
                let _ = writeln!(out, "    AzDom_addChild(&{var}, {child_var});");
            }
            XmlNodeChild::Text(text) => {
                if ctor.consumes_text() {
                    continue;
                }
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    let _ = writeln!(out,
                        "    AzDom_addChild(&{var}, AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{esc}\")));"
                    );
                }
            }
        }
    }
    Ok(var)
}

/// Compile a full HTML page to a compilable **C** Azul app.
#[allow(clippy::result_large_err)] // returns a #[repr(C,u8)] FFI error enum; boxing a variant would break the C ABI/api.json
/// # Errors
///
/// Returns an error if the XML cannot be parsed or compiled to C code.
pub fn str_to_c_code<'a>(
    root_nodes: &'a [XmlNodeChild],
    component_map: &'a ComponentMap,
) -> Result<String, CompileError> {
    let (global_style, body_node) = parse_page_style_and_body(root_nodes)?;
    let body_node = &body_node;
    let mut body = String::new();
    let mut counter = 0usize;

    // Emit the body as the root node, then its children.
    let root = alloc::format!("n{counter}");
    counter += 1;
    let _ = writeln!(body, "    AzDom {root} = AzDom_createBody();");

    let mut matcher = body_matcher(body_node);
    matcher.path.push(CssPathSelector::Type(NodeTypeTag::Body));
    let classes: Vec<String> = body_node
        .attributes
        .get_key("class")
        .map(|v| {
            v.split_whitespace()
                .map(alloc::string::ToString::to_string)
                .collect()
        })
        .unwrap_or_default();
    matcher.path.extend(
        classes
            .iter()
            .map(|c| CssPathSelector::Class(c.clone().into())),
    );
    let blocks = get_css_blocks(&global_style, &matcher);
    if !blocks.is_empty() {
        let inline_css = css_blocks_to_inline_string(&blocks);
        if !inline_css.is_empty() {
            let esc = inline_css.replace('\\', "\\\\").replace('"', "\\\"");
            let _ = writeln!(
                body,
                "    {root} = AzDom_withCss({root}, AZ_STR(\"{esc}\"));"
            );
        }
    }
    for (child_idx, child) in body_node.children.as_ref().iter().enumerate() {
        match child {
            XmlNodeChild::Element(child_node) => {
                let mut m = matcher.clone();
                m.path.push(CssPathSelector::Children);
                m.indices_in_parent.push(child_idx);
                m.children_length.push(body_node.children.len());
                let child_var = compile_node_c(
                    child_node,
                    component_map,
                    &global_style,
                    m,
                    &mut counter,
                    &mut body,
                )?;
                let _ = writeln!(body, "    AzDom_addChild(&{root}, {child_var});");
            }
            XmlNodeChild::Text(text) => {
                let text = text.trim();
                if !text.is_empty() {
                    let esc = text.replace('\\', "\\\\").replace('"', "\\\"");
                    let _ = writeln!(body,
                        "    AzDom_addChild(&{root}, AzDom_createTextDoNotUseWithoutBlockLevelWrapper(AZ_STR(\"{esc}\")));"
                    );
                }
            }
        }
    }

    Ok(alloc::format!(
        "/* Auto-generated UI source code (C). Build:\n\
         *   clang -I <azul>/target/codegen main.c -lazul\n */\n\
         #include \"azul.h\"\n\
         #include <string.h>\n\
         #define AZ_STR(s) AzString_copyFromBytes((const uint8_t*)(s), 0, strlen(s))\n\n\
         AzDom render(AzRefAny data, AzLayoutCallbackInfo info) {{\n\
         {body}    return {root};\n}}\n\n\
         int main(void) {{\n    \
         AzString data_type = AZ_STR(\"Data\");\n    \
         AzRefAny data = AzRefAny_newC((AzGlVoidPtrConst){{ .ptr = NULL }}, 0, 1, 0, data_type, NULL, 0, 0);\n    \
         AzApp app = AzApp_create(data, AzAppConfig_create());\n    \
         AzWindowCreateOptions window = AzWindowCreateOptions_create(render);\n    \
         AzApp_run(&app, window);\n    \
         AzApp_delete(&app);\n    \
         return 0;\n}}\n"
    ))
}

#[cfg(test)]
#[path = "xml_test.rs"]
mod xml_test;