microsoft-webui-parser 0.0.12

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

//! WebUI Framework parser plugin.
//!
//! # Overview
//!
//! Compiles HTML templates into structured metadata objects stored as raw
//! JS IIFE strings in the protocol. During SSR the handler wraps them in
//! a single `<script>` tag; during SPA navigation the router evaluates
//! them directly. Each metadata object contains
//! **marker-free static HTML** plus locator arrays for client-created DOM
//! (`tx`, `ag`, `cl`, `rl`, `el`) and semantic arrays (`a`, `c`, `r`, `e`,
//! `re`, `b`). The client runtime resolves those locators once and then
//! patches direct node references — **no template string parsing, no regex,
//! no DOM scanning** on the client-created path.
//!
//! # Metadata object format
//!
//! ```js
//! window.__webui.templates['my-component'] = {
//!   h: "<button class=\"item\"><span></span></button>",
//!   tx: [[[[0, 0], 0], [["title"]]]],
//!   a: [["title", 0, "title"]],
//!   ag: [[[0], 0, 1]],
//!   c: [[[1, "state", 3, "'done'"], 0]],
//!   cl: [[[0], 1]],
//!   e: [["click", "onClick", 0]],
//!   el: [[0]],
//!   b: [{ h: "<span class=\"check\">✓</span>" }],
//!   sa: "my-component",
//!   re: [["submit", "onSubmit", 1]],
//! };
//! ```
//!
//! # Plugin data protocol
//!
//! Each element with attribute bindings or events produces a 12-byte
//! `Plugin` fragment via [`finish_element`](ParserPlugin::finish_element):
//!
//! | Bytes  | Field              | Description                               |
//! |--------|--------------------|-------------------------------------------|
//! | 0–3    | `binding_count`    | Number of dynamic attribute bindings      |
//! | 4–7    | `event_start_idx`  | Starting index in the global event list   |
//! | 8–11   | `event_count`      | Number of `@event` attrs on this element  |
//!
//! The handler plugin decodes this to emit `data-w-*` binding markers
//! and single `data-ev="COUNT"` event markers on **SSR HTML only**. Compiled templates
//! keep the same binding/event indices but encode client targets via locator
//! arrays instead of embedding client-only marker attrs/comments in `h`.
//!
//! # Lifecycle
//!
//! 1. **`classify_attribute`** — intercepts `@event` attributes,
//!    counts them per-element, and keeps them out of the parsed protocol.
//! 2. **`finish_element`** — encodes the accumulated event count
//!    plus attribute binding count into 12 bytes.
//! 3. **`register_component_template`** — caches the component's final template
//!    HTML for later compilation (deduplicates by tag name).
//! 4. **`take_component_templates`** — called after parsing is complete;
//!    compiles each tracked component into a raw JS IIFE string.

use super::{AttributeAction, ParserPlugin, ParserPluginArtifacts};
use crate::component_registry::Component;
use crate::{ConditionParser, CssStrategy, DomStrategy, Result};
use std::cell::Cell;
use std::fmt::Write;
use webui_protocol::{condition_expr, ConditionExpr, WebUIElementData};

/// A component whose final template HTML has been captured for compilation.
/// Repeated tracking for the same tag updates the stored template so the plugin
/// can prefer processed HTML over raw component source.
struct TrackedComponent {
    tag_name: String,
    template_html: String,
    root_event_source: String,
}

/// WebUI Framework parser plugin.
///
/// Intercepts `@event` attributes and component registrations during parsing,
/// then compiles each component's HTML template into a metadata JS IIFE string.
///
/// # Event tracking
///
/// Event indices are assigned **globally** across all elements in a component.
/// `element_events` counts events on the current element (reset per element),
/// while `next_event_idx` is a monotonically increasing global counter.
/// This preserves event order in the emitted metadata while letting SSR HTML
/// mark one element with a single `data-ev="COUNT"` attribute.
pub struct WebUIParserPlugin {
    components: Vec<TrackedComponent>,
    /// Per-element event count, reset on each `finish_element` call.
    element_events: Cell<u32>,
    /// Global event index, incremented across all elements in a component.
    next_event_idx: Cell<u32>,
    /// DOM strategy — shadow or light.
    dom_strategy: DomStrategy,
}

impl WebUIParserPlugin {
    #[must_use]
    pub fn new() -> Self {
        Self {
            components: Vec::new(),
            element_events: Cell::new(0),
            next_event_idx: Cell::new(0),
            dom_strategy: DomStrategy::default(),
        }
    }

    pub fn set_css_strategy(&mut self, strategy: CssStrategy) {
        let _ = strategy;
    }

    pub fn set_dom_strategy(&mut self, strategy: DomStrategy) {
        self.dom_strategy = strategy;
    }

    /// Compile all tracked components and return `(tag_name, script_block)` pairs.
    ///
    /// Each script block is a self-executing IIFE that registers a metadata
    /// object into `window.__webui.templates[tagName]`. Call this after all
    /// HTML parsing is complete.
    #[must_use]
    pub fn take_component_templates(&self) -> Vec<(String, String)> {
        let use_shadow = matches!(self.dom_strategy, DomStrategy::Shadow);
        self.components
            .iter()
            .map(|c| {
                let script = generate_compiled_template_with_root_source(
                    &c.tag_name,
                    &c.template_html,
                    &c.root_event_source,
                    use_shadow,
                );
                (c.tag_name.clone(), script)
            })
            .collect()
    }

    fn store_component_template(
        &mut self,
        tag_name: &str,
        template_html: &str,
        root_event_source: &str,
    ) {
        if let Some(component) = self.components.iter_mut().find(|c| c.tag_name == tag_name) {
            component.template_html.clear();
            component.template_html.push_str(template_html);
            component.root_event_source.clear();
            component.root_event_source.push_str(root_event_source);
            return;
        }

        self.components.push(TrackedComponent {
            tag_name: tag_name.to_string(),
            template_html: template_html.to_string(),
            root_event_source: root_event_source.to_string(),
        });
    }
}

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

impl ParserPlugin for WebUIParserPlugin {
    fn start_fragment(&mut self, _fragment_id: &str) {
        self.element_events.set(0);
        self.next_event_idx.set(0);
    }

    fn classify_attribute(&mut self, attr_name: &str) -> AttributeAction {
        if attr_name.starts_with('@') {
            self.element_events.set(self.element_events.get() + 1);
            return AttributeAction::Skip;
        }
        AttributeAction::Keep
    }

    fn register_component_template(
        &mut self,
        tag_name: &str,
        component: &Component,
        processed_template: &str,
    ) -> Result<()> {
        self.store_component_template(tag_name, processed_template, &component.html_content);
        Ok(())
    }

    fn finish_element(&mut self, binding_attribute_count: u32) -> Option<Vec<u8>> {
        let ev_count = self.element_events.get();
        let ev_start = self.next_event_idx.get();

        // Advance the global event index
        self.next_event_idx.set(ev_start + ev_count);
        // Reset per-element event counter
        self.element_events.set(0);

        if binding_attribute_count == 0 && ev_count == 0 {
            return None;
        }

        Some(
            WebUIElementData {
                binding_count: binding_attribute_count,
                event_start: ev_start,
                event_count: ev_count,
            }
            .encode()
            .to_vec(),
        )
    }

    fn into_artifacts(self: Box<Self>) -> ParserPluginArtifacts {
        ParserPluginArtifacts::ComponentTemplates(self.take_component_templates())
    }
}

// ── Compiled template generation ───────────────────────────────────

/// A compiled template section.
///
/// Used for the root template and for nested block-table entries.
/// `conditionals` and `repeats` point at block-table indices instead of
/// inlining raw body HTML so the client never reparses nested template syntax.
/// The final `html` payload is marker-free; client-created DOM uses the
/// locator tables to connect bindings without scanning comments or attrs.
#[derive(Default)]
struct TemplateSectionMeta {
    /// Marker-free static HTML for client-created DOM.
    html: String,
    /// Intermediate text binding paths collected during compilation.
    /// These are resolved into `text_runs` during finalization.
    /// Each entry is `(path, raw)` where raw indicates triple-brace `{{{...}}}`.
    text_bindings: Vec<(String, bool)>,
    /// Client text-run metadata: `(slot, parts, raw)`.
    /// `raw` is true when the binding uses triple-brace `{{{...}}}` syntax.
    text_runs: Vec<(SlotLocator, Vec<CompiledAttrPart>, bool)>,
    /// Attribute bindings in source order, shared by SSR markers and client `ag[]` locators.
    attr_bindings: Vec<CompiledAttrBinding>,
    /// Client attribute groups: `(element_path, start, count)`.
    attr_groups: Vec<(Vec<usize>, usize, usize)>,
    /// Conditional blocks: `(condition_expression_ast, block_index)`.
    conditionals: Vec<(ConditionExpr, usize)>,
    /// Client conditional anchor slots aligned to `conditionals`.
    condition_slots: Vec<SlotLocator>,
    /// For-loop blocks: `(collection_path, item_variable, block_index)`.
    repeats: Vec<(String, String, usize)>,
    /// Client repeat anchor slots aligned to `repeats`.
    repeat_slots: Vec<SlotLocator>,
    /// Body-level events: `(event_name, handler_method, needs_event_arg)`.
    events: Vec<(String, String, bool)>,
    /// Client event target element paths aligned to `events`.
    event_targets: Vec<Vec<usize>>,
}

#[derive(Clone)]
struct SlotLocator {
    parent_path: Vec<usize>,
    before_index: usize,
    order: usize,
}

/// Collected metadata produced by [`compile_to_metadata`].
///
/// The root template emits directly into the top-level metadata object.
/// Nested blocks live in `blocks` and are referenced by index from `c` / `r`.
struct TemplateMeta {
    root: TemplateSectionMeta,
    blocks: Vec<TemplateSectionMeta>,
    /// Root-level events from the `<template>` wrapper tag.
    /// Attached to the host element (shadow root host) by the client.
    root_events: Vec<(String, String, bool)>,
}

enum CompiledAttrBinding {
    Simple {
        name: String,
        value: String,
    },
    Complex {
        name: String,
        value: String,
    },
    Boolean {
        name: String,
        condition: ConditionExpr,
    },
    Template {
        name: String,
        parts: Vec<CompiledAttrPart>,
    },
}

enum CompiledAttrPart {
    Static(String),
    Dynamic(String),
}

