what-core 1.7.4

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
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
//! HTML parser for custom tags
//!
//! Parses HTML documents and resolves custom tags like <jumbo>, <loop>, etc.
//! Also handles `<what>` page directives for auth, routing, etc.
//! Also handles `.what` config files for directory-level configuration.

use regex::Regex;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::LazyLock;

/// Regex to match #variable# syntax, including arithmetic expressions like #var + 1#
static VAR_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"#([a-zA-Z_][a-zA-Z0-9_. +\-*/]*(?:\|[^#]*)?)#").unwrap());

/// Regex to match tag attributes
static ATTR_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)""#).unwrap());

/// Regex to match boolean attributes (standalone words after key="value" pairs are removed)
static BOOL_ATTR_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"([a-zA-Z_][a-zA-Z0-9_-]*)"#).unwrap());

/// Regex to match <what> directive tags (self-closing or with content)
/// Does NOT match <what-*> component tags (which have hyphen immediately after "what")
static WHAT_DIRECTIVE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    // Match <what with optional whitespace+attrs, then /> or >...</what>
    // The pattern requires either:
    //   - <what/> (immediate self-close)
    //   - <what> (immediate close, may have content)
    //   - <what attrs...> (space before attrs)
    // This naturally excludes <what-nav> because hyphen is not whitespace, /, or >
    Regex::new(r"(?s)<what((?:\s[^>]*)?)(?:/>|>(.*?)</what>)").unwrap()
});

// ============================================================================
// Wired Variable Scoping
// ============================================================================

/// Scope for a wired variable — determines which WebSocket clients receive updates
#[derive(Clone, Debug, Default)]
pub enum WiredScope {
    /// All clients receive (backwards compatible default)
    #[default]
    Public,
    /// Only clients with a matching JWT role
    Roles(Vec<String>),
    /// Only the specific user who triggered the mutation (user_id filled at mutation time)
    User(String),
}

impl std::fmt::Display for WiredScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WiredScope::Public => write!(f, "public"),
            WiredScope::Roles(r) => write!(f, "roles: {}", r.join(", ")),
            WiredScope::User(_) => write!(f, "per-user"),
        }
    }
}

impl WiredScope {
    /// Check if a client with the given roles/user_id is allowed to receive this update
    pub fn allows(&self, client_roles: &[String], client_user_id: Option<&str>) -> bool {
        match self {
            WiredScope::Public => true,
            WiredScope::Roles(required) => client_roles.iter().any(|r| required.contains(r)),
            WiredScope::User(uid) => client_user_id == Some(uid.as_str()),
        }
    }
}

/// A parsed variable declaration with its scope. Used for both `data.wired`
/// (real-time push, scope filters delivery) and `data.application` (shared
/// state, scope gates who may write via `w-set`).
#[derive(Clone, Debug)]
pub struct WiredVarDecl {
    pub name: String,
    pub scope: WiredScope,
}

/// Alias clarifying intent when a scoped decl governs write access rather than
/// WebSocket delivery (e.g. `data.application = ["revenue [admin]"]`).
pub type ScopedVarDecl = WiredVarDecl;

/// Parse a wired variable value that may contain bracket scope syntax.
/// Examples:
///   "counter"           → WiredVarDecl { name: "counter", scope: Public }
///   "revenue [admin]"   → WiredVarDecl { name: "revenue", scope: Roles(["admin"]) }
///   "x [admin, editor]" → WiredVarDecl { name: "x", scope: Roles(["admin", "editor"]) }
///   "notifs [user]"     → WiredVarDecl { name: "notifs", scope: User("") }
fn parse_wired_decl(s: &str) -> WiredVarDecl {
    let s = s.trim();
    if let Some(bracket_start) = s.find('[') {
        if let Some(bracket_end) = s.find(']') {
            let name = s[..bracket_start].trim().to_string();
            let roles_str = &s[bracket_start + 1..bracket_end];
            let roles: Vec<String> = roles_str
                .split(',')
                .map(|r| r.trim().to_string())
                .filter(|r| !r.is_empty())
                .collect();
            // Special case: [user] means per-user scoping
            if roles.len() == 1 && roles[0] == "user" {
                return WiredVarDecl {
                    name,
                    scope: WiredScope::User(String::new()),
                };
            }
            return WiredVarDecl {
                name,
                scope: WiredScope::Roles(roles),
            };
        }
    }
    WiredVarDecl {
        name: s.to_string(),
        scope: WiredScope::Public,
    }
}

// ============================================================================
// .what File Parser
// ============================================================================

/// Configuration from a .what file
///
/// .what files use a simple key-value format:
/// ```text
/// // Comments start with // or #
/// title = "My Application"
/// port = 8080
/// debug = true
/// nav_items = ["Home", "About", "Contact"]
/// auth = "admin"
/// layout = "sections/main.html"
/// ```
#[derive(Debug, Clone, Default)]
pub(crate) struct WhatConfig {
    /// Parsed configuration values
    pub values: HashMap<String, Value>,
    /// Page directives extracted from the config (auth, protected, etc.)
    pub directives: PageDirectives,
    /// Layout template path (stored separately for easy access)
    pub layout: Option<String>,
    /// Application-level data keys to expose (shared across all sessions).
    /// Bracket scope syntax (`"revenue [admin]"`) gates `w-set` writes.
    pub data_application: Vec<ScopedVarDecl>,
    /// Session-level data keys to expose (per-user)
    pub data_session: Vec<String>,
    /// Wired data keys to expose (shared + real-time push via WebSocket, with optional scope)
    pub data_wired: Vec<WiredVarDecl>,
}

#[allow(dead_code)]
impl WhatConfig {
    /// Get a string value
    pub fn get_string(&self, key: &str) -> Option<&str> {
        self.values.get(key).and_then(|v| v.as_str())
    }

    /// Get a number value
    pub fn get_number(&self, key: &str) -> Option<f64> {
        self.values.get(key).and_then(|v| v.as_f64())
    }

    /// Get a boolean value
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        self.values.get(key).and_then(|v| v.as_bool())
    }

    /// Get an array value
    pub fn get_array(&self, key: &str) -> Option<&Vec<Value>> {
        self.values.get(key).and_then(|v| v.as_array())
    }

    /// Merge another config into this one (other takes precedence)
    pub fn merge(&mut self, other: &WhatConfig) {
        for (key, value) in &other.values {
            self.values.insert(key.clone(), value.clone());
        }
        // For directives, other takes precedence if it sets auth
        if other.directives.requires_auth() {
            self.directives.auth = other.directives.auth.clone();
        }
        if other.directives.protected {
            self.directives.protected = true;
        }
        if !other.directives.roles.is_empty() {
            self.directives.roles = other.directives.roles.clone();
        }
        if other.directives.exclude {
            self.directives.exclude = true;
        }
        if other.directives.title.is_some() {
            self.directives.title = other.directives.title.clone();
        }
        if other.directives.redirect.is_some() {
            self.directives.redirect = other.directives.redirect.clone();
        }
        if other.directives.cache_ttl.is_some() {
            self.directives.cache_ttl = other.directives.cache_ttl;
        }
        // Headers: merge (child overrides parent for same header name)
        for (k, v) in &other.directives.headers {
            self.directives.headers.insert(k.clone(), v.clone());
        }
        // Layout: child overrides parent (including "none" to disable)
        if other.layout.is_some() {
            self.layout = other.layout.clone();
        }
        if other.directives.layout.is_some() {
            self.directives.layout = other.directives.layout.clone();
        }
        // Data: child overrides parent (or could extend - using override for now)
        if !other.data_application.is_empty() {
            self.data_application = other.data_application.clone();
        }
        if !other.data_session.is_empty() {
            self.data_session = other.data_session.clone();
        }
        if !other.data_wired.is_empty() {
            self.data_wired = other.data_wired.clone();
        }
    }

    /// Convert to context for template rendering
    pub fn to_context(&self) -> HashMap<String, Value> {
        self.values.clone()
    }
}

/// Parse a .what file content
///
/// Supports:
/// - Strings: `key = "value"` or `key = 'value'`
/// - Numbers: `key = 123` or `key = 45.67`
/// - Booleans: `key = true` or `key = false`
/// - Arrays: `key = ["a", "b", "c"]` or `key = [1, 2, 3]`
/// - Comments: `// comment` or `# comment`
///
/// Special keys are converted to directives:
/// - `auth` → AuthLevel
/// - `protected` → protected directive
/// - `roles` → roles directive
/// - `exclude` → exclude directive
/// - `title` → title directive
/// - `redirect` → redirect directive
/// - `cache` / `cache_ttl` → cache TTL directive
/// - `layout` → layout template path
pub(crate) fn parse_what_file(content: &str) -> WhatConfig {
    let mut config = WhatConfig::default();

    for line in content.lines() {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with("//") || line.starts_with('#') {
            continue;
        }

        // Parse key = value
        if let Some(idx) = line.find('=') {
            let key = line[..idx].trim().to_lowercase();
            let value_str = line[idx + 1..].trim();

            // Parse the value
            let value = parse_what_value(value_str);

            // Check if this is a directive key that shouldn't be exposed as a template variable
            let is_security_directive = matches!(
                key.as_str(),
                "auth"
                    | "protected"
                    | "roles"
                    | "exclude"
                    | "redirect"
                    | "cache"
                    | "cache_ttl"
                    | "layout"
                    | "data.application"
                    | "data.session"
            );

            // Handle special directive keys
            match key.as_str() {
                "auth" => {
                    if let Some(s) = value.as_str() {
                        config.directives.auth = parse_auth_level(s);
                    }
                }
                "protected" => {
                    if let Some(b) = value.as_bool() {
                        config.directives.protected = b;
                    } else if let Some(s) = value.as_str() {
                        config.directives.protected = s != "false";
                    }
                }
                "roles" => {
                    if let Some(arr) = value.as_array() {
                        config.directives.roles = arr
                            .iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect();
                        if !config.directives.roles.is_empty() {
                            config.directives.protected = true;
                        }
                    } else if let Some(s) = value.as_str() {
                        config.directives.roles = s
                            .split(',')
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect();
                        if !config.directives.roles.is_empty() {
                            config.directives.protected = true;
                        }
                    }
                }
                "exclude" => {
                    if let Some(b) = value.as_bool() {
                        config.directives.exclude = b;
                    }
                }
                "title" => {
                    if let Some(s) = value.as_str() {
                        config.directives.title = Some(s.to_string());
                    }
                }
                "redirect" => {
                    if let Some(s) = value.as_str() {
                        config.directives.redirect = Some(s.to_string());
                    }
                }
                "layout" => {
                    if let Some(s) = value.as_str() {
                        config.layout = Some(s.to_string());
                        config.directives.layout = Some(s.to_string());
                    }
                }
                "cache" | "cache_ttl" => {
                    if let Some(n) = value.as_u64() {
                        config.directives.cache_ttl = Some(n);
                    }
                }
                "data.application" => {
                    config.data_application = parse_wired_array(&value);
                }
                "data.session" => {
                    config.data_session = parse_string_array(&value);
                }
                "data.wired" => {
                    config.data_wired = parse_wired_array(&value);
                }
                _ => {
                    // Handle header.* keys: header.X-Custom = "value"
                    if let Some(header_name) = key.strip_prefix("header.") {
                        if let Some(s) = value.as_str() {
                            config
                                .directives
                                .headers
                                .insert(header_name.to_string(), s.to_string());
                        }
                    }
                }
            }

            // Store non-security values for template access
            let is_header = key.starts_with("header.");
            if !is_security_directive && !is_header {
                // Parity with <what> blocks: recommend quoting string values
                // (data.* keys carry config syntax, not template strings)
                if !key.starts_with("data.")
                    && value.is_string()
                    && !value_str.starts_with('"')
                    && !value_str.starts_with('\'')
                    && is_unquoted_string(value_str)
                {
                    tracing::warn!(
                        "Unquoted string in .what file: {} should be quoted, e.g. {} = \"{}\"",
                        key,
                        key,
                        value_str
                    );
                }
                config.values.insert(key, value);
            }
        }
    }

    config
}

/// Parse a Value into a Vec<String>
fn parse_string_array(value: &Value) -> Vec<String> {
    if let Some(arr) = value.as_array() {
        arr.iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect()
    } else if let Some(s) = value.as_str() {
        // Single string becomes a one-element array
        vec![s.to_string()]
    } else {
        Vec::new()
    }
}

/// Parse a Value into a Vec<WiredVarDecl> with optional bracket scope syntax
fn parse_wired_array(value: &Value) -> Vec<WiredVarDecl> {
    if let Some(arr) = value.as_array() {
        arr.iter()
            .filter_map(|v| v.as_str().map(parse_wired_decl))
            .collect()
    } else if let Some(s) = value.as_str() {
        vec![parse_wired_decl(s)]
    } else {
        Vec::new()
    }
}

/// Split a string on commas that are not inside quotes or nested brackets.
/// Used for `.what` array literals so a scoped element like
/// `"revenue [admin, editor]"` is not split at the inner comma.
fn split_top_level_commas(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut depth = 0i32;
    let mut quote: Option<char> = None;
    for c in s.chars() {
        match quote {
            Some(q) => {
                if c == q {
                    quote = None;
                }
                current.push(c);
            }
            None => match c {
                '"' | '\'' => {
                    quote = Some(c);
                    current.push(c);
                }
                '[' | '{' => {
                    depth += 1;
                    current.push(c);
                }
                ']' | '}' => {
                    depth -= 1;
                    current.push(c);
                }
                ',' if depth == 0 => {
                    parts.push(current.trim().to_string());
                    current.clear();
                }
                _ => current.push(c),
            },
        }
    }
    if !current.trim().is_empty() {
        parts.push(current.trim().to_string());
    }
    parts
}

/// Parse a value from .what file format
fn parse_what_value(s: &str) -> Value {
    let s = s.trim();

    // Boolean
    if s == "true" {
        return json!(true);
    }
    if s == "false" {
        return json!(false);
    }

    // String (double or single quotes)
    if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
        return json!(s[1..s.len() - 1].to_string());
    }

    // Array
    if s.starts_with('[') && s.ends_with(']') {
        let inner = s[1..s.len() - 1].trim();
        if inner.is_empty() {
            return json!([]);
        }

        // Split on top-level commas only — commas inside quotes or nested
        // brackets (e.g. a scope like "revenue [admin, editor]") stay together.
        let items: Vec<Value> = split_top_level_commas(inner)
            .into_iter()
            .map(|item| parse_what_value(item.trim()))
            .collect();
        return json!(items);
    }

    // Number (integer or float)
    if let Ok(n) = s.parse::<i64>() {
        return json!(n);
    }
    if let Ok(n) = s.parse::<f64>() {
        return json!(n);
    }

    // Default to string without quotes
    json!(s.to_string())
}

/// Parse attributes from a tag string
pub(crate) fn parse_attributes(attr_str: &str) -> HashMap<String, String> {
    let mut attrs = HashMap::new();
    for cap in ATTR_REGEX.captures_iter(attr_str) {
        let key = cap[1].to_string();
        let value = cap[2].to_string();
        attrs.insert(key, value);
    }
    attrs
}

// ============================================================================
// Filter System
// ============================================================================

/// A parsed filter with name and arguments
#[derive(Debug, Clone, PartialEq)]
struct Filter {
    name: String,
    args: Vec<String>,
}

/// Result of applying filters — tracks whether output is html_safe
struct FilterResult {
    value: String,
    html_safe: bool,
}

/// Parse the filter chain from a variable expression.
/// Input: "var.path|filter1:arg|filter2:arg1,arg2"
/// Returns: (var_path, Vec<Filter>)
fn parse_filter_chain(expr: &str) -> (&str, Vec<Filter>) {
    let Some(first_pipe) = expr.find('|') else {
        return (expr, Vec::new());
    };

    let var_path = &expr[..first_pipe];
    let filter_str = &expr[first_pipe + 1..];
    let mut filters = Vec::new();

    // Split by | to get individual filters, but respect quoted strings
    for segment in split_filters(filter_str) {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }

        if let Some(colon_pos) = segment.find(':') {
            let name = segment[..colon_pos].trim().to_string();
            let args_str = &segment[colon_pos + 1..];
            let args = parse_filter_args(args_str);
            filters.push(Filter { name, args });
        } else {
            filters.push(Filter {
                name: segment.to_string(),
                args: Vec::new(),
            });
        }
    }

    (var_path, filters)
}

