what-core 1.7.0

Core framework for What - an HTML-first web framework powered by Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
//! Template rendering engine
//!
//! Handles variable replacement, custom components, loops, and conditionals.
//! Uses scraper/html5ever for robust HTML parsing.

use regex::Regex;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::LazyLock;

/// Escape HTML special characters (`& < > "`) to prevent XSS when interpolating
/// untrusted values into framework-generated HTML (dev banners, the inspector).
pub(crate) fn escape_html(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Escape HTML special characters to prevent XSS in dev-mode error banners
fn escape_for_banner(s: &str) -> String {
    escape_html(s)
}

/// Dev-mode inline error banner (same styling as the unresolved-component banner)
fn dev_banner(msg: &str) -> String {
    format!(
        r#"<div style="background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">{}</div>"#,
        escape_for_banner(msg)
    )
}

/// Built-in `<what-*>` tags rendered programmatically by the engine (not from
/// components/*.html). Shared by tag dispatch and the unresolved-tag banner.
const BUILTIN_TAGS: &[&str] = &[
    "what-pagination",
    "what-turnstile",
    "what-fetch",
    "what-clipboard",
    "what-theme-toggle",
];

/// Emit one HTML attribute, picking a quote style that survives the value
/// (w-params JSON is typically written with single quotes around double).
fn push_attr(out: &mut String, name: &str, value: &str) {
    if value.contains('"') {
        out.push_str(&format!(" {}='{}'", name, value));
    } else {
        out.push_str(&format!(" {}=\"{}\"", name, value));
    }
}

/// Valid poll interval: bare seconds or number + ms|s|m|h (mirrors what.js)
static POLL_INTERVAL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\d+(ms|s|m|h)?$").unwrap());

/// `<code>` block spans, for linting raw built-in tags inside code samples
static CODE_BLOCK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s)<code\b[^>]*>.*?</code>").unwrap());

/// Regex matching unresolved #variable# patterns (for strict mode warnings)
static UNRESOLVED_VAR_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"#([a-zA-Z_][\w.]*(?:\|[^#]+)?)#").unwrap());

/// Regex for double-quoted attributes: attr="value"
static DOUBLE_QUOTE_ATTR_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"([a-zA-Z_][\w-]*)\s*=\s*"([^"]*)""#).unwrap());

/// Regex for single-quoted attributes: attr='value'
static SINGLE_QUOTE_ATTR_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([a-zA-Z_][\w-]*)\s*=\s*'([^']*)'").unwrap());

use crate::Result;
use crate::components::{Component, ComponentRegistry};
use crate::parser::{ReactiveReplaceResult, replace_variables, replace_variables_reactive};

/// Comparison operators for <if> conditions
enum CompareOp {
    Eq,
    Ne,
    Gt,
    Lt,
    Gte,
    Lte,
}

/// Auto-wrap bare variable names in `#` for simplified <if> syntax.
/// `active_step == 2` → `#active_step# == 2`
/// Skips: quoted strings, numbers, booleans, operators, keywords.
fn wrap_bare_variables(expr: &str) -> String {
    let mut result = String::new();
    let bytes = expr.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        let c = bytes[i];

        // Skip quoted strings
        if c == b'"' || c == b'\'' {
            let quote = c;
            result.push(c as char);
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                result.push(bytes[i] as char);
                i += 1;
            }
            if i < bytes.len() {
                result.push(bytes[i] as char);
                i += 1;
            }
            continue;
        }

        // Skip whitespace and operators
        if c.is_ascii_whitespace() || b"!=<>".contains(&c) {
            result.push(c as char);
            i += 1;
            continue;
        }

        // Word characters — collect the full word
        if c.is_ascii_alphabetic() || c == b'_' {
            let start = i;
            while i < bytes.len()
                && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'.')
            {
                i += 1;
            }
            let word = &expr[start..i];
            match word {
                "true" | "false" | "contains" | "gt" | "gte" | "lt" | "lte" => {
                    result.push_str(word);
                }
                _ => {
                    result.push('#');
                    result.push_str(word);
                    result.push('#');
                }
            }
            continue;
        }

        // Numbers (including decimals)
        if c.is_ascii_digit() || (c == b'-' && i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit())
        {
            while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
                result.push(bytes[i] as char);
                i += 1;
            }
            continue;
        }

        result.push(c as char);
        i += 1;
    }

    result
}

/// Find the byte offset of the first occurrence of `needle` in `s` that sits
/// outside single- or double-quoted segments. Lets conditional tags carry
/// operators like `>` inside quoted attribute values without truncating the
/// tag: `<if cond="#count# > 0">` ends at the final `>`, not the quoted one.
fn find_outside_quotes(s: &str, needle: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    let needle_bytes = needle.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        let c = bytes[i];

        // Skip quoted segments (same state machine as wrap_bare_variables)
        if c == b'"' || c == b'\'' {
            let quote = c;
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                i += 1;
            }
            i += 1; // consume closing quote (or run off the end on unmatched quotes)
            continue;
        }

        if bytes[i..].starts_with(needle_bytes) {
            return Some(i);
        }
        i += 1;
    }

    None
}

/// Split an expression on a top-level boolean keyword (`and` / `or`).
/// The keyword must be whitespace-delimited on both sides and sit outside
/// quoted strings, so `"up and running"` and identifiers like `android`
/// never split. Returns a single-element vec when the keyword is absent.
fn split_top_level_bool(expr: &str, keyword: &str) -> Vec<String> {
    let bytes = expr.as_bytes();
    let kw = keyword.as_bytes();
    let mut parts = Vec::new();
    let mut seg_start = 0;
    let mut i = 0;

    while i < bytes.len() {
        let c = bytes[i];

        // Skip quoted segments (same state machine as wrap_bare_variables)
        if c == b'"' || c == b'\'' {
            let quote = c;
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                i += 1;
            }
            i += 1;
            continue;
        }

        if bytes[i..].starts_with(kw) {
            let ws_before = i > 0 && bytes[i - 1].is_ascii_whitespace();
            let after = i + kw.len();
            let ws_after = after < bytes.len() && bytes[after].is_ascii_whitespace();
            if ws_before && ws_after {
                parts.push(expr[seg_start..i].trim().to_string());
                i = after + 1;
                seg_start = i;
                continue;
            }
        }
        i += 1;
    }

    parts.push(expr[seg_start..].trim().to_string());
    parts
}

/// Map keyword comparison operators (` gte ` / ` lte ` / ` gt ` / ` lt `) to
/// their symbol forms, skipping quoted segments so a literal like
/// `"the gt debate"` passes through untouched (same quote state machine as
/// find_outside_quotes). A plain `.replace()` would rewrite user content
/// inside string operands.
fn map_keyword_operators(condition: &str) -> String {
    const OPS: [(&str, &str); 4] = [
        (" gte ", " >= "),
        (" lte ", " <= "),
        (" gt ", " > "),
        (" lt ", " < "),
    ];
    let bytes = condition.as_bytes();
    let mut out = String::with_capacity(condition.len());
    let mut seg_start = 0;
    let mut i = 0;

    while i < bytes.len() {
        let c = bytes[i];

        // Skip quoted segments (same state machine as find_outside_quotes)
        if c == b'"' || c == b'\'' {
            let quote = c;
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                i += 1;
            }
            if i < bytes.len() {
                i += 1; // consume closing quote
            }
            continue;
        }

        if let Some((kw, sym)) = OPS
            .iter()
            .find(|(kw, _)| bytes[i..].starts_with(kw.as_bytes()))
        {
            out.push_str(&condition[seg_start..i]);
            out.push_str(sym);
            i += kw.len();
            seg_start = i;
            continue;
        }
        i += 1;
    }

    out.push_str(&condition[seg_start..]);
    out
}

/// Legacy `cond="..."` attribute on a conditional tag (deprecated in favor of
/// the simplified form, e.g. `<if count gt 0>`).
static LEGACY_COND_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"<(?:if|elseif|unless)\b[^>]*\bcond\s*=").unwrap());

/// Malformed trailing else: `</if>` followed by `<else/>`. The engine has no
/// support for an else branch outside the `<if>` block — it always renders.
static TRAILING_ELSE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"</if>\s*<else\s*/?>").unwrap());

/// Template files already linted this process (warn once per file).
static WARNED_TEMPLATE_LINTS: LazyLock<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>> =
    LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));

/// Count word-boundary opening tags (`<if `, `<if>`, ...) — same matching
/// rule as find_tag_start, so `<iframe` never counts as `<if`.
fn count_tag_starts(s: &str, tag: &str) -> usize {
    let mut n = 0;
    let mut from = 0;
    while let Some(pos) = find_tag_start(&s[from..], tag) {
        n += 1;
        from += pos + tag.len();
    }
    n
}

/// A single template-lint finding. `message` is a self-contained sentence
/// (no file path prefix) so it can be logged with a path or shown in the
/// dev inspector as-is.
pub(crate) struct TemplateLint {
    pub kind: &'static str, // "legacy-cond" | "trailing-else" | "unclosed" | "raw-builtin-in-code"
    pub message: String,
}

/// Detect template-authoring mistakes in a raw template. Pure function — no
/// logging, no dedup. Used by both the dev-render warning path and the
/// dev inspector.
pub(crate) fn collect_template_lints(raw: &str) -> Vec<TemplateLint> {
    let mut lints = Vec::new();

    if raw.contains("cond") && LEGACY_COND_RE.is_match(raw) {
        lints.push(TemplateLint {
            kind: "legacy-cond",
            message: "Deprecated cond=\"...\" — use the simplified form, e.g. <if count gt 0> or <if user.role == \"admin\">. The cond attribute still works but the simplified form is recommended.".to_string(),
        });
    }

    if raw.contains("<else") && TRAILING_ELSE_RE.is_match(raw) {
        lints.push(TemplateLint {
            kind: "trailing-else",
            message: "Malformed conditional: <else/> placed after </if> ALWAYS renders. Move it inside the block: <if cond>A<else/>B</if>".to_string(),
        });
    }

    // Unclosed conditional/loop blocks: the engine leaves the raw tag in the
    // output and the "conditional" content renders unconditionally — with no
    // other symptom. Only more-opens-than-closes is a defect signal.
    for t in ["if", "loop", "unless"] {
        let opens = count_tag_starts(raw, &format!("<{}", t));
        if opens == 0 {
            continue;
        }
        let closes = raw.matches(&format!("</{}>", t)).count();
        if opens > closes {
            lints.push(TemplateLint {
                kind: "unclosed",
                message: format!(
                    "Unclosed <{}>: {} opening tag(s) but {} </{}> — the unclosed block is skipped by the engine, so its raw <{}> markup leaks into the page and the content renders unconditionally.",
                    t, opens, closes, t, t
                ),
            });
        }
    }

    // Raw built-in <what-*> tags inside <code> blocks: tag expansion runs
    // BEFORE code-block protection, so the sample expands instead of
    // displaying. Code samples must entity-escape: &lt;what-fetch&gt;
    if raw.contains("<code") {
        let tags: std::collections::HashSet<&str> = CODE_BLOCK_RE
            .find_iter(raw)
            .flat_map(|m| {
                BUILTIN_TAGS
                    .iter()
                    .filter(move |t| m.as_str().contains(&format!("<{}", t)))
                    .copied()
            })
            .collect();
        for tag in tags {
            lints.push(TemplateLint {
                kind: "raw-builtin-in-code",
                message: format!(
                    "Raw <{}> inside a <code> block — built-in tags expand BEFORE code-block protection, so the sample will render instead of displaying. Entity-escape it: &lt;{}&gt;",
                    tag, tag
                ),
            });
        }
    }

    lints
}

/// Dev-mode template lints, emitted once per file per process.
/// Returns true if any warning was emitted (false = clean file or already warned).
pub(crate) fn warn_template_lints_once(path: &std::path::Path, raw: &str) -> bool {
    let lints = collect_template_lints(raw);
    if lints.is_empty() {
        return false;
    }

    let mut warned = WARNED_TEMPLATE_LINTS
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    if !warned.insert(path.to_path_buf()) {
        return false;
    }

    for lint in &lints {
        tracing::warn!("{} in {}", lint.message, path.display());
    }
    true
}

/// Find an opening tag prefix (e.g. `<if`) at a word boundary: the next byte
/// must be whitespace, `>`, or `/`. Prevents `<iframe` from matching `<if`
/// (which would corrupt depth tracking and swallow content up to a real `</if>`).
fn find_tag_start(s: &str, tag: &str) -> Option<usize> {
    let mut from = 0;
    while let Some(rel) = s[from..].find(tag) {
        let pos = from + rel;
        match s.as_bytes().get(pos + tag.len()) {
            Some(b) if b.is_ascii_whitespace() || *b == b'>' || *b == b'/' => return Some(pos),
            None => return Some(pos),
            _ => from = pos + tag.len(),
        }
    }
    None
}

/// Parsed loop tag information
struct LoopInfo {
    start: usize,
    end: usize,
    data_attr: String,
    alias: String,
    body: String,
    /// Items per page (from `paginate` attribute)
    per_page: Option<usize>,
    /// Page expression (from `page` attribute, e.g., "#query.page|1#")
    page_expr: Option<String>,
}

/// Template rendering engine using html5ever for parsing
pub struct RenderEngine {
    components: ComponentRegistry,
}

impl RenderEngine {
    pub fn new(components: ComponentRegistry) -> Self {
        Self { components }
    }

    /// Render a template with the given context
    pub async fn render(&self, template: &str, context: &HashMap<String, Value>) -> Result<String> {
        self.render_with_secret(template, context, None).await
    }

    /// Render a template with an optional validation secret for form signing
    pub async fn render_with_secret(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
        validation_secret: Option<&str>,
    ) -> Result<String> {
        let t_start = std::time::Instant::now();
        let mut output = template.to_string();

        // Process includes first (so included content can have loops, tags, etc.)
        let t0 = std::time::Instant::now();
        output = self.process_includes(&output, context)?;
        let t_includes = t0.elapsed();

        // Process section-level auth (strip elements with auth= attribute if access denied)
        output = Self::process_section_auth(&output, context)?;

        // Process loops using scraper
        let t1 = std::time::Instant::now();
        output = self.process_loops_html(&output, context)?;
        let t_loops = t1.elapsed();

        // Process conditionals using scraper
        let t2 = std::time::Instant::now();
        output = self.process_conditionals_html(&output, context)?;
        let t_conditionals = t2.elapsed();

        // Process custom tags
        let t3 = std::time::Instant::now();
        output = self.process_custom_tags_html(&output, context)?;
        let t_components = t3.elapsed();

        // Process conditionals again — component output may contain <if> tags
        let t4 = std::time::Instant::now();
        output = self.process_conditionals_html(&output, context)?;
        let t_conditionals2 = t4.elapsed();

        // Process validated forms (sign w-* rules as JWT hidden field)
        if let Some(secret) = validation_secret {
            let (processed, _actions) = Self::process_validated_forms(&output, secret);
            output = processed;
        }

        // Protect <code> block content from variable replacement
        let (protected, code_blocks) = Self::protect_code_blocks(&output);

        // Replace remaining variables (simple regex is fine for #var# syntax)
        let t5 = std::time::Instant::now();
        let replaced = replace_variables(&protected, context);
        let t_vars = t5.elapsed();

        // Restore code blocks
        output = Self::restore_code_blocks(&replaced, &code_blocks);

        // Strict mode: warn about unresolved variables
        let is_strict = context
            .get("_strict")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if is_strict {
            for cap in UNRESOLVED_VAR_RE.captures_iter(&output) {
                let var = &cap[1];
                // Skip internal/system variables and CSS color codes
                if !var.starts_with('_') {
                    tracing::warn!("Strict: unresolved variable #{}#", var);
                }
            }
        }

        let t_total = t_start.elapsed();
        tracing::debug!(
            "Template timing: includes={:.2}ms loops={:.2}ms conditionals={:.2}ms components={:.2}ms conditionals2={:.2}ms vars={:.2}ms total={:.2}ms",
            t_includes.as_secs_f64() * 1000.0,
            t_loops.as_secs_f64() * 1000.0,
            t_conditionals.as_secs_f64() * 1000.0,
            t_components.as_secs_f64() * 1000.0,
            t_conditionals2.as_secs_f64() * 1000.0,
            t_vars.as_secs_f64() * 1000.0,
            t_total.as_secs_f64() * 1000.0,
        );

        Ok(output)
    }