/// Generate a compiled template as a raw JS IIFE string.
///
/// The output is a self-executing function that registers the component's
/// metadata on `window.__webui.templates[tagName]`.  During SSR, the
/// handler wraps one or more of these in a single `<script>` tag.  During
/// SPA partial navigation, the router evaluates them directly.
///
/// # Flow
///
/// 1. Extract `@event` bindings from the `<template>` wrapper (→ `root_events`).
/// 2. Strip the `<template shadowrootmode="…">` wrapper if present.
/// 3. Compile the inner body via [`compile_to_metadata`].
/// 4. Serialize into a self-executing IIFE that registers the metadata
///    on `window.__webui.templates[tagName]`.
///
/// # Compilation rules
///
/// | Source syntax                          | Metadata field(s)          | Client `h` result                 |
/// |---------------------------------------|----------------------------|-----------------------------------|
/// | `{{expr}}`, `{{{expr}}}`, mixed text  | `tx[]`                     | dynamic text run removed          |
/// | `href="{{url}}"`, `class="x {{y}}"`   | `a[]` + `ag[]`             | element kept marker-free          |
/// | `?disabled="{{expr}}"`                | `a[]` + `ag[]`             | element kept marker-free          |
/// | `:config="{{settings}}"`              | `a[]` + `ag[]`             | element kept marker-free          |
/// | `<if condition="…">body</if>`         | `c[]` + `cl[]` + `b[]`     | block removed; anchor slot stored |
/// | `<for each="v in coll">body</for>`    | `r[]` + `rl[]` + `b[]`     | block removed; anchor slot stored |
/// | `<link>` / `<style>` child nodes      | `h`                        | preserved in static HTML          |
/// | module adopted stylesheet specifier   | `sa`                       | stored from `<template>` wrapper  |
/// | `@event="{handler(e)}"`               | `e[]` + `el[]`             | element kept marker-free          |
/// | `w-ref="name"` / `w-ref={name}`       | *(stays in HTML)*          | *(unchanged)*                     |
/// | `<outlet />` / `<outlet>`             | *(stays in HTML)*          | `<outlet></outlet>`               |
pub fn generate_compiled_template(tag_name: &str, html_content: &str) -> String {
    generate_compiled_template_with_root_source(tag_name, html_content, html_content, false)
}

fn generate_compiled_template_with_root_source(
    tag_name: &str,
    html_content: &str,
    root_event_source: &str,
    shadow_dom: bool,
) -> String {
    let trimmed = html_content.trim();
    let root_events = extract_root_events(root_event_source.trim());
    let adopted_stylesheet = extract_adopted_stylesheet_specifier(trimmed);
    let body = strip_template_wrapper(trimmed);
    let meta = compile_to_metadata(body, root_events);

    let mut out = String::with_capacity(512 + html_content.len());
    out.push_str("(function(){var w=(window.__webui||(window.__webui={})).templates||(window.__webui.templates={});w['");
    out.push_str(tag_name);
    out.push_str("']={");

    emit_js_template_section(&meta.root, &mut out);

    if let Some(adopted_stylesheet) = adopted_stylesheet.as_deref() {
        out.push_str(",sa:");
        emit_js_string(adopted_stylesheet, &mut out);
    }

    // sd: shadow DOM flag — tells the client runtime to use shadow root
    if shadow_dom {
        out.push_str(",sd:1");
    }

    // re: root events
    if !meta.root_events.is_empty() {
        out.push_str(",re:[");
        for (i, (event, handler, needs_event)) in meta.root_events.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_string(event, &mut out);
            out.push(',');
            emit_js_string(handler, &mut out);
            out.push(',');
            out.push(if *needs_event { '1' } else { '0' });
            out.push(']');
        }
        out.push(']');
    }

    // b: nested block table
    if !meta.blocks.is_empty() {
        out.push_str(",b:[");
        for (i, block) in meta.blocks.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            out.push('{');
            emit_js_template_section(block, &mut out);
            out.push('}');
        }
        out.push(']');
    }

    out.push_str("};})();\n");
    out
}

fn emit_js_string(s: &str, out: &mut String) {
    out.push('"');
    let mut index = 0usize;
    while index < s.len() {
        let remaining = &s[index..];
        if remaining.as_bytes().starts_with(b"</")
            && remaining
                .as_bytes()
                .get(2..8)
                .map(|bytes| bytes.eq_ignore_ascii_case(b"script"))
                .unwrap_or(false)
        {
            out.push_str("\\u003C");
            index += 1;
            continue;
        }
        let Some(ch) = remaining.chars().next() else {
            break;
        };
        match ch {
            '\0' => out.push_str("\\0"),
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            _ => out.push(ch),
        }
        index += ch.len_utf8();
    }
    out.push('"');
}

fn emit_js_attr_binding(binding: &CompiledAttrBinding, out: &mut String) {
    out.push('[');
    match binding {
        CompiledAttrBinding::Simple { name, value } => {
            emit_js_string(name, out);
            out.push_str(",0,");
            emit_js_string(value, out);
        }
        CompiledAttrBinding::Complex { name, value } => {
            emit_js_string(name, out);
            out.push_str(",1,");
            emit_js_string(value, out);
        }
        CompiledAttrBinding::Boolean { name, condition } => {
            emit_js_string(name, out);
            out.push_str(",2,");
            emit_js_condition(condition, out);
        }
        CompiledAttrBinding::Template { name, parts } => {
            emit_js_string(name, out);
            out.push_str(",3,[");
            for (i, part) in parts.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                match part {
                    CompiledAttrPart::Static(value) => emit_js_string(value, out),
                    CompiledAttrPart::Dynamic(path) => {
                        out.push('[');
                        emit_js_string(path, out);
                        out.push(']');
                    }
                }
            }
            out.push(']');
        }
    }
    out.push(']');
}

/// Emit a compiled condition as `[function(v,s){return EXPR},["path1",...]]`.
/// The function evaluates the condition using `v(path,s)` for value resolution.
/// The paths array lists all referenced identifiers for the reactive path index.
fn emit_js_condition(condition: &ConditionExpr, out: &mut String) {
    out.push_str("[function(v,s){return ");
    emit_js_condition_expr(condition, out);
    out.push_str("},[");
    let mut paths = Vec::new();
    collect_condition_paths(condition, &mut paths);
    for (i, path) in paths.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        emit_js_string(path, out);
    }
    out.push_str("]]");
}

/// Emit the JS expression body for a condition (no wrapping).
fn emit_js_condition_expr(condition: &ConditionExpr, out: &mut String) {
    match &condition.expr {
        Some(condition_expr::Expr::Identifier(id)) => {
            // Truthiness check: !!v("path",s)
            out.push_str("!!v(");
            emit_js_string(&id.value, out);
            out.push_str(",s)");
        }
        Some(condition_expr::Expr::Predicate(pred)) => {
            // Comparison: resolve left, compare with right
            out.push_str("v(");
            emit_js_string(&pred.left, out);
            out.push_str(",s)");
            match pred.operator {
                1 => out.push('>'),      // GT
                2 => out.push('<'),      // LT
                3 => out.push_str("=="), // EQ (use == for loose comparison like Object.is)
                4 => out.push_str("!="), // NEQ
                5 => out.push_str(">="), // GTE
                6 => out.push_str("<="), // LTE
                _ => out.push_str("=="),
            }
            // Right side: resolve as value or emit literal
            emit_js_predicate_right(&pred.right, out);
        }
        Some(condition_expr::Expr::Not(not_cond)) => {
            out.push('!');
            if let Some(inner) = not_cond.condition.as_ref() {
                out.push('(');
                emit_js_condition_expr(inner, out);
                out.push(')');
            } else {
                out.push_str("false");
            }
        }
        Some(condition_expr::Expr::Compound(compound)) => {
            out.push('(');
            if let Some(left) = compound.left.as_ref() {
                emit_js_condition_expr(left, out);
            } else {
                out.push_str("false");
            }
            match compound.op {
                1 => out.push_str("&&"), // AND
                2 => out.push_str("||"), // OR
                _ => out.push_str("&&"),
            }
            if let Some(right) = compound.right.as_ref() {
                emit_js_condition_expr(right, out);
            } else {
                out.push_str("false");
            }
            out.push(')');
        }
        None => out.push_str("false"),
    }
}

/// Emit the right-hand side of a predicate comparison.
/// Literals are emitted directly; identifiers are resolved via v().
fn emit_js_predicate_right(value: &str, out: &mut String) {
    // Check for string literals: "..." or '...'
    if (value.starts_with('"') && value.ends_with('"'))
        || (value.starts_with('\'') && value.ends_with('\''))
    {
        // Emit as JS string (strip outer quotes, re-emit as double-quoted)
        emit_js_string(&value[1..value.len() - 1], out);
        return;
    }
    // Boolean literals
    if value == "true" || value == "false" {
        out.push_str(value);
        return;
    }
    // Numeric literals
    if value
        .bytes()
        .all(|b| b.is_ascii_digit() || b == b'.' || b == b'-')
        && !value.is_empty()
    {
        out.push_str(value);
        return;
    }
    // Otherwise it's an identifier — resolve it
    out.push_str("v(");
    emit_js_string(value, out);
    out.push_str(",s)");
}

/// Collect all identifier paths referenced by a condition.
fn collect_condition_paths(condition: &ConditionExpr, paths: &mut Vec<String>) {
    match &condition.expr {
        Some(condition_expr::Expr::Identifier(id)) => {
            paths.push(id.value.clone());
        }
        Some(condition_expr::Expr::Predicate(pred)) => {
            paths.push(pred.left.clone());
            // Right side might also be an identifier (not a literal)
            let r = &pred.right;
            if !((r.starts_with('"') && r.ends_with('"'))
                || (r.starts_with('\'') && r.ends_with('\''))
                || r == "true"
                || r == "false"
                || r.bytes()
                    .all(|b| b.is_ascii_digit() || b == b'.' || b == b'-'))
            {
                paths.push(r.clone());
            }
        }
        Some(condition_expr::Expr::Not(not_cond)) => {
            if let Some(inner) = not_cond.condition.as_ref() {
                collect_condition_paths(inner, paths);
            }
        }
        Some(condition_expr::Expr::Compound(compound)) => {
            if let Some(left) = compound.left.as_ref() {
                collect_condition_paths(left, paths);
            }
            if let Some(right) = compound.right.as_ref() {
                collect_condition_paths(right, paths);
            }
        }
        None => {}
    }
}

fn emit_js_node_path(path: &[usize], out: &mut String) {
    out.push('[');
    for (i, index) in path.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        let _ = write!(out, "{}", index);
    }
    out.push(']');
}

fn emit_js_slot(slot: &SlotLocator, out: &mut String) {
    out.push('[');
    emit_js_node_path(&slot.parent_path, out);
    out.push(',');
    let _ = write!(out, "{}", slot.before_index);
    if slot.order > 0 {
        out.push(',');
        let _ = write!(out, "{}", slot.order);
    }
    out.push(']');
}

fn emit_js_text_parts(parts: &[CompiledAttrPart], out: &mut String) {
    out.push('[');
    for (i, part) in parts.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        match part {
            CompiledAttrPart::Static(value) => emit_js_string(value, out),
            CompiledAttrPart::Dynamic(path) => {
                out.push('[');
                emit_js_string(path, out);
                out.push(']');
            }
        }
    }
    out.push(']');
}