/// Split filter chain by `|`, respecting quoted strings
fn split_filters(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quote = false;
    let mut quote_char = '"';

    for (i, c) in s.char_indices() {
        match c {
            '"' | '\'' if !in_quote => {
                in_quote = true;
                quote_char = c;
            }
            c if c == quote_char && in_quote => {
                in_quote = false;
            }
            '|' if !in_quote => {
                parts.push(&s[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(&s[start..]);
    parts
}

/// Parse filter arguments from a string like `"value"` or `50` or `"old","new"`
fn parse_filter_args(s: &str) -> Vec<String> {
    let mut args = Vec::new();
    let mut current = String::new();
    let mut in_quote = false;
    let mut quote_char = '"';

    for c in s.chars() {
        match c {
            '"' | '\'' if !in_quote => {
                in_quote = true;
                quote_char = c;
                // Don't include the quote in the arg value
            }
            c if c == quote_char && in_quote => {
                in_quote = false;
                // Don't include the closing quote
            }
            ',' if !in_quote => {
                args.push(current.trim().to_string());
                current = String::new();
            }
            _ => {
                current.push(c);
            }
        }
    }
    let trimmed = current.trim().to_string();
    if !trimmed.is_empty() {
        args.push(trimmed);
    }
    args
}

/// Apply a single filter to a value. Returns the filtered value and whether it's html_safe.
fn apply_filter(value: &str, filter: &Filter) -> FilterResult {
    match filter.name.as_str() {
        "raw" => FilterResult {
            value: value.to_string(),
            html_safe: true,
        },
        "uppercase" => FilterResult {
            value: value.to_uppercase(),
            html_safe: false,
        },
        "lowercase" => FilterResult {
            value: value.to_lowercase(),
            html_safe: false,
        },
        "capitalize" => FilterResult {
            value: capitalize_first(value),
            html_safe: false,
        },
        "title" => FilterResult {
            value: title_case(value),
            html_safe: false,
        },
        "truncate" => {
            let max_len: usize = filter
                .args
                .first()
                .and_then(|a| a.parse().ok())
                .unwrap_or(50);
            let suffix = filter.args.get(1).map(|s| s.as_str()).unwrap_or("...");
            FilterResult {
                value: truncate_str(value, max_len, suffix),
                html_safe: false,
            }
        }
        "count" => {
            // Arrays/objects reach filters as their serialized JSON — count
            // items, not bytes of the serialization. Plain strings count
            // characters (not bytes), so "José" is 4, not 5.
            let n = match serde_json::from_str::<Value>(value) {
                Ok(Value::Array(items)) => items.len(),
                Ok(Value::Object(map)) => map.len(),
                Ok(Value::String(s)) => s.chars().count(),
                _ => value.chars().count(),
            };
            FilterResult {
                value: n.to_string(),
                html_safe: false,
            }
        }
        "number" => {
            // Format number with thousands separator
            FilterResult {
                value: format_number(value),
                html_safe: false,
            }
        }
        "currency" => {
            let code = filter.args.first().map(|s| s.as_str()).unwrap_or("USD");
            FilterResult {
                value: format_currency(value, code),
                html_safe: false,
            }
        }
        "date" => {
            let fmt = filter.args.first().map(|s| s.as_str()).unwrap_or("medium");
            FilterResult {
                value: format_date(value, fmt),
                html_safe: false,
            }
        }
        "json" => FilterResult {
            value: serde_json::to_string(&serde_json::Value::String(value.to_string()))
                .unwrap_or_else(|_| format!("\"{}\"", value)),
            html_safe: false,
        },
        "markdown" => FilterResult {
            value: simple_markdown(value),
            html_safe: true,
        },
        "pluralize" => {
            let singular = filter.args.first().map(|s| s.as_str()).unwrap_or("s");
            let plural = filter.args.get(1).map(|s| s.as_str()).unwrap_or(singular);
            // If value is a number, use it to determine singular/plural
            let n: f64 = value.parse().unwrap_or(0.0);
            FilterResult {
                value: if n == 1.0 {
                    // With 2 args: first is singular suffix, second is plural suffix
                    // With 1 arg: it's the plural suffix, singular is empty
                    if filter.args.len() >= 2 {
                        singular.to_string()
                    } else {
                        String::new()
                    }
                } else {
                    plural.to_string()
                },
                html_safe: false,
            }
        }
        "default" => {
            let default_val = filter.args.first().map(|s| s.as_str()).unwrap_or("");
            FilterResult {
                value: if value.is_empty() {
                    default_val.to_string()
                } else {
                    value.to_string()
                },
                html_safe: false,
            }
        }
        "replace" => {
            let old = filter.args.first().map(|s| s.as_str()).unwrap_or("");
            let new = filter.args.get(1).map(|s| s.as_str()).unwrap_or("");
            FilterResult {
                value: value.replace(old, new),
                html_safe: false,
            }
        }
        "slice" => {
            let start: usize = filter
                .args
                .first()
                .and_then(|a| a.parse().ok())
                .unwrap_or(0);
            let end: usize = filter
                .args
                .get(1)
                .and_then(|a| a.parse().ok())
                .unwrap_or(value.len());
            let chars: Vec<char> = value.chars().collect();
            let start = start.min(chars.len());
            let end = end.min(chars.len());
            FilterResult {
                value: chars[start..end].iter().collect(),
                html_safe: false,
            }
        }
        "round" => {
            let decimals: u32 = filter
                .args
                .first()
                .and_then(|a| a.parse().ok())
                .unwrap_or(0);
            let n: f64 = value.parse().unwrap_or(0.0);
            let factor = 10f64.powi(decimals as i32);
            let rounded = (n * factor).round() / factor;
            FilterResult {
                value: if decimals == 0 {
                    format!("{}", rounded as i64)
                } else {
                    format!("{:.prec$}", rounded, prec = decimals as usize)
                },
                html_safe: false,
            }
        }
        "ceil" => {
            let n: f64 = value.parse().unwrap_or(0.0);
            let ceiled = n.ceil();
            FilterResult {
                value: if ceiled.abs() < i64::MAX as f64 {
                    format!("{}", ceiled as i64)
                } else {
                    format!("{}", ceiled)
                },
                html_safe: false,
            }
        }
        "floor" => {
            let n: f64 = value.parse().unwrap_or(0.0);
            let floored = n.floor();
            FilterResult {
                value: if floored.abs() < i64::MAX as f64 {
                    format!("{}", floored as i64)
                } else {
                    format!("{}", floored)
                },
                html_safe: false,
            }
        }
        // Unknown filter — pass through unchanged, but say so: a typo'd
        // filter (#price|currancy#) otherwise fails with no symptom at all
        unknown => {
            warn_unknown_filter_once(unknown);
            FilterResult {
                value: value.to_string(),
                html_safe: false,
            }
        }
    }
}

/// Filter names already reported as unknown (warn once per name per process).
static WARNED_UNKNOWN_FILTERS: LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
    LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));

fn warn_unknown_filter_once(name: &str) {
    let mut warned = WARNED_UNKNOWN_FILTERS
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    if warned.insert(name.to_string()) {
        tracing::warn!(
            "Unknown filter '|{}' — the value passes through unchanged. Check the spelling against the filter reference.",
            name
        );
    }
}

/// Apply a chain of filters, returning final value and html_safe flag
fn apply_filters(value: &str, filters: &[Filter]) -> FilterResult {
    let mut current = FilterResult {
        value: value.to_string(),
        html_safe: false,
    };
    for filter in filters {
        current = apply_filter(&current.value, filter);
    }
    current
}

// -- Arithmetic evaluation --

/// Check if a string contains arithmetic operators (space-separated)
fn contains_arithmetic(s: &str) -> bool {
    s.contains(" + ") || s.contains(" - ") || s.contains(" * ") || s.contains(" / ")
}

/// Resolve variable-like tokens in an arithmetic expression, then evaluate.
/// E.g. "session.age + 1" with context where session.age=25 → "25 + 1" → Some(26.0)
fn resolve_and_evaluate_arithmetic(expr: &str, context: &HashMap<String, Value>) -> Option<String> {
    static INLINE_VAR: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"[a-zA-Z_][a-zA-Z0-9_.]*").unwrap());
    // Resolve all variable-like tokens
    let resolved = INLINE_VAR
        .replace_all(expr, |caps: &regex::Captures| {
            let token = &caps[0];
            let val = resolve_variable(token, context);
            // If unresolved (still #token#), return the token as-is (will fail arithmetic)
            if val.starts_with('#') && val.ends_with('#') {
                token.to_string()
            } else {
                val
            }
        })
        .to_string();
    evaluate_arithmetic(&resolved).map(format_f64_clean)
}

/// Evaluate a simple arithmetic expression: "10 + 1", "25.5 * 0.21", etc.
/// Supports +, -, *, / with standard precedence (* / before + -).
/// Returns None if the expression is not valid arithmetic or contains division by zero.
pub(crate) fn evaluate_arithmetic(expr: &str) -> Option<f64> {
    let expr = expr.trim();
    if expr.is_empty() {
        return None;
    }

    let tokens = tokenize_arithmetic(expr)?;
    if tokens.len() < 3 {
        return None; // Need at least: number op number
    }

    evaluate_with_precedence(&tokens)
}

/// Format f64 cleanly — no trailing .0 for whole numbers
pub(crate) fn format_f64_clean(n: f64) -> String {
    if n == n.trunc() && n.abs() < i64::MAX as f64 {
        format!("{}", n as i64)
    } else {
        format!("{}", n)
    }
}

#[derive(Debug, Clone)]
enum ArithToken {
    Num(f64),
    Op(char), // +, -, *, /
}

/// Tokenize an arithmetic expression into numbers and operators.
/// Handles negative numbers (leading - or - after operator).
fn tokenize_arithmetic(expr: &str) -> Option<Vec<ArithToken>> {
    let mut tokens = Vec::new();
    let mut chars = expr.chars().peekable();

    while let Some(&c) = chars.peek() {
        if c.is_whitespace() {
            chars.next();
            continue;
        }

        // Number (possibly negative at start or after operator)
        if c.is_ascii_digit()
            || c == '.'
            || (c == '-' && (tokens.is_empty() || matches!(tokens.last(), Some(ArithToken::Op(_)))))
        {
            let mut num_str = String::new();
            if c == '-' {
                num_str.push('-');
                chars.next();
            }
            while let Some(&nc) = chars.peek() {
                if nc.is_ascii_digit() || nc == '.' {
                    num_str.push(nc);
                    chars.next();
                } else {
                    break;
                }
            }
            let n: f64 = num_str.parse().ok()?;
            tokens.push(ArithToken::Num(n));
        } else if "+-*/".contains(c) {
            tokens.push(ArithToken::Op(c));
            chars.next();
        } else {
            // Non-arithmetic character — not a valid expression
            return None;
        }
    }

    // Validate: must alternate Num Op Num Op Num ...
    for (i, token) in tokens.iter().enumerate() {
        match (i % 2, token) {
            (0, ArithToken::Num(_)) => {}
            (1, ArithToken::Op(_)) => {}
            _ => return None,
        }
    }
    // Must end with a number
    if tokens.len() % 2 == 0 {
        return None;
    }

    Some(tokens)
}

/// Evaluate tokens with standard precedence: * / first, then + -
fn evaluate_with_precedence(tokens: &[ArithToken]) -> Option<f64> {
    // Extract numbers and operators into separate vecs
    let mut nums: Vec<f64> = Vec::new();
    let mut ops: Vec<char> = Vec::new();
    for token in tokens {
        match token {
            ArithToken::Num(n) => nums.push(*n),
            ArithToken::Op(op) => ops.push(*op),
        }
    }

    // First pass: evaluate * and /
    let mut i = 0;
    while i < ops.len() {
        if ops[i] == '*' || ops[i] == '/' {
            let result = if ops[i] == '*' {
                nums[i] * nums[i + 1]
            } else {
                if nums[i + 1] == 0.0 {
                    return None; // Division by zero
                }
                nums[i] / nums[i + 1]
            };
            nums[i] = result;
            nums.remove(i + 1);
            ops.remove(i);
        } else {
            i += 1;
        }
    }

    // Second pass: evaluate + and -
    let mut result = nums[0];
    for (i, op) in ops.iter().enumerate() {
        match op {
            '+' => result += nums[i + 1],
            '-' => result -= nums[i + 1],
            _ => return None,
        }
    }

    Some(result)
}

// -- Filter helper functions --

fn capitalize_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
    }
}

fn title_case(s: &str) -> String {
    s.split_whitespace()
        .map(|word| capitalize_first(word))
        .collect::<Vec<_>>()
        .join(" ")
}

fn truncate_str(s: &str, max_len: usize, suffix: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max_len {
        return s.to_string();
    }
    let truncated: String = chars[..max_len].iter().collect();
    format!("{}{}", truncated, suffix)
}

fn format_number(s: &str) -> String {
    // Parse as f64, format with thousands separator
    if let Ok(n) = s.parse::<f64>() {
        if n == n.floor() && n.abs() < i64::MAX as f64 {
            // Integer formatting with commas
            let n = n as i64;
            let is_negative = n < 0;
            let s = n.unsigned_abs().to_string();
            let chars: Vec<char> = s.chars().collect();
            let mut result = String::new();
            for (i, c) in chars.iter().enumerate() {
                if i > 0 && (chars.len() - i) % 3 == 0 {
                    result.push(',');
                }
                result.push(*c);
            }
            if is_negative {
                format!("-{}", result)
            } else {
                result
            }
        } else {
            // Float — keep as-is but with commas in integer part
            format!("{}", n)
        }
    } else {
        s.to_string()
    }
}

fn format_currency(s: &str, code: &str) -> String {
    let n: f64 = s.parse().unwrap_or(0.0);
    let symbol = match code.to_uppercase().as_str() {
        "USD" => "$",
        "EUR" => "\u{20ac}",
        "GBP" => "\u{00a3}",
        "JPY" => "\u{00a5}",
        "CAD" => "CA$",
        "AUD" => "A$",
        _ => "$",
    };
    // Format with 2 decimal places and thousands separator
    let abs_n = n.abs();
    let integer_part = abs_n.floor() as i64;
    let decimal_part = ((abs_n - abs_n.floor()) * 100.0).round() as i64;

    let int_str = format_number(&integer_part.to_string());
    let sign = if n < 0.0 { "-" } else { "" };
    format!("{}{}{}.{:02}", sign, symbol, int_str, decimal_part)
}

fn format_date(s: &str, mask: &str) -> String {
    use chrono::{NaiveDate, NaiveDateTime};

    // Parse input into NaiveDateTime
    let dt = if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        date.and_hms_opt(0, 0, 0).unwrap()
    } else if let Ok(dt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
        dt
    } else if let Ok(dt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
        dt
    } else if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
        dt.naive_local()
    } else {
        return s.to_string();
    };

    apply_date_mask(&dt, mask)
}

fn apply_date_mask(dt: &chrono::NaiveDateTime, mask: &str) -> String {
    use chrono::{Datelike, Timelike};

    // Resolve presets
    let mask = match mask {
        "short" => "m/d/yy",
        "medium" => "mmm d, yyyy",
        "long" => "mmmm d, yyyy",
        "full" => "dddd, mmmm d, yyyy",
        "time" => "h:nn tt",
        "iso" => "yyyy-mm-dd",
        other => other,
    };

    static MONTHS: &[&str] = &[
        "",
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];
    static MONTHS_SHORT: &[&str] = &[
        "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    static DAYS: &[&str] = &[
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
        "Sunday",
    ];
    static DAYS_SHORT: &[&str] = &["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

    let day = dt.day();
    let month = dt.month() as usize;
    let year = dt.year();
    let hour24 = dt.hour();
    let hour12 = if hour24 == 0 {
        12
    } else if hour24 > 12 {
        hour24 - 12
    } else {
        hour24
    };
    let minute = dt.minute();
    let second = dt.second();
    let weekday_idx = dt.weekday().num_days_from_monday() as usize;
    let ampm = if hour24 < 12 { "AM" } else { "PM" };

    let mut result = String::new();
    let chars: Vec<char> = mask.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        // Try longest tokens first
        let remaining = &mask[i..];

        if remaining.starts_with("dddd") {
            result.push_str(DAYS[weekday_idx]);
            i += 4;
        } else if remaining.starts_with("ddd") {
            result.push_str(DAYS_SHORT[weekday_idx]);
            i += 3;
        } else if remaining.starts_with("dd") {
            result.push_str(&format!("{:02}", day));
            i += 2;
        } else if remaining.starts_with('d') && !remaining.starts_with("dd") {
            result.push_str(&day.to_string());
            i += 1;
        } else if remaining.starts_with("mmmm") {
            result.push_str(MONTHS[month]);
            i += 4;
        } else if remaining.starts_with("mmm") {
            result.push_str(MONTHS_SHORT[month]);
            i += 3;
        } else if remaining.starts_with("mm") {
            result.push_str(&format!("{:02}", month));
            i += 2;
        } else if remaining.starts_with('m') && !remaining.starts_with("mm") {
            result.push_str(&month.to_string());
            i += 1;
        } else if remaining.starts_with("yyyy") {
            result.push_str(&format!("{:04}", year));
            i += 4;
        } else if remaining.starts_with("yy") {
            result.push_str(&format!("{:02}", year % 100));
            i += 2;
        } else if remaining.starts_with("HH") {
            result.push_str(&format!("{:02}", hour24));
            i += 2;
        } else if remaining.starts_with('H') && !remaining.starts_with("HH") {
            result.push_str(&hour24.to_string());
            i += 1;
        } else if remaining.starts_with("hh") {
            result.push_str(&format!("{:02}", hour12));
            i += 2;
        } else if remaining.starts_with('h') && !remaining.starts_with("hh") {
            result.push_str(&hour12.to_string());
            i += 1;
        } else if remaining.starts_with("nn") {
            result.push_str(&format!("{:02}", minute));
            i += 2;
        } else if remaining.starts_with('n') && !remaining.starts_with("nn") {
            result.push_str(&minute.to_string());
            i += 1;
        } else if remaining.starts_with("ss") {
            result.push_str(&format!("{:02}", second));
            i += 2;
        } else if remaining.starts_with('s') && !remaining.starts_with("ss") {
            result.push_str(&second.to_string());
            i += 1;
        } else if remaining.starts_with("tt") {
            result.push_str(ampm);
            i += 2;
        } else if remaining.starts_with('t') && !remaining.starts_with("tt") {
            result.push(ampm.chars().next().unwrap());
            i += 1;
        } else {
            // Literal character
            result.push(chars[i]);
            i += 1;
        }
    }

    result
}

fn simple_markdown(s: &str) -> String {
    // Escape HTML entities BEFORE markdown processing to prevent XSS.
    // Markdown output (tags like <strong>, <em>, <a>) is added after escaping.
    let escaped = html_escape(s);

    let mut result = String::new();
    let mut in_paragraph = false;

    for line in escaped.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            if in_paragraph {
                result.push_str("</p>");
                in_paragraph = false;
            }
            continue;
        }

        // Process inline formatting
        let processed = process_markdown_inline(trimmed);

        if !in_paragraph {
            result.push_str("<p>");
            in_paragraph = true;
        } else {
            result.push(' ');
        }
        result.push_str(&processed);
    }

    if in_paragraph {
        result.push_str("</p>");
    }

    result
}

// Hoisted: process_markdown_inline runs once per non-blank line of a
// |markdown block — compiling these per call multiplied per render.
static MD_BOLD_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*(.+?)\*\*").unwrap());
static MD_ITALIC_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*(.+?)\*").unwrap());
static MD_LINK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());