    /// Render a template with reactive session variable wrapping
    /// Returns both the rendered HTML and the set of session keys used
    pub async fn render_reactive(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
    ) -> Result<ReactiveReplaceResult> {
        self.render_reactive_with_secret(template, context, None)
            .await
    }

    /// Render reactive with optional validation secret
    pub async fn render_reactive_with_secret(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
        validation_secret: Option<&str>,
    ) -> Result<ReactiveReplaceResult> {
        let mut output = template.to_string();

        // Process includes first (so included content can have loops, tags, etc.)
        output = self.process_includes(&output, context)?;

        // Process section-level auth (strip elements with auth= attribute if access denied)
        output = Self::process_section_auth(&output, context)?;

        // Process loops using scraper
        output = self.process_loops_html(&output, context)?;

        // Process conditionals using scraper
        output = self.process_conditionals_html(&output, context)?;

        // Process custom tags
        output = self.process_custom_tags_html(&output, context)?;

        // Process conditionals again — component output may contain <if> tags
        output = self.process_conditionals_html(&output, context)?;

        // Process validated forms
        if let Some(secret) = validation_secret {
            let (processed, _actions) = Self::process_validated_forms(&output, secret);
            output = processed;
        }

        // Protect <code> block content from variable replacement
        let (protected, code_blocks) = Self::protect_code_blocks(&output);

        // Replace variables with reactive wrapping for session variables
        let mut result = replace_variables_reactive(&protected, context);

        // Restore code blocks in the result
        result.html = Self::restore_code_blocks(&result.html, &code_blocks);

        // Strict mode: warn about unresolved variables
        let is_strict = context
            .get("_strict")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if is_strict {
            for cap in UNRESOLVED_VAR_RE.captures_iter(&result.html) {
                let var = &cap[1];
                if !var.starts_with('_') {
                    tracing::warn!("Strict: unresolved variable #{}#", var);
                }
            }
        }

        Ok(result)
    }

    /// Process `<form w-validate>` tags: extract w-* validation attributes from inputs,
    /// encode as JWT, and inject a hidden `<input name="w-rules">` field.
    /// Returns (processed_html, list_of_action_urls_with_validation).
    fn process_validated_forms(html: &str, secret: &str) -> (String, Vec<String>) {
        use crate::validation;

        // Hoisted: this runs on every render of a page containing forms
        static FORM_RE: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"(?si)<form\b[^>]*\bw-validate\b[^>]*>").unwrap());
        static ACTION_RE: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r#"(?i)action="([^"]+)""#).unwrap());
        let form_re = &*FORM_RE;
        let action_re = &*ACTION_RE;
        let mut output = html.to_string();
        let mut offset: isize = 0;
        let mut validated_actions = Vec::new();

        let captures: Vec<_> = form_re.find_iter(html).collect();
        for mat in captures {
            let form_tag_end = (mat.end() as isize + offset) as usize;

            // Find matching </form>
            if let Some(close_pos) = output[form_tag_end..].find("</form>") {
                let abs_close = form_tag_end + close_pos;
                let form_body = &output[form_tag_end..abs_close];

                // Parse validation rules from the form's inputs
                let rules = validation::parse_form_rules(form_body);
                if rules.fields.is_empty() {
                    continue;
                }

                // Extract form action URL for the validation registry
                let form_tag = mat.as_str();
                if let Some(cap) = action_re.captures(form_tag) {
                    if let Some(action) = cap.get(1) {
                        validated_actions.push(action.as_str().to_string());
                    }
                }

                // Encode rules as JWT
                if let Some(token) = validation::encode_rules(&rules, secret) {
                    let hidden_field =
                        format!(r#"<input type="hidden" name="w-rules" value="{}">"#, token);
                    // Insert hidden field right after the opening <form> tag
                    output.insert_str(form_tag_end, &hidden_field);
                    offset += hidden_field.len() as isize;

                    // Inject HTML5 validation attributes onto inputs
                    let updated_end = (mat.end() as isize + offset) as usize;
                    if let Some(close_pos2) = output[updated_end..].find("</form>") {
                        let abs_close2 = updated_end + close_pos2;
                        let form_section = output[updated_end..abs_close2].to_string();
                        let enhanced = inject_html5_validation_attrs(&form_section, &rules);
                        let diff = enhanced.len() as isize - form_section.len() as isize;
                        output.replace_range(updated_end..abs_close2, &enhanced);
                        offset += diff;
                    }
                }
            }
        }

        (output, validated_actions)
    }
}