fn emit_js_template_section(meta: &TemplateSectionMeta, out: &mut String) {
    out.push_str("h:");
    emit_js_string(&meta.html, out);

    if !meta.text_runs.is_empty() {
        out.push_str(",tx:[");
        for (i, (slot, parts, raw)) in meta.text_runs.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_slot(slot, out);
            out.push(',');
            emit_js_text_parts(parts, out);
            if *raw {
                out.push_str(",1");
            }
            out.push(']');
        }
        out.push(']');
    }

    if !meta.attr_bindings.is_empty() {
        out.push_str(",a:[");
        for (i, binding) in meta.attr_bindings.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            emit_js_attr_binding(binding, out);
        }
        out.push(']');
    }

    if !meta.attr_groups.is_empty() {
        out.push_str(",ag:[");
        for (i, (path, start, count)) in meta.attr_groups.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_node_path(path, out);
            out.push(',');
            let _ = write!(out, "{}", start);
            out.push(',');
            let _ = write!(out, "{}", count);
            out.push(']');
        }
        out.push(']');
    }

    if !meta.conditionals.is_empty() {
        out.push_str(",c:[");
        for (i, ((cond, block_index), slot)) in meta
            .conditionals
            .iter()
            .zip(meta.condition_slots.iter())
            .enumerate()
        {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_condition(cond, out);
            out.push(',');
            let _ = write!(out, "{}", block_index);
            out.push(',');
            emit_js_slot(slot, out);
            out.push(']');
        }
        out.push(']');
    }

    if !meta.repeats.is_empty() {
        out.push_str(",r:[");
        for (i, ((collection, item_var, block_index), slot)) in meta
            .repeats
            .iter()
            .zip(meta.repeat_slots.iter())
            .enumerate()
        {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_string(collection, out);
            out.push(',');
            emit_js_string(item_var, out);
            out.push(',');
            let _ = write!(out, "{}", block_index);
            out.push(',');
            emit_js_slot(slot, out);
            out.push(']');
        }
        out.push(']');
    }

    if !meta.events.is_empty() {
        out.push_str(",e:[");
        for (i, ((event, handler, needs_event), target)) in meta
            .events
            .iter()
            .zip(meta.event_targets.iter())
            .enumerate()
        {
            if i > 0 {
                out.push(',');
            }
            out.push('[');
            emit_js_string(event, out);
            out.push(',');
            emit_js_string(handler, out);
            out.push(',');
            out.push(if *needs_event { '1' } else { '0' });
            out.push(',');
            emit_js_node_path(target, out);
            out.push(']');
        }
        out.push(']');
    }
}

/// Compile a template body into a [`TemplateMeta`] struct.
///
/// Performs a single forward pass over the input bytes to build an intermediate
/// section, then finalizes that section into marker-free client HTML plus
/// locator metadata. During the forward pass:
///
/// - **Multi-byte char boundary check** — ensures we don't split UTF-8 (e.g. emoji).
/// - **`{{{expr}}}`** — triple-brace raw binding → text run metadata.
/// - **`{{expr}}`** — double-brace escaped binding → text run metadata.
/// - **regular start tags** — attrs are compiled into explicit `a[]` metadata plus
///   SSR binding markers that are later stripped from client `h`.
/// - **`<if condition="…">`** — parsed via [`parse_if_block`] → conditional slot.
/// - **`<for each="v in coll">`** — parsed via [`parse_for_block`] → repeat slot.
/// - **`<outlet …>`** — normalized to `<outlet></outlet>`.
/// - **`@event="…"`** (inside a tag) — parsed into `e[]` entries plus
///   SSR `data-ev="COUNT"` markers that are later replaced by client locators.
/// - **Everything else** — copied verbatim to the intermediate static HTML.
///
fn compile_to_metadata(input: &str, root_events: Vec<(String, String, bool)>) -> TemplateMeta {
    let mut blocks = Vec::new();
    let mut root = compile_section(input, &mut blocks);
    finalize_template_section(&mut root);
    for block in &mut blocks {
        finalize_template_section(block);
    }
    TemplateMeta {
        root,
        blocks,
        root_events,
    }
}

fn compile_section(input: &str, blocks: &mut Vec<TemplateSectionMeta>) -> TemplateSectionMeta {
    let mut meta = TemplateSectionMeta {
        html: String::with_capacity(input.len()),
        text_bindings: Vec::new(),
        text_runs: Vec::new(),
        attr_bindings: Vec::new(),
        attr_groups: Vec::new(),
        conditionals: Vec::new(),
        condition_slots: Vec::new(),
        repeats: Vec::new(),
        repeat_slots: Vec::new(),
        events: Vec::new(),
        event_targets: Vec::new(),
    };

    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if !input.is_char_boundary(i) {
            meta.html.push(bytes[i] as char);
            i += 1;
            continue;
        }

        // Triple-brace {{{expr}}} → marker + text binding (raw/unescaped)
        if i + 4 < len && bytes[i] == b'{' && bytes[i + 1] == b'{' && bytes[i + 2] == b'{' {
            if let Some(end) = find_brace_end(input, i + 3, 3) {
                let expr = input[i + 3..end].trim();
                let idx = meta.text_bindings.len();
                meta.text_bindings.push((expr.to_string(), true));
                meta.html.push_str(&format!("<!--t:{idx}-->"));
                i = end + 3;
                continue;
            }
        }

        // Double-brace {{expr}} → marker + text binding (escaped)
        if i + 3 < len && bytes[i] == b'{' && bytes[i + 1] == b'{' {
            if let Some(end) = find_brace_end(input, i + 2, 2) {
                let expr = input[i + 2..end].trim();
                let idx = meta.text_bindings.len();
                meta.text_bindings.push((expr.to_string(), false));
                meta.html.push_str(&format!("<!--t:{idx}-->"));
                i = end + 2;
                continue;
            }
        }

        // <if condition="...">...</if> → marker + conditional
        if bytes[i] == b'<' {
            let remaining = &input[i..];
            if remaining.starts_with("<if ") || remaining.starts_with("<if\n") {
                if let Some((cond, body, consumed)) = parse_if_block(remaining) {
                    let block_index = blocks.len();
                    blocks.push(TemplateSectionMeta::default());
                    let block = compile_section(&body, blocks);
                    blocks[block_index] = block;
                    let idx = meta.conditionals.len();
                    meta.conditionals.push((cond, block_index));
                    meta.html.push_str(&format!("<!--c:{idx}-->"));
                    i += consumed;
                    continue;
                }
            }

            // <for each="item in collection">...</for> → marker + repeat
            if remaining.starts_with("<for ") || remaining.starts_with("<for\n") {
                if let Some((collection, item_var, body, consumed)) = parse_for_block(remaining) {
                    let block_index = blocks.len();
                    blocks.push(TemplateSectionMeta::default());
                    let block = compile_section(&body, blocks);
                    blocks[block_index] = block;
                    let idx = meta.repeats.len();
                    meta.repeats.push((collection, item_var, block_index));
                    meta.html.push_str(&format!("<!--r:{idx}-->"));
                    i += consumed;
                    continue;
                }
            }

            // <outlet ... /> → keep as <outlet></outlet>
            if remaining.starts_with("<outlet") {
                if let Some(close) = find_tag_end(remaining) {
                    meta.html.push_str("<outlet></outlet>");
                    i += close + 1;
                    continue;
                }
            }

            if let Some((tag_html, consumed)) = parse_regular_tag(remaining, &mut meta) {
                meta.html.push_str(&tag_html);
                i += consumed;
                continue;
            }
        }

        // @event attributes → replace with a per-element event-count marker
        if bytes[i] == b'@' && is_inside_tag(input, i) {
            if let Some((event_name, handler, needs_event, consumed)) = parse_event_attr(input, i) {
                meta.events.push((event_name, handler, needs_event));
                meta.html.push_str("data-ev=\"1\"");
                i += consumed;
                continue;
            }
        }

        // w-ref stays in static HTML as-is — the runtime binds from the DOM directly.
        // No metadata entry needed; the attribute value IS the property name.

        // Copy character
        let ch = &input[i..];
        if let Some(c) = ch.chars().next() {
            meta.html.push(c);
            i += c.len_utf8();
        } else {
            i += 1;
        }
    }

    meta
}

#[derive(Clone)]
enum FragmentNode {
    Element(FragmentElement),
    Text(String),
    Comment(String),
}

#[derive(Clone)]
struct FragmentElement {
    tag_name: String,
    attrs: Vec<FragmentAttr>,
    children: Vec<FragmentNode>,
    self_closing: bool,
}

#[derive(Clone)]
struct FragmentAttr {
    name: String,
    value: Option<String>,
}

fn finalize_template_section(meta: &mut TemplateSectionMeta) {
    let raw_html = std::mem::take(&mut meta.html);
    let nodes = parse_fragment_nodes(&raw_html);
    let text_bindings = meta.text_bindings.clone();
    let mut finalized_html = String::with_capacity(raw_html.len());
    let mut text_runs = Vec::new();
    let mut attr_groups = Vec::new();
    let mut condition_slots = vec![None; meta.conditionals.len()];
    let mut repeat_slots = vec![None; meta.repeats.len()];
    let mut event_targets = vec![None; meta.events.len()];
    let mut event_cursor = 0usize;

    process_fragment_children(
        &nodes,
        &[],
        &text_bindings,
        &mut finalized_html,
        &mut text_runs,
        &mut attr_groups,
        &mut condition_slots,
        &mut repeat_slots,
        &mut event_targets,
        &mut event_cursor,
    );
    debug_assert_eq!(event_cursor, meta.events.len());

    meta.html = finalized_html;
    meta.text_runs = text_runs;
    meta.attr_groups = attr_groups;
    meta.condition_slots = condition_slots.into_iter().flatten().collect();
    meta.repeat_slots = repeat_slots.into_iter().flatten().collect();
    meta.event_targets = event_targets.into_iter().flatten().collect();
}

#[allow(clippy::too_many_arguments)]
fn process_fragment_children(
    nodes: &[FragmentNode],
    parent_path: &[usize],
    text_bindings: &[(String, bool)],
    out: &mut String,
    text_runs: &mut Vec<(SlotLocator, Vec<CompiledAttrPart>, bool)>,
    attr_groups: &mut Vec<(Vec<usize>, usize, usize)>,
    condition_slots: &mut [Option<SlotLocator>],
    repeat_slots: &mut [Option<SlotLocator>],
    event_targets: &mut [Option<Vec<usize>>],
    event_cursor: &mut usize,
) {
    let mut child_index = 0usize;
    let mut index = 0usize;
    // Browser HTML parsing merges adjacent emitted text into a single Text node.
    // Track that here so marker-free locator paths match the real client DOM.
    let mut previous_emitted_text = false;
    let mut slot_orders = std::collections::BTreeMap::<usize, usize>::new();

    while index < nodes.len() {
        if let Some((parts, consumed, has_dynamic, is_raw)) =
            collect_text_run(&nodes[index..], text_bindings)
        {
            if has_dynamic {
                // Decode HTML entities in static parts so that runtime
                // textContent assignment renders decoded characters
                // (e.g. `&gt;` → `>`).  Static-only text runs are
                // baked into `meta.h` and parsed via innerHTML which
                // handles entity decoding natively.
                let decoded_parts = parts
                    .into_iter()
                    .map(|part| match part {
                        CompiledAttrPart::Static(s) => {
                            let decoded = html_escape::decode_html_entities(&s);
                            CompiledAttrPart::Static(decoded.into_owned())
                        }
                        other => other,
                    })
                    .collect();
                let order = slot_orders.get(&child_index).copied().unwrap_or(0);
                slot_orders.insert(child_index, order + 1);
                text_runs.push((
                    SlotLocator {
                        parent_path: parent_path.to_vec(),
                        before_index: child_index,
                        order,
                    },
                    decoded_parts,
                    is_raw,
                ));
            } else {
                let static_text = collect_static_text(&parts);
                if !static_text.is_empty() {
                    out.push_str(&static_text);
                    if !previous_emitted_text {
                        child_index += 1;
                    }
                    previous_emitted_text = true;
                }
            }
            index += consumed;
            continue;
        }

        match &nodes[index] {
            FragmentNode::Comment(data) => {
                if let Some(idx) = parse_marker_index(data, "c:") {
                    if let Some(slot) = condition_slots.get_mut(idx) {
                        let order = slot_orders.get(&child_index).copied().unwrap_or(0);
                        slot_orders.insert(child_index, order + 1);
                        *slot = Some(SlotLocator {
                            parent_path: parent_path.to_vec(),
                            before_index: child_index,
                            order,
                        });
                    }
                } else if let Some(idx) = parse_marker_index(data, "r:") {
                    if let Some(slot) = repeat_slots.get_mut(idx) {
                        let order = slot_orders.get(&child_index).copied().unwrap_or(0);
                        slot_orders.insert(child_index, order + 1);
                        *slot = Some(SlotLocator {
                            parent_path: parent_path.to_vec(),
                            before_index: child_index,
                            order,
                        });
                    }
                } else {
                    out.push_str("<!--");
                    out.push_str(data);
                    out.push_str("-->");
                    child_index += 1;
                    previous_emitted_text = false;
                }
            }
            FragmentNode::Text(text) => {
                out.push_str(text);
                if !text.is_empty() {
                    if !previous_emitted_text {
                        child_index += 1;
                    }
                    previous_emitted_text = true;
                }
            }
            FragmentNode::Element(element) => {
                let mut element_path = parent_path.to_vec();
                element_path.push(child_index);
                serialize_fragment_element(
                    element,
                    &element_path,
                    text_bindings,
                    out,
                    text_runs,
                    attr_groups,
                    condition_slots,
                    repeat_slots,
                    event_targets,
                    event_cursor,
                );
                child_index += 1;
                previous_emitted_text = false;
            }
        }

        index += 1;
    }
}