fn process_markdown_inline(s: &str) -> String {
    let mut result = s.to_string();

    // Bold: **text** → <strong>text</strong>
    result = MD_BOLD_RE
        .replace_all(&result, "<strong>$1</strong>")
        .to_string();

    // Italic: *text* → <em>text</em>
    result = MD_ITALIC_RE.replace_all(&result, "<em>$1</em>").to_string();

    // Links: [text](url) → <a href="url">text</a>
    // Only emit an href for a safe URL scheme; otherwise render the text alone.
    result = MD_LINK_RE
        .replace_all(&result, |caps: &regex::Captures| {
            let text = &caps[1];
            let url = caps[2].trim();
            if markdown_url_is_safe(url) {
                format!(r#"<a href="{}">{}</a>"#, url, text)
            } else {
                text.to_string()
            }
        })
        .to_string();

    result
}

/// Whether a markdown link URL is safe to emit as an `href`. Uses a scheme
/// allowlist (http/https/mailto/tel + relative), and first strips characters
/// browsers ignore when evaluating a scheme — so `java\tscript:` / `java\nscript:`
/// cannot smuggle a `javascript:` URL past a naive `starts_with` check.
fn markdown_url_is_safe(url: &str) -> bool {
    let stripped: String = url
        .chars()
        .filter(|c| !c.is_control() && !c.is_whitespace())
        .collect();
    let lower = stripped.to_lowercase();
    match lower.find(':') {
        None => true, // no scheme — relative URL / fragment / query
        Some(colon) => {
            let before = &lower[..colon];
            // A '/', '#' or '?' before the colon means it's a path, not a scheme
            // (e.g. "/a:b" or "foo?x=1:2").
            if before.contains('/') || before.contains('#') || before.contains('?') {
                return true;
            }
            let is_scheme = !before.is_empty()
                && before.chars().next().unwrap().is_ascii_alphabetic()
                && before
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.');
            if is_scheme {
                matches!(before, "http" | "https" | "mailto" | "tel")
            } else {
                true
            }
        }
    }
}

/// Replace #variable# syntax with values from context.
/// All output is HTML-escaped by default. Use `|raw` filter to bypass escaping.
/// Supports filter chaining: `#var|filter1:arg|filter2#`
pub(crate) fn replace_variables(
    template: &str,
    context: &HashMap<String, serde_json::Value>,
) -> String {
    VAR_REGEX
        .replace_all(template, |caps: &regex::Captures| {
            let expr = &caps[1];
            let (var_path, filters) = parse_filter_chain(expr);

            // Check if var_path contains arithmetic operators
            let raw_value = if contains_arithmetic(var_path) {
                resolve_and_evaluate_arithmetic(var_path, context)
                    .unwrap_or_else(|| resolve_variable(var_path, context))
            } else {
                resolve_variable(var_path, context)
            };

            // If variable was unresolved and there's no default filter, keep as #var#
            let is_unresolved = raw_value.starts_with('#') && raw_value.ends_with('#');

            // A strict not-found passthrough returns exactly `#<var_path>#` — the
            // author's own token, which must be preserved verbatim. A resolved
            // value that merely *looks* like a token (e.g. a DB field equal to
            // "#env.SECRET#") does NOT match this, so it is treated as data and
            // gets its `#` neutralized below.
            let is_preserved_token = raw_value == format!("#{var_path}#");

            // Apply filters
            let filtered = if filters.is_empty() {
                FilterResult {
                    value: raw_value,
                    html_safe: false,
                }
            } else {
                // If unresolved and first filter is "default", use empty string to trigger default
                let input = if is_unresolved && filters.iter().any(|f| f.name == "default") {
                    String::new()
                } else {
                    raw_value
                };
                apply_filters(&input, &filters)
            };

            // Auto-escape unless html_safe. Resolved (data) values additionally
            // have their `#` neutralized so they cannot be re-resolved on a later
            // render pass; the preserved `#unknown#` token is emitted as-is.
            if filtered.html_safe {
                filtered.value
            } else if is_preserved_token {
                html_escape(&filtered.value)
            } else {
                escape_and_neutralize_hashes(&filtered.value)
            }
        })
        .to_string()
}

/// Result of reactive variable replacement
#[derive(Debug, Clone, Default)]
pub struct ReactiveReplaceResult {
    /// The rendered HTML content
    pub html: String,
    /// Session keys that were used (for OOB updates)
    pub session_keys: std::collections::HashSet<String>,
}

/// Replace #variable# syntax with values from context, wrapping session variables
/// with reactive `<span w-bind>` elements when they appear in text content.
/// Variables inside attributes are replaced without wrapping.
/// All output is HTML-escaped by default. Supports filter chaining: `#var|filter1:arg|filter2#`
pub(crate) fn replace_variables_reactive(
    template: &str,
    context: &HashMap<String, serde_json::Value>,
) -> ReactiveReplaceResult {
    let mut session_keys = std::collections::HashSet::new();

    // We need to track position to determine if we're in an attribute context
    let mut result = String::with_capacity(template.len());
    let mut last_end = 0;

    for caps in VAR_REGEX.captures_iter(template) {
        let m = caps.get(0).unwrap();
        let expr = &caps[1];
        let start = m.start();

        // Add the text before this match
        result.push_str(&template[last_end..start]);

        // Parse filter chain
        let (var_path, filters) = parse_filter_chain(expr);

        // Check if this is a session or wired variable
        let is_session_var = var_path.starts_with("session.");
        let is_wired_var = var_path.starts_with("wired.");

        // Resolve the variable value (with arithmetic support)
        let raw_value = if contains_arithmetic(var_path) {
            resolve_and_evaluate_arithmetic(var_path, context)
                .unwrap_or_else(|| resolve_variable(var_path, context))
        } else {
            resolve_variable(var_path, context)
        };
        let is_unresolved = raw_value.starts_with('#') && raw_value.ends_with('#');
        // Exact strict not-found passthrough (`#<var_path>#`) — preserve verbatim;
        // a resolved value that merely looks like a token is data and gets its
        // `#` neutralized on the escaped emit paths below (second-order injection).
        let is_preserved_token = raw_value == format!("#{var_path}#");

        // Apply filters
        let filtered = if filters.is_empty() {
            FilterResult {
                value: raw_value,
                html_safe: false,
            }
        } else {
            let input = if is_unresolved && filters.iter().any(|f| f.name == "default") {
                String::new()
            } else {
                raw_value
            };
            apply_filters(&input, &filters)
        };

        if is_session_var || is_wired_var {
            let (bind_prefix, bind_key) = if is_session_var {
                let key = &var_path[8..]; // Skip "session."
                session_keys.insert(key.to_string());
                ("session", key)
            } else {
                let key = &var_path[6..]; // Skip "wired."
                ("wired", key)
            };

            // If the value is unresolved (still looks like #var#), use empty string
            // to prevent double-wrapping when layouts re-process the output
            let display_value = if filtered.value.starts_with('#') && filtered.value.ends_with('#')
            {
                String::new()
            } else {
                filtered.value
            };

            // Check if we're inside an attribute by looking at the text before this match
            let text_before = &template[..start];
            let in_attribute = is_in_attribute_context(text_before);

            if in_attribute {
                // Inside attribute - replace with escaped value (no wrapping)
                if filtered.html_safe {
                    result.push_str(&display_value);
                } else {
                    result.push_str(&escape_and_neutralize_hashes(&display_value));
                }
            } else {
                // In text content - wrap with reactive span
                // The span content is always escaped (XSS protection in reactive updates)
                result.push_str(&format!(
                    r#"<span w-bind="{}.{}">{}</span>"#,
                    bind_prefix,
                    bind_key,
                    escape_and_neutralize_hashes(&display_value)
                ));
            }
        } else {
            // Non-reactive variable
            if filtered.html_safe {
                result.push_str(&filtered.value);
            } else if is_preserved_token {
                result.push_str(&html_escape(&filtered.value));
            } else {
                result.push_str(&escape_and_neutralize_hashes(&filtered.value));
            }
        }

        last_end = m.end();
    }

    // Add any remaining text after the last match
    result.push_str(&template[last_end..]);

    ReactiveReplaceResult {
        html: result,
        session_keys,
    }
}

/// Check if a position in the template is inside an HTML attribute
/// by analyzing the text before that position
fn is_in_attribute_context(text_before: &str) -> bool {
    // Look for the last opening tag or attribute quote
    // We're in an attribute if we find an unclosed attribute pattern
    let mut in_attr_value = false;
    let mut quote_char: Option<char> = None;

    for c in text_before.chars().rev() {
        match c {
            '"' | '\'' if quote_char == Some(c) => {
                // End of attribute value (going backwards, this is actually the start)
                quote_char = None;
                in_attr_value = false;
            }
            '"' | '\'' if quote_char.is_none() => {
                // Start of attribute value (going backwards, this is actually the end)
                quote_char = Some(c);
                in_attr_value = true;
            }
            '>' if quote_char.is_none() => {
                // We hit a '>' before finding an unclosed attribute, so we're in text content
                return false;
            }
            '<' if quote_char.is_none() => {
                // We hit a '<' - we were inside a tag
                // If we have an unclosed quote, we're in an attribute
                return in_attr_value;
            }
            _ => {}
        }
    }

    // If we reach here with an open quote, we're in an attribute
    in_attr_value
}

/// Escape HTML special characters
fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

/// HTML-escape a resolved variable value AND neutralize any `#` it contains so a
/// data-provided value shaped like a template token (e.g. `#env.SECRET#`) cannot
/// be re-interpreted on a later render pass. The engine renders in multiple
/// passes (loops/components/includes resolve their bodies, then a final pass
/// re-scans the whole page); without this, an attacker-controlled field rendered
/// inside a loop could smuggle a live `#env.*#` / `#x|raw#` token into the final
/// pass — leaking secrets or bypassing escaping (second-order template injection).
///
/// `#` is neutralized to the `&num;` HTML entity (renders identically as `#`).
/// A private-use sentinel protects data `#` from html_escape's own `&#39;` output,
/// which itself contains a `#` we must not touch.
fn escape_and_neutralize_hashes(s: &str) -> String {
    const SENTINEL: &str = "\u{E000}"; // Unicode private use — never appears in real content
    let protected = s.replace('#', SENTINEL);
    html_escape(&protected).replace(SENTINEL, "&num;")
}

/// Reverse of html_escape, for comparison operands: values resolve through
/// replace_variables (which escapes for output), so comparing them against
/// an author-written literal like `"Ben & Jerry"` must undo the escaping.
/// `&amp;` is unescaped LAST — the mirror of html_escape escaping `&` first —
/// so `&amp;lt;` round-trips to `&lt;` and never collapses to `<`.
pub(crate) fn html_unescape(s: &str) -> String {
    if !s.contains('&') {
        return s.to_string();
    }
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&amp;", "&")
}

/// Resolve computed variables from page directives and inject them into the context.
/// Computed variables use string interpolation: `compute.name = "Hello #user.name#!"`
/// They become available as `#name#` (without the `compute.` prefix) in templates.
/// Resolved in order, so later computed vars can reference earlier ones.
pub(crate) fn resolve_computed_variables(
    computed: &[(String, String)],
    context: &mut HashMap<String, serde_json::Value>,
) {
    for (name, template) in computed {
        // Interpolate #var# references in the template using current context
        let resolved = VAR_REGEX
            .replace_all(template, |caps: &regex::Captures| {
                let var_path = &caps[1];
                resolve_variable(var_path, context)
            })
            .to_string();

        // Insert as a string value (without the compute. prefix)
        context.insert(name.clone(), serde_json::Value::String(resolved));
    }
}

/// Resolve a variable path like "user.email" from context.
/// Also supports "env.VAR_NAME" to read environment variables.
/// Returns the resolved string value, or "#var_path#" if not found.
fn resolve_variable(path: &str, context: &HashMap<String, serde_json::Value>) -> String {
    let parts: Vec<&str> = path.split('.').collect();

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

    // Check for environment variable: #env.VAR_NAME#
    if parts[0] == "env" && parts.len() >= 2 {
        let env_var_name = parts[1..].join("_"); // env.DATABASE_URL -> DATABASE_URL
        return std::env::var(&env_var_name).unwrap_or_default();
    }

    let root = context.get(parts[0]);
    let mut current: Option<&serde_json::Value> = root;

    for part in parts.iter().skip(1) {
        current = current.and_then(|v| {
            if let serde_json::Value::Object(obj) = v {
                obj.get(*part)
            } else {
                None
            }
        });
    }

    match current {
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(serde_json::Value::Number(n)) => n.to_string(),
        Some(serde_json::Value::Bool(b)) => b.to_string(),
        Some(serde_json::Value::Null) => String::new(),
        Some(v) => v.to_string(),
        None if root.is_some() && parts.len() > 1 => String::new(), // Parent exists, child missing → empty
        None => format!("#{}#", path), // Root not in context → keep literal for strict mode
    }
}

/// Check if a tag name is a standard HTML tag
#[allow(dead_code)]
pub(crate) fn is_standard_html_tag(name: &str) -> bool {
    matches!(
        name,
        "html"
            | "head"
            | "body"
            | "title"
            | "meta"
            | "link"
            | "script"
            | "style"
            | "div"
            | "span"
            | "p"
            | "a"
            | "img"
            | "br"
            | "hr"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
            | "ul"
            | "ol"
            | "li"
            | "dl"
            | "dt"
            | "dd"
            | "table"
            | "thead"
            | "tbody"
            | "tfoot"
            | "tr"
            | "th"
            | "td"
            | "form"
            | "input"
            | "textarea"
            | "select"
            | "option"
            | "button"
            | "label"
            | "header"
            | "footer"
            | "main"
            | "nav"
            | "section"
            | "article"
            | "aside"
            | "figure"
            | "figcaption"
            | "video"
            | "audio"
            | "source"
            | "canvas"
            | "iframe"
            | "embed"
            | "object"
            | "param"
            | "strong"
            | "em"
            | "b"
            | "i"
            | "u"
            | "s"
            | "mark"
            | "small"
            | "sub"
            | "sup"
            | "blockquote"
            | "pre"
            | "code"
            | "kbd"
            | "samp"
            | "var"
            | "time"
            | "address"
            | "abbr"
            | "cite"
            | "q"
            | "ins"
            | "del"
            | "dfn"
            | "ruby"
            | "rt"
            | "rp"
            | "bdi"
            | "bdo"
            | "wbr"
            | "details"
            | "summary"
            | "dialog"
            | "slot"
            | "template"
            | "noscript"
    )
}

/// Authentication level for a page
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum AuthLevel {
    /// Public page - no authentication required (auth: all)
    All,
    /// Any authenticated user (auth: user)
    User,
    /// Specific roles required (auth: admin, editor)
    Roles(Vec<String>),
}

impl std::fmt::Display for AuthLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthLevel::All => write!(f, "all"),
            AuthLevel::User => write!(f, "user"),
            AuthLevel::Roles(v) => write!(f, "roles: {}", v.join(", ")),
        }
    }
}

impl Default for AuthLevel {
    fn default() -> Self {
        AuthLevel::All
    }
}

/// Page directives extracted from <what> tags
///
/// Example usage in HTML:
/// ```html
/// <what auth="all" />              <!-- Public page -->
/// <what auth="user" />             <!-- Any authenticated user -->
/// <what auth="admin, editor" />    <!-- Specific roles -->
/// <what layout="sections/main.html" /> <!-- Use a layout -->
/// ```
///
/// Or with content:
/// ```html
/// <what>
///   auth: all           # Public page (no auth)
///   auth: user          # Any authenticated user
///   auth: admin, editor # Specific roles
///   layout: sections/main.html
///   title: Dashboard
/// </what>
/// ```
///
/// Legacy syntax still supported:
/// ```html
/// <what protected roles="admin,editor" />
/// ```
/// Session mutation operation
#[derive(Debug, Clone)]
pub(crate) enum SessionMutation {
    /// Increment a session variable by a value: session.counter += 1
    Increment { key: String, value: i64 },
    /// Set a session variable: session.name = "value"
    Set { key: String, value: Value },
    /// Push a value to the end of an array: session.list.push(value)
    Push { key: String, value: Value },
    /// Push a value to the end of an array with a max size, dropping oldest: session.list.pushmax(10, value)
    PushMax {
        key: String,
        max: usize,
        value: Value,
    },
    /// Push a value to the beginning of an array: session.list.unshift(value)
    Unshift { key: String, value: Value },
    /// Clear an array: session.list.clear()
    Clear { key: String },
}

#[derive(Debug, Clone, Default)]
pub(crate) struct PageDirectives {
    /// Authentication level for this page
    pub auth: AuthLevel,
    /// Page is protected (requires authentication) - LEGACY, use `auth` instead
    pub protected: bool,
    /// Required roles (any of these roles grants access) - LEGACY, use `auth` instead
    pub roles: Vec<String>,
    /// Page should be excluded from routing
    pub exclude: bool,
    /// Custom page title
    pub title: Option<String>,
    /// Redirect to another page
    pub redirect: Option<String>,
    /// Cache TTL in seconds (overrides global)
    pub cache_ttl: Option<u64>,
    /// Layout template path (e.g., "sections/layout.html")
    /// Use "none" to explicitly disable layout inheritance
    pub layout: Option<String>,
    /// Session mutations to apply before rendering
    pub session_mutations: Vec<SessionMutation>,
    /// Computed variables: compute.name = "interpolated #var# string"
    pub computed: Vec<(String, String)>,
    /// Custom response headers (from `header.Name = "value"` in application.what)
    pub headers: HashMap<String, String>,
    /// Any additional custom directives
    pub custom: HashMap<String, String>,
    /// Inline variables from `<what>` blocks (typed: strings, numbers, arrays, objects)
    pub vars: HashMap<String, Value>,
}

impl PageDirectives {
    /// Check if page requires authentication
    /// Returns true if auth level is User or Roles, or if legacy `protected` is set
    pub fn requires_auth(&self) -> bool {
        match &self.auth {
            AuthLevel::All => self.protected, // Fall back to legacy
            AuthLevel::User => true,
            AuthLevel::Roles(_) => true,
        }
    }

    /// Check if user has access based on auth level
    /// - All: always returns true
    /// - User: returns true if authenticated
    /// - Roles: returns true if user has any required role
    pub fn check_access(&self, authenticated: bool, user_roles: &[String]) -> bool {
        match &self.auth {
            AuthLevel::All => {
                // Legacy fallback
                if self.protected {
                    if !authenticated {
                        return false;
                    }
                    self.has_role(user_roles)
                } else {
                    true
                }
            }
            AuthLevel::User => authenticated,
            AuthLevel::Roles(required) => {
                authenticated && required.iter().any(|r| user_roles.contains(r))
            }
        }
    }

    /// Check if user has any of the required roles (legacy method)
    pub fn has_role(&self, user_roles: &[String]) -> bool {
        if self.roles.is_empty() {
            return true; // No role requirement
        }
        self.roles.iter().any(|r| user_roles.contains(r))
    }
}

/// Parse <what> directives from page content
/// Returns the directives and the content with <what> tags removed
pub(crate) fn parse_page_directives(content: &str) -> (PageDirectives, String) {
    let mut directives = PageDirectives::default();

    let cleaned = WHAT_DIRECTIVE_REGEX
        .replace_all(content, |caps: &regex::Captures| {
            let attrs_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let inner_content = caps.get(2).map(|m| m.as_str());

            // Parse attributes from the tag
            parse_directive_attributes(attrs_str, &mut directives);

            // Parse inner content if present (YAML-like syntax)
            if let Some(inner) = inner_content {
                parse_directive_content(inner, &mut directives);
            }

            "" // Remove the <what> tag from output
        })
        .to_string();

    (directives, cleaned)
}

/// Parse auth value into AuthLevel
pub(crate) fn parse_auth_level(value: &str) -> AuthLevel {
    let value = value.trim().to_lowercase();
    match value.as_str() {
        "all" | "public" | "none" => AuthLevel::All,
        "user" | "authenticated" => AuthLevel::User,
        _ => {
            // Parse as comma-separated roles
            let roles: Vec<String> = value
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if roles.is_empty() {
                AuthLevel::All
            } else {
                AuthLevel::Roles(roles)
            }
        }
    }
}