/// Inject HTML5 validation attributes onto form inputs based on parsed rules.
/// Maps: w-required → required, w-min → minlength, w-max → maxlength, w-type → type, w-pattern → pattern.
/// Also strips w-* validation attributes from the output.
fn inject_html5_validation_attrs(form_body: &str, rules: &crate::validation::FormRules) -> String {
    let mut result = form_body.to_string();

    for (field_name, field_rules) in &rules.fields {
        let name_attr = format!(r#"name="{}""#, field_name);
        if let Some(pos) = result.find(&name_attr) {
            // Find the end of this tag (closing >)
            let tag_end = result[pos..].find('>').map(|p| pos + p);
            let mut attrs = String::new();

            if field_rules.required {
                attrs.push_str(" required");
            }
            if let Some(min) = field_rules.min {
                attrs.push_str(&format!(r#" minlength="{}""#, min));
            }
            if let Some(max) = field_rules.max {
                attrs.push_str(&format!(r#" maxlength="{}""#, max));
            }
            if let Some(ref ft) = field_rules.field_type {
                // Only inject type if the input doesn't already have one
                let tag_start = result[..pos].rfind('<').unwrap_or(0);
                let tag_str = &result[tag_start..tag_end.unwrap_or(result.len())];
                if !tag_str.contains("type=") {
                    match ft.as_str() {
                        "email" => attrs.push_str(r#" type="email""#),
                        "url" => attrs.push_str(r#" type="url""#),
                        "number" => attrs.push_str(r#" type="number""#),
                        "phone" => attrs.push_str(r#" type="tel""#),
                        "date" => attrs.push_str(r#" type="date""#),
                        "time" => attrs.push_str(r#" type="time""#),
                        _ => {}
                    }
                }
            }
            if let Some(ref pattern) = field_rules.pattern {
                attrs.push_str(&format!(r#" pattern="{}""#, pattern));
            }

            if !attrs.is_empty() {
                let insert_pos = pos + name_attr.len();
                result.insert_str(insert_pos, &attrs);
            }
        }
    }

    // Strip w-* validation attributes from output (they're internal directives)
    let w_attr_re = regex::Regex::new(
        r#"\s*w-(required|min|max|type|pattern|match|unique|error)\s*(?:=\s*"[^"]*")?"#,
    )
    .unwrap();
    w_attr_re.replace_all(&result, "").to_string()
}

impl RenderEngine {
    /// Extract content inside <code> blocks, replacing with placeholders.
    /// Returns (protected_html, extracted_blocks).
    fn protect_code_blocks(html: &str) -> (String, Vec<String>) {
        let mut result = String::with_capacity(html.len());
        let mut blocks = Vec::new();
        let mut pos = 0;

        while pos < html.len() {
            // Find next <code
            let remaining = &html[pos..];
            let Some(code_start) = remaining.find("<code") else {
                result.push_str(remaining);
                break;
            };
            let abs_code_start = pos + code_start;

            // Find end of opening tag
            let Some(tag_end_offset) = html[abs_code_start..].find('>') else {
                result.push_str(remaining);
                break;
            };
            let abs_tag_end = abs_code_start + tag_end_offset + 1;

            // Find </code>
            let Some(close_offset) = html[abs_tag_end..].find("</code>") else {
                result.push_str(remaining);
                break;
            };
            let abs_close = abs_tag_end + close_offset;

            // Extract the inner content and replace with placeholder
            let inner_content = &html[abs_tag_end..abs_close];
            let placeholder = format!("__WHAT_CODE_{}__", blocks.len());
            blocks.push(inner_content.to_string());

            // Write: everything before <code...>, the opening tag, the placeholder, </code>
            result.push_str(&html[pos..abs_tag_end]);
            result.push_str(&placeholder);
            pos = abs_close; // continue from </code> (will be added on next iteration or at end)
        }

        (result, blocks)
    }

    /// Process section-level auth: strip any element with `auth="..."` attribute
    /// if the current user doesn't have access. Server-side — denied content never
    /// reaches the client.
    fn process_section_auth(html: &str, context: &HashMap<String, Value>) -> Result<String> {
        // Single AND double quotes: `auth='admin'` must gate exactly like
        // `auth="admin"` — a quote-style mismatch here would silently serve
        // the protected content to everyone.
        static AUTH_ATTR: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new(r#"(?i)<(\w+)\s[^>]*\bauth\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>"#).unwrap()
        });

        // Extract user info from context
        let authenticated = context
            .get("user")
            .and_then(|u| u.get("authenticated"))
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let user_role = context
            .get("user")
            .and_then(|u| u.get("role"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let user_roles: Vec<String> = if user_role.is_empty() {
            vec![]
        } else {
            vec![user_role.to_string()]
        };

        let mut output = html.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        loop {
            if iterations >= MAX_ITERATIONS {
                break;
            }

            let Some(caps) = AUTH_ATTR.captures(&output) else {
                break;
            };
            iterations += 1;

            let match_start = caps.get(0).unwrap().start();
            let after_open = caps.get(0).unwrap().end();
            let tag_name = caps[1].to_lowercase();
            let auth_value = caps
                .get(2)
                .or_else(|| caps.get(3))
                .map(|m| m.as_str())
                .unwrap_or("")
                .to_string();

            // Find the matching closing tag (handle nesting)
            let close_tag = format!("</{}>", tag_name);
            let open_pattern = format!("<{}", tag_name);
            let mut depth = 1;
            let mut pos = after_open;

            let mut found_end: Option<(usize, usize)> = None; // (inner_end, tag_end)
            while depth > 0 && pos < output.len() {
                if let Some(idx) = output[pos..].find('<') {
                    let abs = pos + idx;
                    if output[abs..].starts_with(&close_tag) {
                        depth -= 1;
                        if depth == 0 {
                            found_end = Some((abs, abs + close_tag.len()));
                            break;
                        }
                        pos = abs + close_tag.len();
                    } else if output[abs..].starts_with(&open_pattern)
                        && output
                            .as_bytes()
                            .get(abs + open_pattern.len())
                            .is_some_and(|&b| b == b' ' || b == b'>' || b == b'/')
                    {
                        depth += 1;
                        pos = abs + 1;
                    } else {
                        pos = abs + 1;
                    }
                } else {
                    break;
                }
            }

            if let Some((inner_end, tag_end)) = found_end {
                let inner = output[after_open..inner_end].to_string();

                let auth_level = crate::parser::parse_auth_level(&auth_value);
                let has_access = match &auth_level {
                    crate::parser::AuthLevel::All => true,
                    crate::parser::AuthLevel::User => authenticated,
                    crate::parser::AuthLevel::Roles(required) => {
                        authenticated && required.iter().any(|r| user_roles.contains(r))
                    }
                };

                let replacement = if has_access { inner } else { String::new() };
                output = format!(
                    "{}{}{}",
                    &output[..match_start],
                    replacement,
                    &output[tag_end..]
                );
            } else {
                // No closing tag found — remove opening tag to prevent infinite loop
                output = format!("{}{}", &output[..match_start], &output[after_open..]);
            }
        }

        Ok(output)
    }

    /// Restore <code> blocks from placeholders
    fn restore_code_blocks(html: &str, blocks: &[String]) -> String {
        let mut result = html.to_string();
        for (i, block) in blocks.iter().enumerate() {
            let placeholder = format!("__WHAT_CODE_{}__", i);
            result = result.replacen(&placeholder, block, 1);
        }
        result
    }

    /// Process <include src="path" attr="value"/> tags with attribute passing
    fn process_includes(&self, template: &str, context: &HashMap<String, Value>) -> Result<String> {
        let mut output = template.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 50; // Prevent infinite include loops

        // Get base path from context (set by server)
        let base_path = context
            .get("_base_path")
            .and_then(|v| v.as_str())
            .unwrap_or(".");

        while output.contains("<include") && iterations < MAX_ITERATIONS {
            iterations += 1;

            if let Some((start, end, src, attrs)) = self.find_include_tag(&output) {
                // Dev-mode hint: suggest <what-*> component syntax instead of <include src="components/...">
                let is_dev = context
                    .get("_dev_mode")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                if is_dev && src.starts_with("components/") {
                    let filename = src
                        .trim_start_matches("components/")
                        .trim_end_matches(".html");
                    tracing::info!(
                        "Hint: <include src=\"{}\"> can be written as <what-{}> (component syntax)",
                        src,
                        filename
                    );
                }

                // Resolve the path: try base_path (project root) first, then content_dir (site/)
                let include_path = std::path::Path::new(base_path).join(&src);
                let include_path = if include_path.exists() {
                    include_path
                } else if let Some(content_dir) =
                    context.get("_content_dir").and_then(|v| v.as_str())
                {
                    let alt = std::path::Path::new(content_dir).join(&src);
                    if alt.exists() { alt } else { include_path }
                } else {
                    include_path
                };

                let included_content = if include_path.exists() {
                    match std::fs::read_to_string(&include_path) {
                        Ok(content) => {
                            if is_dev {
                                warn_template_lints_once(&include_path, &content);
                            }
                            // Parse and strip <what> block, get declared attributes with defaults
                            let (stripped_content, declared_attrs) =
                                self.parse_what_block(&content);

                            // Create a merged context for this include
                            let mut include_context = context.clone();

                            // Process all passed attributes (not just declared ones for JSON)
                            // JSON attributes must use strict JSON format with quoted keys:
                            //   groups='[{"id":1,"name":"Admins"}]'
                            // Use single quotes for the attribute to allow double quotes in JSON
                            for (key, value) in &attrs {
                                let resolved_value = replace_variables(value, context);
                                // Try to parse as JSON if it looks like JSON array or object
                                let trimmed = resolved_value.trim();
                                if (trimmed.starts_with('[') && trimmed.ends_with(']'))
                                    || (trimmed.starts_with('{') && trimmed.ends_with('}'))
                                {
                                    if let Ok(json_value) =
                                        serde_json::from_str::<Value>(&resolved_value)
                                    {
                                        include_context.insert(key.clone(), json_value);
                                    }
                                }
                            }

                            // STRICT MODE: Only process declared attributes for string replacement
                            // Passed attributes override defaults, but undeclared attrs are ignored
                            let mut result = stripped_content;
                            for (key, default_value) in &declared_attrs {
                                // Use passed value if provided, otherwise use default
                                let value = attrs.get(key).unwrap_or(default_value);
                                // Resolve any variables in the attribute value
                                let resolved_value = replace_variables(value, context);
                                // Replace #key# in the included content
                                result = result.replace(&format!("#{}#", key), &resolved_value);
                            }

                            // Process loops and conditionals in the included content with the merged context
                            if let Ok(processed) =
                                self.process_loops_html(&result, &include_context)
                            {
                                result = processed;
                            }
                            if let Ok(processed) =
                                self.process_conditionals_html(&result, &include_context)
                            {
                                result = processed;
                            }

                            result
                        }
                        Err(e) => {
                            if is_dev {
                                tracing::warn!(
                                    "Template error: failed to read include '{}': {}",
                                    src,
                                    e
                                );
                                format!(
                                    r#"<div style="background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">Include error: <b>{}</b> — {}</div>"#,
                                    escape_for_banner(&src),
                                    escape_for_banner(&e.to_string())
                                )
                            } else {
                                format!("<!-- include error: {} -->", e)
                            }
                        }
                    }
                } else {
                    if is_dev {
                        tracing::warn!("Template error: include not found '{}'", src);
                        format!(
                            r#"<div style="background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">Include not found: <b>{}</b></div>"#,
                            escape_for_banner(&src)
                        )
                    } else {
                        format!("<!-- include not found: {} -->", src)
                    }
                };

                output = format!("{}{}{}", &output[..start], included_content, &output[end..]);
            } else {
                break;
            }
        }

        Ok(output)
    }

    /// Parse a <what> block from the content and extract attribute defaults
    /// Returns (content_without_what_block, default_attributes)
    fn parse_what_block(&self, content: &str) -> (String, HashMap<String, String>) {
        let mut defaults = HashMap::new();

        // Find <what> block
        if let Some(start) = content.find("<what>") {
            if let Some(end) = content.find("</what>") {
                // Extract the what block content
                let what_content = &content[start + 6..end];

                // Parse attribute definitions
                // Format: attribute.name = "value" or attribute.name = value
                for line in what_content.lines() {
                    let line = line.trim();
                    if line.starts_with("attribute.") {
                        if let Some(eq_pos) = line.find('=') {
                            let key = line[10..eq_pos].trim(); // Skip "attribute."
                            let value = line[eq_pos + 1..].trim();
                            // Remove quotes if present (one symmetric pair only)
                            let value = crate::parser::strip_symmetric_quotes(value).0;
                            defaults.insert(key.to_string(), value.to_string());
                        }
                    }
                }

                // Return content without the <what> block
                let before = &content[..start];
                let after = &content[end + 7..]; // Skip </what>
                return (format!("{}{}", before.trim_start(), after), defaults);
            }
        }

        (content.to_string(), defaults)
    }

    /// Find an <include src="..." attr="value"/> tag and return (start, end, src, attrs)
    fn find_include_tag(
        &self,
        html: &str,
    ) -> Option<(usize, usize, String, HashMap<String, String>)> {
        let start = find_tag_start(html, "<include")?;
        let rest = &html[start..];

        // End of the opening tag — quote-aware, so attribute values that
        // contain `>` or `/>` (e.g. title="5 > 3") don't truncate the tag.
        // Self-closing iff the char before that `>` is `/`.
        let tag_close = find_outside_quotes(rest, ">")?;
        let tag_content = &rest[..tag_close + 1];
        let self_closing = rest.as_bytes()[tag_close - 1] == b'/';

        let end_offset = if self_closing {
            tag_close + 1
        } else if let Some(close_start) = rest.find("</include>") {
            close_start + "</include>".len()
        } else {
            tag_close + 1
        };

        // Parse all attributes
        let attrs = self.parse_tag_attributes(tag_content);
        let src = attrs.get("src")?.clone();

        // Return attrs without 'src' for passing to the include
        let mut pass_attrs = attrs;
        pass_attrs.remove("src");

        Some((start, start + end_offset, src, pass_attrs))
    }

    /// Process <loop> tags using HTML parser
    fn process_loops_html(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
    ) -> Result<String> {
        let mut output = template.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        // Keep processing until no more loop tags
        while output.contains("<loop") && iterations < MAX_ITERATIONS {
            iterations += 1;

            // Find the outermost loop — inner loops are handled recursively in render_loop
            if let Some(info) = self.find_outermost_loop(&output) {
                let rendered = self.render_loop(
                    &info.data_attr,
                    &info.alias,
                    &info.body,
                    context,
                    info.per_page,
                    info.page_expr.as_deref(),
                );
                output = format!(
                    "{}{}{}",
                    &output[..info.start],
                    rendered,
                    &output[info.end..]
                );
            } else {
                break;
            }
        }

        Ok(output)
    }

    /// Find the outermost <loop> tag (handles nesting via depth tracking)
    fn find_outermost_loop(&self, html: &str) -> Option<LoopInfo> {
        self.find_loop_manual(html)
    }

    /// Manual loop finding as fallback
    fn find_loop_manual(&self, html: &str) -> Option<LoopInfo> {
        let start_tag = "<loop";
        let end_tag = "</loop>";

        let start = html.find(start_tag)?;
        let tag_end = html[start..].find('>')? + start + 1;

        // Parse attributes from the opening tag
        let tag_content = &html[start..tag_end];
        let data_attr = self.extract_attr(tag_content, "data").unwrap_or_default();
        let alias = self
            .extract_attr(tag_content, "as")
            .unwrap_or_else(|| "item".to_string());
        let per_page = self
            .extract_attr(tag_content, "paginate")
            .and_then(|v| v.parse().ok());
        let page_expr = self.extract_attr(tag_content, "page");

        // Find matching end tag (handle nesting)
        let mut depth = 1;
        let mut pos = tag_end;
        while depth > 0 && pos < html.len() {
            if let Some(next_start) = html[pos..].find(start_tag) {
                if let Some(next_end) = html[pos..].find(end_tag) {
                    if next_start < next_end {
                        depth += 1;
                        pos = pos + next_start + start_tag.len();
                    } else {
                        depth -= 1;
                        if depth == 0 {
                            let body = html[tag_end..pos + next_end].to_string();
                            let end = pos + next_end + end_tag.len();
                            return Some(LoopInfo {
                                start,
                                end,
                                data_attr,
                                alias,
                                body,
                                per_page,
                                page_expr,
                            });
                        }
                        pos = pos + next_end + end_tag.len();
                    }
                } else {
                    break;
                }
            } else if let Some(next_end) = html[pos..].find(end_tag) {
                depth -= 1;
                if depth == 0 {
                    let body = html[tag_end..pos + next_end].to_string();
                    let end = pos + next_end + end_tag.len();
                    return Some(LoopInfo {
                        start,
                        end,
                        data_attr,
                        alias,
                        body,
                        per_page,
                        page_expr,
                    });
                }
                pos = pos + next_end + end_tag.len();
            } else {
                break;
            }
        }

        None
    }

    /// Extract an attribute value from a tag string
    /// Supports both double and single quoted values
    fn extract_attr(&self, tag: &str, attr_name: &str) -> Option<String> {
        // Scan every occurrence at a word boundary: a bare `find` matched
        // substrings, so extracting `as` found the `as` inside `class="…"`,
        // failed the `=` check there, and gave up — missing the real attr.
        let mut from = 0;
        while let Some(rel) = tag[from..].find(attr_name) {
            let pos = from + rel;
            from = pos + attr_name.len();
            let preceded_ok = pos == 0 || tag.as_bytes()[pos - 1].is_ascii_whitespace();
            if !preceded_ok {
                continue;
            }
            let rest = tag[pos + attr_name.len()..].trim_start();
            let Some(rest) = rest.strip_prefix('=') else {
                continue;
            };
            let rest = rest.trim_start();
            if let Some(rest) = rest.strip_prefix('"') {
                if let Some(end) = rest.find('"') {
                    return Some(rest[..end].to_string());
                }
            } else if let Some(rest) = rest.strip_prefix('\'') {
                if let Some(end) = rest.find('\'') {
                    return Some(rest[..end].to_string());
                }
            }
        }

        None
    }

    /// Render a single loop with optional pagination
    fn render_loop(
        &self,
        data_expr: &str,
        alias: &str,
        body: &str,
        context: &HashMap<String, Value>,
        per_page: Option<usize>,
        page_expr: Option<&str>,
    ) -> String {
        // Extract variable from #expression#
        let var_name = data_expr.trim_matches('#');
        let parts: Vec<&str> = var_name.split('.').collect();

        // Resolve the data
        let data = if let Some(first) = parts.first() {
            let mut current = context.get(*first);
            for part in parts.iter().skip(1) {
                current = current.and_then(|v| {
                    if let Value::Object(obj) = v {
                        obj.get(*part)
                    } else {
                        None
                    }
                });
            }
            current
        } else {
            None
        };

        match data {
            Some(Value::Array(items)) => {
                let total = items.len();

                // Apply pagination if specified
                let (page_items, page_num, total_pages) = if let Some(per_page) = per_page {
                    let per_page = per_page.max(1);
                    let total_pages = (total + per_page - 1) / per_page;

                    // Resolve page expression or default to 1
                    let page_num = page_expr
                        .map(|expr| {
                            let resolved = replace_variables(expr, context);
                            resolved.parse::<usize>().unwrap_or(1)
                        })
                        .unwrap_or(1)
                        .max(1)
                        .min(total_pages.max(1));

                    let start = (page_num - 1) * per_page;
                    let end = (start + per_page).min(total);
                    let slice: Vec<&Value> = items[start..end].iter().collect();
                    (slice, page_num, total_pages)
                } else {
                    let all: Vec<&Value> = items.iter().collect();
                    (all, 1, 1)
                };

                page_items
                    .iter()
                    .enumerate()
                    .map(|(index, item)| {
                        let mut loop_context = context.clone();
                        loop_context.insert(alias.to_string(), (*item).clone());
                        loop_context.insert("index".to_string(), Value::Number(index.into()));
                        loop_context
                            .insert("index1".to_string(), Value::Number((index + 1).into()));
                        loop_context.insert("first".to_string(), Value::Bool(index == 0));
                        loop_context.insert(
                            "last".to_string(),
                            Value::Bool(index == page_items.len() - 1),
                        );
                        // Pagination context vars
                        loop_context.insert("loop_total".to_string(), Value::Number(total.into()));
                        loop_context
                            .insert("loop_pages".to_string(), Value::Number(total_pages.into()));
                        loop_context
                            .insert("loop_page".to_string(), Value::Number(page_num.into()));

                        // Recursively process inner loops, then conditionals, so that
                        // `<if alias.field == ...>` / `<unless alias.field>` inside the
                        // loop body resolve against the current item (not the global
                        // context, where the loop alias does not exist).
                        let processed = self
                            .process_loops_html(body, &loop_context)
                            .unwrap_or_else(|_| body.to_string());
                        let processed = match self
                            .process_conditionals_html(&processed, &loop_context)
                        {
                            Ok(p) => p,
                            Err(_) => processed,
                        };
                        replace_variables(&processed, &loop_context)
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            }
            Some(Value::Object(obj)) => {
                obj.iter()
                    .enumerate()
                    .map(|(index, (key, value))| {
                        let mut loop_context = context.clone();
                        loop_context.insert("key".to_string(), Value::String(key.clone()));
                        loop_context.insert("value".to_string(), value.clone());
                        loop_context.insert(alias.to_string(), value.clone());
                        loop_context.insert("index".to_string(), Value::Number(index.into()));

                        // Recursively process inner loops, then conditionals, so that
                        // `<if alias.field == ...>` / `<unless alias.field>` inside the
                        // loop body resolve against the current item (not the global
                        // context, where the loop alias does not exist).
                        let processed = self
                            .process_loops_html(body, &loop_context)
                            .unwrap_or_else(|_| body.to_string());
                        let processed = match self
                            .process_conditionals_html(&processed, &loop_context)
                        {
                            Ok(p) => p,
                            Err(_) => processed,
                        };
                        replace_variables(&processed, &loop_context)
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            }
            _ => {
                let is_dev = context
                    .get("_dev_mode")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                if is_dev {
                    tracing::warn!("Template error: <loop> has no data for '{}'", var_name);
                    format!(
                        r#"<div style="background:#fefce8;border:1px solid #fde047;color:#854d0e;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">Loop: no data for <b>{}</b></div>"#,
                        escape_for_banner(var_name)
                    )
                } else {
                    format!("<!-- loop: no data for {} -->", var_name)
                }
            }
        }
    }

    /// Process conditional tags using HTML parser
    fn process_conditionals_html(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
    ) -> Result<String> {
        let mut output = template.to_string();

        // Process <if> tags
        output = self.process_if_tags(&output, context)?;

        // Process <unless> tags
        output = self.process_unless_tags(&output, context)?;

        Ok(output)
    }

    /// Process <if> tags (with optional <elseif/> and <else/>)
    fn process_if_tags(&self, html: &str, context: &HashMap<String, Value>) -> Result<String> {
        let mut output = html.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        while output.contains("<if") && iterations < MAX_ITERATIONS {
            iterations += 1;

            if let Some((start, end, branches, else_body)) = self.find_if_tag(&output) {
                // Evaluate branches in order, return first matching
                let mut result = None;
                for (condition, body) in branches {
                    if self.evaluate_condition(&condition, context) {
                        result = Some(body);
                        break;
                    }
                }
                let result = result.unwrap_or_else(|| else_body.unwrap_or_default());
                output = format!("{}{}{}", &output[..start], result, &output[end..]);
            } else {
                break;
            }
        }

        Ok(output)
    }

    /// Find an <if> tag and its components (supports <elseif/> and <else/>)
    /// Returns: (start, end, branches: Vec<(condition, body)>, else_body)
    fn find_if_tag(
        &self,
        html: &str,
    ) -> Option<(usize, usize, Vec<(String, String)>, Option<String>)> {
        let start = find_tag_start(html, "<if")?;
        let tag_end = find_outside_quotes(&html[start..], ">")? + start + 1;

        // Parse condition from the opening tag
        let tag_content = &html[start..tag_end];
        let condition = self.extract_attr(tag_content, "cond").unwrap_or_else(|| {
            // Simplified syntax: <if active_step == 2>
            let inner = tag_content.strip_prefix("<if").unwrap_or("").trim();
            let inner = inner.strip_suffix(">").unwrap_or(inner).trim();
            inner.to_string()
        });

        // Find the closing </if>
        let end_tag = "</if>";
        let mut depth = 1;
        let mut pos = tag_end;

        while depth > 0 && pos < html.len() {
            let next_start = find_tag_start(&html[pos..], "<if");
            let next_end = html[pos..].find(end_tag);

            match (next_start, next_end) {
                (Some(s), Some(e)) if s < e => {
                    depth += 1;
                    pos = pos + s + 3;
                }
                (_, Some(e)) => {
                    depth -= 1;
                    if depth == 0 {
                        let body = &html[tag_end..pos + e];
                        let (branches, else_body) = self.parse_if_body(body, &condition);
                        let end = pos + e + end_tag.len();
                        return Some((start, end, branches, else_body));
                    }
                    pos = pos + e + end_tag.len();
                }
                _ => break,
            }
        }

        None
    }

    /// Parse the body of an <if> tag into branches and optional else
    fn parse_if_body(
        &self,
        body: &str,
        initial_condition: &str,
    ) -> (Vec<(String, String)>, Option<String>) {
        let mut branches = Vec::new();
        let mut remaining = body.to_string();
        let mut current_condition = initial_condition.to_string();

        loop {
            // Look for <elseif or <else at the top level (not inside nested <if>)
            let elseif_pos = self.find_top_level_tag(&remaining, "<elseif");
            let else_pos = self.find_top_level_else(&remaining);

            match (elseif_pos, else_pos) {
                // Found <elseif before <else>
                (Some(ei_pos), Some(e_pos)) if ei_pos < e_pos => {
                    // Add current branch
                    branches.push((current_condition.clone(), remaining[..ei_pos].to_string()));

                    // Extract elseif condition
                    let after_elseif = &remaining[ei_pos..];
                    if let Some(tag_end) = find_outside_quotes(after_elseif, "/>") {
                        let tag = &after_elseif[..tag_end + 2];
                        current_condition = self.extract_attr(tag, "cond").unwrap_or_else(|| {
                            let inner = tag.strip_prefix("<elseif").unwrap_or("").trim();
                            let inner = inner.strip_suffix("/>").unwrap_or(inner).trim();
                            inner.to_string()
                        });
                        remaining = after_elseif[tag_end + 2..].to_string();
                    } else {
                        break;
                    }
                }
                // Found <elseif only
                (Some(ei_pos), None) => {
                    branches.push((current_condition.clone(), remaining[..ei_pos].to_string()));

                    let after_elseif = &remaining[ei_pos..];
                    if let Some(tag_end) = find_outside_quotes(after_elseif, "/>") {
                        let tag = &after_elseif[..tag_end + 2];
                        current_condition = self.extract_attr(tag, "cond").unwrap_or_else(|| {
                            let inner = tag.strip_prefix("<elseif").unwrap_or("").trim();
                            let inner = inner.strip_suffix("/>").unwrap_or(inner).trim();
                            inner.to_string()
                        });
                        remaining = after_elseif[tag_end + 2..].to_string();
                    } else {
                        break;
                    }
                }
                // Found <else> (with or without <elseif before it, but <else> comes first now)
                (_, Some(e_pos)) => {
                    branches.push((current_condition.clone(), remaining[..e_pos].to_string()));

                    // Find the actual else tag to skip it
                    let after_else_start = &remaining[e_pos..];
                    let else_len = if after_else_start.starts_with("<else/>") {
                        7
                    } else if after_else_start.starts_with("<else />") {
                        8
                    } else {
                        7 // default
                    };
                    let else_body = remaining[e_pos + else_len..].to_string();
                    return (branches, Some(else_body));
                }
                // No more elseif or else
                (None, None) => {
                    branches.push((current_condition, remaining));
                    return (branches, None);
                }
            }
        }

        branches.push((current_condition, remaining));
        (branches, None)
    }

    /// Find top-level <elseif tag (not inside nested <if>)
    fn find_top_level_tag(&self, html: &str, tag: &str) -> Option<usize> {
        let mut depth = 0;
        let mut pos = 0;

        while pos < html.len() {
            let next_if = find_tag_start(&html[pos..], "<if");
            let next_endif = html[pos..].find("</if>");
            let next_target = html[pos..].find(tag);

            // Find the earliest occurrence
            let events: Vec<(usize, &str)> = [
                next_if.map(|p| (p, "if")),
                next_endif.map(|p| (p, "endif")),
                next_target.map(|p| (p, "target")),
            ]
            .into_iter()
            .flatten()
            .collect();

            if events.is_empty() {
                break;
            }

            let (offset, event_type) = events.into_iter().min_by_key(|(p, _)| *p)?;

            match event_type {
                "if" => {
                    depth += 1;
                    pos = pos + offset + 3;
                }
                "endif" => {
                    depth -= 1;
                    pos = pos + offset + 5;
                }
                "target" => {
                    if depth == 0 {
                        return Some(pos + offset);
                    }
                    pos = pos + offset + tag.len();
                }
                _ => break,
            }
        }

        None
    }

    /// Find top-level <else/> or <else /> tag
    fn find_top_level_else(&self, html: &str) -> Option<usize> {
        let mut depth = 0;
        let mut pos = 0;

        while pos < html.len() {
            let next_if = find_tag_start(&html[pos..], "<if");
            let next_endif = html[pos..].find("</if>");
            let next_else = html[pos..].find("<else");

            let events: Vec<(usize, &str)> = [
                next_if.map(|p| (p, "if")),
                next_endif.map(|p| (p, "endif")),
                next_else.map(|p| (p, "else")),
            ]
            .into_iter()
            .flatten()
            .collect();

            if events.is_empty() {
                break;
            }

            let (offset, event_type) = events.into_iter().min_by_key(|(p, _)| *p)?;

            match event_type {
                "if" => {
                    depth += 1;
                    pos = pos + offset + 3;
                }
                "endif" => {
                    depth -= 1;
                    pos = pos + offset + 5;
                }
                "else" => {
                    if depth == 0 {
                        // Make sure it's <else/> or <else /> not <elseif
                        let after = &html[pos + offset..];
                        if after.starts_with("<else/>") || after.starts_with("<else />") {
                            return Some(pos + offset);
                        }
                    }
                    pos = pos + offset + 5;
                }
                _ => break,
            }
        }

        None
    }

    /// Process <unless> tags
    fn process_unless_tags(&self, html: &str, context: &HashMap<String, Value>) -> Result<String> {
        let mut output = html.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        while output.contains("<unless") && iterations < MAX_ITERATIONS {
            iterations += 1;

            if let Some((start, end, condition, body)) = self.find_unless_tag(&output) {
                let result = if !self.evaluate_condition(&condition, context) {
                    body
                } else {
                    String::new()
                };
                output = format!("{}{}{}", &output[..start], result, &output[end..]);
            } else {
                break;
            }
        }

        Ok(output)
    }

    /// Find an <unless> tag
    fn find_unless_tag(&self, html: &str) -> Option<(usize, usize, String, String)> {
        let start = find_tag_start(html, "<unless")?;
        let tag_end = find_outside_quotes(&html[start..], ">")? + start + 1;

        let tag_content = &html[start..tag_end];
        let condition = self.extract_attr(tag_content, "cond").unwrap_or_else(|| {
            let inner = tag_content.strip_prefix("<unless").unwrap_or("").trim();
            let inner = inner.strip_suffix(">").unwrap_or(inner).trim();
            inner.to_string()
        });

        let end_tag = "</unless>";
        if let Some(end_pos) = html[tag_end..].find(end_tag) {
            let body = html[tag_end..tag_end + end_pos].to_string();
            let end = tag_end + end_pos + end_tag.len();
            return Some((start, end, condition, body));
        }

        None
    }

    /// Evaluate a condition expression
    fn evaluate_condition(&self, condition: &str, context: &HashMap<String, Value>) -> bool {
        let condition = condition.trim();
        if condition.is_empty() {
            return false;
        }

        // Boolean combinators: split on top-level `or` first, then `and`,
        // so `and` binds tighter (`a or b and c` == `a or (b and c)`).
        // Each part recurses, so leaf logic below stays untouched and
        // any()/all() give short-circuit evaluation.
        let or_parts = split_top_level_bool(condition, "or");
        if or_parts.len() > 1 {
            return or_parts.iter().any(|p| self.evaluate_condition(p, context));
        }
        let and_parts = split_top_level_bool(condition, "and");
        if and_parts.len() > 1 {
            return and_parts.iter().all(|p| self.evaluate_condition(p, context));
        }

        // Auto-wrap bare variable names if condition uses simplified syntax (no #)
        let condition = if !condition.contains('#') {
            wrap_bare_variables(condition)
        } else {
            condition.to_string()
        };
        let condition = condition.trim();

        // Map keyword operators to symbols (for simplified syntax) —
        // quote-aware, so operands containing " gt " etc. stay intact
        let condition = map_keyword_operators(condition);
        let condition = condition.trim();

        // Handle negation: !#variable#
        if condition.starts_with('!') {
            return !self.evaluate_condition(&condition[1..], context);
        }

        // Handle comparison operators (check multi-char first to avoid partial matches)
        // Order: >=, <=, !=, ==, >, <, contains
        for (op, cmp_fn) in &[
            (">=", CompareOp::Gte),
            ("<=", CompareOp::Lte),
            ("!=", CompareOp::Ne),
            ("==", CompareOp::Eq),
            (">", CompareOp::Gt),
            ("<", CompareOp::Lt),
        ] {
            // Quote-aware: an operator character inside a quoted operand
            // (e.g. `name == "a > b"`) must not split the condition
            if let Some(idx) = find_outside_quotes(condition, op) {
                // Strip one symmetric pair of quotes (single OR double) from
                // BOTH sides so quoted operands (`"#a#" == "#b#"`, `'admin'`)
                // compare symmetrically. Single-quoted literals previously
                // kept their quotes and the comparison never matched.
                let (left_raw, left_quoted) =
                    crate::parser::strip_symmetric_quotes(condition[..idx].trim());
                let (right_raw, right_quoted) =
                    crate::parser::strip_symmetric_quotes(condition[idx + op.len()..].trim());
                // Variables resolve HTML-escaped (output semantics); compare
                // the unescaped text so `company == "Ben & Jerry"` and names
                // like O'Brien match their literals.
                let left =
                    crate::parser::html_unescape(&replace_variables(left_raw, context));
                let right =
                    crate::parser::html_unescape(&replace_variables(right_raw, context));

                // Try arithmetic evaluation on both sides
                let left_num = crate::parser::evaluate_arithmetic(&left)
                    .or_else(|| left.parse::<f64>().ok());
                let right_num = crate::parser::evaluate_arithmetic(&right)
                    .or_else(|| right.parse::<f64>().ok());

                // Equality is numeric when both sides are numbers and neither
                // was quoted (10 == 10.0 matches, like gt/lt already do).
                // Quoting forces string semantics: `zip == "01234"` compares
                // text, consistent with quoting in <what> blocks.
                let force_string = left_quoted || right_quoted;

                return match cmp_fn {
                    CompareOp::Eq => match (left_num, right_num) {
                        (Some(l), Some(r)) if !force_string => l == r,
                        _ => left == right,
                    },
                    CompareOp::Ne => match (left_num, right_num) {
                        (Some(l), Some(r)) if !force_string => l != r,
                        _ => left != right,
                    },
                    CompareOp::Gt => match (left_num, right_num) {
                        (Some(l), Some(r)) => l > r,
                        _ => left > right,
                    },
                    CompareOp::Lt => match (left_num, right_num) {
                        (Some(l), Some(r)) => l < r,
                        _ => left < right,
                    },
                    CompareOp::Gte => match (left_num, right_num) {
                        (Some(l), Some(r)) => l >= r,
                        _ => left >= right,
                    },
                    CompareOp::Lte => match (left_num, right_num) {
                        (Some(l), Some(r)) => l <= r,
                        _ => left <= right,
                    },
                };
            }
        }

        // Handle contains: #variable# contains "value" (quote-aware, and the
        // literal may use single or double quotes)
        if let Some(idx) = find_outside_quotes(condition, " contains ") {
            let left = crate::parser::html_unescape(&replace_variables(
                condition[..idx].trim(),
                context,
            ));
            let right_raw = condition[idx + " contains ".len()..].trim();
            let right = crate::parser::strip_symmetric_quotes(right_raw).0;
            return left.contains(right);
        }

        // Exact variable reference: use the underlying JSON value rather than the
        // rendered string so empty arrays/objects remain falsey in <if>/<unless>.
        if let Some(var_name) = condition
            .strip_prefix('#')
            .and_then(|s| s.strip_suffix('#'))
            .filter(|s| !s.contains('#'))
        {
            return Self::is_truthy(self.lookup_context_value(var_name, context));
        }

        // Simple truthy check: #variable#
        let resolved = replace_variables(condition, context);
        // If it resolved to something different, check truthiness of the resolved value
        if resolved != condition.to_string() {
            return match resolved.as_str() {
                "" | "false" | "null" | "0" => false,
                _ => true,
            };
        }

        // Direct context lookup for truthy check
        let var_name = condition.trim_matches('#');
        Self::is_truthy(self.lookup_context_value(var_name, context))
    }

    fn lookup_context_value<'a>(
        &self,
        var_name: &str,
        context: &'a HashMap<String, Value>,
    ) -> Option<&'a Value> {
        let parts: Vec<&str> = var_name.split('.').collect();
        let first = parts.first()?;
        let mut current = context.get(*first);
        for part in parts.iter().skip(1) {
            current = current.and_then(|v| match v {
                Value::Object(obj) => obj.get(*part),
                _ => None,
            });
        }
        current
    }

    fn is_truthy(value: Option<&Value>) -> bool {
        match value {
            Some(Value::Bool(b)) => *b,
            Some(Value::Null) => false,
            Some(Value::String(s)) => !s.is_empty(),
            Some(Value::Number(n)) => n.as_f64().map(|v| v != 0.0).unwrap_or(true),
            Some(Value::Array(arr)) => !arr.is_empty(),
            Some(Value::Object(obj)) => !obj.is_empty(),
            None => false,
        }
    }

    fn component_attr_value(value: &str) -> Value {
        let trimmed = value.trim();
        if (trimmed.starts_with('[') && trimmed.ends_with(']'))
            || (trimmed.starts_with('{') && trimmed.ends_with('}'))
        {
            if let Ok(parsed) = serde_json::from_str::<Value>(trimmed) {
                return parsed;
            }
        }

        Value::String(value.to_string())
    }

    fn build_component_context(
        component: &Component,
        attrs: &HashMap<String, String>,
        context: &HashMap<String, Value>,
    ) -> HashMap<String, Value> {
        let mut component_context = context.clone();

        for prop_name in &component.props {
            if !attrs.contains_key(prop_name) && !component.defaults.contains_key(prop_name) {
                component_context.insert(prop_name.clone(), Value::String(String::new()));
            }
        }

        for (key, value) in &component.defaults {
            if !attrs.contains_key(key) {
                component_context.insert(key.clone(), Value::String(value.clone()));
            }
        }

        for (key, value) in attrs {
            // Resolve #var# references in attribute values before passing to component
            let resolved = replace_variables(value, context);
            component_context.insert(key.clone(), Self::component_attr_value(&resolved));
        }

        component_context
    }

    fn apply_component_slots(mut rendered: String, children: Option<&str>) -> String {
        if let Some(children) = children {
            rendered = rendered.replace("<slot/>", children);
            rendered = rendered.replace("<slot />", children);
        } else {
            rendered = rendered.replace("<slot/>", "");
            rendered = rendered.replace("<slot />", "");
        }

        rendered
    }

    /// Render pagination HTML programmatically
    fn render_pagination(
        attrs: &HashMap<String, String>,
        context: &HashMap<String, Value>,
    ) -> String {
        let total: usize = attrs
            .get("total")
            .map(|v| replace_variables(v, context))
            .and_then(|v| v.parse().ok())
            .unwrap_or(0);
        let per_page: usize = attrs
            .get("per-page")
            .map(|v| replace_variables(v, context))
            .and_then(|v| v.parse().ok())
            .unwrap_or(10)
            .max(1);
        let current: usize = attrs
            .get("current")
            .map(|v| replace_variables(v, context))
            .and_then(|v| v.parse().ok())
            .unwrap_or(1)
            .max(1);
        let base_url = attrs
            .get("base-url")
            .map(|v| replace_variables(v, context))
            .unwrap_or_else(|| "/".to_string());
        let param = attrs
            .get("param")
            .cloned()
            .unwrap_or_else(|| "page".to_string());

        let total_pages = if total == 0 {
            0
        } else {
            (total + per_page - 1) / per_page
        };
        if total_pages <= 1 {
            return String::new();
        }

        let current = current.min(total_pages);
        let page_numbers = Self::compute_page_numbers(current, total_pages);

        let mut html = String::from(r#"<nav class="what-pagination" aria-label="Pagination"><ul>"#);

        // Previous button
        if current > 1 {
            html.push_str(&format!(
                r#"<li><a href="{}?{}={}" class="what-pagination-prev" aria-label="Previous page">&laquo;</a></li>"#,
                base_url, param, current - 1
            ));
        } else {
            html.push_str(r#"<li><span class="what-pagination-prev what-pagination-disabled" aria-disabled="true">&laquo;</span></li>"#);
        }

        // Page numbers with ellipsis
        for &num in &page_numbers {
            if num == 0 {
                // Ellipsis
                html.push_str(r#"<li><span class="what-pagination-ellipsis">&hellip;</span></li>"#);
            } else if num == current {
                html.push_str(&format!(
                    r#"<li><span class="what-pagination-active" aria-current="page">{}</span></li>"#,
                    num
                ));
            } else {
                html.push_str(&format!(
                    r#"<li><a href="{}?{}={}">{}</a></li>"#,
                    base_url, param, num, num
                ));
            }
        }

        // Next button
        if current < total_pages {
            html.push_str(&format!(
                r#"<li><a href="{}?{}={}" class="what-pagination-next" aria-label="Next page">&raquo;</a></li>"#,
                base_url, param, current + 1
            ));
        } else {
            html.push_str(r#"<li><span class="what-pagination-next what-pagination-disabled" aria-disabled="true">&raquo;</span></li>"#);
        }

        html.push_str("</ul></nav>");
        html
    }

    /// Compute page numbers for display: [1, ..., 4, 5, 6, ..., 10]
    fn compute_page_numbers(current: usize, total: usize) -> Vec<usize> {
        if total <= 7 {
            return (1..=total).collect();
        }

        let mut pages = Vec::new();
        pages.push(1);

        if current > 3 {
            pages.push(0); // ellipsis
        }

        let range_start = if current <= 3 { 2 } else { current - 1 };
        let range_end = if current >= total - 2 {
            total - 1
        } else {
            current + 1
        };

        for p in range_start..=range_end {
            pages.push(p);
        }

        if current < total - 2 {
            pages.push(0); // ellipsis
        }

        pages.push(total);
        pages
    }

    /// Render a Cloudflare Turnstile widget
    /// Usage: <what-turnstile/> or <what-turnstile theme="dark"/>
    /// Requires [cloudflare] turnstile_site_key in what.toml
    fn render_turnstile(
        attrs: &HashMap<String, String>,
        context: &HashMap<String, Value>,
    ) -> String {
        // Get site key from context (injected by server from config)
        let site_key = context
            .get("_turnstile_site_key")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        if site_key.is_empty() {
            let is_dev = context
                .get("_dev_mode")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            if is_dev {
                return r#"<div style="background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">Turnstile: missing [cloudflare] turnstile_site_key</div>"#.to_string();
            }
            return String::new();
        }

        let theme = attrs.get("theme").map(|s| s.as_str()).unwrap_or("auto");
        let size = attrs.get("size").map(|s| s.as_str()).unwrap_or("normal");

        format!(
            r#"<div class="cf-turnstile" data-sitekey="{}" data-theme="{}" data-size="{}"></div><script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>"#,
            site_key, theme, size
        )
    }

    /// Copy attrs not consumed by a built-in tag through to the output,
    /// sorted for deterministic rendering.
    fn push_extra_attrs(out: &mut String, attrs: &HashMap<String, String>, handled: &[&str]) {
        let mut extras: Vec<(&String, &String)> = attrs
            .iter()
            .filter(|(k, _)| !handled.contains(&k.as_str()))
            .collect();
        extras.sort();
        for (k, v) in extras {
            push_attr(out, k, v);
        }
    }

    /// Render `<what-fetch>` — a declarative fetch-and-inject region.
    /// Usage: <what-fetch url="/w-partial/stats" poll="5s">fallback</what-fetch>
    ///        <what-fetch url="/w-partial/comments" when="visible">Loading…</what-fetch>
    /// Expands to a container carrying w-get/w-post + w-trigger; children are
    /// the server-rendered initial content. `#var#` in attributes resolves in
    /// the later variable-replacement stage.
    fn render_what_fetch(
        attrs: &HashMap<String, String>,
        children: &str,
        context: &HashMap<String, Value>,
    ) -> String {
        let is_dev = context
            .get("_dev_mode")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let url = match attrs.get("url").filter(|u| !u.is_empty()) {
            Some(u) => u,
            None => {
                return if is_dev {
                    dev_banner("<what-fetch> requires a url attribute")
                } else {
                    String::new()
                };
            }
        };

        let method = attrs
            .get("method")
            .map(|s| s.to_lowercase())
            .unwrap_or_else(|| "get".to_string());
        let fetch_attr = if method == "post" { "w-post" } else { "w-get" };

        let when = attrs.get("when").map(|s| s.as_str()).unwrap_or("load");
        let poll = attrs.get("poll");
        if let Some(p) = poll {
            if !POLL_INTERVAL_RE.is_match(p) {
                if is_dev {
                    return dev_banner(&format!(
                        "<what-fetch> invalid poll=\"{}\" — use e.g. 500ms, 5s, 2m, 1h or bare seconds",
                        p
                    ));
                }
            }
        }
        let mut triggers: Vec<String> = Vec::new();
        match when {
            "load" => triggers.push("load".to_string()),
            "visible" => triggers.push("revealed".to_string()),
            // click is the client-side default for w-get, but the token is
            // needed when combined with poll (otherwise clicks are gated off)
            "click" => {
                if poll.is_some() {
                    triggers.push("click".to_string());
                }
            }
            other => {
                if is_dev {
                    return dev_banner(&format!(
                        "<what-fetch> unknown when=\"{}\" — expected load, visible, or click",
                        other
                    ));
                }
                triggers.push("load".to_string());
            }
        }
        if let Some(p) = poll {
            if POLL_INTERVAL_RE.is_match(p) {
                triggers.push(format!("poll {}", p));
            }
        }

        let wrapper = attrs.get("as").map(|s| s.as_str()).unwrap_or("div");
        let mut class = String::from("w-fetch");
        if let Some(c) = attrs.get("class").filter(|c| !c.is_empty()) {
            class.push(' ');
            class.push_str(c);
        }

        let mut out = format!("<{}", wrapper);
        push_attr(&mut out, "class", &class);
        push_attr(&mut out, fetch_attr, url);
        if !triggers.is_empty() {
            push_attr(&mut out, "w-trigger", &triggers.join(", "));
        }
        for (attr, w_attr) in [
            ("target", "w-target"),
            ("swap", "w-swap"),
            ("params", "w-params"),
            ("include", "w-include"),
            ("loading", "w-loading"),
            ("confirm", "w-confirm"),
        ] {
            if let Some(v) = attrs.get(attr) {
                push_attr(&mut out, w_attr, v);
            }
        }
        Self::push_extra_attrs(
            &mut out,
            attrs,
            &[
                "url", "when", "poll", "method", "target", "swap", "params", "include",
                "loading", "confirm", "as", "class",
            ],
        );
        out.push('>');
        out.push_str(children);
        out.push_str(&format!("</{}>", wrapper));
        out
    }

    /// Render `<what-clipboard>` — a declarative copy-to-clipboard button.
    /// Usage: <what-clipboard value="text to copy">Copy</what-clipboard>
    ///        <what-clipboard from="#room-link" copied-label="copied!">copy</what-clipboard>
    fn render_what_clipboard(
        attrs: &HashMap<String, String>,
        children: &str,
        context: &HashMap<String, Value>,
    ) -> String {
        let is_dev = context
            .get("_dev_mode")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let value = attrs.get("value");
        let from = attrs.get("from");
        if value.is_none() && from.is_none() {
            return if is_dev {
                dev_banner("<what-clipboard> requires value=\"text\" or from=\"selector\"")
            } else {
                String::new()
            };
        }

        let mut out = String::from("<button type=\"button\"");
        // Emit only the provided source attribute — an empty w-clipboard=""
        // would still match the client selector and copy the empty string
        if let Some(v) = value {
            push_attr(&mut out, "w-clipboard", v);
        } else if let Some(f) = from {
            push_attr(&mut out, "w-clipboard-from", f);
        }
        if let Some(l) = attrs.get("copied-label") {
            push_attr(&mut out, "w-copied-label", l);
        }
        Self::push_extra_attrs(&mut out, attrs, &["value", "from", "copied-label"]);
        out.push('>');
        out.push_str(if children.trim().is_empty() {
            "Copy"
        } else {
            children
        });
        out.push_str("</button>");
        out
    }

    /// Render `<what-theme-toggle>` — a declarative dark/light theme button.
    /// Children replace the default sun/moon icons; state persists via the
    /// w-theme localStorage key and is restored pre-paint by the injected
    /// head snippet.
    fn render_what_theme_toggle(attrs: &HashMap<String, String>, children: &str) -> String {
        let mut class = String::from("w-theme-toggle");
        if let Some(c) = attrs.get("class").filter(|c| !c.is_empty()) {
            class.push(' ');
            class.push_str(c);
        }

        let mut out = String::from("<button type=\"button\" w-theme-toggle");
        push_attr(&mut out, "class", &class);
        if !attrs.contains_key("aria-label") {
            push_attr(&mut out, "aria-label", "Toggle theme");
        }
        Self::push_extra_attrs(&mut out, attrs, &["class"]);
        out.push('>');
        if children.trim().is_empty() {
            out.push_str(
                r#"<span class="w-theme-icon-light">☀</span><span class="w-theme-icon-dark">☾</span>"#,
            );
        } else {
            out.push_str(children);
        }
        out.push_str("</button>");
        out
    }

    /// Process custom components by finding them manually (scraper normalizes HTML which breaks string matching)
    fn process_custom_tags_html(
        &self,
        template: &str,
        context: &HashMap<String, Value>,
    ) -> Result<String> {
        let mut output = template.to_string();
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        let component_names = self.get_component_names();

        loop {
            let mut found_any = false;

            // Special-case: <what-pagination> is rendered programmatically
            if let Some((start, end, attrs, _children)) =
                self.find_custom_tag(&output, "what-pagination")
            {
                let rendered = Self::render_pagination(&attrs, context);
                output = format!("{}{}{}", &output[..start], rendered, &output[end..]);
                iterations += 1;
                if iterations >= MAX_ITERATIONS {
                    break;
                }
                continue;
            }

            // Special-case: <what-turnstile> renders Cloudflare Turnstile widget
            if let Some((start, end, attrs, _children)) =
                self.find_custom_tag(&output, "what-turnstile")
            {
                let rendered = Self::render_turnstile(&attrs, context);
                output = format!("{}{}{}", &output[..start], rendered, &output[end..]);
                iterations += 1;
                if iterations >= MAX_ITERATIONS {
                    break;
                }
                continue;
            }

            // Special-case: declarative built-ins (fetch region, clipboard,
            // theme toggle) — server-expanded into w-* attribute form
            let mut handled_builtin = false;
            for tag in ["what-fetch", "what-clipboard", "what-theme-toggle"] {
                if let Some((start, end, attrs, children)) = self.find_custom_tag(&output, tag) {
                    let rendered = match tag {
                        "what-fetch" => Self::render_what_fetch(&attrs, &children, context),
                        "what-clipboard" => Self::render_what_clipboard(&attrs, &children, context),
                        _ => Self::render_what_theme_toggle(&attrs, &children),
                    };
                    output = format!("{}{}{}", &output[..start], rendered, &output[end..]);
                    handled_builtin = true;
                    break;
                }
            }
            if handled_builtin {
                iterations += 1;
                if iterations >= MAX_ITERATIONS {
                    break;
                }
                continue;
            }

            // Check each registered component
            for component_name in &component_names {
                if let Some((start, end, attrs, children)) =
                    self.find_custom_tag(&output, component_name)
                {
                    if let Some(component_def) = self.components.get(component_name) {
                        let children = if children.is_empty() {
                            None
                        } else {
                            Some(children.as_str())
                        };
                        let component_context =
                            Self::build_component_context(&component_def, &attrs, context);

                        // Resolve component control-flow before variable replacement so
                        // `#prop#` keeps its JSON/string semantics.
                        let mut rendered = component_def.template.clone();
                        if rendered.contains("<loop") {
                            if let Ok(processed) =
                                self.process_loops_html(&rendered, &component_context)
                            {
                                rendered = processed;
                            }
                        }
                        if rendered.contains("<if") {
                            if let Ok(processed) =
                                self.process_conditionals_html(&rendered, &component_context)
                            {
                                rendered = processed;
                            }
                        }
                        rendered = replace_variables(&rendered, &component_context);
                        rendered = Self::apply_component_slots(rendered, children);

                        // Replace in output
                        output = format!("{}{}{}", &output[..start], rendered, &output[end..]);
                        found_any = true;
                        break; // Start over after modification
                    }
                }
            }

            iterations += 1;
            if !found_any || iterations >= MAX_ITERATIONS {
                break;
            }
        }

        // Dev-mode: unresolved <what-*> tags get a visible inline banner (the
        // same treatment as a missing <include>) — a log line alone leaves
        // nothing in the browser and the typo'd tag silently renders nothing.
        let is_dev = context
            .get("_dev_mode")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if is_dev {
            let mut unresolved: Vec<(usize, String)> = Vec::new();
            let mut search_from = 0;
            while let Some(pos) = output[search_from..].find("<what-") {
                let abs_pos = search_from + pos;
                let rest = &output[abs_pos..];
                if let Some(end) = rest.find('>') {
                    let tag = &rest[1..end].split_whitespace().next().unwrap_or("");
                    // Skip known built-in tags and closing tags
                    if !tag.starts_with('/')
                        && !BUILTIN_TAGS.contains(&tag.trim_end_matches('/'))
                    {
                        let tag_name = tag.trim_end_matches('/');
                        if !component_names
                            .iter()
                            .any(|c| format!("what-{}", c) == tag_name || *c == tag_name)
                        {
                            tracing::warn!("Template warning: unresolved component <{}>", tag_name);
                            unresolved.push((abs_pos, tag_name.to_string()));
                        }
                    }
                    search_from = abs_pos + end + 1;
                } else {
                    break;
                }
            }
            // Insert banners back-to-front so recorded positions stay valid
            for (pos, tag_name) in unresolved.into_iter().rev() {
                let banner = format!(
                    r#"<div style="background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:8px 12px;margin:4px 0;border-radius:4px;font-family:monospace;font-size:13px">Unknown component: <b>&lt;{}&gt;</b> — no matching file in components/</div>"#,
                    escape_for_banner(&tag_name)
                );
                output.insert_str(pos, &banner);
            }
        }

        Ok(output)
    }

    /// Find a custom tag in HTML and return (start, end, attrs, children)
    fn find_custom_tag(
        &self,
        html: &str,
        tag_name: &str,
    ) -> Option<(usize, usize, HashMap<String, String>, String)> {
        // Find opening tag at a word boundary — a bare `find` would let
        // `<what-card` match inside `<what-card-header`
        let open_pattern = format!("<{}", tag_name);
        let start = find_tag_start(html, &open_pattern)?;

        // Find end of opening tag — quote-aware, so attribute values that
        // contain `>` (e.g. label="a > b") don't truncate the tag
        let tag_start_rest = &html[start..];
        let open_tag_end = find_outside_quotes(tag_start_rest, ">")? + start + 1;

        // Parse attributes from opening tag
        let open_tag = &html[start..open_tag_end];
        let attrs = self.parse_tag_attributes(open_tag);

        // Check for self-closing tag
        if open_tag.ends_with("/>") {
            return Some((start, open_tag_end, attrs, String::new()));
        }

        // Find closing tag - need to handle nesting
        let close_tag = format!("</{}>", tag_name);
        let mut depth = 1;
        let mut pos = open_tag_end;

        while depth > 0 && pos < html.len() {
            let rest = &html[pos..];

            // Find next occurrence of open or close tag
            let next_open = rest.find(&open_pattern);
            let next_close = rest.find(&close_tag);

            match (next_open, next_close) {
                (Some(o), Some(c)) if o < c => {
                    // Found another opening tag first - check if it's a real tag (has > after)
                    let after_open = &rest[o..];
                    if after_open
                        .chars()
                        .skip(open_pattern.len())
                        .next()
                        .map(|c| c == ' ' || c == '>' || c == '/')
                        .unwrap_or(false)
                    {
                        depth += 1;
                    }
                    pos = pos + o + open_pattern.len();
                }
                (_, Some(c)) => {
                    depth -= 1;
                    if depth == 0 {
                        let children = html[open_tag_end..pos + c].to_string();
                        let end = pos + c + close_tag.len();
                        return Some((start, end, attrs, children));
                    }
                    pos = pos + c + close_tag.len();
                }
                _ => break,
            }
        }

        None
    }

    /// Parse attributes from an opening tag string like `<page title="Test" class="foo">`
    fn parse_tag_attributes(&self, tag: &str) -> HashMap<String, String> {
        let mut attrs = HashMap::new();

        // Match attribute="value" (double quotes, can contain single quotes)
        for cap in DOUBLE_QUOTE_ATTR_RE.captures_iter(tag) {
            if let (Some(name), Some(value)) = (cap.get(1), cap.get(2)) {
                attrs.insert(name.as_str().to_string(), value.as_str().to_string());
            }
        }

        // Match attribute='value' (single quotes, can contain double quotes)
        for cap in SINGLE_QUOTE_ATTR_RE.captures_iter(tag) {
            if let (Some(name), Some(value)) = (cap.get(1), cap.get(2)) {
                attrs.insert(name.as_str().to_string(), value.as_str().to_string());
            }
        }

        attrs
    }

    /// Get list of registered component names
    fn get_component_names(&self) -> Vec<String> {
        self.components.component_names()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::ComponentRegistry;
    use scraper::{Html, Selector};
    use serde_json::json;

    fn make_engine() -> RenderEngine {
        let mut components = ComponentRegistry::new();
        components.register_builtins();
        RenderEngine::new(components)
    }

    #[tokio::test]
    async fn test_loop_array() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert(
            "users".to_string(),
            json!([
                {"name": "Alice"},
                {"name": "Bob"}
            ]),
        );

        let template = r##"<loop data="#users#"><li>#item.name#</li></loop>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(result.contains("<li>Alice</li>"));
        assert!(result.contains("<li>Bob</li>"));
    }

    #[tokio::test]
    async fn test_loop_with_alias() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert(
            "posts".to_string(),
            json!([
                {"title": "Post 1"},
                {"title": "Post 2"}
            ]),
        );

        let template = r##"<loop data="#posts#" as="post"><h2>#post.title#</h2></loop>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(result.contains("<h2>Post 1</h2>"));
        assert!(result.contains("<h2>Post 2</h2>"));
    }

    #[tokio::test]
    async fn test_if_condition() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("logged_in".to_string(), json!(true));

        let template = r##"<if cond="#logged_in#">Welcome!</if>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert_eq!(result.trim(), "Welcome!");
    }

    #[tokio::test]
    async fn test_if_else() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("logged_in".to_string(), json!(false));

        let template = r##"<if cond="#logged_in#">Dashboard<else/>Login</if>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert_eq!(result.trim(), "Login");
    }

    #[tokio::test]
    async fn test_elseif() {
        let engine = make_engine();

        // Test first branch matches
        let mut context = HashMap::new();
        context.insert("status".to_string(), json!("success"));
        let template = r##"<if cond='#status# == "success"'>OK<elseif cond='#status# == "error"'/>ERR<else/>UNKNOWN</if>"##;
        let result = engine.render(template, &context).await.unwrap();
        assert_eq!(result.trim(), "OK");

        // Test elseif branch matches
        let mut context = HashMap::new();
        context.insert("status".to_string(), json!("error"));
        let result = engine.render(template, &context).await.unwrap();
        assert_eq!(result.trim(), "ERR");

        // Test else branch (no match)
        let mut context = HashMap::new();
        context.insert("status".to_string(), json!("pending"));
        let result = engine.render(template, &context).await.unwrap();
        assert_eq!(result.trim(), "UNKNOWN");
    }

    #[tokio::test]
    async fn test_elseif_multiple() {
        let engine = make_engine();

        let template = r##"<if cond='#level# == "high"'>HIGH<elseif cond='#level# == "medium"'/>MEDIUM<elseif cond='#level# == "low"'/>LOW<else/>NONE</if>"##;

        let mut context = HashMap::new();
        context.insert("level".to_string(), json!("medium"));
        let result = engine.render(template, &context).await.unwrap();
        assert_eq!(result.trim(), "MEDIUM");

        context.insert("level".to_string(), json!("low"));
        let result = engine.render(template, &context).await.unwrap();
        assert_eq!(result.trim(), "LOW");
    }

    #[tokio::test]
    async fn test_unless() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("error".to_string(), json!(null));

        let template = r##"<unless cond="#error#">All good!</unless>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert_eq!(result.trim(), "All good!");
    }

    #[tokio::test]
    async fn test_unless_empty_array_is_falsey() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("items".to_string(), json!([]));

        let template = r##"<unless cond="#items#">No items</unless>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert_eq!(result.trim(), "No items");
    }

    #[tokio::test]
    async fn test_comparison() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("role".to_string(), json!("admin"));

        // Use single quotes for attribute to allow embedded double quotes
        let template = r##"<if cond='#role# == "admin"'>Admin Panel</if>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(result.contains("Admin Panel"));
    }

    #[tokio::test]
    async fn test_contains_operator() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("lines".to_string(), json!("XOX|XXX|OXO"));

        // Match — "XXX" is in the string
        let template = r##"<if cond='#lines# contains "XXX"'>Winner</if>"##;
        let result = engine.render(template, &context).await.unwrap();
        assert!(result.contains("Winner"));

        // No match
        let template = r##"<if cond='#lines# contains "OOO"'>Winner<else/>No winner</if>"##;
        let result = engine.render(template, &context).await.unwrap();
        assert!(result.contains("No winner"));
    }

    #[tokio::test]
    async fn test_custom_component_page() {
        let engine = make_engine();
        let context = HashMap::new();

        let template = r##"<what-page title="Test Page"><div>Content</div></what-page>"##;
        let result = engine.render(template, &context).await.unwrap();

        println!("Result: {}", result);
        assert!(result.contains("<!DOCTYPE html>"));
        assert!(result.contains("<title>Test Page</title>"));
        assert!(result.contains("<div>Content</div>"));
    }

    #[tokio::test]
    async fn test_scraper_custom_components() {
        // Direct test of scraper with custom components
        let html = r##"<what-page title="Test"><div>Hello</div></what-page>"##;
        let doc = Html::parse_fragment(html);

        println!("Parsed HTML: {}", doc.html());

        let selector = Selector::parse("what-page").unwrap();
        let count = doc.select(&selector).count();
        println!("Found {} what-page elements", count);

        for el in doc.select(&selector) {
            println!("Element outer: {}", el.html());
            println!("Element inner: {}", el.inner_html());
        }

        assert!(
            count > 0,
            "Scraper should find custom <what-page> component"
        );
    }

    #[tokio::test]
    async fn test_what_nav_component() {
        use crate::components::{Component, ComponentRegistry};

        // Load the actual nav.html from demo
        let nav_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("examples/demo/components/nav.html");

        let mut nav_component =
            Component::from_file_with_name(&nav_path).expect("Failed to load nav.html");
        nav_component.name = format!("what-{}", nav_component.name);
        println!("Component name: {}", nav_component.name);
        println!(
            "Component template length: {}",
            nav_component.template.len()
        );
        println!("Component template: '{}'", nav_component.template);

        let mut registry = ComponentRegistry::new();
        registry.register(nav_component);

        println!(
            "Component names in registry: {:?}",
            registry.component_names()
        );

        let engine = RenderEngine::new(registry);
        let context = HashMap::new();

        // Test self-closing tag
        let template = r##"<what-nav active="home"/>"##;
        println!("Input template: '{}'", template);

        let result = engine.render(template, &context).await.unwrap();
        println!("Rendered result: '{}'", result);

        assert!(
            result.contains("<header"),
            "Result should contain <header>, got: '{}'",
            result
        );
        assert!(
            result.contains("nav-brand"),
            "Result should contain nav-brand"
        );
    }

    #[tokio::test]
    async fn test_full_page_with_nav() {
        use crate::components::{Component, ComponentRegistry};

        // Create registry with builtins
        let mut registry = ComponentRegistry::new();
        registry.register_builtins();

        // Load the actual nav.html from demo
        let nav_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("examples/demo/components/nav.html");

        let mut nav_component =
            Component::from_file_with_name(&nav_path).expect("Failed to load nav.html");
        nav_component.name = format!("what-{}", nav_component.name);
        println!(
            "Registering nav component with name: {}",
            nav_component.name
        );
        println!("Nav template length: {}", nav_component.template.len());
        registry.register(nav_component);

        println!("All component names: {:?}", registry.component_names());

        let engine = RenderEngine::new(registry);
        let context = HashMap::new();

        // Test rendering a page that contains what-nav
        let template = r##"<page title="Test">
  <what-nav active="home"/>
  <main>Content</main>
</page>"##;

        println!("Input template:\n{}", template);

        let result = engine.render(template, &context).await.unwrap();
        println!("Rendered result:\n{}", result);

        // Check that the page wrapper is there
        assert!(result.contains("<!DOCTYPE html>"), "Should have doctype");
        assert!(result.contains("<title>Test</title>"), "Should have title");

        // Check that nav content is present
        assert!(
            result.contains("<header"),
            "Result should contain <header> from nav"
        );
        assert!(
            result.contains("nav-brand"),
            "Result should contain nav-brand from nav"
        );
        assert!(
            result.contains("<main>Content</main>"),
            "Should have main content"
        );
    }

    #[tokio::test]
    async fn test_code_block_vars_preserved() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("name".to_string(), json!("Alice"));

        // Variables inside <code> should NOT be replaced
        let template = r##"<p>Hello #name#</p><code class="example-code">#name# syntax</code>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(
            result.contains("<p>Hello Alice</p>"),
            "Variable outside code should be replaced"
        );
        assert!(
            result.contains("#name# syntax"),
            "Variable inside code should be preserved"
        );
    }

    #[tokio::test]
    async fn test_code_block_env_vars_preserved() {
        let engine = make_engine();
        let context = HashMap::new();

        let template = r##"<code class="example-code">#env.API_KEY# and #env.DEBUG#</code>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(
            result.contains("#env.API_KEY#"),
            "Env var in code block should be preserved"
        );
        assert!(
            result.contains("#env.DEBUG#"),
            "Env var in code block should be preserved"
        );
    }

    #[tokio::test]
    async fn test_code_block_multiple_blocks() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("x".to_string(), json!("replaced"));

        let template = r##"<code>#x#</code><p>#x#</p><code>#x# again</code>"##;
        let result = engine.render(template, &context).await.unwrap();

        assert!(
            result.contains("<p>replaced</p>"),
            "Var outside code replaced"
        );
        // Both code blocks should preserve their content
        assert_eq!(
            result.matches("#x#").count(),
            2,
            "Both code block vars preserved"
        );
    }

    #[tokio::test]
    async fn test_component_json_array_loop() {
        use crate::components::Component;

        let component = Component {
            name: "what-groups".to_string(),
            props: vec!["groups".to_string()],
            defaults: HashMap::new(),
            template: r##"<ul><loop data="#groups#" as="g"><li>#g.name#</li></loop></ul>"##
                .to_string(),
        };

        let mut registry = ComponentRegistry::new();
        registry.register(component);
        let engine = RenderEngine::new(registry);
        let context = HashMap::new();

        let template =
            r##"<what-groups groups='[{"id":1,"name":"Admins"},{"id":2,"name":"Editors"}]'/>"##;
        let result = engine.render(template, &context).await.unwrap();

        println!("Component loop result: {}", result);
        assert!(
            result.contains("Admins"),
            "Should contain Admins, got: {}",
            result
        );
        assert!(
            result.contains("Editors"),
            "Should contain Editors, got: {}",
            result
        );
        assert!(
            !result.contains("loop: no data"),
            "Should not have loop error, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_render_with_timing_produces_correct_output() {
        // Template timing is debug logging only — verify rendering still works correctly
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("name".to_string(), json!("World"));
        context.insert("items".to_string(), json!([{"label": "A"}, {"label": "B"}]));
        context.insert("show".to_string(), json!(true));

        let template = r##"<p>Hello #name#</p>
<loop data="#items#" as="item"><span>#item.label#</span></loop>
<if cond="#show#">Visible</if>"##;

        let result = engine.render(template, &context).await.unwrap();
        assert!(result.contains("Hello World"));
        assert!(result.contains("<span>A</span>"));
        assert!(result.contains("<span>B</span>"));
        assert!(result.contains("Visible"));
    }

    #[tokio::test]
    async fn test_code_block_reactive_preserved() {
        let engine = make_engine();
        let mut context = HashMap::new();
        context.insert("session".to_string(), json!({"count": 5}));

        let template = r##"<p>#session.count#</p><code>#session.count#</code>"##;
        let result = engine.render_reactive(template, &context).await.unwrap();

        assert!(
            result.html.contains("w-bind"),
            "Session var outside code should be wrapped"
        );
        assert!(
            result.html.contains("#session.count#"),
            "Session var inside code should be preserved"
        );
    }

    // =========================================================================
    // Section Auth Tests
    // =========================================================================

    #[test]
    fn test_unclosed_if_lint_fires() {
        // Distinct fake paths — the lint dedupes per path per process
        assert!(warn_template_lints_once(
            std::path::Path::new("/lint-test/unclosed-if.html"),
            "<if user.name>Hello #user.name#"
        ));
        assert!(warn_template_lints_once(
            std::path::Path::new("/lint-test/unclosed-loop.html"),
            r##"<loop data="#items#" as="it">#it.name#"##
        ));
        // Balanced templates stay silent
        assert!(!warn_template_lints_once(
            std::path::Path::new("/lint-test/balanced.html"),
            "<if user.name>Hello</if><loop data=\"#items#\" as=\"it\">x</loop>"
        ));
        // <iframe> must not count as <if (word-boundary rule)
        assert!(!warn_template_lints_once(
            std::path::Path::new("/lint-test/iframe.html"),
            r#"<iframe src="x"></iframe>"#
        ));
    }

    #[tokio::test]
    async fn test_unresolved_component_banner_in_dev_mode() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("_dev_mode".to_string(), json!(true));
        let dev = engine
            .render("<what-tyop>oops</what-tyop>", &ctx)
            .await
            .unwrap();
        assert!(
            dev.contains("Unknown component"),
            "dev mode should show a banner: {}",
            dev
        );

        let mut prod_ctx = HashMap::new();
        prod_ctx.insert("_dev_mode".to_string(), json!(false));
        let prod = engine
            .render("<what-tyop>oops</what-tyop>", &prod_ctx)
            .await
            .unwrap();
        assert!(
            !prod.contains("Unknown component"),
            "prod must not show banners: {}",
            prod
        );
    }

    // =========================================================================
    // Built-in Declarative Tags (<what-fetch>, <what-clipboard>, <what-theme-toggle>)
    // =========================================================================

    #[tokio::test]
    async fn test_what_fetch_default_when_is_load() {
        let engine = make_engine();
        let ctx = HashMap::new();
        let html = engine
            .render(
                r#"<what-fetch url="/w-partial/stats">fallback</what-fetch>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"w-get="/w-partial/stats""#), "{}", html);
        assert!(html.contains(r#"w-trigger="load""#), "{}", html);
        assert!(html.contains(r#"class="w-fetch""#), "{}", html);
        assert!(html.contains("fallback"), "{}", html);
        assert!(html.contains("</div>"), "{}", html);
        assert!(!html.contains("<what-fetch"), "{}", html);
    }

    #[tokio::test]
    async fn test_what_fetch_triggers_and_poll_grammar() {
        let engine = make_engine();
        let ctx = HashMap::new();

        // visible → revealed
        let html = engine
            .render(
                r#"<what-fetch url="/w-partial/c" when="visible">Loading…</what-fetch>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"w-trigger="revealed""#), "{}", html);

        // default when + poll combine
        let html = engine
            .render(r#"<what-fetch url="/w-partial/t" poll="5s"/>"#, &ctx)
            .await
            .unwrap();
        assert!(html.contains(r#"w-trigger="load, poll 5s""#), "{}", html);

        // click + poll keeps the click token (clicks would be gated off otherwise)
        let html = engine
            .render(
                r#"<what-fetch url="/w-partial/t" when="click" poll="30s"/>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"w-trigger="click, poll 30s""#), "{}", html);

        // plain click emits no w-trigger at all (client default)
        let html = engine
            .render(r#"<what-fetch url="/w-partial/t" when="click"/>"#, &ctx)
            .await
            .unwrap();
        assert!(!html.contains("w-trigger"), "{}", html);

        // interval units: ms, m, h, and bare seconds
        for poll in ["500ms", "2m", "1h", "45"] {
            let html = engine
                .render(
                    &format!(r#"<what-fetch url="/w-partial/t" poll="{}"/>"#, poll),
                    &ctx,
                )
                .await
                .unwrap();
            assert!(
                html.contains(&format!("poll {}", poll)),
                "poll={} → {}",
                poll,
                html
            );
        }
    }

    #[tokio::test]
    async fn test_what_fetch_method_target_swap_as_passthrough() {
        let engine = make_engine();
        let ctx = HashMap::new();
        let html = engine
            .render(
                r##"<what-fetch url="/w-partial/rows" method="post" target="#list" swap="append" as="tbody" id="rows" data-x="1">seed</what-fetch>"##,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"w-post="/w-partial/rows""#), "{}", html);
        assert!(!html.contains("w-get"), "{}", html);
        assert!(html.contains(r##"w-target="#list""##), "{}", html);
        assert!(html.contains(r#"w-swap="append""#), "{}", html);
        assert!(html.starts_with("<tbody"), "{}", html);
        assert!(html.ends_with("</tbody>"), "{}", html);
        assert!(html.contains(r#"id="rows""#), "{}", html);
        assert!(html.contains(r#"data-x="1""#), "{}", html);
    }

    #[tokio::test]
    async fn test_what_fetch_dev_banners_and_prod_fallbacks() {
        let engine = make_engine();
        let mut dev = HashMap::new();
        dev.insert("_dev_mode".to_string(), json!(true));
        let mut prod = HashMap::new();
        prod.insert("_dev_mode".to_string(), json!(false));

        // missing url
        let html = engine.render("<what-fetch>x</what-fetch>", &dev).await.unwrap();
        assert!(html.contains("requires a url"), "{}", html);
        let html = engine.render("<what-fetch>x</what-fetch>", &prod).await.unwrap();
        assert!(!html.contains("what-fetch"), "{}", html);

        // bad poll interval
        let html = engine
            .render(r#"<what-fetch url="/x" poll="soon"/>"#, &dev)
            .await
            .unwrap();
        assert!(html.contains("invalid poll"), "{}", html);
        let html = engine
            .render(r#"<what-fetch url="/x" poll="soon"/>"#, &prod)
            .await
            .unwrap();
        assert!(!html.contains("poll"), "{}", html);

        // unknown when
        let html = engine
            .render(r#"<what-fetch url="/x" when="hover"/>"#, &dev)
            .await
            .unwrap();
        assert!(html.contains("unknown when"), "{}", html);
        let html = engine
            .render(r#"<what-fetch url="/x" when="hover"/>"#, &prod)
            .await
            .unwrap();
        assert!(html.contains(r#"w-trigger="load""#), "{}", html);
    }

    #[tokio::test]
    async fn test_what_fetch_var_in_url_resolves() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("uid".to_string(), json!(7));
        let html = engine
            .render(r#"<what-fetch url="/w-partial/user/#uid#"/>"#, &ctx)
            .await
            .unwrap();
        assert!(html.contains(r#"w-get="/w-partial/user/7""#), "{}", html);
    }

    #[tokio::test]
    async fn test_what_fetch_nested_regions_both_expand() {
        let engine = make_engine();
        let ctx = HashMap::new();
        let html = engine
            .render(
                r#"<what-fetch url="/w-partial/outer"><what-fetch url="/w-partial/inner" when="visible">inner</what-fetch></what-fetch>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"w-get="/w-partial/outer""#), "{}", html);
        assert!(html.contains(r#"w-get="/w-partial/inner""#), "{}", html);
        assert!(!html.contains("<what-fetch"), "{}", html);
    }

    #[tokio::test]
    async fn test_what_clipboard_value_and_from() {
        let engine = make_engine();
        let ctx = HashMap::new();

        let html = engine
            .render(
                r#"<what-clipboard value="cargo install run-what"/>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(
            html.contains(r#"<button type="button" w-clipboard="cargo install run-what""#),
            "{}",
            html
        );
        assert!(html.contains(">Copy</button>"), "{}", html);

        let html = engine
            .render(
                r##"<what-clipboard from="#room-link" copied-label="copied!">copy</what-clipboard>"##,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r##"w-clipboard-from="#room-link""##), "{}", html);
        assert!(html.contains(r#"w-copied-label="copied!""#), "{}", html);
        assert!(html.contains(">copy</button>"), "{}", html);
        // from-only must not emit an empty w-clipboard="" (it would match the
        // client selector and copy the empty string)
        assert!(!html.contains("w-clipboard="), "{}", html);
    }

    #[tokio::test]
    async fn test_what_clipboard_missing_source() {
        let engine = make_engine();
        let mut dev = HashMap::new();
        dev.insert("_dev_mode".to_string(), json!(true));
        let html = engine
            .render("<what-clipboard>Copy</what-clipboard>", &dev)
            .await
            .unwrap();
        assert!(html.contains("requires value="), "{}", html);

        let mut prod = HashMap::new();
        prod.insert("_dev_mode".to_string(), json!(false));
        let html = engine
            .render("<what-clipboard>Copy</what-clipboard>", &prod)
            .await
            .unwrap();
        assert!(!html.contains("button"), "{}", html);
    }

    #[tokio::test]
    async fn test_what_theme_toggle_defaults_and_children() {
        let engine = make_engine();
        let ctx = HashMap::new();

        let html = engine.render("<what-theme-toggle/>", &ctx).await.unwrap();
        assert!(html.contains("w-theme-toggle"), "{}", html);
        assert!(html.contains(r#"class="w-theme-toggle""#), "{}", html);
        assert!(html.contains("w-theme-icon-light"), "{}", html);
        assert!(html.contains("w-theme-icon-dark"), "{}", html);
        assert!(html.contains(r#"aria-label="Toggle theme""#), "{}", html);

        let html = engine
            .render(
                r#"<what-theme-toggle class="nav-btn">Theme</what-theme-toggle>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(html.contains(r#"class="w-theme-toggle nav-btn""#), "{}", html);
        assert!(html.contains(">Theme</button>"), "{}", html);
        assert!(!html.contains("w-theme-icon"), "{}", html);
    }

    #[tokio::test]
    async fn test_escaped_builtin_in_code_survives() {
        let engine = make_engine();
        let ctx = HashMap::new();
        let template =
            r#"<code>&lt;what-fetch url="/w-partial/stats" poll="5s"&gt;&lt;/what-fetch&gt;</code>"#;
        let html = engine.render(template, &ctx).await.unwrap();
        assert!(html.contains("&lt;what-fetch"), "{}", html);
        assert!(!html.contains("w-trigger"), "{}", html);
    }

    #[test]
    fn test_raw_builtin_in_code_lint() {
        assert!(warn_template_lints_once(
            std::path::Path::new("/lint-test/raw-builtin-in-code.html"),
            r#"<code><what-fetch url="/x">sample</what-fetch></code>"#
        ));
        // Entity-escaped samples are fine
        assert!(!warn_template_lints_once(
            std::path::Path::new("/lint-test/escaped-builtin-in-code.html"),
            r#"<code>&lt;what-fetch url="/x"&gt;sample&lt;/what-fetch&gt;</code>"#
        ));
    }

    #[test]
    fn test_include_tag_gt_inside_attr_value() {
        // Regression: the tag-end scan stopped at the first raw `>`, so an
        // attribute value containing `>` truncated the tag mid-attribute.
        let engine = make_engine();
        let html = r#"<p>before</p><include src="box.html" title="5 > 3"/><p>after</p>"#;
        let (start, end, src, attrs) = engine.find_include_tag(html).unwrap();
        assert_eq!(src, "box.html");
        assert_eq!(attrs.get("title").map(String::as_str), Some("5 > 3"));
        assert_eq!(
            &html[start..end],
            r#"<include src="box.html" title="5 > 3"/>"#
        );
    }

    #[test]
    fn test_extract_attr_word_boundary() {
        // `as` must not match inside `class="…"` (and then give up); the
        // real as="item" later in the tag must be found
        let engine = make_engine();
        let tag = r##"<loop class="list" data="#items#" as="item">"##;
        assert_eq!(engine.extract_attr(tag, "as").as_deref(), Some("item"));
        // `target` must not read w-target's value
        let tag2 = r##"<a w-target="#panel" href="/x">"##;
        assert_eq!(engine.extract_attr(tag2, "target"), None);
    }

    #[test]
    fn test_custom_tag_prefix_name_no_collision() {
        // <what-card must not match inside <what-card-header
        let engine = make_engine();
        let html = "<what-card-header>H</what-card-header><what-card>C</what-card>";
        let (start, _end, _attrs, children) = engine.find_custom_tag(html, "what-card").unwrap();
        assert_eq!(children, "C", "matched the wrong tag at {}", start);
    }

    #[test]
    fn test_custom_tag_gt_inside_attr_value() {
        let engine = make_engine();
        let html = r#"<what-badge label="a > b">child</what-badge>"#;
        let (start, end, attrs, children) = engine.find_custom_tag(html, "what-badge").unwrap();
        assert_eq!(start, 0);
        assert_eq!(end, html.len());
        assert_eq!(attrs.get("label").map(String::as_str), Some("a > b"));
        assert_eq!(children, "child");
    }

    #[test]
    fn section_auth_admin_sees_admin_content() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            json!({"authenticated": true, "role": "admin"}),
        );

        let html = r#"<section auth="admin"><p>Admin panel</p></section>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Admin panel"));
    }

    #[test]
    fn section_auth_user_denied_admin_content() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            json!({"authenticated": true, "role": "user"}),
        );

        let html = r#"<section auth="admin"><p>Admin panel</p></section>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(!result.contains("Admin panel"));
    }

    #[test]
    fn section_auth_anonymous_denied() {
        let mut context = HashMap::new();
        context.insert("user".to_string(), json!({"authenticated": false}));

        let html = r#"<div auth="user"><p>Members only</p></div>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(!result.contains("Members only"));
    }

    #[test]
    fn section_auth_authenticated_sees_user_content() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            json!({"authenticated": true, "role": "viewer"}),
        );

        let html = r#"<div auth="user"><p>Welcome back</p></div>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Welcome back"));
    }

    #[test]
    fn section_auth_multiple_roles() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            json!({"authenticated": true, "role": "editor"}),
        );

        let html = r#"<section auth="admin, editor"><p>Staff tools</p></section>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Staff tools"));
    }

    #[test]
    fn section_auth_single_quoted_attr_denies_anonymous() {
        // Regression: `auth='admin'` (single quotes) previously failed to
        // match the double-quote-only gate regex, so the protected content
        // was served to everyone.
        let mut context = HashMap::new();
        context.insert("user".to_string(), json!({"authenticated": false}));

        let html = r#"<section auth='admin'><p>Admin panel</p></section>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(!result.contains("Admin panel"), "got: {}", result);
    }

    #[test]
    fn section_auth_single_quoted_attr_allows_matching_role() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            json!({"authenticated": true, "role": "admin"}),
        );

        let html = r#"<section auth='admin'><p>Admin panel</p></section>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Admin panel"), "got: {}", result);
    }

    #[test]
    fn section_auth_public_always_shown() {
        let mut context = HashMap::new();
        context.insert("user".to_string(), json!({"authenticated": false}));

        let html = r#"<div auth="all"><p>Public info</p></div>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Public info"));
    }

    #[test]
    fn section_auth_preserves_non_auth_elements() {
        let mut context = HashMap::new();
        context.insert("user".to_string(), json!({"authenticated": false}));

        let html = r#"<div><p>Visible</p></div><section auth="admin"><p>Hidden</p></section><p>Also visible</p>"#;
        let result = RenderEngine::process_section_auth(html, &context).unwrap();
        assert!(result.contains("Visible"));
        assert!(result.contains("Also visible"));
        assert!(!result.contains("Hidden"));
    }

    // =========================================================================
    // Simplified <if> Syntax + Numeric Comparisons
    // =========================================================================

    #[tokio::test]
    async fn test_simplified_if_truthy() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("logged_in".to_string(), json!(true));
        let result = engine
            .render("<if logged_in>Welcome!</if>", &ctx)
            .await
            .unwrap();
        assert!(result.contains("Welcome!"));
    }

    #[tokio::test]
    async fn test_if_inside_loop_resolves_alias() {
        // Regression: `<if alias.field == "x">` / `<unless alias.field == "x">`
        // inside a loop must resolve against the current item, not the global
        // context (where the loop alias does not exist).
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert(
            "items".to_string(),
            json!([
                {"name": "A", "done": "true"},
                {"name": "B", "done": "false"}
            ]),
        );
        let tpl = r##"<loop data="#items#" as="it"><if it.done == "true">DONE:#it.name#</if><unless it.done == "true">TODO:#it.name#</unless></loop>"##;
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("DONE:A"), "got: {}", result);
        assert!(result.contains("TODO:B"), "got: {}", result);
        assert!(!result.contains("DONE:B"), "got: {}", result);
        assert!(!result.contains("TODO:A"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_if_quoted_both_sides() {
        // Regression: quoting both operands (e.g. `"#a#" == "#b#"`, as the chat
        // demo does to highlight own messages) must compare symmetrically.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("a".to_string(), json!("alice"));
        ctx.insert("b".to_string(), json!("alice"));
        ctx.insert("c".to_string(), json!("bob"));
        let same = engine.render(r##"<if "#a#" == "#b#">MATCH</if>"##, &ctx).await.unwrap();
        let diff = engine.render(r##"<if "#a#" == "#c#">MATCH</if>"##, &ctx).await.unwrap();
        assert!(same.contains("MATCH"), "equal quoted operands should match: {}", same);
        assert!(!diff.contains("MATCH"), "unequal quoted operands should not match: {}", diff);
    }

    #[tokio::test]
    async fn test_if_equality_unescapes_operands() {
        // Regression: variables resolve HTML-escaped, so values containing
        // & < > ' " never compared equal to their author-written literals.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("company".to_string(), json!("Ben & Jerry"));
        ctx.insert("name".to_string(), json!("O'Brien"));
        let amp = engine
            .render(r#"<if company == "Ben & Jerry">HIT</if>"#, &ctx)
            .await
            .unwrap();
        let apos = engine
            .render(r#"<if name == "O'Brien">HIT</if>"#, &ctx)
            .await
            .unwrap();
        assert!(amp.contains("HIT"), "ampersand value should match: {}", amp);
        assert!(apos.contains("HIT"), "apostrophe value should match: {}", apos);
    }

    #[tokio::test]
    async fn test_if_numeric_equality_coerces() {
        // 10 == 10.0 must match, consistent with gt/lt which already
        // compare numerically.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), json!(10.0));
        let eq = engine.render("<if price == 10>HIT</if>", &ctx).await.unwrap();
        let ne = engine.render("<if price != 10>MISS</if>", &ctx).await.unwrap();
        assert!(eq.contains("HIT"), "10.0 == 10 should match: {}", eq);
        assert!(!ne.contains("MISS"), "10.0 != 10 should not match: {}", ne);
    }

    #[tokio::test]
    async fn test_if_quoted_literal_forces_string_equality() {
        // Quoting forces string semantics (as in <what> blocks): a quoted
        // "01234" never numerically equals 1234.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("zip".to_string(), json!("01234"));
        ctx.insert("num".to_string(), json!(1234));
        let string_match = engine
            .render(r#"<if zip == "01234">HIT</if>"#, &ctx)
            .await
            .unwrap();
        let no_coerce = engine
            .render(r#"<if num == "01234">MISS</if>"#, &ctx)
            .await
            .unwrap();
        assert!(string_match.contains("HIT"), "got: {}", string_match);
        assert!(!no_coerce.contains("MISS"), "quoted literal must not numeric-coerce: {}", no_coerce);
    }

    #[tokio::test]
    async fn test_if_single_quoted_literal() {
        // Regression: single-quoted literals kept their quotes (only `"` was
        // stripped) and the comparison never matched.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("role".to_string(), json!("admin"));
        let hit = engine
            .render(r#"<if role == 'admin'>Panel</if>"#, &ctx)
            .await
            .unwrap();
        let miss = engine
            .render(r#"<if role == 'editor'>Panel</if>"#, &ctx)
            .await
            .unwrap();
        assert!(hit.contains("Panel"), "single-quoted literal should match: {}", hit);
        assert!(!miss.contains("Panel"), "wrong literal should not match: {}", miss);
    }

    #[tokio::test]
    async fn test_if_keyword_operator_inside_quoted_literal() {
        // Regression: ` gt ` / ` lt ` etc. were string-replaced even inside
        // quoted operands, corrupting the literal before comparison.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("title".to_string(), json!("the gt debate"));
        let result = engine
            .render(r#"<if title == "the gt debate">HIT</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("HIT"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_if_operator_inside_quoted_left_operand() {
        // An operator sequence inside a quoted operand must not split the
        // condition — the real operator is the one outside quotes.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("mode".to_string(), json!("a == b"));
        let result = engine
            .render(r#"<if "a == b" == mode>HIT</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("HIT"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_contains_single_quoted_literal() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("title".to_string(), json!("the gt debate"));
        let result = engine
            .render(r#"<if title contains 'debate'>HIT</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("HIT"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_simplified_if_equality() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("status".to_string(), json!("admin"));
        let result = engine
            .render(r#"<if status == "admin">Panel</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("Panel"));
    }

    #[tokio::test]
    async fn test_simplified_if_numeric_eq() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("active_step".to_string(), json!(2));
        let result = engine
            .render("<if active_step == 2>Step 2!</if>", &ctx)
            .await
            .unwrap();
        assert!(result.contains("Step 2!"));
    }

    #[tokio::test]
    async fn test_simplified_elseif() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("level".to_string(), json!("low"));
        let result = engine
            .render(
                r#"<if level == "high">H<elseif level == "low"/>L<else/>M</if>"#,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.contains("L"));
        assert!(!result.contains("H"));
        assert!(!result.contains("M"));
    }

    #[tokio::test]
    async fn test_simplified_unless() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("error".to_string(), json!(false));
        let result = engine
            .render("<unless error>All good!</unless>", &ctx)
            .await
            .unwrap();
        assert!(result.contains("All good!"));
    }

    #[test]
    fn test_split_top_level_bool() {
        // Basic split
        assert_eq!(
            split_top_level_bool("a == 1 and b == 2", "and"),
            vec!["a == 1", "b == 2"]
        );
        // No keyword → single element
        assert_eq!(split_top_level_bool("a == 1", "and"), vec!["a == 1"]);
        // Keyword inside quotes must not split
        assert_eq!(
            split_top_level_bool(r#"status == "up and running""#, "and"),
            vec![r#"status == "up and running""#]
        );
        // Identifiers containing the keyword must not split
        assert_eq!(
            split_top_level_bool("android == 1", "and"),
            vec!["android == 1"]
        );
        assert_eq!(
            split_top_level_bool("category == 2", "or"),
            vec!["category == 2"]
        );
        // Multiple keywords
        assert_eq!(
            split_top_level_bool("a and b and c", "and"),
            vec!["a", "b", "c"]
        );
    }

    #[tokio::test]
    async fn test_if_and_both_true() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(5));
        ctx.insert("role".to_string(), json!("admin"));
        let result = engine
            .render(r#"<if count gt 0 and role == "admin">BOTH</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("BOTH"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_if_and_one_false() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(0));
        ctx.insert("role".to_string(), json!("admin"));
        let result = engine
            .render(r#"<if count gt 0 and role == "admin">BOTH</if>"#, &ctx)
            .await
            .unwrap();
        assert!(!result.contains("BOTH"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_if_or() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("role".to_string(), json!("editor"));
        let tpl = r#"<if role == "admin" or role == "editor">STAFF</if>"#;
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("STAFF"), "got: {}", result);

        ctx.insert("role".to_string(), json!("guest"));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(!result.contains("STAFF"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_and_binds_tighter_than_or() {
        // `a or b and c` must read as `a or (b and c)`.
        let engine = make_engine();
        let tpl = "<if a or b and c>YES</if>";

        // a=true, b/c false → true via the `a` disjunct
        let mut ctx = HashMap::new();
        ctx.insert("a".to_string(), json!(true));
        ctx.insert("b".to_string(), json!(false));
        ctx.insert("c".to_string(), json!(false));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("YES"), "a alone should satisfy: {}", result);

        // a=false, b=true, c=false → (b and c) is false → false
        ctx.insert("a".to_string(), json!(false));
        ctx.insert("b".to_string(), json!(true));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(!result.contains("YES"), "b alone must not satisfy: {}", result);

        // a=false, b=true, c=true → (b and c) true → true
        ctx.insert("c".to_string(), json!(true));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("YES"), "b and c should satisfy: {}", result);
    }

    #[tokio::test]
    async fn test_and_with_quoted_operand_containing_keyword() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("status".to_string(), json!("up and running"));
        ctx.insert("ok".to_string(), json!(true));
        let result = engine
            .render(r#"<if status == "up and running" and ok>LIVE</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("LIVE"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_elseif_with_and() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("n".to_string(), json!(7));
        ctx.insert("enabled".to_string(), json!(true));
        let tpl = "<if n gt 10>BIG<elseif n gt 5 and enabled/>MID<else/>SMALL</if>";
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("MID"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_unless_with_and_de_morgan() {
        // <unless a and b> renders when NOT (a && b).
        let engine = make_engine();
        let tpl = "<unless a and b>SHOWN</unless>";

        let mut ctx = HashMap::new();
        ctx.insert("a".to_string(), json!(true));
        ctx.insert("b".to_string(), json!(false));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("SHOWN"), "got: {}", result);

        ctx.insert("b".to_string(), json!(true));
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(!result.contains("SHOWN"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_negation_applies_per_leaf() {
        // `!a and b` reads as `(!a) and b`.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("a".to_string(), json!(false));
        ctx.insert("b".to_string(), json!(true));
        let result = engine.render("<if !a and b>OK</if>", &ctx).await.unwrap();
        assert!(result.contains("OK"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_legacy_cond_attr_supports_and() {
        // cond= shares the evaluation path, so AND/OR works there too
        // (documented only for the simplified syntax).
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(3));
        ctx.insert("active".to_string(), json!(true));
        let result = engine
            .render(r##"<if cond="#count# gt 0 and #active#">ON</if>"##, &ctx)
            .await
            .unwrap();
        assert!(result.contains("ON"), "got: {}", result);
    }

    #[test]
    fn test_template_lint_regexes() {
        // Legacy cond= matches all three conditional tags
        assert!(LEGACY_COND_RE.is_match(r##"<if cond="#a#">x</if>"##));
        assert!(LEGACY_COND_RE.is_match(r##"<elseif cond='#a#'/>"##));
        assert!(LEGACY_COND_RE.is_match(r##"<unless cond = "#a#">x</unless>"##));
        // Simplified syntax and escaped doc examples must NOT match
        assert!(!LEGACY_COND_RE.is_match("<if count gt 0>x</if>"));
        assert!(!LEGACY_COND_RE.is_match("&lt;if cond=\"#a#\"&gt;"));
        assert!(!LEGACY_COND_RE.is_match("<iframe cond=\"x\">"));
        assert!(!LEGACY_COND_RE.is_match("<if conditional_flag>x</if>"));

        // Trailing else after </if> (always-renders bug)
        assert!(TRAILING_ELSE_RE.is_match("</if><else/>oops</else>"));
        assert!(TRAILING_ELSE_RE.is_match("</if>\n  <else/>"));
        assert!(TRAILING_ELSE_RE.is_match("</if> <else />"));
        // The valid inline form must NOT match
        assert!(!TRAILING_ELSE_RE.is_match("<if a>x<else/>y</if>"));
    }

    #[test]
    fn test_collect_template_lints_kinds() {
        let kinds = |raw: &str| -> Vec<&'static str> {
            collect_template_lints(raw).iter().map(|l| l.kind).collect()
        };
        assert_eq!(kinds(r##"<if cond="#a#">x</if>"##), vec!["legacy-cond"]);
        assert_eq!(kinds("</if><else/>oops</else>"), vec!["trailing-else"]);
        assert_eq!(kinds("<if x>oops"), vec!["unclosed"]);
        assert_eq!(
            kinds(r#"<code><what-fetch url="/x">y</what-fetch></code>"#),
            vec!["raw-builtin-in-code"]
        );
        // Clean templates produce no findings
        assert!(collect_template_lints("<if a>x<else/>y</if>").is_empty());
        assert!(collect_template_lints("<p>plain</p>").is_empty());
        // escaped doc sample is clean
        assert!(collect_template_lints("&lt;what-fetch&gt; in prose").is_empty());
    }

    #[test]
    fn test_escape_html_helper() {
        assert_eq!(escape_html(r#"<script>&"#), "&lt;script&gt;&amp;");
        assert_eq!(escape_html(r#"a"b"#), "a&quot;b");
    }

    #[test]
    fn test_warn_template_lints_once_dedup() {
        let path = std::path::Path::new("/tmp/lint-test-template-a.html");
        let raw = r##"<if cond="#a#">x</if>"##;
        // First call warns, second is deduplicated
        assert!(warn_template_lints_once(path, raw));
        assert!(!warn_template_lints_once(path, raw));
        // Clean content never warns
        let clean_path = std::path::Path::new("/tmp/lint-test-template-b.html");
        assert!(!warn_template_lints_once(clean_path, "<if a>x<else/>y</if>"));
    }

    #[test]
    fn test_find_outside_quotes_skips_quoted_segments() {
        assert_eq!(find_outside_quotes(r##"cond="#count# > 0">"##, ">"), Some(18));
        assert_eq!(find_outside_quotes("plain > here", ">"), Some(6));
        assert_eq!(find_outside_quotes(r#""all > quoted""#, ">"), None);
        assert_eq!(find_outside_quotes(r#"a='x > y'/>"#, "/>"), Some(9));
    }

    #[test]
    fn test_find_tag_start_requires_word_boundary() {
        assert_eq!(find_tag_start("<iframe src='x'>", "<if"), None);
        assert_eq!(find_tag_start("<iframe><if a>", "<if"), Some(8));
        assert_eq!(find_tag_start("<if a == 1>", "<if"), Some(0));
        assert_eq!(find_tag_start("text <if>", "<if"), Some(5));
    }

    #[tokio::test]
    async fn test_cond_attr_with_gt_symbol() {
        // Regression: the tag scanner used the first `>` in the document, so
        // `cond="#count# > 0"` truncated the tag and the condition never matched.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(5));
        let result = engine
            .render(r##"<if cond="#count# > 0">HAS_ITEMS</if>"##, &ctx)
            .await
            .unwrap();
        assert!(result.contains("HAS_ITEMS"), "got: {}", result);

        ctx.insert("count".to_string(), json!(0));
        let result = engine
            .render(r##"<if cond="#count# > 0">HAS_ITEMS</if>"##, &ctx)
            .await
            .unwrap();
        assert!(!result.contains("HAS_ITEMS"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_cond_attr_with_gte_symbol_and_elseif() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("score".to_string(), json!(50));
        let tpl = r##"<if cond="#score# >= 90">GRADE_A<elseif cond="#score# >= 50"/>GRADE_PASS<else/>GRADE_FAIL</if>"##;
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("GRADE_PASS"), "got: {}", result);
        assert!(!result.contains("GRADE_A"), "got: {}", result);
        assert!(!result.contains("GRADE_FAIL"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_unless_cond_attr_with_gt_symbol() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(0));
        let result = engine
            .render(r##"<unless cond="#count# > 0">EMPTY</unless>"##, &ctx)
            .await
            .unwrap();
        assert!(result.contains("EMPTY"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_simplified_if_quoted_operand_with_spaces() {
        // Quoted operands containing spaces must survive wrapping and comparison.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("status".to_string(), json!("up and running"));
        let result = engine
            .render(r#"<if status == "up and running">HEALTHY</if>"#, &ctx)
            .await
            .unwrap();
        assert!(result.contains("HEALTHY"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_simplified_if_quoted_gt_does_not_truncate_tag() {
        // A literal `>` inside a quoted operand must not terminate the tag.
        // (Note: comparison operands are HTML-escaped during resolution, so a
        // value containing `>` never equals its literal — use `!=` to prove the
        // tag boundary without tripping over escaping.)
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("note".to_string(), json!("something else"));
        let result = engine
            .render(r#"<if note != "x > y">DIFF</if>"#, &ctx)
            .await
            .unwrap();
        // Truncation at the quoted `>` would leak `y">` into the body.
        assert_eq!(result.trim(), "DIFF", "got: {}", result);
    }

    #[tokio::test]
    async fn test_iframe_not_mistaken_for_if_tag() {
        // `<iframe` must not match the `<if` scanner: before a real <if> it would
        // swallow content up to the real </if>; inside a body it corrupts depth.
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("flag".to_string(), json!(true));
        let tpl = r#"<iframe src="/embed"></iframe><p>KEEP</p><if flag><iframe src="/inner"></iframe>YES</if>"#;
        let result = engine.render(tpl, &ctx).await.unwrap();
        assert!(result.contains("<iframe src=\"/embed\">"), "got: {}", result);
        assert!(result.contains("KEEP"), "got: {}", result);
        assert!(result.contains("YES"), "got: {}", result);
        assert!(result.contains("<iframe src=\"/inner\">"), "got: {}", result);
    }

    #[tokio::test]
    async fn test_numeric_gt_keyword() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("age".to_string(), json!(25));
        let result = engine
            .render("<if age gt 18>Adult</if>", &ctx)
            .await
            .unwrap();
        assert!(result.contains("Adult"));
    }

    #[tokio::test]
    async fn test_numeric_lte_keyword() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), json!(5));
        let result = engine
            .render("<if count lte 5>Ok</if>", &ctx)
            .await
            .unwrap();
        assert!(result.contains("Ok"));
    }

    #[tokio::test]
    async fn test_numeric_gt_cond_attr() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("age".to_string(), json!(25));
        let result = engine
            .render(r##"<if cond="#age# > 18">Adult</if>"##, &ctx)
            .await
            .unwrap();
        assert!(result.contains("Adult"));
    }

    // =========================================================================
    // Nested Loop Tests
    // =========================================================================

    #[tokio::test]
    async fn test_nested_loop() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert(
            "categories".to_string(),
            json!([
                {"name": "Fruit", "items": [{"label": "Apple"}, {"label": "Banana"}]},
                {"name": "Veggie", "items": [{"label": "Carrot"}]},
            ]),
        );
        let template = r##"<loop data="#categories#" as="cat"><h2>#cat.name#</h2><loop data="#cat.items#" as="item"><li>#item.label#</li></loop></loop>"##;
        let result = engine.render(template, &ctx).await.unwrap();
        assert!(result.contains("Fruit"));
        assert!(result.contains("Apple"));
        assert!(result.contains("Banana"));
        assert!(result.contains("Veggie"));
        assert!(result.contains("Carrot"));
    }

    #[tokio::test]
    async fn test_nested_loop_three_levels() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert(
            "data".to_string(),
            json!([
                {"groups": [{"items": ["a", "b"]}]}
            ]),
        );
        let template = r##"<loop data="#data#" as="d"><loop data="#d.groups#" as="g"><loop data="#g.items#" as="i">[#i#]</loop></loop></loop>"##;
        let result = engine.render(template, &ctx).await.unwrap();
        assert!(
            result.contains("[a]"),
            "Should contain [a], got: {}",
            result
        );
        assert!(
            result.contains("[b]"),
            "Should contain [b], got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_nested_loop_empty_inner() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert(
            "categories".to_string(),
            json!([
                {"name": "Empty", "items": []},
            ]),
        );
        let template = r##"<loop data="#categories#" as="cat"><h2>#cat.name#</h2><loop data="#cat.items#" as="item"><li>#item.label#</li></loop></loop>"##;
        let result = engine.render(template, &ctx).await.unwrap();
        assert!(result.contains("Empty"));
        assert!(!result.contains("<li>"));
    }

    #[tokio::test]
    async fn test_backward_compat_cond() {
        let engine = make_engine();
        let mut ctx = HashMap::new();
        ctx.insert("show".to_string(), json!(true));
        let result = engine
            .render(r##"<if cond="#show#">Visible</if>"##, &ctx)
            .await
            .unwrap();
        assert!(result.contains("Visible"));
    }
}