#[allow(clippy::too_many_arguments)]
fn serialize_fragment_element(
    element: &FragmentElement,
    element_path: &[usize],
    text_bindings: &[(String, bool)],
    out: &mut String,
    text_runs: &mut Vec<(SlotLocator, Vec<CompiledAttrPart>, bool)>,
    attr_groups: &mut Vec<(Vec<usize>, usize, usize)>,
    condition_slots: &mut [Option<SlotLocator>],
    repeat_slots: &mut [Option<SlotLocator>],
    event_targets: &mut [Option<Vec<usize>>],
    event_cursor: &mut usize,
) {
    out.push('<');
    out.push_str(&element.tag_name);

    for attr in &element.attrs {
        if let Some((start, count)) = parse_attr_group_marker(&attr.name) {
            attr_groups.push((element_path.to_vec(), start, count));
            continue;
        }

        if attr.name == "data-ev" {
            if let Some(count) = attr.value.as_deref().and_then(parse_event_marker_count) {
                let target_path = element_path.to_vec();
                for slot in event_targets.iter_mut().skip(*event_cursor).take(count) {
                    *slot = Some(target_path.clone());
                }
                *event_cursor += count;
            }
            continue;
        }

        out.push(' ');
        out.push_str(&attr.name);
        if let Some(value) = &attr.value {
            out.push_str("=\"");
            emit_html_attr_value(value, out);
            out.push('"');
        }
    }

    if element.self_closing {
        out.push_str(" />");
        return;
    }

    out.push('>');
    process_fragment_children(
        &element.children,
        element_path,
        text_bindings,
        out,
        text_runs,
        attr_groups,
        condition_slots,
        repeat_slots,
        event_targets,
        event_cursor,
    );
    out.push_str("</");
    out.push_str(&element.tag_name);
    out.push('>');
}

fn collect_text_run(
    nodes: &[FragmentNode],
    text_bindings: &[(String, bool)],
) -> Option<(Vec<CompiledAttrPart>, usize, bool, bool)> {
    let mut parts = Vec::new();
    let mut consumed = 0usize;
    let mut has_dynamic = false;
    let mut is_raw = false;

    for node in nodes {
        match node {
            FragmentNode::Text(text) => {
                if !text.is_empty() {
                    parts.push(CompiledAttrPart::Static(text.clone()));
                }
                consumed += 1;
            }
            FragmentNode::Comment(data) => {
                if let Some(index) = parse_marker_index(data, "t:") {
                    if let Some((path, raw)) = text_bindings.get(index) {
                        parts.push(CompiledAttrPart::Dynamic(path.clone()));
                        has_dynamic = true;
                        if *raw {
                            is_raw = true;
                        }
                    }
                    consumed += 1;
                } else {
                    break;
                }
            }
            FragmentNode::Element(_) => break,
        }
    }

    if consumed == 0 {
        return None;
    }

    Some((parts, consumed, has_dynamic, is_raw))
}

fn collect_static_text(parts: &[CompiledAttrPart]) -> String {
    let mut text = String::new();
    for part in parts {
        if let CompiledAttrPart::Static(value) = part {
            text.push_str(value);
        }
    }
    text
}

fn parse_marker_index(data: &str, prefix: &str) -> Option<usize> {
    data.strip_prefix(prefix)?.parse().ok()
}

fn parse_attr_group_marker(name: &str) -> Option<(usize, usize)> {
    if let Some(start) = name.strip_prefix("data-w-b-") {
        return start.parse::<usize>().ok().map(|index| (index, 1));
    }

    let rest = name.strip_prefix("data-w-c-")?;
    let mut parts = rest.split('-');
    let start = parts.next()?.parse::<usize>().ok()?;
    let count = parts.next()?.parse::<usize>().ok()?;
    Some((start, count))
}

fn parse_event_marker_count(value: &str) -> Option<usize> {
    let count = value.parse::<usize>().ok()?;
    (count > 0).then_some(count)
}

fn emit_html_attr_value(value: &str, out: &mut String) {
    for ch in value.chars() {
        match ch {
            '"' => out.push_str("&quot;"),
            _ => out.push(ch),
        }
    }
}

fn parse_fragment_nodes(input: &str) -> Vec<FragmentNode> {
    let mut roots = Vec::new();
    let mut stack: Vec<FragmentElement> = Vec::new();
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut index = 0usize;

    while index < len {
        let remaining = &input[index..];
        if remaining.starts_with("<!--") {
            if let Some(close) = remaining.find("-->") {
                push_fragment_node(
                    &mut roots,
                    &mut stack,
                    FragmentNode::Comment(remaining[4..close].to_string()),
                );
                index += close + 3;
                continue;
            }
        }

        if remaining.starts_with("</") {
            if let Some(close) = remaining.find('>') {
                if let Some(element) = stack.pop() {
                    push_fragment_node(&mut roots, &mut stack, FragmentNode::Element(element));
                }
                index += close + 1;
                continue;
            }
        }

        if remaining.starts_with('<') {
            if let Some((element, consumed)) = parse_fragment_start_tag(remaining) {
                if element.self_closing {
                    push_fragment_node(&mut roots, &mut stack, FragmentNode::Element(element));
                } else {
                    stack.push(element);
                }
                index += consumed;
                continue;
            }
        }

        let next = remaining.find('<').unwrap_or(remaining.len());
        let text = &remaining[..next];
        if !text.is_empty() {
            push_fragment_node(&mut roots, &mut stack, FragmentNode::Text(text.to_string()));
        }
        index += next.max(1);
    }

    while let Some(element) = stack.pop() {
        push_fragment_node(&mut roots, &mut stack, FragmentNode::Element(element));
    }

    roots
}

fn push_fragment_node(
    roots: &mut Vec<FragmentNode>,
    stack: &mut [FragmentElement],
    node: FragmentNode,
) {
    if let Some(parent) = stack.last_mut() {
        parent.children.push(node);
    } else {
        roots.push(node);
    }
}

fn parse_fragment_start_tag(input: &str) -> Option<(FragmentElement, usize)> {
    if !input.starts_with('<') || input.starts_with("</") || input.starts_with("<!--") {
        return None;
    }

    let end = find_tag_end(input)?;
    let tag_content = &input[1..end];
    let tag_body = tag_content.trim_end();
    let self_closing = tag_body.ends_with('/');
    let tag_body = if self_closing {
        tag_body[..tag_body.len().saturating_sub(1)].trim_end()
    } else {
        tag_body
    };

    let body_bytes = tag_body.as_bytes();
    let mut cursor = 0usize;
    while cursor < body_bytes.len() && !body_bytes[cursor].is_ascii_whitespace() {
        cursor += 1;
    }

    let tag_name = &tag_body[..cursor];
    if tag_name.is_empty() {
        return None;
    }

    let mut attrs = Vec::new();
    while cursor < body_bytes.len() {
        while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }
        if cursor >= body_bytes.len() {
            break;
        }

        let attr_start = cursor;
        while cursor < body_bytes.len()
            && !body_bytes[cursor].is_ascii_whitespace()
            && body_bytes[cursor] != b'='
        {
            cursor += 1;
        }
        if attr_start == cursor {
            cursor += 1;
            continue;
        }

        let name = tag_body[attr_start..cursor].to_string();
        while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }

        let mut value: Option<String> = None;
        if cursor < body_bytes.len() && body_bytes[cursor] == b'=' {
            cursor += 1;
            while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
                cursor += 1;
            }

            if cursor < body_bytes.len()
                && (body_bytes[cursor] == b'"' || body_bytes[cursor] == b'\'')
            {
                let quote = body_bytes[cursor];
                cursor += 1;
                let value_start = cursor;
                while cursor < body_bytes.len() && body_bytes[cursor] != quote {
                    cursor += 1;
                }
                value = Some(tag_body[value_start..cursor].to_string());
                if cursor < body_bytes.len() {
                    cursor += 1;
                }
            } else {
                let value_start = cursor;
                while cursor < body_bytes.len() && !body_bytes[cursor].is_ascii_whitespace() {
                    cursor += 1;
                }
                value = Some(tag_body[value_start..cursor].to_string());
            }
        }

        attrs.push(FragmentAttr { name, value });
    }

    Some((
        FragmentElement {
            tag_name: tag_name.to_string(),
            attrs,
            children: Vec::new(),
            self_closing: self_closing || is_void_element(tag_name),
        },
        end + 1,
    ))
}