/// Parse attributes from <what> tag
fn parse_directive_attributes(attrs_str: &str, directives: &mut PageDirectives) {
    // Parse key="value" attributes
    let attrs = parse_attributes(attrs_str);

    for (key, value) in &attrs {
        match key.as_str() {
            "auth" => {
                directives.auth = parse_auth_level(value);
            }
            // Legacy support
            "protected" => directives.protected = value != "false",
            "roles" => {
                directives.roles = value
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                // If roles are specified, page is implicitly protected
                if !directives.roles.is_empty() {
                    directives.protected = true;
                }
            }
            "exclude" => directives.exclude = value != "false",
            "title" => directives.title = Some(value.clone()),
            "redirect" => directives.redirect = Some(value.clone()),
            "layout" => directives.layout = Some(value.clone()),
            "cache" | "cache-ttl" => {
                directives.cache_ttl = value.parse().ok();
            }
            _ => {
                // Handle header.* keys
                if let Some(header_name) = key.strip_prefix("header.") {
                    directives
                        .headers
                        .insert(header_name.to_string(), value.clone());
                } else {
                    warn_access_directive_near_miss(key);
                    directives.custom.insert(key.clone(), value.clone());
                }
            }
        }
    }

    // Parse boolean attributes (no value)
    // Find words that aren't part of key="value" pairs
    let without_attrs = ATTR_REGEX.replace_all(attrs_str, "");
    for cap in BOOL_ATTR_REGEX.captures_iter(&without_attrs) {
        let key = &cap[1];
        match key {
            "protected" => directives.protected = true,
            "exclude" => directives.exclude = true,
            _ => {}
        }
    }
}

/// Reserved directive keys — these are NOT inline variables
fn is_reserved_directive(key: &str) -> bool {
    matches!(
        key,
        "auth"
            | "protected"
            | "roles"
            | "exclude"
            | "title"
            | "redirect"
            | "layout"
            | "cache"
            | "cache-ttl"
            | "method"
            | "paginate"
    ) || key.starts_with("fetch.")
        || key.starts_with("session.")
        || key.starts_with("compute.")
        || key.starts_with("set.")
        || key.starts_with("data.")
        || key.starts_with("header.")
        || key.starts_with("mutation.")
}

/// True when `a` and `b` are within one edit of each other: a single
/// substitution, insertion, deletion, or adjacent transposition.
fn within_one_edit(a: &str, b: &str) -> bool {
    if a == b {
        return true;
    }
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    if a.len().abs_diff(b.len()) > 1 {
        return false;
    }
    if a.len() == b.len() {
        let diffs: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect();
        match diffs.len() {
            1 => true,
            2 => {
                diffs[1] == diffs[0] + 1
                    && a[diffs[0]] == b[diffs[1]]
                    && a[diffs[1]] == b[diffs[0]]
            }
            _ => false,
        }
    } else {
        let (short, long) = if a.len() < b.len() { (&a, &b) } else { (&b, &a) };
        let mut i = 0;
        let mut j = 0;
        let mut skipped = false;
        while i < short.len() && j < long.len() {
            if short[i] == long[j] {
                i += 1;
                j += 1;
            } else if skipped {
                return false;
            } else {
                skipped = true;
                j += 1;
            }
        }
        true
    }
}

/// Detect a likely misspelling of an access-control directive key.
///
/// An unknown `<what>` key falls through to "inline variable", and
/// `AuthLevel` defaults to `All` — so `auht: user` would silently leave the
/// page PUBLIC. Only the access-control keys get fuzzy matching: a typo'd
/// `title` or `layout` breaks visibly, but a typo'd `auth` fails open with
/// no symptom. Requires a matching first letter so common real variable
/// names near these words (e.g. `oauth`) don't trip it.
fn access_directive_near_miss(key: &str) -> Option<&'static str> {
    const ACCESS_KEYS: [&str; 3] = ["auth", "protected", "roles"];
    let lower = key.to_lowercase();
    // Compare the ORIGINAL key for the exact-match exclusion: `Auth` is a
    // case typo worth flagging, only a byte-exact `auth` parses as the
    // real directive.
    ACCESS_KEYS.into_iter().find(|reserved| {
        key != *reserved
            && lower.chars().next() == reserved.chars().next()
            && within_one_edit(&lower, reserved)
    })
}

/// Keys already reported as access-directive near-misses (warn once per key
/// per process — directives re-parse on every request).
static WARNED_NEAR_MISSES: LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
    LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));

/// Warn loudly (all modes, not just dev) when a `<what>` key looks like a
/// misspelled access-control directive. The page renders unchanged — this
/// must never fail closed on a false positive — but silence here means a
/// world-readable page the author believes is protected.
fn warn_access_directive_near_miss(key: &str) {
    if let Some(reserved) = access_directive_near_miss(key) {
        let mut warned = WARNED_NEAR_MISSES.lock().unwrap();
        if warned.insert(key.to_string()) {
            tracing::error!(
                "<what> key '{}' looks like a misspelling of the '{}' access-control directive. \
                 It was treated as an inline variable, so NO access restriction was applied to this page. \
                 If you meant '{}', fix the spelling; if it is a real variable, rename it.",
                key,
                reserved,
                reserved
            );
        }
    }
}

/// Parse inner content of <what> tag (YAML-like syntax)
fn parse_directive_content(content: &str, directives: &mut PageDirectives) {
    let mut current_section: Option<String> = None;

    // Multi-line JSON accumulation state
    let mut json_key: Option<String> = None;
    let mut json_buf = String::new();
    let mut json_depth: usize = 0;
    let mut json_bracket: char = ' '; // '[' or '{'

    let lines: Vec<&str> = content.lines().collect();
    let mut i = 0;

    while i < lines.len() {
        let raw_line = lines[i];
        let trimmed = raw_line.trim();
        i += 1;

        // If we're accumulating a multi-line JSON value, keep appending
        if json_key.is_some() {
            json_buf.push('\n');
            json_buf.push_str(trimmed);
            let close_char = if json_bracket == '[' { ']' } else { '}' };
            json_depth += trimmed.matches(json_bracket).count();
            json_depth -= trimmed.matches(close_char).count();
            if json_depth == 0 {
                // Done accumulating — parse the JSON
                let key = json_key.take().unwrap();
                let relaxed = relax_json(&json_buf);
                match serde_json::from_str::<Value>(&relaxed) {
                    Ok(val) => {
                        directives.vars.insert(key, val);
                    }
                    Err(e) => {
                        tracing::warn!("Invalid JSON for inline var: {}", e);
                    }
                }
                json_buf.clear();
            }
            continue;
        }

        if trimmed.is_empty() {
            continue;
        }

        // Section header: [name] sets prefix, [] resets to root
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            let inner = trimmed[1..trimmed.len() - 1].trim();
            if inner.is_empty() {
                current_section = None;
            } else {
                current_section = Some(inner.to_lowercase().to_string());
            }
            continue;
        }

        // Apply section prefix to raw line (syntactic sugar for flat dotted keys)
        let line_owned;
        let line: &str = if let Some(ref section) = current_section {
            line_owned = format!("{}.{}", section, trimmed);
            line_owned.trim()
        } else {
            trimmed
        };

        // Check for session mutation: session.key += value or session.key = value
        if line.starts_with("session.") {
            if let Some(mutation) = parse_session_mutation(line) {
                directives.session_mutations.push(mutation);
            }
            continue;
        }

        // Check for computed variable: compute.name = "interpolated #var# string"
        if line.starts_with("compute.") {
            if let Some(eq_pos) = line.find('=') {
                let name = line[8..eq_pos].trim().to_string(); // Skip "compute."
                let value = line[eq_pos + 1..].trim();
                // Remove surrounding quotes if present (one symmetric pair only)
                let value = strip_symmetric_quotes(value).0.to_string();
                directives.computed.push((name, value));
            }
            continue;
        }

        // Check for boolean directive (just a word)
        if !line.contains(':') && !line.contains('=') {
            match line.to_lowercase().as_str() {
                "protected" => directives.protected = true,
                "exclude" => directives.exclude = true,
                _ => {}
            }
            continue;
        }

        // Parse key: value or key = value
        // Prefer '=' when it appears before ':' (handles URLs like https://...)
        let colon_idx = line.find(':');
        let equals_idx = line.find('=');
        let (key, value) = match (colon_idx, equals_idx) {
            (Some(c), Some(e)) => {
                if e < c {
                    (&line[..e], line[e + 1..].trim())
                } else {
                    (&line[..c], line[c + 1..].trim())
                }
            }
            (Some(c), None) => (&line[..c], line[c + 1..].trim()),
            (None, Some(e)) => (&line[..e], line[e + 1..].trim()),
            _ => continue,
        };

        let key = key.trim().to_lowercase();
        let (value, value_was_quoted) = strip_symmetric_quotes(value);
        if !value_was_quoted
            && value.len() >= 2
            && (value.starts_with('"')
                || value.starts_with('\'')
                || value.ends_with('"')
                || value.ends_with('\''))
        {
            tracing::warn!(
                "Mismatched quotes in <what> block value for '{}': {} — use one matching pair, e.g. \"value\"",
                key,
                value
            );
        }

        match key.as_str() {
            "auth" => {
                directives.auth = parse_auth_level(value);
            }
            // Legacy support
            "protected" => directives.protected = value != "false",
            "roles" => {
                directives.roles = value
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                if !directives.roles.is_empty() {
                    directives.protected = true;
                }
            }
            "exclude" => directives.exclude = value != "false",
            "title" => {
                if !value_was_quoted && is_unquoted_string(value) {
                    tracing::warn!(
                        "Unquoted string in <what> block: title should be quoted, e.g. title: \"{}\"",
                        value
                    );
                }
                directives.title = Some(value.to_string());
            }
            "redirect" => {
                if !value_was_quoted && is_unquoted_string(value) {
                    tracing::warn!(
                        "Unquoted string in <what> block: redirect should be quoted, e.g. redirect: \"{}\"",
                        value
                    );
                }
                directives.redirect = Some(value.to_string());
            }
            "layout" => {
                if !value_was_quoted && is_unquoted_string(value) {
                    tracing::warn!(
                        "Unquoted string in <what> block: layout should be quoted, e.g. layout: \"{}\"",
                        value
                    );
                }
                directives.layout = Some(value.to_string());
            }
            "cache" | "cache-ttl" => {
                directives.cache_ttl = value.parse().ok();
            }
            _ => {
                // Handle header.* keys
                if let Some(header_name) = key.strip_prefix("header.") {
                    directives
                        .headers
                        .insert(header_name.to_string(), value.to_string());
                } else if is_reserved_directive(&key) {
                    // Reserved prefixed directives (fetch.*, set.*, data.*, etc.)
                    if !value_was_quoted && !value.is_empty() && is_unquoted_string(value) {
                        tracing::warn!(
                            "Unquoted string in <what> block: {} should be quoted, e.g. {} = \"{}\"",
                            key,
                            key,
                            value
                        );
                    }
                    directives.custom.insert(key, value.to_string());
                } else {
                    // Non-reserved key — treat as inline variable
                    warn_access_directive_near_miss(&key);
                    // Check if value starts a multi-line JSON block
                    let value_untrimmed = {
                        let eq_pos = line.find('=').or_else(|| line.find(':')).unwrap();
                        line[eq_pos + 1..].trim()
                    };
                    if (value_untrimmed.starts_with('[') || value_untrimmed.starts_with('{'))
                        && !value_untrimmed.ends_with(']')
                        && !value_untrimmed.ends_with('}')
                    {
                        // Start multi-line JSON accumulation
                        json_bracket = value_untrimmed.chars().next().unwrap();
                        json_buf = value_untrimmed.to_string();
                        json_depth = value_untrimmed.matches(json_bracket).count();
                        let close_char = if json_bracket == '[' { ']' } else { '}' };
                        json_depth -= value_untrimmed.matches(close_char).count();
                        if json_depth == 0 {
                            // Single-line JSON that's complete
                            let relaxed = relax_json(value_untrimmed);
                            match serde_json::from_str::<Value>(&relaxed) {
                                Ok(val) => {
                                    directives.vars.insert(key, val);
                                }
                                Err(e) => {
                                    tracing::warn!("Invalid JSON for inline var '{}': {}", key, e);
                                }
                            }
                            json_buf.clear();
                        } else {
                            json_key = Some(key);
                        }
                    } else if value_untrimmed.starts_with('[') || value_untrimmed.starts_with('{') {
                        // Single-line JSON (complete on one line)
                        let relaxed = relax_json(value_untrimmed);
                        match serde_json::from_str::<Value>(&relaxed) {
                            Ok(val) => {
                                directives.vars.insert(key, val);
                            }
                            Err(e) => {
                                tracing::warn!("Invalid JSON for inline var '{}': {}", key, e);
                            }
                        }
                    } else {
                        // Scalar inline variable — quoting forces string type
                        // (`zip = "01234"` stays "01234"; unquoted values are
                        // type-inferred as before).
                        let parsed = if value_was_quoted {
                            Value::String(value.to_string())
                        } else {
                            parse_inline_value(value)
                        };
                        // Warn if string value is unquoted (numbers/bools are fine)
                        if !value_was_quoted && is_unquoted_string(value) {
                            tracing::warn!(
                                "Unquoted string in <what> block: {} should be quoted, e.g. {} = \"{}\"",
                                key,
                                key,
                                value
                            );
                        }
                        directives.vars.insert(key, parsed);
                    }
                }
            }
        }
    }
}

/// Strip exactly one symmetric pair of matching quotes.
/// Returns (stripped_value, was_quoted). Mismatched, unterminated, or nested
/// quotes are left intact so author mistakes stay visible instead of being
/// silently swallowed (the old `trim_matches` stripped repeated AND mismatched
/// quote characters).
pub(crate) fn strip_symmetric_quotes(s: &str) -> (&str, bool) {
    let bytes = s.as_bytes();
    if bytes.len() >= 2 {
        let first = bytes[0];
        if (first == b'"' || first == b'\'') && bytes[bytes.len() - 1] == first {
            return (&s[1..s.len() - 1], true);
        }
    }
    (s, false)
}

/// Check if a value is a string that should have been quoted.
/// Returns false for numbers, booleans, and known keywords.
fn is_unquoted_string(value: &str) -> bool {
    if value.is_empty() {
        return false;
    }
    if value.parse::<f64>().is_ok() {
        return false;
    }
    match value.to_lowercase().as_str() {
        "true" | "false" | "none" | "all" | "user" => false,
        _ => true,
    }
}