fn is_void_element(tag_name: &str) -> bool {
    matches!(
        tag_name,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

// ── Parsing helpers ────────────────────────────────────────────────

/// Find the position of `count` consecutive closing braces (`}`).
/// Returns `Some(start_of_closing_braces)` or `None` if not found.
fn find_brace_end(input: &str, start: usize, count: usize) -> Option<usize> {
    let bytes = input.as_bytes();
    let mut i = start;
    while i + count - 1 < bytes.len() {
        let all_close = (0..count).all(|j| bytes[i + j] == b'}');
        if all_close {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Check whether byte position `pos` is inside an HTML tag (between `<` and `>`).
/// Scans backward from `pos` — returns `true` if we hit `<` before `>`.
fn is_inside_tag(input: &str, pos: usize) -> bool {
    let bytes = input.as_bytes();
    let mut i = pos;
    while i > 0 {
        i -= 1;
        if bytes[i] == b'>' {
            return false;
        }
        if bytes[i] == b'<' {
            return true;
        }
    }
    false
}

/// Strip `<template shadowrootmode="…">…</template>` wrapper, returning inner content.
/// Returns the input unchanged if no wrapper is present.
fn strip_template_wrapper(html: &str) -> &str {
    if !html.starts_with("<template") {
        return html;
    }
    let Some(open_end) = find_tag_end(html) else {
        return html;
    };
    let inner_start = open_end + 1;
    let inner_end = html.rfind("</template>").unwrap_or(html.len());
    if inner_start >= inner_end {
        return "";
    }
    &html[inner_start..inner_end]
}

fn find_next_block_token(input: &str, cursor: usize, token: &str) -> Option<usize> {
    let bytes = input.as_bytes();
    let token_bytes = token.as_bytes();
    let mut index = cursor;
    let mut in_tag = false;
    let mut in_comment = false;
    let mut quote: Option<u8> = None;

    while index + token_bytes.len() <= bytes.len() {
        if in_comment {
            if bytes[index..].starts_with(b"-->") {
                in_comment = false;
                index += 3;
                continue;
            }
            index += 1;
            continue;
        }

        if let Some(active) = quote {
            if bytes[index] == active {
                quote = None;
            }
            index += 1;
            continue;
        }

        if in_tag {
            match bytes[index] {
                b'"' | b'\'' => quote = Some(bytes[index]),
                b'>' => in_tag = false,
                _ => {}
            }
            index += 1;
            continue;
        }

        if &bytes[index..index + token_bytes.len()] == token_bytes {
            return Some(index);
        }

        if bytes[index] == b'<' {
            if bytes[index..].starts_with(b"<!--") {
                in_comment = true;
                index += 4;
                continue;
            }
            in_tag = true;
        }

        index += 1;
    }

    None
}

fn find_next_block_open(input: &str, cursor: usize, name: &str) -> Option<usize> {
    let token = format!("<{name}");
    let bytes = input.as_bytes();
    let token_bytes = token.as_bytes();
    let mut search = cursor;

    while let Some(index) = find_next_block_token(input, search, &token) {
        let next = bytes.get(index + token_bytes.len()).copied();
        if match next {
            None => true,
            Some(byte) => byte == b'>' || byte.is_ascii_whitespace(),
        } {
            return Some(index);
        }
        search = index + 1;
    }

    None
}

fn find_next_block_close(input: &str, cursor: usize, name: &str) -> Option<usize> {
    let token = format!("</{name}>");
    find_next_block_token(input, cursor, &token)
}

fn find_matching_block_end(input: &str, name: &str) -> Option<usize> {
    let open_token = format!("<{name}");
    let close_token = format!("</{name}>");
    if !input.starts_with(&open_token) {
        return None;
    }

    let mut depth = 1usize;
    let mut cursor = open_token.len();

    while cursor < input.len() {
        let next_open = find_next_block_open(input, cursor, name);
        let next_close = find_next_block_close(input, cursor, name);

        match (next_open, next_close) {
            (_, None) => return None,
            (Some(open_pos), Some(close_pos)) if open_pos < close_pos => {
                depth += 1;
                cursor = open_pos + open_token.len();
            }
            (_, Some(close_pos)) => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return Some(close_pos);
                }
                cursor = close_pos + close_token.len();
            }
        }
    }

    None
}

/// Parse `<if condition="EXPR">BODY</if>` → `(condition, body, bytes_consumed)`.
///
/// Only handles the outermost `<if>` — nested `<if>` blocks inside the body
/// are left as raw HTML for the client runtime to process.
fn parse_if_block(input: &str) -> Option<(ConditionExpr, String, usize)> {
    let close_tag = "</if>";
    let end_pos = find_matching_block_end(input, "if")?;
    let tag_content = &input[..end_pos];

    // Extract condition
    let cond_start = tag_content.find("condition=\"")? + "condition=\"".len();
    let cond_end = tag_content[cond_start..].find('"')? + cond_start;
    let condition = compile_condition_expr(&tag_content[cond_start..cond_end]);

    // Extract body (after the closing >)
    let body_start = find_tag_end(tag_content)? + 1;
    let body = tag_content[body_start..].trim().to_string();

    Some((condition, body, end_pos + close_tag.len()))
}

fn compile_condition_expr(input: &str) -> ConditionExpr {
    let parser = ConditionParser::new();
    match parser.parse(input) {
        Ok(condition) => condition,
        // Component HTML is compiled after the main parser has already validated
        // condition syntax. Keep the emitted metadata structurally valid if that
        // earlier guarantee regresses.
        Err(_) => ConditionExpr::identifier(input),
    }
}

/// Parse `<for each="item in collection">BODY</for>` → `(collection, item_var, body, consumed)`.
///
/// The `each` attribute must follow the `"item in collection"` pattern.
/// The body template retains `{{expr}}` mustaches — they are resolved by the
/// client runtime during reconciliation.
fn parse_for_block(input: &str) -> Option<(String, String, String, usize)> {
    let close_tag = "</for>";
    let end_pos = find_matching_block_end(input, "for")?;
    let tag_content = &input[..end_pos];

    // Extract each="item in collection"
    let each_start = tag_content.find("each=\"")? + "each=\"".len();
    let each_end = tag_content[each_start..].find('"')? + each_start;
    let each_val = &tag_content[each_start..each_end];

    let parts: Vec<&str> = each_val.splitn(3, ' ').collect();
    if parts.len() != 3 || parts[1] != "in" {
        return None;
    }
    let item_var = parts[0].to_string();
    let collection = parts[2].to_string();

    // Extract body
    let body_start = find_tag_end(tag_content)? + 1;
    let body = tag_content[body_start..].trim().to_string();

    Some((collection, item_var, body, end_pos + close_tag.len()))
}

/// Parse `@event="{handler()}"` or `@event={handler()}` → `(event_name, handler_name, needs_event, consumed)`.
///
/// Supports three value quoting styles:
/// - `@click="{onClick()}"` — quoted with braces inside
/// - `@click={onClick()}` — unquoted braces
/// - `@click='onClick()'` — single-quoted
///
/// The handler name is extracted from the function call syntax. `needs_event`
/// is `true` when the argument list contains `(e)`.
fn parse_event_attr(input: &str, pos: usize) -> Option<(String, String, bool, usize)> {
    let remaining = &input[pos..];
    let eq_pos = remaining.find('=')?;
    let event_name = remaining[1..eq_pos].to_string(); // skip @

    let after_eq = &remaining[eq_pos + 1..];
    if after_eq.is_empty() {
        return None;
    }

    let first = after_eq.as_bytes()[0];
    let (raw_value, total_consumed) = if first == b'"' || first == b'\'' {
        let value_start = eq_pos + 2;
        let close = remaining[value_start..].find(first as char)?;
        (
            &remaining[value_start..value_start + close],
            value_start + close + 1,
        )
    } else if first == b'{' {
        let value_start = eq_pos + 2;
        let close = remaining[value_start..].find('}')?;
        (
            &remaining[value_start..value_start + close],
            value_start + close + 1,
        )
    } else {
        return None;
    };

    let inner = raw_value
        .trim()
        .strip_prefix('{')
        .and_then(|s| s.strip_suffix('}'))
        .unwrap_or(raw_value)
        .trim();

    // Extract method name from "handler()" or "handler(e)"
    if inner.is_empty() {
        return None;
    }
    let paren = match inner.find('(') {
        Some(p) => p,
        None => panic!(
            "Invalid @{event_name} handler: \"{inner}\". \
             Use @{event_name}=\"{{handler()}}\" or \
             @{event_name}=\"{{handler(e)}}\" to pass the event.",
        ),
    };
    let handler_name = inner[..paren].to_string();
    let needs_event = inner.contains("(e)");

    Some((event_name, handler_name, needs_event, total_consumed))
}

fn parse_regular_tag(input: &str, meta: &mut TemplateSectionMeta) -> Option<(String, usize)> {
    if !input.starts_with('<') || input.starts_with("</") || input.starts_with("<!") {
        return None;
    }

    let bytes = input.as_bytes();
    if bytes.len() < 2 || !bytes[1].is_ascii_alphabetic() {
        return None;
    }

    let end = find_tag_end(input)?;
    let tag_content = &input[1..end];
    let tag_body = tag_content.trim_end();
    let self_closing = tag_body.ends_with('/');
    let tag_body = if self_closing {
        tag_body[..tag_body.len().saturating_sub(1)].trim_end()
    } else {
        tag_body
    };

    let body_bytes = tag_body.as_bytes();
    let mut cursor = 0;
    while cursor < body_bytes.len() && !body_bytes[cursor].is_ascii_whitespace() {
        cursor += 1;
    }

    let tag_name = &tag_body[..cursor];
    if tag_name.is_empty() {
        return None;
    }

    let mut out = String::with_capacity(tag_body.len() + 24);
    out.push('<');
    out.push_str(tag_name);

    let binding_start = meta.attr_bindings.len();
    let event_start = meta.events.len();
    let mut binding_count = 0usize;

    while cursor < body_bytes.len() {
        while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }
        if cursor >= body_bytes.len() {
            break;
        }

        let attr_start = cursor;
        while cursor < body_bytes.len()
            && !body_bytes[cursor].is_ascii_whitespace()
            && body_bytes[cursor] != b'='
        {
            cursor += 1;
        }
        if attr_start == cursor {
            cursor += 1;
            continue;
        }

        let name = &tag_body[attr_start..cursor];

        while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
            cursor += 1;
        }

        let mut value: Option<&str> = None;
        if cursor < body_bytes.len() && body_bytes[cursor] == b'=' {
            cursor += 1;
            while cursor < body_bytes.len() && body_bytes[cursor].is_ascii_whitespace() {
                cursor += 1;
            }

            if cursor < body_bytes.len()
                && (body_bytes[cursor] == b'"' || body_bytes[cursor] == b'\'')
            {
                let quote = body_bytes[cursor];
                cursor += 1;
                let value_start = cursor;
                while cursor < body_bytes.len() && body_bytes[cursor] != quote {
                    cursor += 1;
                }
                value = Some(&tag_body[value_start..cursor]);
                if cursor < body_bytes.len() {
                    cursor += 1;
                }
            } else {
                let value_start = cursor;
                while cursor < body_bytes.len() && !body_bytes[cursor].is_ascii_whitespace() {
                    cursor += 1;
                }
                value = Some(&tag_body[value_start..cursor]);
            }
        }

        let raw_attr = tag_body[attr_start..cursor].trim();
        if raw_attr.is_empty() {
            continue;
        }

        if let Some(event_name) = name.strip_prefix('@') {
            let Some(raw_value) = value else {
                continue;
            };
            match parse_event_handler(raw_value) {
                EventHandler::Valid(handler_name, needs_event) => {
                    meta.events
                        .push((event_name.to_string(), handler_name, needs_event));
                }
                EventHandler::Invalid(raw) => {
                    panic!(
                        "Invalid @{event_name} handler: \"{raw}\". \
                         Use @{event_name}=\"{{handler()}}\" or \
                         @{event_name}=\"{{handler(e)}}\" to pass the event.",
                    );
                }
                EventHandler::Empty => {}
            }
            continue;
        }

        if name == "w-ref" {
            // Validate: w-ref must use {braces} to bind to a component property.
            // This is a build-time check — the runtime also validates.
            if let Some(val) = value {
                if !val.starts_with('{') || !val.ends_with('}') {
                    eprintln!(
                        "\x1b[1;31merror\x1b[0m: invalid w-ref=\"{}\" in <{}> — \
                         use w-ref={{{}}} with braces to bind to a component property",
                        val, tag_name, val
                    );
                }
            }
            out.push(' ');
            out.push_str(raw_attr);
            continue;
        }

        if let Some(bool_name) = name.strip_prefix('?') {
            if let Some(raw_value) = value.and_then(extract_single_handlebars) {
                meta.attr_bindings.push(CompiledAttrBinding::Boolean {
                    name: bool_name.to_string(),
                    condition: compile_condition_expr(&raw_value),
                });
                binding_count += 1;
            }
            continue;
        }

        if name.starts_with(':') {
            if let Some(raw_value) = value.and_then(extract_single_handlebars) {
                // Strip the ':' prefix and convert to camelCase for the JS property name.
                // The runtime uses el[name] = value directly — no conversion needed.
                let prop_name = webui_protocol::attrs::attribute_to_camel(
                    name.strip_prefix(':').unwrap_or(name),
                );
                meta.attr_bindings.push(CompiledAttrBinding::Complex {
                    name: prop_name,
                    value: raw_value,
                });
                binding_count += 1;
            }
            continue;
        }

        if let Some(raw_value) = value {
            if let Some(parts) = parse_attr_parts(raw_value) {
                let is_simple =
                    parts.len() == 1 && matches!(parts.first(), Some(CompiledAttrPart::Dynamic(_)));
                if is_simple {
                    if let Some(CompiledAttrPart::Dynamic(path)) = parts.into_iter().next() {
                        meta.attr_bindings.push(CompiledAttrBinding::Simple {
                            name: name.to_string(),
                            value: path,
                        });
                    }
                } else {
                    meta.attr_bindings.push(CompiledAttrBinding::Template {
                        name: name.to_string(),
                        parts,
                    });
                }
                binding_count += 1;
                continue;
            }
        }

        out.push(' ');
        out.push_str(raw_attr);
    }

    if binding_count == 1 {
        out.push_str(" data-w-b-");
        out.push_str(&binding_start.to_string());
    } else if binding_count > 1 {
        out.push_str(" data-w-c-");
        out.push_str(&binding_start.to_string());
        out.push('-');
        out.push_str(&binding_count.to_string());
    }

    let event_count = meta.events.len().saturating_sub(event_start);
    if event_count > 0 {
        out.push_str(" data-ev=\"");
        let _ = write!(out, "{}", event_count);
        out.push('"');
    }

    if self_closing {
        out.push_str(" />");
    } else {
        out.push('>');
    }

    Some((out, end + 1))
}

fn find_tag_end(input: &str) -> Option<usize> {
    let bytes = input.as_bytes();
    let mut quote: Option<u8> = None;
    let mut i = 1;

    while i < bytes.len() {
        let ch = bytes[i];
        if let Some(active) = quote {
            if ch == active {
                quote = None;
            }
        } else if ch == b'"' || ch == b'\'' {
            quote = Some(ch);
        } else if ch == b'>' {
            return Some(i);
        }
        i += 1;
    }

    None
}

enum EventHandler {
    Valid(String, bool),
    Invalid(String),
    Empty,
}

fn parse_event_handler(raw_value: &str) -> EventHandler {
    let inner = raw_value
        .trim()
        .strip_prefix('{')
        .and_then(|s| s.strip_suffix('}'))
        .unwrap_or(raw_value)
        .trim();
    if inner.is_empty() {
        return EventHandler::Empty;
    }
    // `handler(e)` → needs event, `handler()` → no event
    match inner.find('(') {
        Some(paren) => {
            EventHandler::Valid(inner[..paren].trim().to_string(), inner.contains("(e)"))
        }
        None => EventHandler::Invalid(inner.to_string()),
    }
}

fn extract_single_handlebars(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if let Some(inner) = trimmed
        .strip_prefix("{{{")
        .and_then(|s| s.strip_suffix("}}}"))
    {
        return Some(inner.trim().to_string());
    }

    if let Some(inner) = trimmed
        .strip_prefix("{{")
        .and_then(|s| s.strip_suffix("}}"))
    {
        return Some(inner.trim().to_string());
    }

    None
}

fn parse_attr_parts(value: &str) -> Option<Vec<CompiledAttrPart>> {
    let bytes = value.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut last = 0;
    let mut dynamic_found = false;
    let mut parts = Vec::new();

    while i < len {
        if i + 2 < len && bytes[i] == b'{' && bytes[i + 1] == b'{' {
            let brace_count = if i + 2 < len && bytes[i + 2] == b'{' {
                3
            } else {
                2
            };

            if let Some(end) = find_brace_end(value, i + brace_count, brace_count) {
                if last < i {
                    parts.push(CompiledAttrPart::Static(value[last..i].to_string()));
                }
                parts.push(CompiledAttrPart::Dynamic(
                    value[i + brace_count..end].trim().to_string(),
                ));
                dynamic_found = true;
                i = end + brace_count;
                last = i;
                continue;
            }
        }

        i += 1;
    }

    if !dynamic_found {
        return None;
    }

    if last < len {
        parts.push(CompiledAttrPart::Static(value[last..].to_string()));
    }

    Some(parts)
}

/// Extract `@event` bindings from the opening `<template>` tag.
///
/// These become "root events" (`re` array) attached to the host element
/// rather than to an element inside the shadow DOM.
fn extract_root_events(html: &str) -> Vec<(String, String, bool)> {
    if !html.starts_with("<template") {
        return Vec::new();
    }
    let Some(close) = find_tag_end(html) else {
        return Vec::new();
    };
    let tag = &html[..close];
    let mut events = Vec::new();
    let bytes = tag.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if bytes[i] == b'@' {
            if let Some((name, handler, needs_event, consumed)) = parse_event_attr(tag, i) {
                events.push((name, handler, needs_event));
                i += consumed;
                continue;
            }
        }
        i += 1;
    }

    events
}