/// Relax JSON: quote unquoted object keys so serde_json can parse it.
/// Turns `{ name: "Widget" }` into `{ "name": "Widget" }`.
fn relax_json(s: &str) -> String {
    static UNQUOTED_KEY: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r#"(?m)([{\[,])\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:"#).unwrap());
    UNQUOTED_KEY.replace_all(s, r#"$1 "$2":"#).into_owned()
}

/// Parse a scalar inline value to a typed JSON Value
fn parse_inline_value(s: &str) -> Value {
    // Try integer
    if let Ok(n) = s.parse::<i64>() {
        return json!(n);
    }
    // Try float
    if let Ok(n) = s.parse::<f64>() {
        return json!(n);
    }
    // Booleans
    if s == "true" {
        return json!(true);
    }
    if s == "false" {
        return json!(false);
    }
    // String (already had quotes stripped)
    json!(s)
}

/// Parse session mutation from line like "session.counter += 1" or "session.name = value"
fn parse_session_mutation(line: &str) -> Option<SessionMutation> {
    // Remove "session." prefix
    let rest = line.strip_prefix("session.")?;

    // Check for array operations: key.pushmax(N, value), key.push(value), key.unshift(value), key.clear()
    // pushmax must be checked before push since ".push(" is a prefix of ".pushmax("
    if let Some(idx) = rest.find(".pushmax(") {
        let key = rest[..idx].trim().to_string();
        let value_start = idx + 9; // len of ".pushmax("
        let value_end = rest.rfind(')')?;
        let inner = rest[value_start..value_end].trim();
        // Parse "N, value" — first arg is max size, second is the value
        if let Some(comma) = inner.find(',') {
            let max_str = inner[..comma].trim();
            let (value_str, was_quoted) = strip_symmetric_quotes(inner[comma + 1..].trim());
            if let Ok(max) = max_str.parse::<usize>() {
                let value = parse_mutation_value(value_str, was_quoted);
                return Some(SessionMutation::PushMax { key, max, value });
            }
        }
    }

    if let Some(idx) = rest.find(".push(") {
        let key = rest[..idx].trim().to_string();
        let value_start = idx + 6; // len of ".push("
        let value_end = rest.rfind(')')?;
        let (value_str, was_quoted) = strip_symmetric_quotes(rest[value_start..value_end].trim());
        let value = parse_mutation_value(value_str, was_quoted);
        return Some(SessionMutation::Push { key, value });
    }

    if let Some(idx) = rest.find(".unshift(") {
        let key = rest[..idx].trim().to_string();
        let value_start = idx + 9; // len of ".unshift("
        let value_end = rest.rfind(')')?;
        let (value_str, was_quoted) = strip_symmetric_quotes(rest[value_start..value_end].trim());
        let value = parse_mutation_value(value_str, was_quoted);
        return Some(SessionMutation::Unshift { key, value });
    }

    if let Some(idx) = rest.find(".clear()") {
        let key = rest[..idx].trim().to_string();
        return Some(SessionMutation::Clear { key });
    }

    // Check for increment: key += value
    if let Some(idx) = rest.find("+=") {
        let key = rest[..idx].trim().to_string();
        let value_str = rest[idx + 2..].trim();
        let value: i64 = value_str.parse().ok()?;
        return Some(SessionMutation::Increment { key, value });
    }

    // Check for decrement: key -= value (convert to negative increment)
    if let Some(idx) = rest.find("-=") {
        let key = rest[..idx].trim().to_string();
        let value_str = rest[idx + 2..].trim();
        let value: i64 = value_str.parse().ok()?;
        return Some(SessionMutation::Increment { key, value: -value });
    }

    // Check for assignment: key = value
    if let Some(idx) = rest.find('=') {
        let key = rest[..idx].trim().to_string();
        let (value_str, was_quoted) = strip_symmetric_quotes(rest[idx + 1..].trim());
        let value = parse_mutation_value(value_str, was_quoted);
        return Some(SessionMutation::Set { key, value });
    }

    None
}

/// Parse a mutation value — quoting forces string type, unquoted values are
/// type-inferred (`session.zip = "01234"` stays "01234"; `session.count = 42`
/// is a number).
fn parse_mutation_value(value_str: &str, was_quoted: bool) -> Value {
    if was_quoted {
        json!(value_str)
    } else {
        parse_value_str(value_str)
    }
}

/// Parse a value string into a JSON Value
fn parse_value_str(value_str: &str) -> Value {
    // Check for empty array
    if value_str == "[]" {
        return json!([]);
    }
    // Try to parse as number first, then boolean, then string
    if let Ok(n) = value_str.parse::<i64>() {
        json!(n)
    } else if let Ok(f) = value_str.parse::<f64>() {
        json!(f)
    } else if value_str == "true" {
        json!(true)
    } else if value_str == "false" {
        json!(false)
    } else {
        json!(value_str)
    }
}

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

    #[test]
    fn test_parse_attributes() {
        let attrs = parse_attributes(r#"title="Hello" size="large""#);
        assert_eq!(attrs.get("title"), Some(&"Hello".to_string()));
        assert_eq!(attrs.get("size"), Some(&"large".to_string()));
    }

    #[test]
    fn test_replace_variables() {
        let mut context = HashMap::new();
        context.insert("name".to_string(), serde_json::json!("World"));

        let result = replace_variables("Hello #name#!", &context);
        assert_eq!(result, "Hello World!");
    }

    #[test]
    fn test_nested_variables() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            serde_json::json!({
                "name": "Alice",
                "email": "alice@example.com"
            }),
        );

        let result = replace_variables("#user.name# (#user.email#)", &context);
        assert_eq!(result, "Alice (alice@example.com)");
    }

    #[test]
    fn test_resolved_value_hashes_are_neutralized() {
        // A data value that looks like a template token must NOT survive as a
        // live token — otherwise a later render pass re-resolves it (second-order
        // template injection). See escape_and_neutralize_hashes.
        let mut context = HashMap::new();
        context.insert(
            "bio".to_string(),
            serde_json::json!("#env.SECRET# and #other|raw#"),
        );
        let result = replace_variables("<p>#bio#</p>", &context);
        // The '#' characters are emitted as &num; entities (render as '#' in the
        // browser) so VAR_REGEX cannot match them on a subsequent pass.
        assert_eq!(result, "<p>&num;env.SECRET&num; and &num;other|raw&num;</p>");
        assert!(!result.contains("#env.SECRET#"));
    }

    #[test]
    fn test_unresolved_token_preserved_verbatim() {
        // Strict not-found passthrough keeps the author's literal #unknown# token.
        let context = HashMap::new();
        let result = replace_variables("<p>#unknown_var#</p>", &context);
        assert_eq!(result, "<p>#unknown_var#</p>");
    }

    #[test]
    fn test_reactive_resolved_value_hashes_neutralized() {
        // The reactive render path (used for live pages) must also neutralize '#'
        // in resolved data so a session/data value like "#env.SECRET#" cannot be
        // re-resolved on a later pass. Covers the non-reactive var branch...
        let mut context = HashMap::new();
        context.insert("bio".to_string(), serde_json::json!("#env.SECRET#"));
        let out = replace_variables_reactive("<p>#bio#</p>", &context).html;
        assert!(!out.contains("#env.SECRET#"), "reactive path leaked a live token: {out}");
        assert!(out.contains("&num;env.SECRET&num;"));

        // ...and the reactive <span w-bind> text branch for a session value.
        let mut ctx2 = HashMap::new();
        ctx2.insert(
            "session".to_string(),
            serde_json::json!({ "note": "x #env.SECRET# y" }),
        );
        let out2 = replace_variables_reactive("<p>#session.note#</p>", &ctx2).html;
        assert!(!out2.contains("#env.SECRET#"), "reactive span leaked a live token: {out2}");

        // Strict not-found token still preserved verbatim on the reactive path.
        let empty = HashMap::new();
        let out3 = replace_variables_reactive("<p>#nope#</p>", &empty).html;
        assert_eq!(out3, "<p>#nope#</p>");
    }

    #[test]
    fn test_env_variables() {
        // Set a test environment variable
        unsafe {
            std::env::set_var("WHAT_TEST_VAR", "test_value");
        }

        let context = HashMap::new();
        let result = replace_variables("Value: #env.WHAT_TEST_VAR#", &context);
        assert_eq!(result, "Value: test_value");

        // Clean up
        unsafe {
            std::env::remove_var("WHAT_TEST_VAR");
        }
    }

    #[test]
    fn test_env_variable_not_found() {
        let context = HashMap::new();
        let result = replace_variables("#env.NONEXISTENT_VAR_12345#", &context);
        assert_eq!(result, ""); // Returns empty string for missing env vars
    }

    #[test]
    fn test_page_directives_self_closing() {
        let content = r#"<what protected roles="admin,editor" />
<!DOCTYPE html>
<html>
<body>Hello</body>
</html>"#;

        let (directives, cleaned) = parse_page_directives(content);

        assert!(directives.protected);
        assert_eq!(directives.roles, vec!["admin", "editor"]);
        assert!(cleaned.contains("<!DOCTYPE html>"));
        assert!(!cleaned.contains("<what"));
    }

    #[test]
    fn test_page_directives_boolean() {
        let content = r#"<what protected exclude />
<html></html>"#;

        let (directives, cleaned) = parse_page_directives(content);

        assert!(directives.protected);
        assert!(directives.exclude);
        assert!(!cleaned.contains("<what"));
    }

    #[test]
    fn test_page_directives_content_syntax() {
        let content = r#"<what>
protected
roles: admin, manager
title: Admin Dashboard
</what>
<!DOCTYPE html>
<html></html>"#;

        let (directives, cleaned) = parse_page_directives(content);

        assert!(directives.protected);
        assert_eq!(directives.roles, vec!["admin", "manager"]);
        assert_eq!(directives.title, Some("Admin Dashboard".to_string()));
        assert!(cleaned.contains("<!DOCTYPE html>"));
    }

    #[test]
    fn test_page_directives_roles_imply_protected() {
        let content = r#"<what roles="admin" />
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert!(directives.protected); // Implied by roles
        assert_eq!(directives.roles, vec!["admin"]);
    }

    #[test]
    fn test_no_directives() {
        let content = r#"<!DOCTYPE html>
<html><body>Hello</body></html>"#;

        let (directives, cleaned) = parse_page_directives(content);

        assert!(!directives.protected);
        assert!(directives.roles.is_empty());
        assert_eq!(content, cleaned);
    }

    #[test]
    fn test_page_tag_preserved() {
        // Ensure parse_page_directives doesn't touch <page> tags
        let content = r#"<page title="Test">
  <what-nav active="home"/>
  <main>Content</main>
</page>"#;

        let (_, cleaned) = parse_page_directives(content);
        println!("Cleaned content: '{}'", cleaned);

        assert!(cleaned.contains("<page"), "Should preserve <page> tag");
        assert!(cleaned.contains("</page>"), "Should preserve </page> tag");
        assert!(
            cleaned.contains("<what-nav"),
            "Should preserve <what-nav> tag"
        );
        assert_eq!(content, cleaned, "Content should be unchanged");
    }

    #[test]
    fn test_auth_all() {
        let content = r#"<what auth="all" />
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(directives.auth, AuthLevel::All);
        assert!(!directives.requires_auth());
    }

    #[test]
    fn test_auth_user() {
        let content = r#"<what auth="user" />
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(directives.auth, AuthLevel::User);
        assert!(directives.requires_auth());
        assert!(directives.check_access(true, &[]));
        assert!(!directives.check_access(false, &[]));
    }

    #[test]
    fn test_auth_roles() {
        let content = r#"<what auth="admin, editor" />
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(
            directives.auth,
            AuthLevel::Roles(vec!["admin".to_string(), "editor".to_string()])
        );
        assert!(directives.requires_auth());

        // Has admin role
        assert!(directives.check_access(true, &["admin".to_string()]));
        // Has editor role
        assert!(directives.check_access(true, &["editor".to_string()]));
        // Has neither role
        assert!(!directives.check_access(true, &["viewer".to_string()]));
        // Not authenticated
        assert!(!directives.check_access(false, &["admin".to_string()]));
    }

    #[test]
    fn test_auth_content_syntax() {
        let content = r#"<what>
auth: admin, manager
title: Dashboard
</what>
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(
            directives.auth,
            AuthLevel::Roles(vec!["admin".to_string(), "manager".to_string()])
        );
        assert_eq!(directives.title, Some("Dashboard".to_string()));
    }

    #[test]
    fn test_auth_public_aliases() {
        // Test "public" alias
        let (d1, _) = parse_page_directives(r#"<what auth="public" /><html></html>"#);
        assert_eq!(d1.auth, AuthLevel::All);

        // Test "none" alias
        let (d2, _) = parse_page_directives(r#"<what auth="none" /><html></html>"#);
        assert_eq!(d2.auth, AuthLevel::All);

        // Test "authenticated" alias
        let (d3, _) = parse_page_directives(r#"<what auth="authenticated" /><html></html>"#);
        assert_eq!(d3.auth, AuthLevel::User);
    }

    // =========================================================================
    // Fetch Directive Parsing Tests
    // =========================================================================

    #[test]
    fn test_fetch_directive_url_with_equals() {
        let content = r#"<what>
title: Remote Data
fetch.dog_facts = "https://dogapi.dog/api/v2/facts?limit=3"
</what>
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(directives.title, Some("Remote Data".to_string()));
        assert_eq!(
            directives.custom.get("fetch.dog_facts"),
            Some(&"https://dogapi.dog/api/v2/facts?limit=3".to_string()),
            "fetch URL should be parsed correctly with = delimiter"
        );
    }

    #[test]
    fn test_fetch_directive_url_with_multiple_equals() {
        // URLs with query params containing = signs
        let content = r#"<what>
fetch.dog_breeds = "https://dogapi.dog/api/v2/breeds?page[number]=1&page[size]=6"
</what>
<html></html>"#;

        let (directives, _) = parse_page_directives(content);

        assert_eq!(
            directives.custom.get("fetch.dog_breeds"),
            Some(&"https://dogapi.dog/api/v2/breeds?page[number]=1&page[size]=6".to_string()),
            "URL with multiple = in query params should be preserved"
        );
    }

    #[test]
    fn test_fetch_directive_full_remote_data_page() {
        // Exact <what> block from remote-data.html
        let content = r#"<what>
title: Remote Data
page: remote-data
fetch.dog_facts = "https://dogapi.dog/api/v2/facts?limit=3"
fetch.dog_breeds = "https://dogapi.dog/api/v2/breeds?page[number]=1&page[size]=6"
fetch.dog_images = "https://dog.ceo/api/breeds/image/random/4"
</what>
<html></html>"#;

        let (directives, cleaned) = parse_page_directives(content);

        assert_eq!(directives.title, Some("Remote Data".to_string()));
        assert_eq!(directives.vars.get("page"), Some(&json!("remote-data")));
        assert_eq!(
            directives.custom.get("fetch.dog_facts"),
            Some(&"https://dogapi.dog/api/v2/facts?limit=3".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.dog_breeds"),
            Some(&"https://dogapi.dog/api/v2/breeds?page[number]=1&page[size]=6".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.dog_images"),
            Some(&"https://dog.ceo/api/breeds/image/random/4".to_string())
        );
        assert!(!cleaned.contains("<what>"));
    }

    // =========================================================================
    // Section Header Tests
    // =========================================================================

    #[test]
    fn test_section_header_fetch() {
        let content = r##"<what>
title: Dashboard
[fetch.weather]
url = "https://api.weather.com/current"
method = "GET"
headers = "Authorization: Bearer abc123"
path = "data.current"
limit = 5
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.title, Some("Dashboard".to_string()));
        assert_eq!(
            directives.custom.get("fetch.weather.url"),
            Some(&"https://api.weather.com/current".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.method"),
            Some(&"GET".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.headers"),
            Some(&"Authorization: Bearer abc123".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.path"),
            Some(&"data.current".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.limit"),
            Some(&"5".to_string())
        );
    }

    #[test]
    fn test_section_header_og() {
        let content = r##"<what>
[og]
title: My Dashboard
description: Real-time weather data
image: /images/dashboard-og.png
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(
            directives.vars.get("og.title"),
            Some(&json!("My Dashboard"))
        );
        assert_eq!(
            directives.vars.get("og.description"),
            Some(&json!("Real-time weather data"))
        );
        assert_eq!(
            directives.vars.get("og.image"),
            Some(&json!("/images/dashboard-og.png"))
        );
    }

    #[test]
    fn test_section_header_session() {
        let content = r##"<what>
[session]
visit_count += 1
theme = "dark"
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.session_mutations.len(), 2);
    }

    #[test]
    fn test_section_header_compute() {
        let content = r##"<what>
[compute]
greeting = "Hello, #user.full_name#!"
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.computed.len(), 1);
        assert_eq!(directives.computed[0].0, "greeting");
        assert_eq!(directives.computed[0].1, "Hello, #user.full_name#!");
    }

    #[test]
    fn test_section_header_reset() {
        let content = r##"<what>
[fetch.weather]
url = "https://api.weather.com/current"

[]
session.visit_count += 1
compute.greeting = "Hello!"
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(
            directives.custom.get("fetch.weather.url"),
            Some(&"https://api.weather.com/current".to_string())
        );
        assert_eq!(directives.session_mutations.len(), 1);
        assert_eq!(directives.computed.len(), 1);
    }

    #[test]
    fn test_section_header_mixed() {
        // Flat syntax and section syntax in the same block
        let content = r##"<what>
title: Dashboard
auth: user
fetch.legacy = "https://old-api.com/data"

[fetch.weather]
url = "https://api.weather.com/current"
method = "POST"

[]
session.count += 1
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.title, Some("Dashboard".to_string()));
        assert_eq!(
            directives.custom.get("fetch.legacy"),
            Some(&"https://old-api.com/data".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.url"),
            Some(&"https://api.weather.com/current".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.method"),
            Some(&"POST".to_string())
        );
        assert_eq!(directives.session_mutations.len(), 1);
    }

    #[test]
    fn test_section_header_multiple_fetch() {
        let content = r##"<what>
[fetch.weather]
url = "https://api.weather.com/current"
path = "data.current"

[fetch.news]
url = "https://api.news.com/latest"
path = "articles"
limit = 10
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(
            directives.custom.get("fetch.weather.url"),
            Some(&"https://api.weather.com/current".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.weather.path"),
            Some(&"data.current".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.news.url"),
            Some(&"https://api.news.com/latest".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.news.path"),
            Some(&"articles".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.news.limit"),
            Some(&"10".to_string())
        );
    }

    #[test]
    fn test_section_header_backward_compat() {
        // Old flat syntax must still work identically
        let content = r##"<what>
title: Remote Data
fetch.dogs = "https://dogapi.dog/api/v2/facts?limit=3"
fetch.dogs.path = "data"
session.count += 1
compute.greeting = "Hello!"
og.title: My Page
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.title, Some("Remote Data".to_string()));
        assert_eq!(
            directives.custom.get("fetch.dogs"),
            Some(&"https://dogapi.dog/api/v2/facts?limit=3".to_string())
        );
        assert_eq!(
            directives.custom.get("fetch.dogs.path"),
            Some(&"data".to_string())
        );
        assert_eq!(directives.session_mutations.len(), 1);
        assert_eq!(directives.computed.len(), 1);
        assert_eq!(directives.vars.get("og.title"), Some(&json!("My Page")));
    }

    // =========================================================================
    // Inline Variable Tests
    // =========================================================================

    #[test]
    fn inline_var_string() {
        let content = r#"<what>
title = "My Page"
subtitle = "Welcome"
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        // title is a reserved directive
        assert_eq!(directives.title, Some("My Page".to_string()));
        // subtitle is an inline variable
        assert_eq!(directives.vars.get("subtitle"), Some(&json!("Welcome")));
    }

    #[test]
    fn inline_var_number() {
        let content = r#"<what>
count = 42
price = 9.99
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.vars.get("count"), Some(&json!(42)));
        assert_eq!(directives.vars.get("price"), Some(&json!(9.99)));
    }

    #[test]
    fn inline_var_boolean() {
        let content = r#"<what>
show_banner = true
debug = false
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.vars.get("show_banner"), Some(&json!(true)));
        assert_eq!(directives.vars.get("debug"), Some(&json!(false)));
    }

    #[test]
    fn inline_var_single_line_array() {
        let content = r#"<what>
colors = ["red", "green", "blue"]
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(
            directives.vars.get("colors"),
            Some(&json!(["red", "green", "blue"]))
        );
    }

    #[test]
    fn inline_var_multi_line_array() {
        let content = r##"<what>
products = [
  { "name": "Widget", "price": 9.99 },
  { "name": "Gadget", "price": 24.99 }
]
</what>
<html></html>"##;
        let (directives, _) = parse_page_directives(content);
        let products = directives.vars.get("products").unwrap();
        assert!(products.is_array());
        assert_eq!(products.as_array().unwrap().len(), 2);
        assert_eq!(products[0]["name"], json!("Widget"));
        assert_eq!(products[1]["price"], json!(24.99));
    }

    #[test]
    fn inline_var_multi_line_object() {
        let content = r##"<what>
config = {
  "theme": "dark",
  "sidebar": true
}
</what>
<html></html>"##;
        let (directives, _) = parse_page_directives(content);
        let config = directives.vars.get("config").unwrap();
        assert!(config.is_object());
        assert_eq!(config["theme"], json!("dark"));
        assert_eq!(config["sidebar"], json!(true));
    }

    #[test]
    fn inline_var_relaxed_json_unquoted_keys() {
        let content = r##"<what>
products = [
  { name: "Widget", price: 9.99 },
  { name: "Gadget", price: 24.99 }
]
</what>
<html></html>"##;
        let (directives, _) = parse_page_directives(content);
        let products = directives.vars.get("products").unwrap();
        assert!(products.is_array());
        assert_eq!(products[0]["name"], json!("Widget"));
        assert_eq!(products[1]["price"], json!(24.99));
    }

    #[test]
    fn inline_var_relaxed_json_single_line() {
        let content = r##"<what>
item = { name: "Widget", price: 9.99 }
</what>
<html></html>"##;
        let (directives, _) = parse_page_directives(content);
        let item = directives.vars.get("item").unwrap();
        assert_eq!(item["name"], json!("Widget"));
        assert_eq!(item["price"], json!(9.99));
    }

    #[test]
    fn inline_var_does_not_affect_reserved() {
        let content = r#"<what>
auth = user
layout = main.html
fetch.api = "https://example.com"
my_var = "hello"
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        // Reserved directives work normally
        assert!(directives.requires_auth());
        assert_eq!(directives.layout, Some("main.html".to_string()));
        assert_eq!(
            directives.custom.get("fetch.api"),
            Some(&"https://example.com".to_string())
        );
        // Non-reserved goes to vars
        assert_eq!(directives.vars.get("my_var"), Some(&json!("hello")));
        // Reserved keys NOT in vars
        assert!(directives.vars.get("auth").is_none());
        assert!(directives.vars.get("layout").is_none());
    }

    #[test]
    fn inline_var_mixed_with_directives() {
        let content = r##"<what>
title = "Dashboard"
items_per_page = 25
nav_items = ["Home", "About", "Contact"]
fetch.data = "https://api.example.com/data"
compute.greeting = "Hello #user.name#!"
</what>
<html></html>"##;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.title, Some("Dashboard".to_string()));
        assert_eq!(directives.vars.get("items_per_page"), Some(&json!(25)));
        assert_eq!(
            directives.vars.get("nav_items"),
            Some(&json!(["Home", "About", "Contact"]))
        );
        assert_eq!(
            directives.custom.get("fetch.data"),
            Some(&"https://api.example.com/data".to_string())
        );
        assert_eq!(directives.computed.len(), 1);
    }

    // =========================================================================
    // Named Mutation Block Tests
    // =========================================================================

    #[test]
    fn mutation_stored_as_custom_string() {
        let content = r#"<what>
mutation.reset = "session.score = 0; session.lives = 3"
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(
            directives.custom.get("mutation.reset"),
            Some(&"session.score = 0; session.lives = 3".to_string())
        );
        // Should NOT be in vars (not JSON-parsed)
        assert!(directives.vars.get("mutation.reset").is_none());
    }

    #[test]
    fn mutation_not_parsed_as_inline_var() {
        let content = r#"<what>
mutation.toggle = "session.dark_mode = 1"
my_var = 42
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        // mutation goes to custom, my_var goes to vars
        assert!(directives.custom.contains_key("mutation.toggle"));
        assert_eq!(directives.vars.get("my_var"), Some(&json!(42)));
    }

    // =========================================================================
    // .what File Parser Tests
    // =========================================================================

    #[test]
    fn test_what_file_strings() {
        let content = r#"
title = "My Application"
description = 'Single quotes work too'
bare_string = unquoted
"#;
        let config = parse_what_file(content);

        assert_eq!(config.get_string("title"), Some("My Application"));
        assert_eq!(
            config.get_string("description"),
            Some("Single quotes work too")
        );
        assert_eq!(config.get_string("bare_string"), Some("unquoted"));
    }

    #[test]
    fn test_what_file_numbers() {
        let content = r#"
port = 8080
version = 1.5
negative = -42
"#;
        let config = parse_what_file(content);

        assert_eq!(config.get_number("port"), Some(8080.0));
        assert_eq!(config.get_number("version"), Some(1.5));
        assert_eq!(config.get_number("negative"), Some(-42.0));
    }

    #[test]
    fn test_what_file_booleans() {
        let content = r#"
debug = true
production = false
"#;
        let config = parse_what_file(content);

        assert_eq!(config.get_bool("debug"), Some(true));
        assert_eq!(config.get_bool("production"), Some(false));
    }

    #[test]
    fn test_what_file_arrays() {
        let content = r#"
nav_items = ["Home", "About", "Contact"]
numbers = [1, 2, 3]
mixed = ["a", 1, true]
empty = []
"#;
        let config = parse_what_file(content);

        let nav = config.get_array("nav_items").unwrap();
        assert_eq!(nav.len(), 3);
        assert_eq!(nav[0].as_str(), Some("Home"));

        let nums = config.get_array("numbers").unwrap();
        assert_eq!(nums.len(), 3);
        assert_eq!(nums[0].as_i64(), Some(1));

        let empty = config.get_array("empty").unwrap();
        assert!(empty.is_empty());
    }

    #[test]
    fn test_what_file_comments() {
        let content = r#"
// This is a comment
title = "Hello"
# This is also a comment
name = "World"
"#;
        let config = parse_what_file(content);

        assert_eq!(config.get_string("title"), Some("Hello"));
        assert_eq!(config.get_string("name"), Some("World"));
        // Comments should not appear as values
        assert!(config.values.len() == 2);
    }

    #[test]
    fn test_what_file_auth_directive() {
        let content = r#"
auth = "admin"
title = "Dashboard"
"#;
        let config = parse_what_file(content);

        assert_eq!(
            config.directives.auth,
            AuthLevel::Roles(vec!["admin".to_string()])
        );
        assert_eq!(config.directives.title, Some("Dashboard".to_string()));
    }

    #[test]
    fn test_what_file_auth_all() {
        let content = r#"
auth = "all"
"#;
        let config = parse_what_file(content);

        assert_eq!(config.directives.auth, AuthLevel::All);
        assert!(!config.directives.requires_auth());
    }

    #[test]
    fn test_what_file_roles_array() {
        let content = r#"
roles = ["admin", "editor"]
"#;
        let config = parse_what_file(content);

        assert_eq!(config.directives.roles, vec!["admin", "editor"]);
        assert!(config.directives.protected);
    }

    #[test]
    fn test_what_config_merge() {
        let content1 = r#"
title = "Parent"
theme = "light"
auth = "all"
"#;
        let content2 = r#"
title = "Child"
nav = ["Home"]
auth = "admin"
"#;
        let mut config1 = parse_what_file(content1);
        let config2 = parse_what_file(content2);

        config1.merge(&config2);

        // Child overrides parent
        assert_eq!(config1.get_string("title"), Some("Child"));
        // Parent value preserved
        assert_eq!(config1.get_string("theme"), Some("light"));
        // Child adds new value
        assert!(config1.get_array("nav").is_some());
        // Auth from child takes precedence
        assert_eq!(
            config1.directives.auth,
            AuthLevel::Roles(vec!["admin".to_string()])
        );
    }

    // =========================================================================
    // Edge Case Tests
    // =========================================================================

    #[test]
    fn test_auth_level_edge_cases() {
        // Empty string should be All
        assert_eq!(parse_auth_level(""), AuthLevel::All);

        // Whitespace-only should be All
        assert_eq!(parse_auth_level("   "), AuthLevel::All);

        // Case insensitivity
        assert_eq!(parse_auth_level("ALL"), AuthLevel::All);
        assert_eq!(parse_auth_level("User"), AuthLevel::User);
        assert_eq!(
            parse_auth_level("ADMIN"),
            AuthLevel::Roles(vec!["admin".to_string()])
        );

        // Whitespace in roles
        assert_eq!(
            parse_auth_level("  admin  ,  editor  "),
            AuthLevel::Roles(vec!["admin".to_string(), "editor".to_string()])
        );

        // Single role
        assert_eq!(
            parse_auth_level("superuser"),
            AuthLevel::Roles(vec!["superuser".to_string()])
        );
    }

    #[test]
    fn test_page_directives_cache_ttl() {
        // Self-closing with cache attribute
        let content = r#"<what cache="3600" />
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.cache_ttl, Some(3600));

        // Content syntax with cache-ttl
        let content = r#"<what>
cache-ttl: 1800
</what>
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.cache_ttl, Some(1800));
    }

    #[test]
    fn test_page_directives_custom() {
        let content = r#"<what custom_field="my_value" another="test" />
<html></html>"#;
        let (directives, _) = parse_page_directives(content);

        assert_eq!(
            directives.custom.get("custom_field"),
            Some(&"my_value".to_string())
        );
        assert_eq!(directives.custom.get("another"), Some(&"test".to_string()));
    }

    #[test]
    fn test_page_directives_redirect() {
        let content = r#"<what redirect="/new-page" />
<html></html>"#;
        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.redirect, Some("/new-page".to_string()));
    }

    #[test]
    fn test_what_file_empty() {
        let content = "";
        let config = parse_what_file(content);
        assert!(config.values.is_empty());
        assert_eq!(config.directives.auth, AuthLevel::All);
    }

    #[test]
    fn test_what_file_only_comments() {
        let content = r#"
// This is a comment
# Another comment
// More comments
"#;
        let config = parse_what_file(content);
        assert!(config.values.is_empty());
    }

    #[test]
    fn test_what_file_data_application() {
        let content = r#"
data.application = ["posts", "products"]
"#;
        let config = parse_what_file(content);
        let names: Vec<&str> = config.data_application.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["posts", "products"]);
        // Should not be exposed as template variable
        assert!(!config.values.contains_key("data.application"));
    }

    #[test]
    fn test_what_file_data_application_scoped() {
        let content = r#"
data.application = ["visits", "revenue [admin, editor]"]
"#;
        let config = parse_what_file(content);
        assert_eq!(config.data_application[0].name, "visits");
        assert!(matches!(config.data_application[0].scope, WiredScope::Public));
        assert_eq!(config.data_application[1].name, "revenue");
        match &config.data_application[1].scope {
            WiredScope::Roles(r) => assert_eq!(r, &vec!["admin".to_string(), "editor".to_string()]),
            other => panic!("expected Roles, got {other:?}"),
        }
    }

    #[test]
    fn test_what_file_data_session() {
        let content = r#"
data.session = ["cart", "wishlist"]
"#;
        let config = parse_what_file(content);
        assert_eq!(config.data_session, vec!["cart", "wishlist"]);
        // Should not be exposed as template variable
        assert!(!config.values.contains_key("data.session"));
    }

    #[test]
    fn test_what_file_data_single_value() {
        // Single string instead of array should still work
        let content = r#"
data.application = "posts"
data.session = "cart"
"#;
        let config = parse_what_file(content);
        assert_eq!(config.data_application.len(), 1);
        assert_eq!(config.data_application[0].name, "posts");
        assert_eq!(config.data_session, vec!["cart"]);
    }

    #[test]
    fn test_what_value_edge_cases() {
        // Empty array
        assert_eq!(parse_what_value("[]"), serde_json::json!([]));

        // Negative float
        assert_eq!(parse_what_value("-3.14"), serde_json::json!(-3.14));

        // Zero
        assert_eq!(parse_what_value("0"), serde_json::json!(0));

        // Very large number
        assert_eq!(
            parse_what_value("9999999999"),
            serde_json::json!(9999999999_i64)
        );
    }

    #[test]
    fn test_page_directives_mixed_syntax() {
        // Mix of boolean and key-value
        let content = r#"<what protected title="Dashboard" exclude />
<html></html>"#;
        let (directives, _) = parse_page_directives(content);

        assert!(directives.protected);
        assert!(directives.exclude);
        assert_eq!(directives.title, Some("Dashboard".to_string()));
    }

    #[test]
    fn test_is_standard_html_tag() {
        // Standard tags
        assert!(is_standard_html_tag("div"));
        assert!(is_standard_html_tag("span"));
        assert!(is_standard_html_tag("html"));
        assert!(is_standard_html_tag("body"));
        assert!(is_standard_html_tag("form"));
        assert!(is_standard_html_tag("input"));
        assert!(is_standard_html_tag("template"));
        assert!(is_standard_html_tag("slot"));

        // Custom tags
        assert!(!is_standard_html_tag("jumbo"));
        assert!(!is_standard_html_tag("card"));
        assert!(!is_standard_html_tag("my-component"));
        assert!(!is_standard_html_tag("loop"));
    }

    #[test]
    fn test_page_directives_requires_auth() {
        // auth: all should not require auth
        let mut d = PageDirectives::default();
        d.auth = AuthLevel::All;
        assert!(!d.requires_auth());

        // auth: user should require auth
        d.auth = AuthLevel::User;
        assert!(d.requires_auth());

        // auth: roles should require auth
        d.auth = AuthLevel::Roles(vec!["admin".to_string()]);
        assert!(d.requires_auth());

        // Legacy: protected = true should require auth even with auth: all
        d.auth = AuthLevel::All;
        d.protected = true;
        assert!(d.requires_auth());
    }

    #[test]
    fn test_page_directives_check_access_legacy() {
        // Test legacy protected + roles behavior
        let mut d = PageDirectives::default();
        d.protected = true;
        d.roles = vec!["admin".to_string(), "editor".to_string()];

        // Not authenticated - denied
        assert!(!d.check_access(false, &[]));

        // Authenticated without roles - denied
        assert!(!d.check_access(true, &[]));

        // Authenticated with wrong role - denied
        assert!(!d.check_access(true, &["viewer".to_string()]));

        // Authenticated with correct role - allowed
        assert!(d.check_access(true, &["admin".to_string()]));
        assert!(d.check_access(true, &["editor".to_string()]));
    }

    // =========================================================================
    // Layout System Tests
    // =========================================================================

    #[test]
    fn test_layout_in_what_file() {
        let content = r#"
layout = "sections/main.html"
title = "Test Page"
"#;
        let config = parse_what_file(content);

        assert_eq!(config.layout, Some("sections/main.html".to_string()));
        assert_eq!(
            config.directives.layout,
            Some("sections/main.html".to_string())
        );
        // Layout should not be exposed as a template variable
        assert!(config.get_string("layout").is_none());
    }

    #[test]
    fn test_layout_in_page_directive_attribute() {
        let content = r#"<what layout="sections/page.html" />
<h1>Hello</h1>"#;
        let (directives, cleaned) = parse_page_directives(content);

        assert_eq!(directives.layout, Some("sections/page.html".to_string()));
        assert!(cleaned.contains("<h1>Hello</h1>"));
        assert!(!cleaned.contains("<what"));
    }

    #[test]
    fn test_layout_in_page_directive_content() {
        let content = r#"<what>
layout: sections/admin.html
title: Dashboard
</what>
<h1>Admin Dashboard</h1>"#;
        let (directives, cleaned) = parse_page_directives(content);

        assert_eq!(directives.layout, Some("sections/admin.html".to_string()));
        assert_eq!(directives.title, Some("Dashboard".to_string()));
        assert!(cleaned.contains("<h1>Admin Dashboard</h1>"));
    }

    #[test]
    fn test_layout_none_disables() {
        // Page can use layout: none to disable inherited layout
        let content = r#"<what layout="none" />
<h1>No Layout</h1>"#;
        let (directives, _) = parse_page_directives(content);

        assert_eq!(directives.layout, Some("none".to_string()));
    }

    #[test]
    fn test_what_config_layout_merge() {
        let parent_content = r#"
layout = "sections/base.html"
title = "Parent"
"#;
        let child_content = r#"
layout = "sections/admin.html"
"#;
        let mut parent = parse_what_file(parent_content);
        let child = parse_what_file(child_content);

        parent.merge(&child);

        // Child layout overrides parent
        assert_eq!(parent.layout, Some("sections/admin.html".to_string()));
    }

    #[test]
    fn test_what_config_layout_inherit() {
        let parent_content = r#"
layout = "sections/base.html"
title = "Parent"
"#;
        let child_content = r#"
title = "Child"
"#;
        let mut parent = parse_what_file(parent_content);
        let child = parse_what_file(child_content);

        parent.merge(&child);

        // Parent layout is preserved when child doesn't set one
        assert_eq!(parent.layout, Some("sections/base.html".to_string()));
        assert_eq!(parent.get_string("title"), Some("Child"));
    }

    #[test]
    fn test_what_config_layout_none_override() {
        let parent_content = r#"
layout = "sections/base.html"
"#;
        let child_content = r#"
layout = "none"
"#;
        let mut parent = parse_what_file(parent_content);
        let child = parse_what_file(child_content);

        parent.merge(&child);

        // Child's "none" overrides parent layout
        assert_eq!(parent.layout, Some("none".to_string()));
    }

    // =========================================================================
    // Reactive Variable Replacement Tests
    // =========================================================================

    #[test]
    fn test_reactive_session_var_in_text() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "count": 8
            }),
        );

        let template = "<p>Counter: #session.count#</p>";
        let result = replace_variables_reactive(template, &context);

        assert!(
            result
                .html
                .contains(r#"<span w-bind="session.count">8</span>"#)
        );
        assert!(result.session_keys.contains("count"));
    }

    #[test]
    fn test_reactive_session_var_in_attribute() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "count": 8
            }),
        );

        // Session variable in attribute should NOT be wrapped
        let template = r##"<div title="#session.count#">Content</div>"##;
        let result = replace_variables_reactive(template, &context);

        // Should replace value but not wrap
        assert!(result.html.contains(r##"title="8""##));
        // Should NOT contain span with w-bind
        assert!(!result.html.contains("w-bind"));
        // But should still track the key
        assert!(result.session_keys.contains("count"));
    }

    #[test]
    fn test_reactive_non_session_var() {
        let mut context = HashMap::new();
        context.insert("name".to_string(), serde_json::json!("Alice"));

        let template = "<p>Hello #name#!</p>";
        let result = replace_variables_reactive(template, &context);

        // Non-session variables should be replaced without wrapping
        assert!(result.html.contains("Hello Alice!"));
        assert!(!result.html.contains("w-bind"));
        assert!(result.session_keys.is_empty());
    }

    #[test]
    fn test_reactive_multiple_session_vars() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "count": 5,
                "name": "Test"
            }),
        );

        let template = "<p>Count: #session.count#, Name: #session.name#</p>";
        let result = replace_variables_reactive(template, &context);

        assert!(
            result
                .html
                .contains(r#"<span w-bind="session.count">5</span>"#)
        );
        assert!(
            result
                .html
                .contains(r#"<span w-bind="session.name">Test</span>"#)
        );
        assert!(result.session_keys.contains("count"));
        assert!(result.session_keys.contains("name"));
    }

    #[test]
    fn test_is_in_attribute_context() {
        // Text content cases (should return false)
        assert!(!is_in_attribute_context("<p>"));
        assert!(!is_in_attribute_context("<p>Hello "));
        assert!(!is_in_attribute_context("<div><span>"));

        // Attribute cases (should return true)
        assert!(is_in_attribute_context(r#"<div title=""#));
        assert!(is_in_attribute_context(r#"<div class="foo "#));
        assert!(is_in_attribute_context(r#"<input value=""#));

        // After closing attribute (should return false)
        assert!(!is_in_attribute_context(r#"<div title="test">"#));
        assert!(!is_in_attribute_context(r#"<div class="foo">Hello"#));
    }

    #[test]
    fn test_html_escape() {
        assert_eq!(html_escape("<"), "&lt;");
        assert_eq!(html_escape(">"), "&gt;");
        assert_eq!(html_escape("&"), "&amp;");
        assert_eq!(html_escape("\""), "&quot;");
        assert_eq!(html_escape("'"), "&#39;");
        assert_eq!(
            html_escape("<script>alert('xss')</script>"),
            "&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;"
        );
    }

    #[test]
    fn test_parse_session_mutation_push() {
        let m = parse_session_mutation("session.items.push(\"hello\")").unwrap();
        match m {
            SessionMutation::Push { key, value } => {
                assert_eq!(key, "items");
                assert_eq!(value, serde_json::json!("hello"));
            }
            _ => panic!("Expected Push"),
        }
    }

    #[test]
    fn test_parse_session_mutation_pushmax() {
        let m = parse_session_mutation("session.history.pushmax(5, \"page1\")").unwrap();
        match m {
            SessionMutation::PushMax { key, max, value } => {
                assert_eq!(key, "history");
                assert_eq!(max, 5);
                assert_eq!(value, serde_json::json!("page1"));
            }
            _ => panic!("Expected PushMax"),
        }
    }

    #[test]
    fn test_parse_session_mutation_pushmax_numeric() {
        let m = parse_session_mutation("session.ids.pushmax(10, 42)").unwrap();
        match m {
            SessionMutation::PushMax { key, max, value } => {
                assert_eq!(key, "ids");
                assert_eq!(max, 10);
                assert_eq!(value, serde_json::json!(42));
            }
            _ => panic!("Expected PushMax"),
        }
    }

    // =========================================================================
    // Auto-Escaping Tests
    // =========================================================================

    #[test]
    fn test_auto_escape_html_in_variables() {
        let mut context = HashMap::new();
        context.insert(
            "name".to_string(),
            serde_json::json!("<script>alert('xss')</script>"),
        );

        let result = replace_variables("Hello #name#!", &context);
        assert_eq!(
            result,
            "Hello &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;!"
        );
        assert!(!result.contains("<script>"));
    }

    #[test]
    fn test_auto_escape_ampersand() {
        let mut context = HashMap::new();
        context.insert("text".to_string(), serde_json::json!("Tom & Jerry"));

        let result = replace_variables("#text#", &context);
        assert_eq!(result, "Tom &amp; Jerry");
    }

    #[test]
    fn test_auto_escape_quotes() {
        let mut context = HashMap::new();
        context.insert("text".to_string(), serde_json::json!(r#"He said "hello""#));

        let result = replace_variables("#text#", &context);
        assert_eq!(result, "He said &quot;hello&quot;");
    }

    #[test]
    fn test_raw_filter_bypasses_escaping() {
        let mut context = HashMap::new();
        context.insert("html".to_string(), serde_json::json!("<b>bold</b>"));

        let result = replace_variables("#html|raw#", &context);
        assert_eq!(result, "<b>bold</b>");
    }

    #[test]
    fn test_raw_filter_with_default_value() {
        let mut context = HashMap::new();
        context.insert("html".to_string(), serde_json::json!("<em>yes</em>"));

        // |raw at end of filter chain
        let result = replace_variables("#html|raw#", &context);
        assert_eq!(result, "<em>yes</em>");
    }

    #[test]
    fn test_auto_escape_preserves_safe_text() {
        let mut context = HashMap::new();
        context.insert("name".to_string(), serde_json::json!("Alice"));

        let result = replace_variables("Hello #name#!", &context);
        assert_eq!(result, "Hello Alice!");
    }

    #[test]
    fn test_auto_escape_nested_variables() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            serde_json::json!({
                "name": "<b>Admin</b>",
                "bio": "Loves coding & testing"
            }),
        );

        let result = replace_variables("#user.name# - #user.bio#", &context);
        assert_eq!(
            result,
            "&lt;b&gt;Admin&lt;/b&gt; - Loves coding &amp; testing"
        );
    }

    #[test]
    fn test_auto_escape_with_default_filter() {
        let context = HashMap::new();

        // New syntax: |default:"value"
        let result = replace_variables(r##"#missing|default:"<fallback>"#"##, &context);
        assert_eq!(result, "&lt;fallback&gt;");
    }

    #[test]
    fn test_reactive_auto_escape_non_session_var() {
        let mut context = HashMap::new();
        context.insert(
            "name".to_string(),
            serde_json::json!("<script>xss</script>"),
        );

        let result = replace_variables_reactive("<p>#name#</p>", &context);
        assert!(result.html.contains("&lt;script&gt;xss&lt;/script&gt;"));
        assert!(!result.html.contains("<script>xss</script>"));
    }

    #[test]
    fn test_reactive_auto_escape_session_var_in_attribute() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "name": "Tom & Jerry"
            }),
        );

        let template = r##"<div title="#session.name#">Content</div>"##;
        let result = replace_variables_reactive(template, &context);

        // Attribute should be escaped
        assert!(result.html.contains("Tom &amp; Jerry"));
        assert!(!result.html.contains("w-bind"));
    }

    #[test]
    fn test_reactive_raw_filter_non_session_var() {
        let mut context = HashMap::new();
        context.insert("html".to_string(), serde_json::json!("<b>bold</b>"));

        let result = replace_variables_reactive("<p>#html|raw#</p>", &context);
        assert!(result.html.contains("<b>bold</b>"));
    }

    #[test]
    fn test_reactive_session_var_always_escaped_in_span() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "name": "<script>xss</script>"
            }),
        );

        let result = replace_variables_reactive("<p>#session.name#</p>", &context);
        // Session vars in text are always escaped inside the reactive span
        assert!(result.html.contains("&lt;script&gt;xss&lt;/script&gt;"));
        assert!(result.html.contains("w-bind"));
    }

    #[test]
    fn test_reactive_session_raw_in_attribute() {
        let mut context = HashMap::new();
        context.insert(
            "session".to_string(),
            serde_json::json!({
                "url": "/path?a=1&b=2"
            }),
        );

        // |raw in attribute context should skip escaping
        let template = r##"<a href="#session.url|raw#">Link</a>"##;
        let result = replace_variables_reactive(template, &context);
        assert!(result.html.contains(r#"href="/path?a=1&b=2""#));
    }

    #[test]
    fn test_auto_escape_number_values() {
        let mut context = HashMap::new();
        context.insert("count".to_string(), serde_json::json!(42));

        let result = replace_variables("Count: #count#", &context);
        assert_eq!(result, "Count: 42");
    }

    #[test]
    fn test_auto_escape_boolean_values() {
        let mut context = HashMap::new();
        context.insert("flag".to_string(), serde_json::json!(true));

        let result = replace_variables("Flag: #flag#", &context);
        assert_eq!(result, "Flag: true");
    }

    #[test]
    fn test_auto_escape_unresolved_variable() {
        let context = HashMap::new();
        // Unresolved variables stay as #var# — this should NOT be escaped
        // because the hash signs are part of the template syntax, not user data
        let result = replace_variables("#unknown#", &context);
        // The unresolved var format "#unknown#" gets escaped as-is
        assert_eq!(result, "#unknown#");
    }

    #[test]
    fn test_nested_var_on_empty_parent_resolves_empty() {
        let mut context = HashMap::new();
        // Parent object exists but child key is missing → empty, not literal
        context.insert("old".into(), serde_json::json!({}));
        let result = replace_variables("#old.title#", &context);
        assert_eq!(
            result, "",
            "Missing child on existing parent should be empty"
        );
    }

    #[test]
    fn test_nested_var_on_missing_root_stays_literal() {
        let context = HashMap::new();
        // Root key not in context at all → preserve literal for strict mode
        let result = replace_variables("#old.title#", &context);
        assert_eq!(result, "#old.title#", "Missing root should keep literal");
    }

    #[test]
    fn test_nested_var_on_populated_parent_resolves() {
        let mut context = HashMap::new();
        context.insert("user".into(), serde_json::json!({"name": "Alice"}));
        // Existing child → resolves normally
        assert_eq!(replace_variables("#user.name#", &context), "Alice");
        // Missing child on populated parent → empty
        assert_eq!(replace_variables("#user.role#", &context), "");
    }

    // =========================================================================
    // Filter System Tests
    // =========================================================================

    #[test]
    fn test_filter_parse_chain() {
        let (path, filters) = parse_filter_chain("name|uppercase");
        assert_eq!(path, "name");
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name, "uppercase");
        assert!(filters[0].args.is_empty());
    }

    #[test]
    fn test_filter_parse_with_arg() {
        let (path, filters) = parse_filter_chain("title|truncate:50");
        assert_eq!(path, "title");
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name, "truncate");
        assert_eq!(filters[0].args, vec!["50"]);
    }

    #[test]
    fn test_filter_parse_chained() {
        let (path, filters) = parse_filter_chain("title|truncate:50|uppercase");
        assert_eq!(path, "title");
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0].name, "truncate");
        assert_eq!(filters[1].name, "uppercase");
    }

    #[test]
    fn test_filter_parse_quoted_args() {
        let (path, filters) = parse_filter_chain(r#"name|default:"Anonymous""#);
        assert_eq!(path, "name");
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name, "default");
        assert_eq!(filters[0].args, vec!["Anonymous"]);
    }

    #[test]
    fn test_filter_parse_multiple_args() {
        let (path, filters) = parse_filter_chain(r#"text|replace:"old","new""#);
        assert_eq!(path, "text");
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name, "replace");
        assert_eq!(filters[0].args, vec!["old", "new"]);
    }

    #[test]
    fn test_filter_uppercase() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello"));
        let result = replace_variables("#name|uppercase#", &ctx);
        assert_eq!(result, "HELLO");
    }

    #[test]
    fn test_filter_lowercase() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("HELLO"));
        let result = replace_variables("#name|lowercase#", &ctx);
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_filter_capitalize() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello world"));
        let result = replace_variables("#name|capitalize#", &ctx);
        assert_eq!(result, "Hello world");
    }

    #[test]
    fn test_filter_title() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello world today"));
        let result = replace_variables("#name|title#", &ctx);
        assert_eq!(result, "Hello World Today");
    }

    #[test]
    fn test_filter_truncate() {
        let mut ctx = HashMap::new();
        ctx.insert(
            "text".to_string(),
            serde_json::json!("This is a long text that should be truncated"),
        );
        let result = replace_variables("#text|truncate:10#", &ctx);
        assert_eq!(result, "This is a ...");
    }

    #[test]
    fn test_filter_truncate_short_text() {
        let mut ctx = HashMap::new();
        ctx.insert("text".to_string(), serde_json::json!("Short"));
        let result = replace_variables("#text|truncate:10#", &ctx);
        assert_eq!(result, "Short");
    }

    #[test]
    fn test_filter_count() {
        let mut ctx = HashMap::new();
        ctx.insert("text".to_string(), serde_json::json!("hello"));
        let result = replace_variables("#text|count#", &ctx);
        assert_eq!(result, "5");
    }

    #[test]
    fn test_filter_number() {
        let mut ctx = HashMap::new();
        ctx.insert("n".to_string(), serde_json::json!(1234567));
        let result = replace_variables("#n|number#", &ctx);
        assert_eq!(result, "1,234,567");
    }

    #[test]
    fn test_filter_currency_usd() {
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), serde_json::json!(1299.99));
        let result = replace_variables(r##"#price|currency:"USD"#"##, &ctx);
        assert_eq!(result, "$1,299.99");
    }

    #[test]
    fn test_filter_currency_eur() {
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), serde_json::json!(49.5));
        let result = replace_variables(r##"#price|currency:"EUR"#"##, &ctx);
        assert_eq!(result, "\u{20ac}49.50");
    }

    #[test]
    fn test_filter_date() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables("#d|date#", &ctx);
        assert_eq!(result, "Mar 15, 2025"); // default = "medium" preset
    }

    #[test]
    fn test_filter_date_custom_format() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables(r##"#d|date:"dd/mm/yyyy"#"##, &ctx);
        assert_eq!(result, "15/03/2025");
    }

    #[test]
    fn test_date_mask_short() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-05"));
        let result = replace_variables(r##"#d|date:"short"#"##, &ctx);
        assert_eq!(result, "3/5/25");
    }

    #[test]
    fn test_date_mask_full() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables(r##"#d|date:"full"#"##, &ctx);
        assert_eq!(result, "Saturday, March 15, 2025");
    }

    #[test]
    fn test_date_mask_long() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables(r##"#d|date:"long"#"##, &ctx);
        assert_eq!(result, "March 15, 2025");
    }

    #[test]
    fn test_date_mask_iso() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-05"));
        let result = replace_variables(r##"#d|date:"iso"#"##, &ctx);
        assert_eq!(result, "2025-03-05");
    }

    #[test]
    fn test_date_mask_time() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15T14:05:09"));
        let result = replace_variables(r##"#d|date:"time"#"##, &ctx);
        assert_eq!(result, "2:05 PM");
    }

    #[test]
    fn test_date_mask_combined() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15T14:30:00"));
        let result = replace_variables(r##"#d|date:"mmm d, yyyy h:nn tt"#"##, &ctx);
        assert_eq!(result, "Mar 15, 2025 2:30 PM");
    }

    #[test]
    fn test_date_mask_24hour() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15T09:05:00"));
        let result = replace_variables(r##"#d|date:"HH:nn"#"##, &ctx);
        assert_eq!(result, "09:05");
    }

    #[test]
    fn test_date_mask_weekday() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables(r##"#d|date:"ddd"#"##, &ctx);
        assert_eq!(result, "Sat");
    }

    #[test]
    fn test_date_mask_literals() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15"));
        let result = replace_variables(r##"#d|date:"yyyy-mm-dd"#"##, &ctx);
        assert_eq!(result, "2025-03-15");
    }

    #[test]
    fn test_date_mask_midnight_12hr() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15T00:00:00"));
        let result = replace_variables(r##"#d|date:"h:nn tt"#"##, &ctx);
        assert_eq!(result, "12:00 AM");
    }

    #[test]
    fn test_date_rfc3339_input() {
        let mut ctx = HashMap::new();
        ctx.insert("d".to_string(), serde_json::json!("2025-03-15T14:30:00Z"));
        let result = replace_variables(r##"#d|date:"mmm d"#"##, &ctx);
        assert_eq!(result, "Mar 15");
    }

    #[test]
    fn test_filter_json() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello"));
        let result = replace_variables("#name|json#", &ctx);
        assert_eq!(result, "&quot;hello&quot;"); // Escaped because auto-escape
    }

    #[test]
    fn test_filter_json_raw() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello"));
        let result = replace_variables("#name|json|raw#", &ctx);
        assert_eq!(result, "\"hello\""); // Not escaped because |raw
    }

    #[test]
    fn test_filter_markdown() {
        let mut ctx = HashMap::new();
        ctx.insert(
            "text".to_string(),
            serde_json::json!("This is **bold** and *italic*"),
        );
        let result = replace_variables("#text|markdown#", &ctx);
        assert!(result.contains("<strong>bold</strong>"));
        assert!(result.contains("<em>italic</em>"));
        // markdown is html_safe, so not escaped
        assert!(result.contains("<p>"));
    }

    #[test]
    fn test_markdown_url_scheme_allowlist() {
        // Safe schemes and relative URLs get an href
        assert!(markdown_url_is_safe("https://example.com"));
        assert!(markdown_url_is_safe("http://example.com"));
        assert!(markdown_url_is_safe("mailto:a@b.com"));
        assert!(markdown_url_is_safe("/relative/path"));
        assert!(markdown_url_is_safe("#anchor"));
        assert!(markdown_url_is_safe("page?x=1:2"));
        // Dangerous schemes are blocked — including control-char smuggling that
        // browsers would strip before evaluating the scheme.
        assert!(!markdown_url_is_safe("javascript:alert(1)"));
        assert!(!markdown_url_is_safe("JavaScript:alert(1)"));
        assert!(!markdown_url_is_safe("java\tscript:alert(1)"));
        assert!(!markdown_url_is_safe("java\nscript:alert(1)"));
        assert!(!markdown_url_is_safe("data:text/html,<script>"));
        assert!(!markdown_url_is_safe("vbscript:msgbox(1)"));

        // End-to-end through the filter: no href, no javascript
        let mut ctx = HashMap::new();
        ctx.insert(
            "t".to_string(),
            serde_json::json!("[x](java\tscript:alert(1))"),
        );
        let out = replace_variables("#t|markdown#", &ctx);
        assert!(!out.contains("href"), "dangerous URL emitted an href: {out}");
    }

    #[test]
    fn test_filter_pluralize() {
        let mut ctx = HashMap::new();
        ctx.insert("count".to_string(), serde_json::json!(1));
        let result = replace_variables(r##"#count# item#count|pluralize:"","s"#"##, &ctx);
        assert_eq!(result, "1 item");

        ctx.insert("count".to_string(), serde_json::json!(5));
        let result = replace_variables(r##"#count# item#count|pluralize:"","s"#"##, &ctx);
        assert_eq!(result, "5 items");
    }

    #[test]
    fn test_filter_default() {
        let ctx = HashMap::new();
        let result = replace_variables(r##"#missing|default:"N/A"#"##, &ctx);
        assert_eq!(result, "N/A");
    }

    #[test]
    fn test_filter_default_not_needed() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("Alice"));
        let result = replace_variables(r##"#name|default:"N/A"#"##, &ctx);
        assert_eq!(result, "Alice");
    }

    #[test]
    fn test_filter_replace() {
        let mut ctx = HashMap::new();
        ctx.insert("text".to_string(), serde_json::json!("Hello World"));
        let result = replace_variables(r##"#text|replace:"World","Rust"#"##, &ctx);
        assert_eq!(result, "Hello Rust");
    }

    #[test]
    fn test_filter_slice() {
        let mut ctx = HashMap::new();
        ctx.insert("text".to_string(), serde_json::json!("Hello World"));
        let result = replace_variables("#text|slice:0,5#", &ctx);
        assert_eq!(result, "Hello");
    }

    #[test]
    fn test_filter_chaining() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello world"));
        let result = replace_variables("#name|uppercase|truncate:5#", &ctx);
        assert_eq!(result, "HELLO...");
    }

    #[test]
    fn test_filter_chaining_with_escaping() {
        let mut ctx = HashMap::new();
        ctx.insert("text".to_string(), serde_json::json!("<b>hello</b>"));
        // Without |raw, output is escaped after filters
        let result = replace_variables("#text|uppercase#", &ctx);
        assert_eq!(result, "&lt;B&gt;HELLO&lt;/B&gt;");
    }

    #[test]
    fn test_filter_raw_bypasses_escaping() {
        let mut ctx = HashMap::new();
        ctx.insert("html".to_string(), serde_json::json!("<b>bold</b>"));
        let result = replace_variables("#html|raw#", &ctx);
        assert_eq!(result, "<b>bold</b>");
    }

    #[test]
    fn test_filter_in_reactive_mode() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello"));
        let result = replace_variables_reactive("<p>#name|uppercase#</p>", &ctx);
        assert!(result.html.contains("HELLO"));
    }

    #[test]
    fn test_filter_default_with_session_var() {
        let ctx = HashMap::new();
        let result = replace_variables_reactive(r##"<p>#session.count|default:"0"#</p>"##, &ctx);
        // Session var not found, default filter triggers, wrapped in span
        assert!(result.html.contains("w-bind"));
        assert!(result.html.contains(">0<"));
    }

    #[test]
    fn test_filter_unknown_passes_through() {
        let mut ctx = HashMap::new();
        ctx.insert("name".to_string(), serde_json::json!("hello"));
        // Unknown filter should pass value through unchanged
        let result = replace_variables("#name|bogusfilter#", &ctx);
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_filter_round() {
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), json!("3.14159"));
        assert_eq!(replace_variables("#price|round:2#", &ctx), "3.14");
    }

    #[test]
    fn test_filter_round_no_args() {
        let mut ctx = HashMap::new();
        ctx.insert("val".to_string(), json!("3.7"));
        assert_eq!(replace_variables("#val|round#", &ctx), "4");
    }

    #[test]
    fn test_filter_ceil() {
        let mut ctx = HashMap::new();
        ctx.insert("val".to_string(), json!("3.2"));
        assert_eq!(replace_variables("#val|ceil#", &ctx), "4");
    }

    #[test]
    fn test_filter_floor() {
        let mut ctx = HashMap::new();
        ctx.insert("val".to_string(), json!("3.9"));
        assert_eq!(replace_variables("#val|floor#", &ctx), "3");
    }

    #[test]
    fn test_filter_ceil_negative() {
        let mut ctx = HashMap::new();
        ctx.insert("val".to_string(), json!("-2.3"));
        assert_eq!(replace_variables("#val|ceil#", &ctx), "-2");
    }

    #[test]
    fn test_filter_floor_negative() {
        let mut ctx = HashMap::new();
        ctx.insert("val".to_string(), json!("-2.3"));
        assert_eq!(replace_variables("#val|floor#", &ctx), "-3");
    }

    // =========================================================================
    // Arithmetic Tests
    // =========================================================================

    #[test]
    fn test_arithmetic_basic_addition() {
        assert_eq!(evaluate_arithmetic("10 + 1"), Some(11.0));
    }

    #[test]
    fn test_arithmetic_subtraction() {
        assert_eq!(evaluate_arithmetic("10 - 3"), Some(7.0));
    }

    #[test]
    fn test_arithmetic_multiply() {
        assert_eq!(evaluate_arithmetic("5 * 3"), Some(15.0));
    }

    #[test]
    fn test_arithmetic_divide() {
        assert_eq!(evaluate_arithmetic("10 / 4"), Some(2.5));
    }

    #[test]
    fn test_arithmetic_precedence() {
        // 2 + 3 * 4 = 14 (not 20)
        assert_eq!(evaluate_arithmetic("2 + 3 * 4"), Some(14.0));
    }

    #[test]
    fn test_arithmetic_division_by_zero() {
        assert_eq!(evaluate_arithmetic("10 / 0"), None);
    }

    #[test]
    fn test_arithmetic_negative_result() {
        assert_eq!(evaluate_arithmetic("3 - 10"), Some(-7.0));
    }

    #[test]
    fn test_arithmetic_not_arithmetic() {
        assert_eq!(evaluate_arithmetic("hello"), None);
        assert_eq!(evaluate_arithmetic("42"), None);
    }

    #[test]
    fn test_arithmetic_in_template() {
        let mut ctx = HashMap::new();
        ctx.insert("session".to_string(), json!({"age": 25}));
        let result = replace_variables("#session.age + 1#", &ctx);
        assert_eq!(result, "26");
    }

    #[test]
    fn test_arithmetic_multiply_in_template() {
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), json!(100));
        let result = replace_variables("#price * 0.21#", &ctx);
        assert_eq!(result, "21");
    }

    #[test]
    fn test_arithmetic_with_filter() {
        let mut ctx = HashMap::new();
        ctx.insert("price".to_string(), json!(99.99));
        let result = replace_variables("#price * 0.21|round:2#", &ctx);
        assert_eq!(result, "21.00");
    }

    #[test]
    fn test_no_filters_still_escapes() {
        let mut ctx = HashMap::new();
        ctx.insert(
            "xss".to_string(),
            serde_json::json!("<script>alert(1)</script>"),
        );
        let result = replace_variables("#xss#", &ctx);
        assert!(!result.contains("<script>"));
        assert!(result.contains("&lt;script&gt;"));
    }

    // =========================================================================
    // Computed Variables Tests
    // =========================================================================

    #[test]
    fn test_computed_variable_parsing() {
        let content = r##"<what>
title: My Page
compute.greeting = "Hello #user.name#!"
compute.full_url = "/posts/#post.id#"
</what>
<html></html>"##;

        let (directives, _) = parse_page_directives(content);
        assert_eq!(directives.computed.len(), 2);
        assert_eq!(directives.computed[0].0, "greeting");
        assert_eq!(directives.computed[0].1, "Hello #user.name#!");
        assert_eq!(directives.computed[1].0, "full_url");
        assert_eq!(directives.computed[1].1, "/posts/#post.id#");
    }

    #[test]
    fn test_computed_variable_resolution() {
        let mut context = HashMap::new();
        context.insert(
            "user".to_string(),
            serde_json::json!({
                "name": "Alice"
            }),
        );

        let computed = vec![("greeting".to_string(), "Hello #user.name#!".to_string())];

        resolve_computed_variables(&computed, &mut context);

        assert_eq!(
            context.get("greeting"),
            Some(&serde_json::json!("Hello Alice!"))
        );
    }

    #[test]
    fn test_computed_variable_chained() {
        let mut context = HashMap::new();
        context.insert("first".to_string(), serde_json::json!("John"));
        context.insert("last".to_string(), serde_json::json!("Doe"));

        let computed = vec![
            ("full_name".to_string(), "#first# #last#".to_string()),
            ("greeting".to_string(), "Hello #full_name#!".to_string()),
        ];

        resolve_computed_variables(&computed, &mut context);

        assert_eq!(
            context.get("full_name"),
            Some(&serde_json::json!("John Doe"))
        );
        assert_eq!(
            context.get("greeting"),
            Some(&serde_json::json!("Hello John Doe!"))
        );
    }

    #[test]
    fn test_computed_variable_with_nested_path() {
        let mut context = HashMap::new();
        context.insert(
            "post".to_string(),
            serde_json::json!({
                "id": 42,
                "title": "My Post"
            }),
        );

        let computed = vec![(
            "edit_url".to_string(),
            "/admin/posts/#post.id#/edit".to_string(),
        )];

        resolve_computed_variables(&computed, &mut context);

        assert_eq!(
            context.get("edit_url"),
            Some(&serde_json::json!("/admin/posts/42/edit"))
        );
    }

    #[test]
    fn test_computed_variable_unresolved_reference() {
        let mut context = HashMap::new();

        let computed = vec![("url".to_string(), "/page/#missing_var#".to_string())];

        resolve_computed_variables(&computed, &mut context);

        // Unresolved vars stay as-is
        assert_eq!(
            context.get("url"),
            Some(&serde_json::json!("/page/#missing_var#"))
        );
    }

    #[test]
    fn test_computed_variable_no_prefix_in_template() {
        // Computed vars are available as #name# not #compute.name#
        let mut context = HashMap::new();
        context.insert("x".to_string(), serde_json::json!("world"));

        let computed = vec![("greeting".to_string(), "hello #x#".to_string())];

        resolve_computed_variables(&computed, &mut context);

        // Use in template
        let result = replace_variables("Say: #greeting#", &context);
        assert_eq!(result, "Say: hello world");
    }

    #[test]
    fn test_computed_variable_empty() {
        let mut context = HashMap::new();
        let computed: Vec<(String, String)> = Vec::new();

        resolve_computed_variables(&computed, &mut context);
        // No crash, context unchanged
        assert!(context.is_empty());
    }

    // ---- Wired Scope Parsing Tests ----

    #[test]
    fn parse_wired_no_brackets() {
        let decl = parse_wired_decl("counter");
        assert_eq!(decl.name, "counter");
        assert!(matches!(decl.scope, WiredScope::Public));
    }

    #[test]
    fn parse_wired_single_role() {
        let decl = parse_wired_decl("revenue [admin]");
        assert_eq!(decl.name, "revenue");
        match decl.scope {
            WiredScope::Roles(roles) => assert_eq!(roles, vec!["admin"]),
            _ => panic!("Expected Roles scope"),
        }
    }

    #[test]
    fn parse_wired_multi_role() {
        let decl = parse_wired_decl("x [admin, editor]");
        assert_eq!(decl.name, "x");
        match decl.scope {
            WiredScope::Roles(roles) => assert_eq!(roles, vec!["admin", "editor"]),
            _ => panic!("Expected Roles scope"),
        }
    }

    #[test]
    fn parse_wired_user_scope() {
        let decl = parse_wired_decl("notifs [user]");
        assert_eq!(decl.name, "notifs");
        assert!(matches!(decl.scope, WiredScope::User(_)));
    }

    #[test]
    fn wired_backwards_compat() {
        // data.wired = ["counter", "visitors"] without brackets → all Public
        let content = r#"data.wired = ["counter", "visitors"]"#;
        let config = parse_what_file(content);
        assert_eq!(config.data_wired.len(), 2);
        assert_eq!(config.data_wired[0].name, "counter");
        assert!(matches!(config.data_wired[0].scope, WiredScope::Public));
        assert_eq!(config.data_wired[1].name, "visitors");
        assert!(matches!(config.data_wired[1].scope, WiredScope::Public));
    }

    #[test]
    fn wired_scope_allows_public() {
        let scope = WiredScope::Public;
        assert!(scope.allows(&[], None));
        assert!(scope.allows(&["admin".into()], Some("user1")));
    }

    #[test]
    fn wired_scope_allows_role_match() {
        let scope = WiredScope::Roles(vec!["admin".into(), "editor".into()]);
        assert!(scope.allows(&["admin".into()], None));
        assert!(scope.allows(&["editor".into()], None));
        assert!(!scope.allows(&["viewer".into()], None));
        assert!(!scope.allows(&[], None));
    }

    #[test]
    fn wired_scope_allows_user_match() {
        let scope = WiredScope::User("user42".into());
        assert!(scope.allows(&[], Some("user42")));
        assert!(!scope.allows(&[], Some("user99")));
        assert!(!scope.allows(&[], None));
    }

    #[test]
    fn test_is_unquoted_string() {
        // Numbers are not unquoted strings
        assert!(!is_unquoted_string("42"));
        assert!(!is_unquoted_string("3.14"));
        assert!(!is_unquoted_string("-1"));
        // Booleans and keywords are not unquoted strings
        assert!(!is_unquoted_string("true"));
        assert!(!is_unquoted_string("false"));
        assert!(!is_unquoted_string("none"));
        assert!(!is_unquoted_string("all"));
        assert!(!is_unquoted_string("user"));
        assert!(!is_unquoted_string("None"));
        assert!(!is_unquoted_string(""));
        // Actual strings should be flagged
        assert!(is_unquoted_string("Hello World"));
        assert!(is_unquoted_string("local:items"));
        assert!(is_unquoted_string("main"));
        assert!(is_unquoted_string("/login"));
    }

    #[test]
    fn test_quoted_strings_no_warning() {
        // Quoted values should parse without warnings
        let content = r#"title: "My Page"
layout: "main"
fetch.items = "local:items"
greeting = "Hello World""#;
        let mut directives = PageDirectives::default();
        parse_directive_content(content, &mut directives);
        assert_eq!(directives.title.as_deref(), Some("My Page"));
        assert_eq!(directives.layout.as_deref(), Some("main"));
        assert_eq!(
            directives.custom.get("fetch.items").map(|s| s.as_str()),
            Some("local:items")
        );
        assert_eq!(
            directives.vars.get("greeting"),
            Some(&serde_json::json!("Hello World"))
        );
    }

    #[test]
    fn test_unquoted_numbers_and_bools_ok() {
        // Numbers and booleans should not trigger warnings
        let content = "count = 42\nprice = 9.99\nactive = true";
        let mut directives = PageDirectives::default();
        parse_directive_content(content, &mut directives);
        assert_eq!(directives.vars.get("count"), Some(&serde_json::json!(42)));
        assert_eq!(directives.vars.get("price"), Some(&serde_json::json!(9.99)));
        assert_eq!(
            directives.vars.get("active"),
            Some(&serde_json::json!(true))
        );
    }

    #[test]
    fn test_html_unescape_round_trip() {
        assert_eq!(html_unescape(&html_escape("Ben & Jerry")), "Ben & Jerry");
        assert_eq!(html_unescape(&html_escape("O'Brien")), "O'Brien");
        assert_eq!(html_unescape(&html_escape("a < b > c")), "a < b > c");
        // Author-written entity text survives the round trip un-collapsed
        assert_eq!(html_unescape(&html_escape("&lt;")), "&lt;");
        assert_eq!(html_unescape("plain"), "plain");
    }

    #[test]
    fn test_count_filter_counts_items_not_bytes() {
        let mut ctx = HashMap::new();
        ctx.insert(
            "items".to_string(),
            serde_json::json!([{"name": "a"}, {"name": "b"}, {"name": "c"}]),
        );
        ctx.insert("name".to_string(), serde_json::json!("José"));
        assert_eq!(replace_variables("#items|count#", &ctx), "3");
        assert_eq!(replace_variables("#name|count#", &ctx), "4");
    }

    #[test]
    fn test_within_one_edit() {
        assert!(within_one_edit("auth", "auth"));
        assert!(within_one_edit("auht", "auth")); // adjacent transposition
        assert!(within_one_edit("atuh", "auth")); // adjacent transposition
        assert!(within_one_edit("aut", "auth")); // deletion
        assert!(within_one_edit("auths", "auth")); // insertion
        assert!(within_one_edit("autj", "auth")); // substitution
        assert!(within_one_edit("oauth", "auth")); // deletion (filtered by first-letter guard)
        assert!(!within_one_edit("author", "auth"));
        assert!(!within_one_edit("au", "auth"));
        assert!(!within_one_edit("layout", "auth"));
    }

    #[test]
    fn test_access_directive_near_miss() {
        assert_eq!(access_directive_near_miss("auht"), Some("auth"));
        assert_eq!(access_directive_near_miss("atuh"), Some("auth"));
        assert_eq!(access_directive_near_miss("aut"), Some("auth"));
        assert_eq!(access_directive_near_miss("Auth"), Some("auth")); // case typo
        assert_eq!(access_directive_near_miss("role"), Some("roles"));
        assert_eq!(access_directive_near_miss("protectd"), Some("protected"));
        // Exact key is not a near-miss (it parses as the real directive)
        assert_eq!(access_directive_near_miss("auth"), None);
        // Different first letter: legitimate variable names near these words
        assert_eq!(access_directive_near_miss("oauth"), None);
        // Unrelated keys
        assert_eq!(access_directive_near_miss("title"), None);
        assert_eq!(access_directive_near_miss("items"), None);
    }

    #[test]
    fn test_auth_typo_key_stays_inline_var_and_page_stays_public() {
        // Documents the fail-open the near-miss warning exists for: `auht:`
        // is NOT `auth`, so the page keeps AuthLevel::All (public) and the
        // key becomes an inline variable.
        let content = r#"auht: "user""#;
        let mut directives = PageDirectives::default();
        parse_directive_content(content, &mut directives);
        assert!(matches!(directives.auth, AuthLevel::All));
        assert_eq!(directives.vars.get("auht"), Some(&serde_json::json!("user")));
    }

    #[test]
    fn test_strip_symmetric_quotes() {
        assert_eq!(strip_symmetric_quotes(r#""hello""#), ("hello", true));
        assert_eq!(strip_symmetric_quotes("'hello'"), ("hello", true));
        assert_eq!(strip_symmetric_quotes("hello"), ("hello", false));
        // Mismatched quotes are left intact
        assert_eq!(strip_symmetric_quotes(r#""hello'"#), (r#""hello'"#, false));
        // Only ONE pair is stripped (the old trim_matches stripped repeats)
        assert_eq!(strip_symmetric_quotes("''x''"), ("'x'", true));
        // Empty quoted string
        assert_eq!(strip_symmetric_quotes(r#""""#), ("", true));
        // Bare quote char is not a pair
        assert_eq!(strip_symmetric_quotes(r#"""#), (r#"""#, false));
    }

    #[test]
    fn test_quoting_forces_string_type_inline_vars() {
        // v1.0 rule: quoted values are strings, unquoted values are type-inferred.
        let content = "zip = \"01234\"\nversion = \"1.0\"\nflag = \"true\"\ncount = 42";
        let mut directives = PageDirectives::default();
        parse_directive_content(content, &mut directives);
        assert_eq!(
            directives.vars.get("zip"),
            Some(&serde_json::json!("01234")),
            "quoted leading-zero value must stay a string"
        );
        assert_eq!(
            directives.vars.get("version"),
            Some(&serde_json::json!("1.0")),
            "quoted numeric-looking value must stay a string"
        );
        assert_eq!(
            directives.vars.get("flag"),
            Some(&serde_json::json!("true")),
            "quoted boolean-looking value must stay a string"
        );
        assert_eq!(directives.vars.get("count"), Some(&serde_json::json!(42)));
    }

    #[test]
    fn test_quoting_forces_string_type_session_mutations() {
        let set = parse_session_mutation(r#"session.zip = "01234""#).unwrap();
        match set {
            SessionMutation::Set { key, value } => {
                assert_eq!(key, "zip");
                assert_eq!(value, serde_json::json!("01234"));
            }
            other => panic!("expected Set, got {:?}", other),
        }
        let set = parse_session_mutation("session.count = 42").unwrap();
        match set {
            SessionMutation::Set { value, .. } => {
                assert_eq!(value, serde_json::json!(42));
            }
            other => panic!("expected Set, got {:?}", other),
        }
        let push = parse_session_mutation(r#"session.items.push("42")"#).unwrap();
        match push {
            SessionMutation::Push { value, .. } => {
                assert_eq!(value, serde_json::json!("42"));
            }
            other => panic!("expected Push, got {:?}", other),
        }
    }

    #[test]
    fn test_mismatched_quotes_left_intact() {
        // A mismatched pair must not be silently swallowed.
        let content = "label = \"oops'";
        let mut directives = PageDirectives::default();
        parse_directive_content(content, &mut directives);
        assert_eq!(
            directives.vars.get("label"),
            Some(&serde_json::json!("\"oops'"))
        );
    }

    #[test]
    fn test_what_file_quoted_number_stays_string() {
        // application.what files already kept quoted numbers as strings — lock it.
        let config = parse_what_file("zip = \"01234\"\ncount = 7");
        assert_eq!(config.values.get("zip"), Some(&serde_json::json!("01234")));
        assert_eq!(config.values.get("count"), Some(&serde_json::json!(7)));
    }
}