fn extract_adopted_stylesheet_specifier(html: &str) -> Option<String> {
    if !html.starts_with("<template") {
        return None;
    }
    let close = find_tag_end(html)?;
    let tag = &html[..close];
    let attr = "shadowrootadoptedstylesheets=\"";
    let start = tag.find(attr)? + attr.len();
    let end = tag[start..].find('"')? + start;
    Some(tag[start..end].to_string())
}

// ── Tests ──────────────────────────────────────────────────────────

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

    fn assert_no_client_markers(result: &str) {
        assert!(!result.contains("<!--t:"), "text markers should be removed");
        assert!(
            !result.contains("<!--c:"),
            "conditional markers should be removed"
        );
        assert!(
            !result.contains("<!--r:"),
            "repeat markers should be removed"
        );
        assert!(
            !result.contains("data-w-b-"),
            "attribute binding markers should be removed"
        );
        assert!(
            !result.contains("data-w-c-"),
            "attribute binding range markers should be removed"
        );
        assert!(
            !result.contains("data-ev="),
            "event markers should be removed"
        );
    }

    #[test]
    fn test_skip_event_attributes() {
        let mut plugin = WebUIParserPlugin::new();
        assert_eq!(plugin.classify_attribute("@click"), AttributeAction::Skip);
        assert_eq!(plugin.classify_attribute("@keydown"), AttributeAction::Skip);
        assert_eq!(plugin.classify_attribute("w-ref"), AttributeAction::Keep);
        assert_eq!(plugin.classify_attribute("class"), AttributeAction::Keep);
    }

    #[test]
    fn test_metadata_has_text_bindings() {
        let result = generate_compiled_template("my-comp", "<h1>{{title}}</h1>");
        assert_no_client_markers(&result);
        assert!(result.contains(r#"h:"<h1></h1>""#));
        assert!(result.contains("\"title\""));
        assert!(result.contains(r#",tx:[[[[0],0],[["title"]]]]"#));
        assert!(!result.contains("{{"));
    }

    #[test]
    fn test_metadata_has_conditionals() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<if condition="state == 'done'"><span>yes</span></if>"#,
        );
        assert_no_client_markers(&result);
        assert!(result
            .contains(r#"c:[[[function(v,s){return v("state",s)=="done"},["state"]],0,[[],0]]]"#));
        assert!(result.contains("<span>yes</span>"));
        assert!(!result.contains("<if"));
    }

    #[test]
    fn test_metadata_has_conditionals_with_gt_in_condition_attr() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<if condition="count > 0"><span>yes</span></if>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(",c:["), "conditional metadata expected");
        assert!(result.contains("<span>yes</span>"));
        assert!(!result.contains("<if"));
    }

    #[test]
    fn test_parse_if_block_ignores_close_marker_inside_attr_value() {
        let input = r#"<if condition="count > 0"><div data-note="</if>">yes</div></if>"#;
        let (_, body, consumed) = parse_if_block(input).expect("if block should parse");

        assert_eq!(body, r#"<div data-note="</if>">yes</div>"#);
        assert_eq!(consumed, input.len());
    }

    #[test]
    fn test_metadata_has_for_loops() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="item in items"><p>{{item.name}}</p></for>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains("\"items\""));
        assert!(result.contains("\"item\""));
        assert!(!result.contains("<for"));
    }

    #[test]
    fn test_parse_for_block_ignores_open_marker_inside_attr_value() {
        let input =
            r#"<for each="item in items"><div data-note="<for fake>">{{item.name}}</div></for>"#;
        let (collection, item_var, body, consumed) =
            parse_for_block(input).expect("for block should parse");

        assert_eq!(collection, "items");
        assert_eq!(item_var, "item");
        assert_eq!(body, r#"<div data-note="<for fake>">{{item.name}}</div>"#);
        assert_eq!(consumed, input.len());
    }

    #[test]
    fn test_metadata_has_for_loops_with_gt_in_other_attr() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="item in items" data-note="a > b"><p>{{item.name}}</p></for>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains("\"items\""));
        assert!(result.contains("\"item\""));
        assert!(!result.contains("<for"));
        assert!(!result.contains("{{item.name}}"));
    }

    #[test]
    fn test_metadata_has_events() {
        let result =
            generate_compiled_template("my-comp", r#"<button @click="{onClick()}">Go</button>"#);
        assert_no_client_markers(&result);
        assert!(result.contains("\"click\""));
        assert!(result.contains("\"onClick\""));
        assert!(!result.contains("@click"));
    }

    #[test]
    fn test_metadata_has_events_unquoted() {
        let result =
            generate_compiled_template("my-comp", r#"<button @click={onClick()}>Go</button>"#);
        assert_no_client_markers(&result);
        assert!(result.contains("\"click\""));
        assert!(result.contains("\"onClick\""));
    }

    #[test]
    fn test_metadata_has_events_with_arg() {
        let result = generate_compiled_template("my-comp", r#"<input @keydown="{onKey(e)}" />"#);
        assert_no_client_markers(&result);
        assert!(result.contains("\"keydown\""));
        assert!(result.contains("\"onKey\""));
        assert!(result.contains(",1")); // needs_event = true
    }

    #[test]
    fn test_metadata_has_simple_attr_bindings() {
        let result = generate_compiled_template("my-comp", r#"<input title="{{title}}" />"#);
        assert_no_client_markers(&result);
        assert!(result.contains(",a:["));
        assert!(result.contains(",ag:[[[0],0,1]]"));
        assert!(result.contains(r#"["title",0,"title"]"#));
        assert!(!result.contains(r#"title=\"<!--t:"#));
    }

    #[test]
    fn test_metadata_has_template_attr_bindings() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<a href="/product/{{handle}}" class="card {{variant}}">Go</a>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(",a:["));
        assert!(result.contains(",ag:[[[0],0,2]]"));
        assert!(result.contains(r#"["href",3,["/product/",["handle"]]]"#));
        assert!(result.contains(r#"["class",3,["card ",["variant"]]]"#));
        assert!(!result.contains(r#"/product/<!--t:"#));
    }

    #[test]
    fn test_metadata_has_boolean_attr_bindings() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<a ?data-active="{{page == 'dashboard'}}">Go</a>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(",a:["));
        assert!(result.contains(",ag:[[[0],0,1]]"));
        assert!(result.contains(
            r#"["data-active",2,[function(v,s){return v("page",s)=="dashboard"},["page"]]]"#
        ));
    }

    #[test]
    fn test_metadata_has_complex_attr_bindings() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<child-view :config="{{settings}}"></child-view>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(",a:["));
        assert!(result.contains(",ag:[[[0],0,1]]"));
        assert!(result.contains(r#""config",1,"settings""#));
    }

    #[test]
    fn test_w_ref_stays_in_html() {
        let result = generate_compiled_template("my-comp", r#"<input w-ref="{myInput}" />"#);
        // w-ref stays in the static HTML — runtime binds from the DOM directly
        assert!(result.contains("w-ref"));
        assert!(result.contains("myInput"));
    }

    #[test]
    fn test_w_ref_unquoted_stays_in_html() {
        let result = generate_compiled_template("my-comp", r#"<span w-ref={myLabel}>0</span>"#);
        assert!(result.contains("w-ref"));
        assert!(result.contains("myLabel"));
    }

    #[test]
    fn test_metadata_has_root_events() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>hi</div></template>"#,
        );
        assert!(result.contains(",re:["));
        assert!(result.contains("\"click\""));
        assert!(result.contains("\"onClick\""));
    }

    #[test]
    fn test_strips_shadowrootmode() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open"><p>{{title}}</p></template>"#,
        );
        assert!(!result.contains("shadowrootmode"));
        assert_no_client_markers(&result);
        assert!(result.contains(r#",tx:[[[[0],0],[["title"]]]]"#));
    }

    #[test]
    fn test_root_template_allows_gt_in_quoted_attr_values() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open" data-note="a > b" @click="{onClick()}"><p>hi</p></template>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(r#"h:"<p>hi</p>""#));
        assert!(result.contains(r#",re:[["click","onClick",0]]"#));
    }

    #[test]
    fn test_outlet_converted() {
        let result = generate_compiled_template("my-comp", r#"<main><outlet /></main>"#);
        assert!(result.contains("<outlet></outlet>"));
    }

    #[test]
    fn test_emoji_safe() {
        let result = generate_compiled_template("my-comp", r#"<span>📚 {{title}}</span>"#);
        assert!(result.contains("📚"));
        assert_no_client_markers(&result);
        assert!(result.contains(r#",tx:[[[[0],0],["📚 ",["title"]]]]"#));
    }

    #[test]
    fn test_boolean_attr_in_for() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="s in sections"><a ?active="{{s.id == sectionId}}">{{s.name}}</a></for>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(r#"["active",2,[function(v,s){return v("s.id",s)==v("sectionId",s)},["s.id","sectionId"]]]"#));
        assert!(!result.contains("?active"));
    }

    #[test]
    fn test_deduplicates_components() {
        let mut plugin = WebUIParserPlugin::new();
        let comp = Component {
            tag_name: "test-el".to_string(),
            html_content: "<p>hi</p>".to_string(),
            css_content: None,
            css_tokens: Vec::new(),
            source_path: std::path::PathBuf::new(),
            class_name: None,
        };
        plugin
            .register_component_template("test-el", &comp, &comp.html_content)
            .unwrap();
        plugin
            .register_component_template("test-el", &comp, &comp.html_content)
            .unwrap();
        assert_eq!(plugin.take_component_templates().len(), 1);
    }

    #[test]
    fn test_compiled_template_preserves_link_node_in_static_html() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open"><link rel="stylesheet" href="my-comp.css"><p>hi</p></template>"#,
        );
        assert!(result.contains(r#"rel=\"stylesheet\""#));
        assert!(result.contains(r#"href=\"my-comp.css\""#));
        assert!(result.contains(r#"<p>hi</p>"#));
        assert!(!result.contains(",css:"));
    }

    #[test]
    fn test_compiled_template_preserves_inline_style_in_static_html() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open"><style>.root{color:red}</style><p>hi</p></template>"#,
        );
        assert!(result.contains(r#"h:"<style>.root{color:red}</style><p>hi</p>""#));
    }

    #[test]
    fn test_compiled_template_emits_adopted_stylesheet_specifier() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open" shadowrootadoptedstylesheets="my-comp"><p>hi</p></template>"#,
        );
        assert!(result.contains(r#",sa:"my-comp""#));
    }

    #[test]
    fn test_plugin_uses_processed_link_template_html() {
        let mut plugin = WebUIParserPlugin::new();

        let comp = Component {
            tag_name: "test-el".to_string(),
            html_content: "<p>hi</p>".to_string(),
            css_content: Some(".root { color: red; }".to_string()),
            css_tokens: Vec::new(),
            source_path: std::path::PathBuf::new(),
            class_name: None,
        };

        plugin
            .register_component_template(
                "test-el",
                &comp,
                r#"<template shadowrootmode="open"><link rel="stylesheet" href="test-el.css"><p>hi</p></template>"#,
            )
            .unwrap();
        let templates = plugin.take_component_templates();
        assert_eq!(templates.len(), 1);
        assert!(templates[0].1.contains(r#"rel=\"stylesheet\""#));
        assert!(templates[0].1.contains(r#"href=\"test-el.css\""#));
        assert!(templates[0].1.contains(r#"<p>hi</p>"#));
    }

    #[test]
    fn test_plugin_preserves_root_events_from_raw_template_source() {
        let mut plugin = WebUIParserPlugin::new();

        let comp = Component {
            tag_name: "test-el".to_string(),
            html_content:
                r#"<template shadowrootmode="open" @click="{onClick(e)}"><p>hi</p></template>"#
                    .to_string(),
            css_content: Some(".root { color: red; }".to_string()),
            css_tokens: Vec::new(),
            source_path: std::path::PathBuf::new(),
            class_name: None,
        };

        plugin
            .register_component_template(
                "test-el",
                &comp,
                r#"<template shadowrootmode="open"><link rel="stylesheet" href="test-el.css"><p>hi</p></template>"#,
            )
            .unwrap();
        let templates = plugin.take_component_templates();
        assert_eq!(templates.len(), 1);
        assert!(templates[0].1.contains(r#",re:[["click","onClick",1]]"#));
    }

    #[test]
    fn test_plugin_uses_processed_module_template_html() {
        let mut plugin = WebUIParserPlugin::new();

        let comp = Component {
            tag_name: "test-el".to_string(),
            html_content: "<p>hi</p>".to_string(),
            css_content: Some(".root { color: red; }".to_string()),
            css_tokens: Vec::new(),
            source_path: std::path::PathBuf::new(),
            class_name: None,
        };

        plugin
            .register_component_template(
                "test-el",
                &comp,
                r#"<template shadowrootmode="open" shadowrootadoptedstylesheets="test-el"><p>hi</p></template>"#,
            )
            .unwrap();
        let templates = plugin.take_component_templates();
        assert_eq!(templates.len(), 1);
        assert!(templates[0].1.contains(r#",sa:"test-el""#));
    }

    #[test]
    fn test_nested_if_inside_for_compiles_nested_blocks() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="item in items"><if condition="item.active"><span>{{item.name}}</span></if></for>"#,
        );

        assert_no_client_markers(&result);
        assert!(result.contains(",b:["), "compiled block table expected");
        assert!(
            result.contains(r#"["items","item",0,[[],0]]"#),
            "repeat block index expected"
        );
        assert!(
            result.contains(
                r#"[[function(v,s){return !!v("item.active",s)},["item.active"]],1,[[],0]]"#
            ),
            "nested conditional block index expected"
        );
        assert!(!result.contains("<if"), "nested if should be compiled");
        assert!(!result.contains("{{"), "nested bindings should be compiled");
    }

    #[test]
    fn test_for_inside_if_compiles_nested_blocks() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<if condition="showList"><for each="item in items"><p>{{item.name}}</p></for></if>"#,
        );

        assert_no_client_markers(&result);
        assert!(result.contains(",b:["), "compiled block table expected");
        assert!(
            result.contains(r#"[[function(v,s){return !!v("showList",s)},["showList"]],0,[[],0]]"#),
            "conditional block index expected"
        );
        assert!(
            result.contains(r#"["items","item",1,[[],0]]"#),
            "nested repeat block index expected"
        );
        assert!(!result.contains("<for"), "nested for should be compiled");
        assert!(!result.contains("{{"), "nested bindings should be compiled");
    }

    #[test]
    fn test_nested_for_inside_for_compiles_nested_blocks() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="group in groups"><div><for each="item in group.items"><button data-group="{{group.name}}" ?disabled="{{item.disabled}}">{{item.label}}</button></for></div></for>"#,
        );

        assert_no_client_markers(&result);
        assert!(result.contains(",b:["), "compiled block table expected");
        assert!(
            result.contains(r#"["groups","group",0,[[],0]]"#),
            "outer repeat block index expected"
        );
        assert!(
            result.contains(r#"["group.items","item",1,[[0],0]]"#),
            "inner repeat block index expected"
        );
        assert!(!result.contains("<for"), "nested for should be compiled");
        assert!(!result.contains("{{"), "nested bindings should be compiled");
        assert!(
            !result.contains("?disabled"),
            "nested boolean attrs should be compiled"
        );
    }

    #[test]
    fn test_multiple_events_on_same_element() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<input @keydown="{onKey(e)}" @focus="{onFocus()}" />"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains("\"keydown\""), "keydown event expected");
        assert!(result.contains("\"onKey\""), "onKey handler expected");
        assert!(result.contains("\"focus\""), "focus event expected");
        assert!(result.contains("\"onFocus\""), "onFocus handler expected");
    }

    #[test]
    fn test_regular_tag_uses_single_event_marker_per_element() {
        let mut meta = TemplateSectionMeta::default();
        let (tag_html, _) = parse_regular_tag(
            r#"<input @keydown="{onKey(e)}" @focus="{onFocus()}" />"#,
            &mut meta,
        )
        .expect("regular tag should parse");

        assert_eq!(tag_html, r#"<input data-ev="2" />"#);
    }

    #[test]
    fn test_empty_template() {
        let result = generate_compiled_template("my-comp", "");
        assert!(result.contains("__webui.templates"));
        assert!(result.contains("h:\"\""), "empty html expected");
        // No optional arrays should be present
        assert!(!result.contains(",t:"), "no text bindings");
        assert!(!result.contains(",c:"), "no conditionals");
        assert!(!result.contains(",r:"), "no repeats");
        assert!(!result.contains(",e:"), "no events");
        assert!(!result.contains(",re:"), "no root events");
    }

    #[test]
    fn test_whitespace_only_template() {
        let result = generate_compiled_template("my-comp", "   \n  ");
        assert!(result.contains("__webui.templates"));
        assert!(
            result.contains("h:\"\""),
            "whitespace-only should produce empty html"
        );
    }

    #[test]
    fn test_multiple_text_bindings() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<p>{{first}}</p><p>{{second}}</p><p>{{third}}</p>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains(
            r#",tx:[[[[0],0],[["first"]]],[[[1],0],[["second"]]],[[[2],0],[["third"]]]]"#
        ));
        assert!(result.contains("\"first\""));
        assert!(result.contains("\"second\""));
        assert!(result.contains("\"third\""));
    }

    #[test]
    fn test_multiple_conditionals() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<if condition="a"><span>A</span></if><if condition="b"><span>B</span></if>"#,
        );
        assert_no_client_markers(&result);
    }

    #[test]
    fn test_locator_paths_merge_adjacent_static_text_nodes() {
        let result = generate_compiled_template(
            "mp-product-grid",
            r#"
<template shadowrootmode="open">
  <if condition="products.length == 0 && query">
    <p class="empty-results">There are no products that match "<strong>{{query}}</strong>"</p>
  </if>
  <div class="grid">
    <for each="product in products">
      <mp-product-card
        handle="{{product.handle}}"
        title="{{product.title}}"
        price="{{product.price}}"
        gradient="{{product.gradient}}"
        image-url="{{product.imageUrl}}"
        image-loading="lazy"
        variant="grid"
      ></mp-product-card>
    </for>
  </div>
</template>
"#,
        );

        assert_no_client_markers(&result);
    }

    #[test]
    fn test_mixed_bindings_events_refs() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<button w-ref="{myBtn}" @click="{onClick()}">{{label}}</button>"#,
        );
        // w-ref stays in HTML (quotes escaped inside JS string)
        assert_no_client_markers(&result);
        assert!(result.contains("w-ref"));
        assert!(result.contains("myBtn"));
        // event compiled
        assert!(result.contains("\"click\""));
        assert!(result.contains("\"onClick\""));
        // text binding compiled
        assert!(result.contains(r#",tx:[[[[0],0],[["label"]]]]"#));
        assert!(result.contains("\"label\""));
    }

    #[test]
    fn test_event_without_e_arg() {
        let result =
            generate_compiled_template("my-comp", r#"<button @click="{onClick()}">Go</button>"#);
        assert!(
            result.contains(r#"["click","onClick",0,[0]]"#),
            "needs_event should be 0"
        );
    }

    #[test]
    fn test_root_event_without_e_arg() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<template shadowrootmode="open" @submit="{onSubmit()}"><form>hi</form></template>"#,
        );
        assert!(result.contains(",re:["));
        assert!(result.contains("\"submit\""));
        assert!(result.contains("\"onSubmit\""));
        assert!(result.contains(",0]"), "needs_event should be 0 for no (e)");
    }

    #[test]
    fn test_triple_brace_raw_binding() {
        let result = generate_compiled_template("my-comp", r#"<div>{{{rawHtml}}}</div>"#);
        assert_no_client_markers(&result);
        assert!(
            result.contains(r#",tx:[[[[0],0],[["rawHtml"]],1]]"#),
            "triple brace produces text locator with raw flag: {result}"
        );
        assert!(
            result.contains("\"rawHtml\""),
            "rawHtml path in text bindings"
        );
    }

    #[test]
    fn test_for_with_complex_body() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<for each="user in users"><div class="card"><h2>{{user.name}}</h2><p>{{user.bio}}</p></div></for>"#,
        );
        assert_no_client_markers(&result);
        assert!(result.contains("\"users\""), "collection path");
        assert!(result.contains("\"user\""), "item variable");
        assert!(result.contains(",b:["), "compiled block table expected");
        assert!(
            !result.contains("{{user.name}}"),
            "bindings should be compiled"
        );
        assert!(
            !result.contains("{{user.bio}}"),
            "bindings should be compiled"
        );
    }

    #[test]
    fn test_mixed_text_uses_text_runs() {
        let result = generate_compiled_template("my-comp", r#"<p>Hello {{name}}!</p>"#);

        assert_no_client_markers(&result);
        assert!(result.contains(r#"h:"<p></p>""#));
        assert!(result.contains(r#",tx:[[[[0],0],["Hello ",["name"],"!"]]]"#));
    }

    #[test]
    fn test_js_string_escaping() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<if condition="name == &quot;test&quot;"><span>ok</span></if>"#,
        );
        assert!(result.contains(",c:["), "conditional array present");
        // The right-side literal should remain properly escaped in the AST payload.
        assert!(
            result.contains(r#"function(v,s){return v("name",s)==v("&quot;test&quot;",s)}"#),
            "condition function with escaped quotes should be present: {}",
            result
        );
    }

    #[test]
    fn test_js_string_escapes_script_breakout_sequences() {
        let result = generate_compiled_template(
            "my-comp",
            r#"<div title="</script><script>alert(1)</script>"></div>"#,
        );

        assert!(
            result.contains(r#"\u003C/script><script>alert(1)\u003C/script>"#),
            "script-closing sequences should be neutralized inside metadata strings: {result}"
        );
        assert!(
            !result.contains(r#"title=\"</script><script>alert(1)</script>\""#),
            "raw </script> must not appear inside serialized metadata strings: {result}"
        );
    }

    #[test]
    fn test_js_string_escapes_line_separator_codepoints() {
        let html = format!("<p>before{}middle{}after</p>", '\u{2028}', '\u{2029}');
        let result = generate_compiled_template("my-comp", &html);

        assert!(
            result.contains(r#"\u2028"#),
            "U+2028 should be escaped in metadata strings: {result}"
        );
        assert!(
            result.contains(r#"\u2029"#),
            "U+2029 should be escaped in metadata strings: {result}"
        );
    }

    #[test]
    fn test_on_element_parsed_encodes_12_bytes() {
        let mut plugin = WebUIParserPlugin::new();
        // Simulate 2 event attributes skipped
        let _ = plugin.classify_attribute("@click");
        let _ = plugin.classify_attribute("@keydown");
        // Call on_element_parsed with 3 binding attributes
        let data = plugin.finish_element(3);
        assert!(data.is_some());
        let bytes = data.unwrap();
        assert_eq!(bytes.len(), 12, "plugin data should be 12 bytes");
        let binding_count = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let event_start = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        let event_count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
        assert_eq!(binding_count, 3);
        assert_eq!(event_start, 0);
        assert_eq!(event_count, 2);
    }

    #[test]
    fn test_on_element_parsed_no_data_when_empty() {
        let mut plugin = WebUIParserPlugin::new();
        let data = plugin.finish_element(0);
        assert!(
            data.is_none(),
            "no plugin data when no bindings and no events"
        );
    }

    #[test]
    fn test_on_element_parsed_events_only() {
        let mut plugin = WebUIParserPlugin::new();
        let _ = plugin.classify_attribute("@click");
        let data = plugin.finish_element(0);
        assert!(
            data.is_some(),
            "should emit data for events even with 0 bindings"
        );
        let bytes = data.unwrap();
        let binding_count = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let event_count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
        assert_eq!(binding_count, 0);
        assert_eq!(event_count, 1);
    }

    #[test]
    fn test_event_index_increments_across_elements() {
        let mut plugin = WebUIParserPlugin::new();
        // First element: 2 events
        let _ = plugin.classify_attribute("@click");
        let _ = plugin.classify_attribute("@focus");
        let data1 = plugin.finish_element(0).unwrap();
        let ev_start_1 = u32::from_le_bytes([data1[4], data1[5], data1[6], data1[7]]);
        assert_eq!(ev_start_1, 0, "first element starts at event 0");

        // Second element: 1 event
        let _ = plugin.classify_attribute("@blur");
        let data2 = plugin.finish_element(0).unwrap();
        let ev_start_2 = u32::from_le_bytes([data2[4], data2[5], data2[6], data2[7]]);
        assert_eq!(
            ev_start_2, 2,
            "second element starts at event 2 (after first element's 2 events)"
        );
    }

    #[test]
    fn test_text_run_decodes_html_entities_in_static_parts() {
        // Template: `<nav>{{sectionName}} &gt; {{topicName}}</nav>`
        // The `&gt;` is a static part between two dynamic bindings.
        // On the client, $resolveAttrParts concatenates parts and sets
        // textContent, which does NOT decode entities — so the compiler
        // must decode them in the metadata.
        let result =
            generate_compiled_template("my-comp", "<nav>{{sectionName}} &gt; {{topicName}}</nav>");
        assert_no_client_markers(&result);
        // The static part " > " should be decoded, not " &gt; "
        assert!(
            result.contains(r#"" > ""#),
            "static text run part should contain decoded '>' not '&gt;': {}",
            result
        );
        assert!(
            !result.contains(r#"" &gt; ""#),
            "static text run part should not contain raw '&gt;': {}",
            result
        );
    }

    #[test]
    fn test_parse_event_handler_bare_name_is_invalid() {
        assert!(matches!(
            parse_event_handler("{closeMenu}"),
            EventHandler::Invalid(ref name) if name == "closeMenu"
        ));
    }

    #[test]
    #[should_panic(expected = "Invalid @click handler")]
    fn test_parse_event_attr_bare_name_panics() {
        let input = r#"<button @click="{closeMenu}">Click</button>"#;
        parse_event_attr(input, 8);
    }

    #[test]
    fn test_parse_event_handler_with_parens() {
        assert!(matches!(
            parse_event_handler("{onClick()}"),
            EventHandler::Valid(ref name, false) if name == "onClick"
        ));
    }

    #[test]
    fn test_parse_event_handler_with_event_arg() {
        assert!(matches!(
            parse_event_handler("{onClick(e)}"),
            EventHandler::Valid(ref name, true) if name == "onClick"
        ));
    }

    #[test]
    fn test_parse_event_handler_empty_value() {
        assert!(matches!(parse_event_handler("{}"), EventHandler::Empty));
    }

    #[test]
    fn test_attribute_to_camel_aria() {
        use webui_protocol::attrs::attribute_to_camel;
        assert_eq!(attribute_to_camel("aria-describedby"), "ariaDescribedBy");
        assert_eq!(attribute_to_camel("aria-labelledby"), "ariaLabelledBy");
        assert_eq!(
            attribute_to_camel("aria-activedescendant"),
            "ariaActiveDescendant"
        );
        assert_eq!(attribute_to_camel("aria-label"), "ariaLabel");
        assert_eq!(attribute_to_camel("aria-hidden"), "ariaHidden");
    }

    #[test]
    fn test_attribute_to_camel_html_global() {
        use webui_protocol::attrs::attribute_to_camel;
        assert_eq!(attribute_to_camel("readonly"), "readOnly");
        assert_eq!(attribute_to_camel("tabindex"), "tabIndex");
        assert_eq!(attribute_to_camel("accesskey"), "accessKey");
        assert_eq!(attribute_to_camel("contenteditable"), "contentEditable");
        assert_eq!(attribute_to_camel("inputmode"), "inputMode");
        assert_eq!(attribute_to_camel("maxlength"), "maxLength");
        assert_eq!(attribute_to_camel("formaction"), "formAction");
    }
}