esi 0.7.0-beta.4

A streaming parser and executor for Edge Side Includes
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
use bytes::Bytes;
// STREAMING parsers: for document structure (content between tags, closing tags).
// They return Incomplete when they need more data, enabling bounded-memory streaming.
use nom::bytes::streaming as streaming_bytes;
use nom::character::streaming as streaming_char;
// COMPLETE parsers: for (1) expression parsing (attribute values are fully extracted)
// and (2) re-parsing gated opening tags (esi_opening_tag guarantees all bytes are buffered).
use nom::bytes::complete::{tag, tag_no_case, take_until, take_while, take_while1};
use nom::character::complete::{multispace0, multispace1};

use nom::branch::alt;
use nom::combinator::{not, opt, peek, recognize};
use nom::error::Error;
use nom::multi::separated_list0;
use nom::sequence::{delimited, preceded, terminated};
use nom::IResult;
use nom::Parser;

use crate::literals::*;
use crate::parser_types::{DcaMode, Element, Expr, IncludeAttributes, Operator, Tag, WhenBranch};

/// Attribute list preserving duplicates (needed for `appendheader`, `setheader`, etc.).
type Attrs<'a> = Vec<(&'a str, &'a str)>;

/// Remove the *first* attribute whose key equals `name` and return its value.
fn attrs_remove<'a>(attrs: &mut Attrs<'a>, name: &str) -> Option<&'a str> {
    attrs
        .iter()
        .position(|(k, _)| *k == name)
        .map(|i| attrs.remove(i).1)
}

/// Return the value of the *first* attribute whose key equals `name`.
fn attrs_get<'a>(attrs: &'a Attrs<'_>, name: &str) -> Option<&'a str> {
    attrs.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)
}

// ============================================================================
// Zero-Copy Helpers
// ============================================================================

/// View a slice from nom parsing as a Bytes reference
/// This enables zero-copy: we calculate the slice's offset within the original
/// Bytes and return a new Bytes that references the same underlying data (just increments ref count)
#[inline]
fn slice_as_bytes(original: &Bytes, slice: &[u8]) -> Bytes {
    // Calculate the offset of the slice within the original Bytes
    let original_ptr = original.as_ptr() as usize;
    let slice_ptr = slice.as_ptr() as usize;

    // Safety check: slice must be within original's memory range
    debug_assert!(
        slice_ptr >= original_ptr && slice_ptr + slice.len() <= original_ptr + original.len(),
        "slice must be within original Bytes range"
    );

    let offset = slice_ptr - original_ptr;
    let len = slice.len();

    // Zero-copy: slice the original Bytes (just increments refcount)
    original.slice(offset..offset + len)
}

/// Helper for parsing loops that accumulate results
/// Handles the common pattern of calling a parser in a loop and accumulating elements
enum ParsingMode {
    /// Return Incomplete if no elements parsed yet, otherwise return accumulated results
    Streaming,
    /// Treat Incomplete as EOF, convert remaining bytes to Text
    Complete,
    /// Like Complete, but return error on Incomplete (document is truncated)
    Eof,
}

/// Parser output that avoids Vec allocation for single elements
/// This is a key optimization: most parsers return exactly one element,
/// so we avoid the Vec allocation overhead in the common case.
enum ParseResult {
    /// Single element (most common case - no Vec allocation)
    Single(Element),
    /// Multiple elements (for parsers that return variable number of elements)
    Multiple(Vec<Element>),
    /// No elements (for esi:comment, esi:remove that produce nothing)
    Empty,
}

impl ParseResult {
    /// Append elements to an existing Vec
    #[inline]
    fn append_to(self, acc: &mut Vec<Element>) {
        match self {
            Self::Single(e) => acc.push(e),
            Self::Multiple(mut v) => acc.append(&mut v),
            Self::Empty => {}
        }
    }
}

/// Zero-copy parse loop that threads Bytes through the parser chain
fn parse_loop<'a, F>(
    original: &'a Bytes,
    mut parser: F,
    incomplete_strategy: &ParsingMode,
) -> IResult<&'a [u8], Vec<Element>, Error<&'a [u8]>>
where
    F: FnMut(&Bytes, &'a [u8]) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>>,
{
    let mut result = Vec::with_capacity(8);
    let mut remaining = original.as_ref();

    loop {
        match parser(original, remaining) {
            Ok((rest, parse_result)) => {
                parse_result.append_to(&mut result);

                // If we consumed nothing, break to avoid infinite loop
                if rest.len() == remaining.len() {
                    return Ok((rest, result));
                }
                remaining = rest;

                // If all input consumed, return immediately — don't call the
                // parser on empty input (streaming parsers return Incomplete
                // on empty, which the Eof strategy would treat as truncation).
                if remaining.is_empty() {
                    return Ok((remaining, result));
                }
            }
            Err(nom::Err::Incomplete(needed)) => {
                return match incomplete_strategy {
                    ParsingMode::Streaming => {
                        // Return accumulated results or propagate Incomplete
                        if result.is_empty() {
                            Err(nom::Err::Incomplete(needed))
                        } else {
                            Ok((remaining, result))
                        }
                    }
                    ParsingMode::Complete => {
                        // Treat remaining bytes as text - refcount increment, zero-copy
                        if !remaining.is_empty() {
                            result.push(Element::Content(slice_as_bytes(original, remaining)));
                        }
                        Ok((&remaining[remaining.len()..], result))
                    }
                    ParsingMode::Eof => {
                        // element_eof uses a complete text parser, so Incomplete
                        // here can only come from tag_handler hitting a partial
                        // ESI tag — the document is truncated.
                        Err(nom::Err::Failure(Error::new(
                            remaining,
                            nom::error::ErrorKind::Eof,
                        )))
                    }
                };
            }
            Err(e) => {
                if result.is_empty() {
                    // Return a real parse error
                    return Err(e);
                }
                // Else - return what we have so far
                return Ok((remaining, result));
            }
        }
    }
}

// ============================================================================
// Public APIs - Zero-Copy Streaming Parsers
// ============================================================================

/// Parse input bytes into ESI elements using streaming parsers
///
/// Uses streaming parsers that return `Incomplete` when they need more data.
/// The caller (typically lib.rs) must handle `Incomplete` by reading more data into the buffer.
///
/// # Errors
/// - `Err(Incomplete)` - Parser needs more data to continue
/// - `Err(Error)` - Parse error occurred
pub fn parse(input: &Bytes) -> IResult<&[u8], Vec<Element>, Error<&[u8]>> {
    parse_loop(input, element, &ParsingMode::Streaming)
}

/// Parse remaining input when no more data will arrive (at EOF)
///
/// Uses the same streaming parsers as [`parse`], but when they return `Incomplete`,
/// treats the remaining unparseable bytes as literal text instead of requesting more data.
/// Use this when you've reached EOF and want to finalize parsing.
///
/// # Errors
/// Returns `Err` if a parse error occurs (but not `Incomplete`, which is handled internally
/// by converting unparseable remainder to `Text` elements).
pub fn parse_complete(input: &Bytes) -> IResult<&[u8], Vec<Element>, Error<&[u8]>> {
    parse_loop(input, element, &ParsingMode::Complete)
}

/// Parse input at EOF, treating incomplete ESI tags as truncation errors.
///
/// Uses a **complete** text parser so trailing non-ESI content is consumed
/// normally, while any `Incomplete` from `tag_handler` (= partial ESI tag)
/// becomes `Err(Failure(Eof))` for the caller to surface as
/// `ESIError::UnexpectedEndOfDocument`.
pub fn parse_eof(input: &Bytes) -> IResult<&[u8], Vec<Element>, Error<&[u8]>> {
    if input.is_empty() {
        return Ok((input.as_ref(), vec![]));
    }
    parse_loop(input, element_eof, &ParsingMode::Eof)
}

/// Convert ASCII bytes to String.
/// # Safety
/// All callers guarantee ASCII-only input (alphanumeric + underscore),
/// so UTF-8 validation is unnecessary.
#[inline]
fn bytes_to_string(bytes: &[u8]) -> String {
    // SAFETY: callers use take_while1(is_alphanumeric_or_underscore) or similar,
    // which only matches ASCII bytes — always valid UTF-8.
    unsafe { std::str::from_utf8_unchecked(bytes) }.to_owned()
}

// ============================================================================
// Expression Parsing - Uses COMPLETE parsers (input is always complete)
// Expressions come from attribute values which are fully extracted before parsing
// ============================================================================

/// Accepts str for convenience but works on bytes internally
pub fn parse_expression(input: &str) -> IResult<&str, Expr, Error<&str>> {
    let bytes = input.as_bytes();
    match expr(bytes) {
        Ok((remaining_bytes, expr)) => {
            let consumed = bytes.len() - remaining_bytes.len();
            Ok((&input[consumed..], expr))
        }
        Err(nom::Err::Error(e)) => Err(nom::Err::Error(Error::new(input, e.code))),
        Err(nom::Err::Failure(e)) => Err(nom::Err::Failure(Error::new(input, e.code))),
        Err(nom::Err::Incomplete(_)) => {
            // Complete parsers should never return Incomplete
            unreachable!("complete parsers don't return Incomplete")
        }
    }
}

// Used by parse_interpolated - zero-copy with original Bytes reference
fn interpolated_text<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    streaming_bytes::take_while1(|c| !is_open_bracket(c) && !is_dollar(c) && c != BACKSLASH)
        .map(|s: &[u8]| ParseResult::Single(Element::Content(slice_as_bytes(original, s))))
        .parse(input)
}

// Complete version for attribute value parsing - doesn't return Incomplete
fn interpolated_text_complete<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    take_while1(|c| !is_open_bracket(c) && !is_dollar(c) && c != BACKSLASH)
        .map(|s: &[u8]| ParseResult::Single(Element::Content(slice_as_bytes(original, s))))
        .parse(input)
}

/// Parses a string that may contain interpolated expressions like $(VAR)
/// Accepts &Bytes and returns Bytes slices that reference the original (zero-copy)
///
/// # Errors
/// Returns an error if the string contains invalid ESI expressions (e.g., unclosed $(, invalid variable names)
pub fn interpolated_content(input: &Bytes) -> IResult<&[u8], Vec<Element>, Error<&[u8]>> {
    // NOTE: This function parses complete strings (like attribute values), not streaming input
    let mut acc = Vec::with_capacity(4);
    let mut rest = input.as_ref();
    loop {
        if let Ok((r, item)) = interpolated_expression(rest) {
            item.append_to(&mut acc);
            rest = r;
        } else if let Ok((r, item)) = esi_escape_complete(input, rest) {
            item.append_to(&mut acc);
            rest = r;
        } else if let Ok((r, item)) = interpolated_text_complete(input, rest) {
            item.append_to(&mut acc);
            rest = r;
        } else {
            break;
        }
    }
    Ok((rest, acc))
}

/// Zero-copy element parser - dispatches to text or tags
/// Note: Variable expressions like $(VAR) in plain HTML are NOT evaluated - only inside ESI tags
fn element<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    // For top-level HTML content, we only parse tags, not variable expressions
    // Variable expressions are only evaluated inside ESI tags
    alt((|i| parse_text(original, i), |i| tag_handler(original, i))).parse(input)
}

/// Text parser for plain content - stops only at '<', not at '$()'
/// This ensures $(VAR) in plain HTML is treated as literal text
fn parse_text<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    streaming_bytes::take_while1(|c| !is_open_bracket(c))
        .map(|s: &[u8]| ParseResult::Single(Element::Content(slice_as_bytes(original, s))))
        .parse(input)
}

/// Complete version of [`parse_text`] for EOF parsing.
/// Returns `Ok` for trailing text instead of `Incomplete`.
fn parse_text_complete<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    take_while1(|c: u8| !is_open_bracket(c))
        .map(|s: &[u8]| ParseResult::Single(Element::Content(slice_as_bytes(original, s))))
        .parse(input)
}

/// EOF element parser — complete text + streaming tags.
///
/// Text is parsed with complete semantics (never returns `Incomplete`),
/// so any `Incomplete` from this parser is guaranteed to come from
/// `tag_handler` encountering a genuinely truncated ESI tag.
fn element_eof<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    alt((
        |i| parse_text_complete(original, i),
        |i| tag_handler(original, i),
    ))
    .parse(input)
}

fn interpolated_element<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    // Fast path: check the first byte to decide which parser to call.
    // interpolated_text stops at '<', '$', or '\', so the first byte here
    // is one of those (or we're at the start of content).
    match input.first() {
        Some(&OPEN_BRACKET) => tag_handler(original, input),
        Some(&BACKSLASH) => esi_escape(original, input),
        Some(&DOLLAR) => alt((interpolated_expression, |i| tag_handler(original, i))).parse(input),
        _ => alt((
            |i| interpolated_text(original, i),
            interpolated_expression,
            |i| tag_handler(original, i),
        ))
        .parse(input),
    }
}

// Parse a sequence of interpolated elements (text + expressions + tags)
// Used for parsing content inside tags that allow nested ESI
fn tag_content<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], Vec<Element>, Error<&'a [u8]>> {
    let mut acc = Vec::with_capacity(10);
    let mut rest = input;

    loop {
        match interpolated_element(original, rest) {
            Ok((r, item)) => {
                item.append_to(&mut acc);
                if r.len() == rest.len() {
                    break;
                }
                rest = r;
            }
            Err(nom::Err::Incomplete(needed)) => return Err(nom::Err::Incomplete(needed)),
            Err(_) => break,
        }
    }

    Ok((rest, acc))
}

/// Validates a variable name according to ESI spec:
/// - Up to 256 alphanumeric characters (A-Z, a-z, 0-9)
/// - Can include underscores (_)
/// - Cannot start with $ (dollar sign) or digit
/// - First character must be alphabetic (A-Z, a-z)
/// - Can include subscript notation with braces {} containing expressions
fn is_valid_variable_name(name: &str) -> bool {
    if name.is_empty() || name.len() > 256 {
        return false;
    }

    // Check if there's a subscript by finding opening brace
    if let Some(brace_pos) = name.find('{') {
        // Has subscript - validate base name and check brace matching
        let base_name = &name[..brace_pos];

        // Validate base name strictly (alphanumeric + underscore, starting with alpha)
        if !is_valid_base_variable_name(base_name) {
            return false;
        }

        // Check that subscript has matching closing brace
        if !name.ends_with('}') {
            return false;
        }

        // Subscript content (between braces) can contain any characters for expressions
        // We don't validate it here - expression parser will handle it
        true
    } else {
        // No subscript - validate as a simple variable name
        is_valid_base_variable_name(name)
    }
}

/// Validates a base variable name (without subscripts):
/// - Must start with alphabetic character
/// - Can only contain ASCII alphanumeric characters and underscores
///   (per ESI spec, variable names are ASCII-only \[A-Z a-z 0-9\])
fn is_valid_base_variable_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    match bytes.first() {
        Some(b) if b.is_ascii_alphabetic() => {}
        _ => return false,
    }
    // Remaining characters must be ASCII alphanumeric or underscore
    bytes[1..]
        .iter()
        .all(|b| b.is_ascii_alphanumeric() || *b == UNDERSCORE)
}

// Parse variable name with optional subscript like "colors{0}" or "ages{joan}"
fn parse_variable_name_with_subscript(name: &str) -> (String, Option<Expr>) {
    if let Some(brace_pos) = name.find('{') {
        if name.ends_with('}') {
            let var_name = &name[..brace_pos];
            let subscript_str = &name[brace_pos + 1..name.len() - 1];

            // Try to parse the subscript as an expression
            // Check different patterns:
            let subscript_expr = subscript_str.parse::<i32>().map_or_else(
                |_| {
                    if subscript_str
                        .bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b == UNDERSCORE)
                    {
                        // Bare identifier like "joan" - treat as string literal key
                        Some(Expr::String(Some(Bytes::copy_from_slice(
                            subscript_str.as_bytes(),
                        ))))
                    } else if let Ok((_, expr)) = parse_expression(subscript_str) {
                        // Successfully parsed as expression (e.g., "'key'", "$(var)", complex expression)
                        Some(expr)
                    } else {
                        // Failed to parse - ignore subscript
                        None
                    }
                },
                |num| Some(Expr::Integer(num)),
            );

            if let Some(expr) = subscript_expr {
                return (var_name.to_string(), Some(expr));
            }
        }
    }
    (name.to_string(), None)
}

fn esi_assign<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    alt((esi_assign_short, |i| esi_assign_long(original, i))).parse(input)
}

fn assign_attributes_short(mut attrs: Attrs<'_>) -> ParseResult {
    let name = attrs_remove(&mut attrs, "name").unwrap_or_default();

    // Validate variable name according to ESI spec
    if !is_valid_variable_name(name) {
        // Invalid name - silently drop this tag per ESI spec for invalid constructs
        // ParseResult::Empty causes the parser to consume the tag but emit nothing
        return ParseResult::Empty;
    }

    // Parse name and optional subscript (e.g., "colors{0}" or "ages{joan}")
    let (var_name, subscript) = parse_variable_name_with_subscript(name);

    let value_str = attrs_remove(&mut attrs, "value").unwrap_or_default();

    // Per ESI spec, short form value attribute contains an expression
    // Try to parse as ESI expression. If it fails, treat as string literal.
    let value = match parse_expression(value_str) {
        Ok((_, expr)) => expr,
        Err(_) => {
            // If parsing fails (e.g., plain text), treat as a string literal
            Expr::String(Some(Bytes::copy_from_slice(value_str.as_bytes())))
        }
    };

    ParseResult::Single(Element::Esi(Tag::Assign {
        name: var_name,
        subscript,
        value,
    }))
}

/// Parse an attribute value as an ESI expression
/// Used for parsing src/alt/param values which can contain variables, functions, etc.
/// Examples:
///
///   - "`simple_string`" -> `Expr::String(Some("simple_string"))`
///   - "`$(VARIABLE)`" -> `Expr::Variable("VARIABLE", ...)`
///   - "`http://example.com/?q=$(QUERY_STRING{'query'})`" -> `Expr::Interpolated([Text, Expr])`
fn parse_attr_as_expr(value_str: &str) -> Expr {
    // Fast-path: empty string
    if value_str.is_empty() {
        return Expr::String(Some(Bytes::new()));
    }

    // Try to parse as pure ESI expression first (variables/functions/quoted strings/integers/dict/list literals)
    if let Ok((remaining, expr)) = parse_expression(value_str) {
        // Only accept if we consumed the entire string (pure expression)
        if remaining.is_empty() {
            return expr;
        }
    }

    // Not a pure expression - try interpolation (mixed text + expressions)
    let bytes = Bytes::copy_from_slice(value_str.as_bytes());
    match interpolated_content(&bytes) {
        Ok(([], elements)) => {
            if elements.len() == 1 {
                match elements.into_iter().next().unwrap() {
                    Element::Expr(expr) => expr,
                    Element::Content(text) => Expr::String(Some(text)),
                    _ => Expr::String(Some(bytes.clone())),
                }
            } else if !elements.is_empty() {
                Expr::Interpolated(elements)
            } else {
                Expr::String(Some(Bytes::new()))
            }
        }
        _ => Expr::String(Some(bytes.clone())),
    }
}

fn assign_long(attrs: &Attrs<'_>, mut content: Vec<Element>) -> ParseResult {
    let name = attrs_get(attrs, "name").unwrap_or_default();

    // Validate variable name according to ESI spec
    if !is_valid_variable_name(name) {
        // Invalid name - silently drop this tag per ESI spec for invalid constructs
        // ParseResult::Empty causes the parser to consume the tag but emit nothing
        return ParseResult::Empty;
    }

    // Parse name and optional subscript (e.g., "colors{0}" or "ages{joan}")
    let (var_name, subscript) = parse_variable_name_with_subscript(name);

    // Per ESI spec, long form value comes from content between tags
    // Content is already parsed as Vec<Element> (can be text, expressions, etc.)
    // We need to convert it to a single expression
    let value = if content.is_empty() {
        // Empty content - empty string
        Expr::String(Some(Bytes::new()))
    } else if content.len() == 1 {
        // Single element - pop to take ownership
        match content.pop().expect("checked len == 1") {
            Element::Expr(expr) => expr,
            Element::Content(text) => {
                // Try to parse the text as an expression
                match std::str::from_utf8(text.as_ref()) {
                    Ok(text_str) => match parse_expression(text_str) {
                        Ok((_, expr)) => expr,
                        Err(_) => Expr::String(Some(text)),
                    },
                    Err(_) => Expr::String(Some(text)),
                }
            }
            _ => {
                // HTML or other - treat as empty string
                Expr::String(Some(Bytes::new()))
            }
        }
    } else {
        // Multiple elements - this is a compound expression per ESI spec
        // Examples: <esi:assign name="x">prefix$(VAR)suffix</esi:assign>
        //           <esi:assign name="y">$(A) + $(B)</esi:assign>
        // Store the elements as-is for runtime evaluation
        Expr::Interpolated(content)
    };

    ParseResult::Single(Element::Esi(Tag::Assign {
        name: var_name,
        subscript,
        value,
    }))
}

fn esi_assign_short(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_ASSIGN_OPEN),
        attributes,
        preceded(multispace0, self_closing),
    )
    .map(assign_attributes_short)
    .parse(input)
}

fn esi_assign_long<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    // Per ESI spec, esi:assign cannot contain nested ESI tags - only text and expressions
    // Capture content first with take_until, then parse as complete
    (
        delimited(
            tag(TAG_ESI_ASSIGN_OPEN),
            attributes,
            preceded(multispace0, close_bracket),
        ),
        streaming_bytes::take_until(TAG_ESI_ASSIGN_CLOSE),
        streaming_bytes::tag(TAG_ESI_ASSIGN_CLOSE),
    )
        .map(|(attrs, content, _)| {
            // Parse the captured content in complete mode (text + expressions only)
            let elements = parse_content_complete(original, content);
            assign_long(&attrs, elements)
        })
        .parse(input)
}

// ============================================================================
// Generic Container Tag Parser
// ============================================================================

/// Generic parser for container tags (tags with opening/closing pairs and content)
/// This reduces duplication for tags like <esi:attempt>, <esi:except>, <esi:otherwise>
fn parse_container_tag<'a>(
    original: &Bytes,
    input: &'a [u8],
    opening_tag: &'static [u8],
    closing_tag: &'static [u8],
    constructor: impl FnOnce(Vec<Element>) -> Tag,
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    let (input, content) = delimited(
        tag(opening_tag), // complete: opening tag is gated
        |i| tag_content(original, i),
        streaming_bytes::tag(closing_tag), // streaming: closing tag not gated
    )
    .parse(input)?;

    Ok((
        input,
        ParseResult::Single(Element::Esi(constructor(content))),
    ))
}

fn esi_except<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    parse_container_tag(
        original,
        input,
        TAG_ESI_EXCEPT_OPEN,
        TAG_ESI_EXCEPT_CLOSE,
        Tag::Except,
    )
}

fn esi_attempt<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    parse_container_tag(
        original,
        input,
        TAG_ESI_ATTEMPT_OPEN,
        TAG_ESI_ATTEMPT_CLOSE,
        Tag::Attempt,
    )
}

/// Parse <esi:try> which contains multiple <esi:attempt> and an optional <esi:except>
///
/// Per ESI spec, <esi:try> can contain multiple <esi:attempt> blocks and at most one <esi:except> block.
/// We parse the entire content of <esi:try> and then separate out the attempts and except blocks to construct the Try tag.
fn esi_try<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    let (input, _) = tag(TAG_ESI_TRY_OPEN).parse(input)?;
    let (input, v) = tag_content(original, input)?;
    let (input, _) = streaming_bytes::tag(TAG_ESI_TRY_CLOSE).parse(input)?;

    let mut attempts = Vec::with_capacity(v.len());
    let mut except = None;
    for element in v {
        match element {
            Element::Esi(Tag::Attempt(cs)) => attempts.push(cs),
            Element::Esi(Tag::Except(cs)) => {
                except = Some(cs);
            }
            _ => {} // Ignore content outside attempt/except blocks
        }
    }
    Ok((
        input,
        ParseResult::Single(Element::Esi(Tag::Try {
            attempt_events: attempts,
            except_events: except.unwrap_or_default(),
        })),
    ))
}

fn esi_otherwise<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    delimited(
        tag(TAG_ESI_OTHERWISE_OPEN),
        |i| tag_content(original, i),
        streaming_bytes::tag(TAG_ESI_OTHERWISE_CLOSE),
    )
    .map(|mut content| {
        // Reuse content Vec — insert marker at front instead of creating a new Vec
        content.insert(0, Element::Esi(Tag::Otherwise));
        ParseResult::Multiple(content)
    })
    .parse(input)
}

fn esi_when<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    (
        delimited(
            tag(TAG_ESI_WHEN_OPEN),
            attributes,
            preceded(multispace0, alt((close_bracket, self_closing))),
        ),
        |i| tag_content(original, i),
        streaming_bytes::tag(TAG_ESI_WHEN_CLOSE),
    )
        .map(|(mut attrs, content, _)| {
            let test = attrs_remove(&mut attrs, "test")
                .unwrap_or_default()
                .to_owned();
            let match_name = attrs_remove(&mut attrs, "matchname").map(ToOwned::to_owned);

            // Reuse content Vec — insert marker at front instead of creating a new Vec
            let mut result = content;
            result.insert(0, Element::Esi(Tag::When { test, match_name }));
            ParseResult::Multiple(result)
        })
        .parse(input)
}

/// Parse <esi:foreach collection="..." item="...">...</esi:foreach>
fn esi_foreach<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    (
        delimited(
            tag(TAG_ESI_FOREACH_OPEN),
            attributes,
            preceded(multispace0, close_bracket),
        ),
        |i| tag_content(original, i),
        streaming_bytes::tag(TAG_ESI_FOREACH_CLOSE),
    )
        .map(|(mut attrs, content, _)| {
            let collection_str = attrs_remove(&mut attrs, "collection").unwrap_or_default();
            let collection = parse_attr_as_expr(collection_str);
            let item = attrs_remove(&mut attrs, "item").map(ToOwned::to_owned);

            ParseResult::Single(Element::Esi(Tag::Foreach {
                collection,
                item,
                content,
            }))
        })
        .parse(input)
}

/// Parse <esi:break />
fn esi_break(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(tag(TAG_ESI_BREAK_OPEN), multispace0, self_closing)
        .map(|_| ParseResult::Single(Element::Esi(Tag::Break)))
        .parse(input)
}

/// Parse <esi:function name="...">...</esi:function>
///
/// Per ESI spec, the content of <esi:function> is treated as a literal string and not parsed for nested tags or expressions.
/// However, we still need to capture the content as a Bytes slice for runtime evaluation.
/// We use `tag_content` to capture the raw content bytes without parsing nested tags,
/// and then construct the Function tag with the name and raw body.
fn esi_function_tag<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    (
        delimited(
            tag(TAG_ESI_FUNCTION_OPEN),
            attributes,
            preceded(multispace0, close_bracket),
        ),
        |i| tag_content(original, i),
        streaming_bytes::tag(TAG_ESI_FUNCTION_CLOSE),
    )
        .map(|(mut attrs, body, _)| {
            let name = attrs_remove(&mut attrs, "name")
                .unwrap_or_default()
                .to_owned();

            ParseResult::Single(Element::Esi(Tag::Function { name, body }))
        })
        .parse(input)
}

/// Parse <esi:return value="..." />
fn esi_return(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_RETURN_OPEN),
        attributes,
        preceded(multispace0, self_closing),
    )
    .map(|mut attrs| {
        let value_str = attrs_remove(&mut attrs, "value").unwrap_or_default();
        let value = parse_attr_as_expr(value_str);

        ParseResult::Single(Element::Esi(Tag::Return { value }))
    })
    .parse(input)
}

/// Parse <esi:choose> which contains multiple <esi:when> and an optional <esi:otherwise>
///
/// Per ESI spec, <esi:choose> can contain multiple <esi:when> blocks and at most one <esi:otherwise> block.
/// We parse the entire content of <esi:choose> and then separate out the when branches and otherwise block to construct the Choose tag.
fn esi_choose<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    let (input, _) = tag(TAG_ESI_CHOOSE_OPEN).parse(input)?;
    let (input, v) = tag_content(original, input)?;
    let (input, _) = streaming_bytes::tag(TAG_ESI_CHOOSE_CLOSE).parse(input)?;

    let mut when_branches = Vec::with_capacity(v.len());
    let mut otherwise_events = Vec::new();
    let mut current_when: Option<WhenBranch> = None;
    let mut in_otherwise = false;

    for element in v {
        match element {
            Element::Esi(Tag::When { test, match_name }) => {
                // Save any previous when
                if let Some(when_branch) = current_when.take() {
                    when_branches.push(when_branch);
                }
                in_otherwise = false;

                // Parse the test expression now, at parse time (not at eval time)
                let test_expr = match parse_expression(&test) {
                    Ok((_, expr)) => expr,
                    Err(_) => {
                        // If parsing fails, create a simple false expression
                        // This matches the behavior of treating parse failures gracefully
                        Expr::Integer(0)
                    }
                };

                // Start collecting for this new when
                current_when = Some(WhenBranch {
                    test: test_expr,
                    match_name,
                    content: Vec::new(),
                });
            }
            Element::Esi(Tag::Otherwise) => {
                // Save any pending when
                if let Some(when_branch) = current_when.take() {
                    when_branches.push(when_branch);
                }
                in_otherwise = true;
            }
            _ => {
                // Accumulate content for the current when or otherwise
                if in_otherwise {
                    otherwise_events.push(element);
                } else if let Some(ref mut when_branch) = current_when {
                    when_branch.content.push(element);
                }
                // Content outside when/otherwise blocks is discarded (per ESI spec)
            }
        }
    }

    // Don't forget the last when if there is one
    if let Some(when_branch) = current_when {
        when_branches.push(when_branch);
    }

    Ok((
        input,
        ParseResult::Single(Element::Esi(Tag::Choose {
            when_branches,
            otherwise_events,
        })),
    ))
}

// Note: <esi:vars> does NOT create a Tag::Vars element. Instead, it parses the content
// (either the body of <esi:vars>...</esi:vars> or the name attribute of <esi:vars name="..."/>)
// and returns the evaluated content directly as Vec<Element>. These elements (Text, Expr, Html, etc.)
// are then flattened into the main element stream and processed normally by process_elements() in lib.rs.
fn esi_vars<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    alt((esi_vars_short, |i| esi_vars_long(original, i))).parse(input)
}

fn parse_vars_attributes(mut attrs: Attrs<'_>) -> Result<ParseResult, &'static str> {
    attrs_remove(&mut attrs, "name").map_or_else(
        || Err("no name field in short form vars"),
        |name_val| {
            if let Ok((_, expr)) = parse_expression(name_val) {
                Ok(ParseResult::Single(Element::Expr(expr)))
            } else {
                Err("failed to parse expression")
            }
        },
    )
}

fn esi_vars_short(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_VARS_OPEN),
        attributes,
        preceded(multispace0, self_closing), // Short form must be self-closing per ESI spec
    )
    .map_res(parse_vars_attributes)
    .parse(input)
}

/// Parse content for tags that don't support nested ESI (text + expressions only)
/// Uses COMPLETE mode - input must be captured entirely before calling this
/// Parses: text and expressions ($...)
/// Does NOT parse: nested ESI tags or HTML tags (treated as literal text)
fn parse_content_complete(original: &Bytes, content: &[u8]) -> Vec<Element> {
    // Parse content using complete parsers
    let mut elements = Vec::new();
    let mut remaining = content;

    while !remaining.is_empty() {
        // Try backslash escape first
        if let Ok((rest, result)) = esi_escape_complete(original, remaining) {
            result.append_to(&mut elements);
            remaining = rest;
            continue;
        }

        // Try expression first (starts with $)
        if let Ok((rest, result)) = interpolated_expression(remaining) {
            result.append_to(&mut elements);
            remaining = rest;
            continue;
        }

        // Try text (stops at $, \) — reuses interpolated_text_complete
        if let Ok((rest, result)) = interpolated_text_complete(original, remaining) {
            result.append_to(&mut elements);
            remaining = rest;
            continue;
        }

        // Fallback: consume one byte as text if nothing else matches
        // This handles stray $ or < characters that aren't valid expressions
        elements.push(Element::Content(slice_as_bytes(original, &remaining[..1])));
        remaining = &remaining[1..];
    }

    elements
}

fn esi_vars_long<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    // esi:vars supports nested ESI tags (like esi:assign) per common usage patterns
    let (input, _) = tag(TAG_ESI_VARS_OPEN_COMPLETE).parse(input)?;
    let (input, elements) = tag_content(original, input)?;
    let (input, _) = streaming_bytes::tag(TAG_ESI_VARS_CLOSE).parse(input)?;

    Ok((input, ParseResult::Multiple(elements)))
}

fn esi_comment(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_COMMENT_OPEN),
        attributes,
        preceded(multispace0, self_closing), // ESI comment must be self-closing per ESI spec
    )
    .map(|_| ParseResult::Empty)
    .parse(input)
}

/// Zero-copy esi:remove parser
/// Per ESI spec, esi:remove content is discarded - no nested ESI processing needed
fn esi_remove(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    let (input, _) = tag(TAG_ESI_REMOVE_OPEN).parse(input)?;
    let (input, _) = streaming_bytes::take_until(TAG_ESI_REMOVE_CLOSE).parse(input)?;
    let (input, _) = streaming_bytes::tag(TAG_ESI_REMOVE_CLOSE).parse(input)?;
    Ok((input, ParseResult::Empty))
}

fn esi_text<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    delimited(
        tag(TAG_ESI_TEXT_OPEN),
        streaming_bytes::take_until(TAG_ESI_TEXT_CLOSE),
        streaming_bytes::tag(TAG_ESI_TEXT_CLOSE),
    )
    .map(|v| ParseResult::Single(Element::Content(slice_as_bytes(original, v))))
    .parse(input)
}
fn esi_include(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    alt((esi_include_self_closing, esi_include_with_params)).parse(input)
}

/// Helper to extract include attributes from the attribute list
fn extract_include_attrs(mut attrs: Attrs<'_>, params: Vec<(String, Expr)>) -> IncludeAttributes {
    let src = parse_attr_as_expr(attrs_remove(&mut attrs, "src").unwrap_or_default());
    let alt = attrs_remove(&mut attrs, "alt").map(parse_attr_as_expr);
    let continue_on_error = attrs_get(&attrs, "onerror").is_some_and(|v| v == "continue");

    // Parse dca attribute - default to None
    let dca = if attrs_get(&attrs, "dca").is_some_and(|v| v.eq_ignore_ascii_case("esi")) {
        DcaMode::Esi
    } else {
        DcaMode::None
    };

    let ttl = attrs_remove(&mut attrs, "ttl").map(ToOwned::to_owned);
    let maxwait = attrs_remove(&mut attrs, "maxwait").and_then(|s| s.parse::<u32>().ok());
    let no_store = attrs_get(&attrs, "no-store").is_some_and(|v| v.eq_ignore_ascii_case("on"));
    let method = attrs_remove(&mut attrs, "method").map(parse_attr_as_expr);
    let entity = attrs_remove(&mut attrs, "entity").map(parse_attr_as_expr);

    // Parse header manipulation attributes — duplicates are now preserved.
    // The full attribute value is stored as a single Expr and split into
    // "name: value" at runtime, supporting dynamic header names per ESI spec.
    let mut appendheaders = Vec::new();
    let mut setheaders = Vec::new();
    let mut removeheaders = Vec::new();

    for (key, value) in &attrs {
        if key.starts_with("appendheader") {
            appendheaders.push(parse_attr_as_expr(value));
        } else if key.starts_with("setheader") {
            setheaders.push(parse_attr_as_expr(value));
        } else if key.starts_with("removeheader") {
            removeheaders.push(parse_attr_as_expr(value));
        }
    }

    IncludeAttributes {
        src,
        alt,
        continue_on_error,
        dca,
        ttl,
        maxwait,
        no_store,
        method,
        entity,
        appendheaders,
        removeheaders,
        setheaders,
        params,
    }
}

fn esi_include_self_closing(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_INCLUDE_OPEN),
        attributes,
        preceded(multispace0, self_closing),
    )
    .map(|attrs| {
        let attrs = extract_include_attrs(attrs, Vec::new());

        ParseResult::Single(Element::Esi(Tag::Include { attrs }))
    })
    .parse(input)
}

fn esi_include_with_params(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    let (rest, attrs) = delimited(
        tag(TAG_ESI_INCLUDE_OPEN),
        attributes,
        preceded(multispace0, close_bracket),
    )
    .parse(input)?;
    let mut params = Vec::new();
    let mut rest = rest;
    loop {
        match streaming_char::multispace0::<_, Error<&[u8]>>(rest) {
            Err(nom::Err::Incomplete(needed)) => return Err(nom::Err::Incomplete(needed)),
            Err(_) => break,
            Ok((r, _)) => match esi_param(r) {
                Ok((r, param)) => {
                    params.push(param);
                    rest = r;
                }
                Err(nom::Err::Incomplete(needed)) => return Err(nom::Err::Incomplete(needed)),
                Err(_) => break,
            },
        }
    }
    let (rest, _) = preceded(
        streaming_char::multispace0,
        streaming_bytes::tag(TAG_ESI_INCLUDE_CLOSE),
    )
    .parse(rest)?;
    let attrs = extract_include_attrs(attrs, params);
    Ok((
        rest,
        ParseResult::Single(Element::Esi(Tag::Include { attrs })),
    ))
}

/// Parse <esi:eval> tag - similar to include but always evaluates as ESI
/// Note: eval does NOT support alt attribute - use try/except instead
fn esi_eval(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    alt((esi_eval_self_closing, esi_eval_with_params)).parse(input)
}

fn esi_eval_self_closing(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    delimited(
        tag(TAG_ESI_EVAL_OPEN),
        attributes,
        preceded(multispace0, self_closing),
    )
    .map(|attrs| {
        let mut attrs = extract_include_attrs(attrs, Vec::new());
        // Eval does not support alt - clear it if somehow present
        attrs.alt = None;

        ParseResult::Single(Element::Esi(Tag::Eval { attrs }))
    })
    .parse(input)
}

fn esi_eval_with_params(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    let (rest, attrs) = delimited(
        tag(TAG_ESI_EVAL_OPEN),
        attributes,
        preceded(multispace0, close_bracket),
    )
    .parse(input)?;
    let mut params = Vec::new();
    let mut rest = rest;
    loop {
        match streaming_char::multispace0::<_, Error<&[u8]>>(rest) {
            Err(nom::Err::Incomplete(needed)) => return Err(nom::Err::Incomplete(needed)),
            Err(_) => break,
            Ok((r, _)) => match esi_param(r) {
                Ok((r, param)) => {
                    params.push(param);
                    rest = r;
                }
                Err(nom::Err::Incomplete(needed)) => return Err(nom::Err::Incomplete(needed)),
                Err(_) => break,
            },
        }
    }
    let (rest, _) = preceded(
        streaming_char::multispace0,
        streaming_bytes::tag(TAG_ESI_EVAL_CLOSE),
    )
    .parse(rest)?;
    let mut attrs = extract_include_attrs(attrs, params);
    attrs.alt = None;
    Ok((rest, ParseResult::Single(Element::Esi(Tag::Eval { attrs }))))
}

fn esi_param(input: &[u8]) -> IResult<&[u8], (String, Expr), Error<&[u8]>> {
    // Streaming gate: ensure the full <esi:param ... > or <esi:param ... /> is available
    let (after, _) = esi_opening_tag(input)?;
    let tag_slice = &input[..input.len() - after.len()];

    // Complete parse of the gated tag content
    let (_, mut attrs) = delimited(
        tag(TAG_ESI_PARAM_OPEN),
        attributes,
        preceded(
            multispace0,
            alt((tag(TAG_SELF_CLOSE), tag(&[CLOSE_BRACKET] as &[u8]))),
        ),
    )
    .parse(tag_slice)?;

    let name = attrs_remove(&mut attrs, "name")
        .unwrap_or_default()
        .to_owned();
    let value = parse_attr_as_expr(attrs_remove(&mut attrs, "value").unwrap_or_default());
    Ok((after, (name, value)))
}

/// Parse tag attributes (complete mode — caller must ensure full tag is available).
/// Returns a `Vec` so that duplicate attribute names (e.g. multiple `setheader`)
/// are preserved, matching the ESI spec.
fn attributes(input: &[u8]) -> IResult<&[u8], Attrs<'_>, Error<&[u8]>> {
    let mut acc = Vec::new();
    let mut rest = input;
    loop {
        let Ok((r, _)) = multispace1::<_, Error<&[u8]>>(rest) else {
            break;
        };
        let Ok((r, k)): Result<_, nom::Err<Error<&[u8]>>> =
            take_while1(|c: u8| c.is_ascii_alphanumeric() || c == b'-').parse(r)
        else {
            break;
        };
        let Ok((r, _)): Result<_, nom::Err<Error<&[u8]>>> = tag(EQUALS).parse(r) else {
            break;
        };
        let Ok((r, v)) = htmlstring(r) else { break };
        // SAFETY: key parser only allows ASCII attribute-name bytes
        let key = unsafe { std::str::from_utf8_unchecked(k) };
        // Values come from htmlstring (arbitrary quoted content) — must validate
        if let Ok(val) = std::str::from_utf8(v) {
            acc.push((key, val));
        }
        rest = r;
    }
    Ok((rest, acc))
}

/// Parse a quoted attribute value (complete mode — caller must ensure full tag is available).
fn htmlstring(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    alt((
        delimited(
            tag(&[DOUBLE_QUOTE] as &[u8]),
            take_while(|c: u8| !is_double_quote(c)),
            tag(&[DOUBLE_QUOTE] as &[u8]),
        ),
        delimited(
            tag(&[SINGLE_QUOTE] as &[u8]),
            take_while(|c: u8| !is_single_quote(c)),
            tag(&[SINGLE_QUOTE] as &[u8]),
        ),
    ))
    .parse(input)
}

// ============================================================================
// Zero-Copy HTML/Text Parsers
// ============================================================================

// -- Complete-mode helpers (for re-parsing gated opening tags) ----------------

/// Complete: consume the closing '>' character
#[inline]
fn close_bracket(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    tag(&[CLOSE_BRACKET] as &[u8]).parse(input)
}

/// Complete: consume the self-closing '/>' sequence
#[inline]
fn self_closing(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    tag(TAG_SELF_CLOSE).parse(input)
}

// -- Streaming-mode helpers (for ungated content / closing tags) --------------

/// Streaming: consume the closing '>' character
#[inline]
fn streaming_close_bracket(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    streaming_bytes::tag(&[CLOSE_BRACKET] as &[u8]).parse(input)
}

/// Helper to find and consume the opening '<' character
#[inline]
fn streaming_open_bracket(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    streaming_bytes::tag(&[OPEN_BRACKET] as &[u8]).parse(input)
}

/// Check if byte is an opening bracket '<'
#[inline]
const fn is_close_bracket(b: u8) -> bool {
    b == CLOSE_BRACKET
}

/// Check if byte is a double quote '"'
#[inline]
const fn is_double_quote(b: u8) -> bool {
    b == DOUBLE_QUOTE
}

/// Check if byte is a single quote '\''
#[inline]
const fn is_single_quote(b: u8) -> bool {
    b == SINGLE_QUOTE
}

/// Check if byte can start a tag name (alphanumeric or `!` for comments/DOCTYPE)
#[inline]
const fn is_tag_start(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == EXCLAMATION
}

/// Check if byte can continue a tag name
/// Covers ESI (`esi:include` → colon), HTML custom elements (`my-component` → hyphen),
/// and underscores for safety. Unknown tags become opaque `Element::Html` blobs.
#[inline]
const fn is_tag_cont(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, HYPHEN | UNDERSCORE | COLON)
}

/// Parse an HTML/XML-style tag name.
/// Returns the subslice of the original input containing only the tag name.
#[inline]
fn tag_name(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    recognize((
        streaming_bytes::take_while_m_n(1, 1, is_tag_start), // first letter
        streaming_bytes::take_while(is_tag_cont),            // rest of name
    ))
    .parse(input)
}

/// Streaming: skip forward past attribute content, respecting quoted strings.
/// Stops at (but does not consume) the first unquoted `>`.
/// Returns `Incomplete` if input ends before finding an unquoted `>`.
fn skip_tag_attrs(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    let mut i = 0;
    while i < input.len() {
        match input[i] {
            CLOSE_BRACKET => return Ok((&input[i..], &input[..i])),
            DOUBLE_QUOTE | SINGLE_QUOTE => {
                let quote = input[i];
                i += 1;
                while i < input.len() && input[i] != quote {
                    i += 1;
                }
                if i >= input.len() {
                    return Err(nom::Err::Incomplete(nom::Needed::Unknown));
                }
                i += 1; // skip closing quote
            }
            _ => i += 1,
        }
    }
    Err(nom::Err::Incomplete(nom::Needed::Unknown))
}

/// Parse a complete opening tag (streaming gate)
/// Ensures the tag is fully available before dispatching to downstream
/// complete parsers. Respects quoted strings (skips `>` inside quotes).
/// Returns (`remaining_input`, (`tag_name`, `full_tag_slice`))
#[allow(clippy::type_complexity)]
fn esi_opening_tag(input: &[u8]) -> IResult<&[u8], (&[u8], &[u8]), Error<&[u8]>> {
    let start = input;

    // Parse <tagname
    let (rest, _) = streaming_open_bracket(input)?;
    let (rest, name) = tag_name(rest)?;

    // Skip attributes, respecting quoted strings
    let (rest, _) = skip_tag_attrs(rest)?;

    // Must have > to be complete
    let (rest, _) = streaming_close_bracket(rest)?;

    Ok((rest, (name, start)))
}

// ============================================================================
// Unified Tag Dispatcher
// ============================================================================

/// Single dispatcher for ALL tags - ESI, HTML script, comments, regular HTML
/// Parses tag name once, then dispatches to specific handlers
fn tag_handler<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    alt((
        // Try HTML comment first (special syntax `<!--`)
        |i| html_comment_content(original, i),
        // Try closing tag (starts with `</`)
        |i| closing_tag(original, i),
        // Try opening tags (parses tag name once, then dispatches)
        |i| {
            // First, parse the complete opening tag (including >)
            // This ensures we don't dispatch on partial tag names like "esi:ass"
            let (rest, (name, start)) = esi_opening_tag(i)?;
            // Dispatch based on tag name without re-parsing
            match name {
                // ESI tags - pass start position to parse from <esi:tagname
                TAG_NAME_ESI_ASSIGN => esi_assign(original, start),
                TAG_NAME_ESI_INCLUDE => esi_include(start),
                TAG_NAME_ESI_EVAL => esi_eval(start),
                TAG_NAME_ESI_VARS => esi_vars(original, start),
                TAG_NAME_ESI_COMMENT => esi_comment(start),
                TAG_NAME_ESI_REMOVE => esi_remove(start),
                TAG_NAME_ESI_TEXT => esi_text(original, start),
                TAG_NAME_ESI_CHOOSE => esi_choose(original, start),
                TAG_NAME_ESI_TRY => esi_try(original, start),
                TAG_NAME_ESI_WHEN => esi_when(original, start),
                TAG_NAME_ESI_OTHERWISE => esi_otherwise(original, start),
                TAG_NAME_ESI_ATTEMPT => esi_attempt(original, start),
                TAG_NAME_ESI_EXCEPT => esi_except(original, start),
                TAG_NAME_ESI_FOREACH => esi_foreach(original, start),
                TAG_NAME_ESI_BREAK => esi_break(start),
                TAG_NAME_ESI_FUNCTION => esi_function_tag(original, start),
                TAG_NAME_ESI_RETURN => esi_return(start),

                // Special HTML tags - pass start to re-parse from beginning
                // (script needs to check attributes, so easier to re-parse than continue)
                _ if name.eq_ignore_ascii_case(TAG_NAME_SCRIPT) => html_script_tag(original, start),

                // Regular HTML tag - continue parsing from where we left off
                _ => {
                    let full_tag = &start[..start.len() - rest.len()];
                    Ok((
                        rest,
                        ParseResult::Single(Element::Html(slice_as_bytes(original, full_tag))),
                    ))
                }
            }
        },
    ))
    .parse(input)
}

/// Parse HTML comment - input starts at <!--
fn html_comment_content<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    let start = input;
    let (rest, _) = delimited(
        streaming_bytes::tag(HTML_COMMENT_OPEN),
        streaming_bytes::take_until(HTML_COMMENT_CLOSE),
        streaming_bytes::tag(HTML_COMMENT_CLOSE),
    )
    .parse(input)?;
    let full_comment = &start[..start.len() - rest.len()];
    Ok((
        rest,
        ParseResult::Single(Element::Html(slice_as_bytes(original, full_comment))),
    ))
}

/// Helper to find closing script tag, handling any content including other closing tags
/// Looks for </script (case insensitive) and returns content before it  
fn script_content(input: &[u8]) -> IResult<&[u8], &[u8], Error<&[u8]>> {
    // recognize(many_till(take(1usize), peek(tag_no_case(TAG_SCRIPT_CLOSE)))).parse(input)
    // Scan for </script (case insensitive) - much faster than many_till
    const CLOSING_SCRIPT: &[u8] = TAG_SCRIPT_CLOSE;

    for i in 0..input.len() {
        if i + CLOSING_SCRIPT.len() <= input.len() {
            let window = &input[i..i + CLOSING_SCRIPT.len()];
            if window.eq_ignore_ascii_case(CLOSING_SCRIPT) {
                return Ok((&input[i..], &input[..i]));
            }
        }
    }

    // Not found - need more data (streaming)
    Err(nom::Err::Incomplete(nom::Needed::Unknown))
}
/// script tag parser - input starts at <script
/// Treats all script tags (inline and external) as HTML elements
fn html_script_tag<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    let start = input;

    // Parse opening tag (complete: gated by esi_opening_tag)
    let (input, _) = recognize(delimited(
        tag_no_case(TAG_SCRIPT_OPEN),
        take_while(|c: u8| !is_close_bracket(c)),
        close_bracket,
    ))
    .parse(input)?;

    // Parse content (if any) and closing tag (if any)
    let (input, _) = opt((
        script_content,
        recognize(delimited(
            streaming_bytes::tag_no_case(TAG_SCRIPT_CLOSE),
            streaming_char::multispace0,
            streaming_close_bracket,
        )),
    ))
    .parse(input)?;

    // Return entire script tag as single HTML element
    let full_script = &start[..start.len() - input.len()];
    Ok((
        input,
        ParseResult::Single(Element::Html(slice_as_bytes(original, full_script))),
    ))
}

// ============================================================================
// ESI Tag Parsers (continue from where tag_dispatch left off)
// ============================================================================

fn closing_tag<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    // Reject ESI closing tags before trying to parse
    let (_, _) = peek(not(streaming_bytes::tag(ESI_CLOSE_PREFIX))).parse(input)?;

    recognize((
        streaming_bytes::tag(TAG_OPEN_CLOSE),
        tag_name,
        streaming_char::multispace0,
        streaming_close_bracket,
    ))
    .map(|s: &[u8]| ParseResult::Single(Element::Html(slice_as_bytes(original, s))))
    .parse(input)
}

// ============================================================================
// Byte Predicate Helpers
// ============================================================================

/// Check if byte is the opening bracket '<'
#[inline]
const fn is_open_bracket(b: u8) -> bool {
    b == OPEN_BRACKET
}

/// Check if byte is a dollar sign '$'
#[inline]
const fn is_dollar(b: u8) -> bool {
    b == DOLLAR
}
#[inline]
const fn is_alphanumeric_or_underscore(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == UNDERSCORE
}

#[inline]
const fn is_lower_alphanumeric_or_underscore(c: u8) -> bool {
    c.is_ascii_lowercase() || c.is_ascii_digit() || c == UNDERSCORE
}

fn esi_fn_name(input: &[u8]) -> IResult<&[u8], String, Error<&[u8]>> {
    preceded(
        tag(&[DOLLAR] as &[u8]),
        take_while1(is_lower_alphanumeric_or_underscore),
    )
    .map(bytes_to_string)
    .parse(input)
}

fn esi_var_name(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    (
        take_while1(is_alphanumeric_or_underscore),
        opt(delimited(
            tag(&[OPEN_BRACE] as &[u8]),
            esi_var_key_expr,
            tag(&[CLOSE_BRACE] as &[u8]),
        )),
        opt(preceded(tag(PIPE), fn_nested_argument)),
    )
        .map(|(name, key, default): (&[u8], _, _)| {
            Expr::Variable(
                bytes_to_string(name),
                key.map(Box::new),
                default.map(Box::new),
            )
        })
        .parse(input)
}

fn not_dollar_or_curlies(input: &[u8]) -> IResult<&[u8], Bytes, Error<&[u8]>> {
    take_while(|c| {
        !is_dollar(c) && c != OPEN_BRACE && c != CLOSE_BRACE && c != COMMA && c != DOUBLE_QUOTE
    })
    .map(Bytes::copy_from_slice)
    .parse(input)
}

/// Parse the body of a single-quoted string, handling backslash escapes.
/// `\X` → literal X for any character (including `\\` → `\` and `\'` → `'`).
/// Returns the unescaped bytes as a Vec.
fn escaped_string_content(input: &[u8]) -> IResult<&[u8], Vec<u8>, Error<&[u8]>> {
    let mut result = Vec::new();
    let mut remaining = input;
    loop {
        // Consume bytes until we hit a single-quote or backslash
        let (rest, chunk) =
            take_while(|c: u8| c != SINGLE_QUOTE && c != BACKSLASH).parse(remaining)?;
        result.extend_from_slice(chunk);
        if rest.is_empty() || rest[0] == SINGLE_QUOTE {
            return Ok((rest, result));
        }
        // rest[0] == BACKSLASH
        if rest.len() < 2 {
            // Trailing backslash with no following char — treat as literal
            result.push(BACKSLASH);
            return Ok((&rest[1..], result));
        }
        // Push the escaped character (whatever follows the backslash)
        result.push(rest[1]);
        remaining = &rest[2..];
    }
}

/// Streaming backslash-escape parser for interpolated content.
/// Consumes `\X` and emits the byte after `\` as Content.
fn esi_escape<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    use nom::error::ErrorKind;
    if input.is_empty() {
        return Err(nom::Err::Incomplete(nom::Needed::new(2)));
    }
    if input[0] != BACKSLASH {
        return Err(nom::Err::Error(Error::new(input, ErrorKind::Tag)));
    }
    if input.len() < 2 {
        return Err(nom::Err::Incomplete(nom::Needed::new(1)));
    }
    // Emit the byte after `\` as Content (zero-copy from original)
    let escaped_byte = &input[1..2];
    Ok((
        &input[2..],
        ParseResult::Single(Element::Content(slice_as_bytes(original, escaped_byte))),
    ))
}

/// Complete-mode backslash-escape parser for attribute values and esi:assign bodies.
fn esi_escape_complete<'a>(
    original: &Bytes,
    input: &'a [u8],
) -> IResult<&'a [u8], ParseResult, Error<&'a [u8]>> {
    use nom::error::ErrorKind;
    if input.len() < 2 || input[0] != BACKSLASH {
        return Err(nom::Err::Error(Error::new(input, ErrorKind::Tag)));
    }
    let escaped_byte = &input[1..2];
    Ok((
        &input[2..],
        ParseResult::Single(Element::Content(slice_as_bytes(original, escaped_byte))),
    ))
}

fn single_quoted_string(input: &[u8]) -> IResult<&[u8], Bytes, Error<&[u8]>> {
    let (input, _) = tag(&[SINGLE_QUOTE] as &[u8]).parse(input)?;
    let (input, content) = escaped_string_content(input)?;
    let (input, _) = tag(&[SINGLE_QUOTE] as &[u8]).parse(input)?;
    Ok((input, Bytes::from(content)))
}
fn triple_quoted_string(input: &[u8]) -> IResult<&[u8], Bytes, Error<&[u8]>> {
    delimited(
        tag(QUOTE_TRIPLE),
        take_until(QUOTE_TRIPLE),
        tag(QUOTE_TRIPLE),
    )
    .map(Bytes::copy_from_slice)
    .parse(input)
}

fn string(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    alt((triple_quoted_string, single_quoted_string))
        .map(|bytes: Bytes| {
            if bytes.is_empty() {
                Expr::String(None)
            } else {
                Expr::String(Some(bytes))
            }
        })
        .parse(input)
}

fn var_key(input: &[u8]) -> IResult<&[u8], Bytes, Error<&[u8]>> {
    alt((
        triple_quoted_string,
        single_quoted_string,
        not_dollar_or_curlies,
    ))
    .parse(input)
}

/// Parse subscript key - can be a string or a nested variable expression
fn esi_var_key_expr(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    alt((
        // Try to parse as a variable first (e.g., $(keyVar))
        esi_variable,
        // Otherwise parse as a string
        var_key.map(|b: Bytes| Expr::String(Some(b))),
    ))
    .parse(input)
}

fn fn_argument(input: &[u8]) -> IResult<&[u8], Vec<Expr>, Error<&[u8]>> {
    let (input, mut parsed) = separated_list0(
        (multispace0, tag(&[COMMA] as &[u8]), multispace0),
        fn_nested_argument,
    )
    .parse(input)?;

    // If the parsed list contains a single empty string element return an empty vec
    if parsed.len() == 1 && parsed[0] == Expr::String(None) {
        parsed = vec![];
    }
    Ok((input, parsed))
}

fn fn_nested_argument(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    // Try full expression parsing first (supports $(ARGS{0}) - 1)
    // expr() will naturally stop at commas and closing parens
    // If expr fails, fall back to bareword for backward compatibility
    alt((expr, bareword)).parse(input)
}

fn integer(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    recognize((
        opt(tag(&[HYPHEN] as &[u8])),
        take_while1(|c: u8| c.is_ascii_digit()),
    ))
    .map_res(|s: &[u8]| {
        // SAFETY: s is ASCII digits + optional hyphen — always valid UTF-8
        unsafe { std::str::from_utf8_unchecked(s) }
            .parse::<i32>()
            .map(Expr::Integer)
    })
    .parse(input)
}

fn bareword(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    take_while1(is_alphanumeric_or_underscore)
        .map(|name: &[u8]| Expr::Variable(bytes_to_string(name), None, None))
        .parse(input)
}

fn esi_function(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    let (input, parsed) = (
        esi_fn_name,
        delimited(
            terminated(tag(&[OPEN_PAREN] as &[u8]), multispace0),
            fn_argument,
            preceded(multispace0, tag(&[CLOSE_PAREN] as &[u8])),
        ),
    )
        .parse(input)?;

    let (name, args) = parsed;

    Ok((input, Expr::Call(name, args)))
}

fn esi_variable(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    delimited(tag(VAR_OPEN), esi_var_name, tag(&[CLOSE_PAREN] as &[u8])).parse(input)
}

/// Parse all binary operators
/// Per ESI spec: all operators at same precedence level, evaluated left-to-right
fn operator(input: &[u8]) -> IResult<&[u8], Operator, Error<&[u8]>> {
    alt((
        // Longer operators first to avoid partial matches
        tag(OP_MATCHES_I).map(|_| Operator::MatchesInsensitive),
        tag(OP_MATCHES).map(|_| Operator::Matches),
        tag(OP_HAS_I).map(|_| Operator::HasInsensitive),
        tag(OP_HAS).map(|_| Operator::Has),
        tag(OP_EQUALS_COMP).map(|_| Operator::Equals),
        tag(OP_NOT_EQUALS).map(|_| Operator::NotEquals),
        tag(OP_LESS_EQUAL).map(|_| Operator::LessThanOrEqual),
        tag(OP_GREATER_EQUAL).map(|_| Operator::GreaterThanOrEqual),
        tag(&[OPEN_BRACKET] as &[u8]).map(|_| Operator::LessThan),
        tag(&[CLOSE_BRACKET] as &[u8]).map(|_| Operator::GreaterThan),
        tag(OP_AND).map(|_| Operator::And),
        tag(OP_OR).map(|_| Operator::Or),
        // Arithmetic operators (after comparison to avoid conflicts with <=, >=)
        tag(OP_ADD).map(|_| Operator::Add),
        tag(&[HYPHEN] as &[u8]).map(|_| Operator::Subtract),
        tag(OP_MULTIPLY).map(|_| Operator::Multiply),
        tag(OP_DIVIDE).map(|_| Operator::Divide),
        tag(OP_MODULO).map(|_| Operator::Modulo),
        // Note: Range (..) is NOT in the general operator list - it's only parsed in list literals
    ))
    .parse(input)
}

fn interpolated_expression(input: &[u8]) -> IResult<&[u8], ParseResult, Error<&[u8]>> {
    let expr = match input.first() {
        Some(&OPEN_BRACE) => dict_literal(input),
        Some(&OPEN_SQ_BRACKET) => list_literal(input),
        Some(&DOLLAR) => alt((esi_function, esi_variable)).parse(input),
        Some(b'0'..=b'9') => integer(input),
        Some(&SINGLE_QUOTE) => string(input),
        _ => {
            return Err(nom::Err::Error(Error::new(
                input,
                nom::error::ErrorKind::Alt,
            )))
        }
    }?;
    Ok((expr.0, ParseResult::Single(Element::Expr(expr.1))))
}

fn dict_literal(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    delimited(
        tag(&[OPEN_BRACE] as &[u8]),
        separated_list0(
            (multispace0, tag(&[COMMA] as &[u8]), multispace0),
            (
                delimited(multispace0, primary_expr, multispace0),
                preceded(
                    tag(&[COLON] as &[u8]),
                    delimited(multispace0, primary_expr, multispace0),
                ),
            ),
        ),
        preceded(multispace0, tag(&[CLOSE_BRACE] as &[u8])),
    )
    .map(Expr::DictLiteral)
    .parse(input)
}

fn list_literal(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    delimited(
        tag(&[OPEN_SQ_BRACKET] as &[u8]),
        alt((
            // Try range first: [start..end]
            (
                delimited(multispace0, primary_expr, multispace0),
                tag(OP_RANGE),
                delimited(multispace0, primary_expr, multispace0),
            )
                .map(|(start, _, end)| {
                    // Create a Comparison expression with Range operator
                    Expr::Comparison {
                        left: Box::new(start),
                        operator: Operator::Range,
                        right: Box::new(end),
                    }
                }),
            // Otherwise parse as regular list: [item, item, ...]
            separated_list0(
                (multispace0, tag(&[COMMA] as &[u8]), multispace0),
                delimited(multispace0, primary_expr, multispace0),
            )
            .map(Expr::ListLiteral),
        )),
        preceded(multispace0, tag(CLOSE_SQ_BRACKET)),
    )
    .parse(input)
}

/// Parse primary expressions (highest precedence atoms)
/// Handles: variables, functions, literals, grouped expressions
/// Extends `interpolated_expression` with grouped expressions and negative integers
fn primary_expr(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    match input.first() {
        // Parse grouped expression: (expr) — only valid in expression context, not interpolated content
        Some(&OPEN_PAREN) => delimited(
            tag(&[OPEN_PAREN] as &[u8]),
            delimited(multispace0, expr, multispace0),
            tag(&[CLOSE_PAREN] as &[u8]),
        )
        .parse(input),
        // Parse negative integer — only valid in expression context
        Some(&HYPHEN) => integer(input),
        // Delegate shared cases to interpolated_expression's dispatch
        _ => {
            let (rest, result) = interpolated_expression(input)?;
            match result {
                ParseResult::Single(Element::Expr(expr)) => Ok((rest, expr)),
                _ => unreachable!("interpolated_expression always returns Single(Expr)"),
            }
        }
    }
}

/// Entry point for expression parsing
///
/// Per ESI spec: "Operands associate from left to right"
/// All operators at same precedence, evaluated left-to-right
/// Format: `unary_expr` (operator `unary_expr`)*
/// Left-associative: A op B op C -> (A op B) op C
fn expr(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    let (mut rest, mut left) = unary_expr(input)?;
    loop {
        let Ok((r, _)) = multispace0::<_, Error<&[u8]>>(rest) else {
            break;
        };
        let Ok((r, op)) = operator(r) else { break };
        let Ok((r, _)) = multispace0::<_, Error<&[u8]>>(r) else {
            break;
        };
        let Ok((r, right)) = unary_expr(r) else { break };
        left = Expr::Comparison {
            left: Box::new(left),
            operator: op,
            right: Box::new(right),
        };
        rest = r;
    }
    Ok((rest, left))
}

/// Parse unary expressions (!, highest precedence for operators)
///
/// Format: ! `unary_expr` | `primary_expr`
/// Handles negation recursively (supports !!expr, !!!expr, etc.)
fn unary_expr(input: &[u8]) -> IResult<&[u8], Expr, Error<&[u8]>> {
    alt((
        // Parse negation: !expr (recursively handles multiple !)
        preceded(
            tag(&[EXCLAMATION] as &[u8]),
            preceded(multispace0, unary_expr),
        )
        .map(|expr| Expr::Not(Box::new(expr))),
        // Otherwise parse primary expression
        primary_expr,
    ))
    .parse(input)
}

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

    #[test]
    fn test_empty_choose() {
        let input = b"<esi:choose></esi:choose>";
        let bytes = Bytes::from_static(input);
        let result = parse_complete(&bytes);
        match result {
            Ok((rest, _)) => {
                assert_eq!(rest.len(), 0, "Should parse completely");
            }
            Err(e) => {
                panic!("Parse failed with error: {:?}", e);
            }
        }
    }

    #[test]
    fn test_choose_with_when() {
        let input = b"<esi:choose><esi:when test=\"1\">hi</esi:when></esi:choose>";
        let bytes = Bytes::from_static(input);
        let result = parse_complete(&bytes);
        match result {
            Ok((rest, result)) => {
                if rest.is_empty() {
                    println!("Success! Result: {:?}", result);
                } else {
                    panic!(
                        "Did not parse completely. Remaining: {:?}",
                        String::from_utf8_lossy(rest)
                    );
                }
            }
            Err(e) => {
                panic!("Parse failed with error: {:?}", e);
            }
        }
    }

    #[test]
    fn test_greater_than_in_quoted_attribute() {
        // `>` inside a quoted test expression must not confuse the tag gate
        let input = b"<esi:choose><esi:when test=\"$(x) > 5\">big</esi:when></esi:choose>";
        let bytes = Bytes::from_static(input);
        let result = parse_complete(&bytes);
        match result {
            Ok((rest, _)) => {
                assert!(
                    rest.is_empty(),
                    "Should parse completely, remaining: {:?}",
                    String::from_utf8_lossy(rest)
                );
            }
            Err(e) => panic!("Parse failed: {:?}", e),
        }

        // Single-quoted variant
        let input = b"<esi:choose><esi:when test='$(x) > 5'>big</esi:when></esi:choose>";
        let bytes = Bytes::from_static(input);
        let result = parse_complete(&bytes);
        match result {
            Ok((rest, _)) => {
                assert!(
                    rest.is_empty(),
                    "Should parse completely, remaining: {:?}",
                    String::from_utf8_lossy(rest)
                );
            }
            Err(e) => panic!("Parse failed: {:?}", e),
        }
    }

    #[test]
    fn test_parse() {
        let input = br#"
<a>foo</a>
<bar />
baz
<esi:vars name="$(hello)"/>
<esi:vars>
hello <br>
</esi:vars>
<sCripT src="whatever">
<baz>
<script> less </fuckery more </script>
<esi:remove>should not appear</esi:remove>
<esi:comment text="also should not appear" />
<esi:text> this <esi:vars>$(should)</esi> appear unchanged</esi:text>
<esi:include src="whatever" />
<esi:choose>
should not appear
</esi:choose>
<esi:choose>
should not appear
<esi:when test="whatever">hi</esi:when>
<esi:otherwise>goodbye</esi:otherwise>
should not appear
</esi:choose>
<esi:try>
should not appear
<esi:attempt>
attempt 1
</esi:attempt>
should not appear
<esi:attempt>
attempt 2
</esi:attempt>
should not appear
<esi:except>
exception!
</esi:except>
</esi:try>"#;
        let bytes = Bytes::from_static(input);
        let result = parse_complete(&bytes);
        match result {
            Ok((rest, _)) => {
                // Just test to make sure it parsed the whole thing
                if !rest.is_empty() {
                    panic!(
                        "Failed to parse completely. Remaining: {:?}",
                        String::from_utf8_lossy(rest)
                    );
                }
            }
            Err(e) => {
                panic!("Parse failed with error: {:?}", e);
            }
        }
    }
    #[test]
    fn test_parse_script() {
        let input = b"<sCripT> less < more </scRIpt>";
        let bytes = Bytes::from_static(input);
        let (rest, x) = html_script_tag(&bytes, input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            x,
            ParseResult::Single(Element::Html(ref h)) if h.as_ref() == b"<sCripT> less < more </scRIpt>"
        ));
    }
    #[test]
    fn test_parse_script_with_src() {
        let input = b"<sCripT src=\"whatever\"></sCripT>";
        let bytes = Bytes::from_static(input);
        let (rest, x) = html_script_tag(&bytes, input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            x,
            ParseResult::Single(Element::Html(ref h)) if h.as_ref() == b"<sCripT src=\"whatever\"></sCripT>"
        ));
    }
    #[test]
    fn test_parse_esi_vars_short() {
        let input = br#"<esi:vars name="$(hello)"/>"#;
        let bytes = Bytes::from_static(input);
        let (rest, x) = esi_vars(&bytes, input).unwrap();
        assert_eq!(rest.len(), 0);
        // esi_vars returns Single when parsing short form with expression
        match x {
            ParseResult::Single(Element::Expr(Expr::Variable(name, None, None))) => {
                assert_eq!(name, "hello");
            }
            ParseResult::Single(e) => {
                panic!("Expected Variable expression, got {:?}", e);
            }
            ParseResult::Multiple(_) => {
                panic!("Expected ParseResult::Single, got Multiple");
            }
            ParseResult::Empty => {
                panic!("Expected ParseResult::Single, got Empty");
            }
        }
    }
    #[test]
    fn test_parse_esi_vars_long() {
        // <esi:vars> can contain text, expressions, HTML, and nested ESI tags (like <esi:assign>)
        let input = br#"<esi:vars>hello<br></esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, x) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(
            x,
            [
                Element::Content(Bytes::from_static(b"hello")),
                Element::Html(Bytes::from_static(b"<br>")),
            ]
        );
    }

    #[test]
    fn test_nested_vars() {
        // Nested <esi:vars> tags ARE supported - the inner vars tag is parsed recursively
        let input = br#"<esi:vars>outer<esi:vars>inner</esi:vars></esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();

        assert_eq!(rest.len(), 0, "Should parse completely");
        assert_eq!(
            elements,
            [
                Element::Content(Bytes::from_static(b"outer")),
                Element::Content(Bytes::from_static(b"inner")),
            ]
        );
    }

    #[test]
    fn test_vars_with_expressions() {
        // This is the proper use of esi:vars - text with expressions
        let input = br#"<esi:vars>Hello $(name), welcome!</esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();

        assert_eq!(rest.len(), 0, "Should parse completely");
        assert_eq!(elements.len(), 3);
        assert!(matches!(&elements[0], Element::Content(t) if t.as_ref() == b"Hello "));
        assert!(matches!(&elements[1], Element::Expr(_)));
        assert!(matches!(&elements[2], Element::Content(t) if t.as_ref() == b", welcome!"));
    }

    #[test]
    fn test_assign_inside_vars() {
        // Per ESI spec, <esi:vars> can contain <esi:assign> tags
        let input = br#"
<esi:vars>
    <esi:assign name="xyz" value="'test'" />
    Result: $(xyz)
</esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();

        assert_eq!(rest.len(), 0, "Should parse completely");

        // Should have: whitespace, assign tag, whitespace, text "Result: ", expression $(xyz), whitespace
        assert!(
            elements.len() >= 3,
            "Should have at least assign tag, text, and expression"
        );

        // Find the assign tag
        let has_assign = elements
            .iter()
            .any(|e| matches!(e, Element::Esi(Tag::Assign { name, .. }) if name == "xyz"));
        assert!(has_assign, "Should contain esi:assign tag with name='xyz'");

        // Find the expression
        let has_expr = elements
            .iter()
            .any(|e| matches!(e, Element::Expr(Expr::Variable(name, None, None)) if name == "xyz"));
        assert!(has_expr, "Should contain expression $(xyz)");
    }

    #[test]
    fn test_parse_complex_expr() {
        let input = br#"<esi:vars name="$call('hello') matches $(var{'key'})"/>"#;
        let bytes = Bytes::from_static(input);
        let (rest, x) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(
            x,
            [Element::Expr(Expr::Comparison {
                left: Box::new(Expr::Call(
                    "call".to_string(),
                    vec![Expr::String(Some(Bytes::from("hello")))]
                )),
                operator: Operator::Matches,
                right: Box::new(Expr::Variable(
                    "var".to_string(),
                    Some(Box::new(Expr::String(Some(Bytes::from("key"))))),
                    None
                ))
            })]
        );
    }

    #[test]
    fn test_vars_with_content() {
        let input = br#"<esi:vars>
            $(QUERY_STRING{param})
        </esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let result = esi_vars_long(&bytes, input);
        assert!(
            result.is_ok(),
            "esi_vars_long should parse successfully: {:?}",
            result.err()
        );
        let (rest, _elements) = result.unwrap();
        assert_eq!(
            rest.len(),
            0,
            "Parser should consume all input. Remaining: '{:?}'",
            String::from_utf8_lossy(rest)
        );
    }

    #[test]
    fn test_exact_failing_input() {
        // This is the exact input from the failing test
        let input = br#"
        <esi:assign name="keyVar" value="'param'" />
        <esi:vars>
            $(QUERY_STRING{param})
            $(QUERY_STRING{$(keyVar)})
        </esi:vars>
    "#;
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        eprintln!("Chunks: {:?}", elements);
        eprintln!("Remaining: {:?}", String::from_utf8_lossy(rest));
        assert_eq!(
            rest.len(),
            0,
            "Parser should consume all input. Remaining: '{:?}'",
            String::from_utf8_lossy(rest)
        );
    }

    #[test]
    fn test_esi_vars_directly() {
        let input = br#"<esi:vars>
            $(QUERY_STRING{param})
            $(QUERY_STRING{$(keyVar)})
        </esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let result = esi_vars(&bytes, input);
        assert!(result.is_ok(), "esi_vars should parse: {:?}", result.err());
        let (rest, _) = result.unwrap();
        assert_eq!(rest.len(), 0, "Should consume all input");
    }

    #[test]
    fn test_esi_tag_on_vars() {
        let input = br#"<esi:vars>
            $(QUERY_STRING{param})
        </esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, _result) = esi_vars(&bytes, input).unwrap();
        assert_eq!(rest.len(), 0, "Parser should consume all input");
    }

    #[test]
    fn test_assign_then_vars() {
        // Test simple case without nested variables (which aren't supported yet)
        let input =
            br#"<esi:assign name="key" value="'val'" /><esi:vars>$(QUERY_STRING{param})</esi:vars>"#;
        let bytes = Bytes::from_static(input);
        let (rest, _elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
    }

    #[test]
    fn test_parse_plain_text() {
        let input = b"hello\nthere";
        let bytes = Bytes::from_static(input);
        let (rest, x) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(x, [Element::Content(Bytes::from_static(b"hello\nthere"))]);
    }
    #[test]
    fn test_parse_interpolated() {
        let input = b"hello $(foo)<esi:vars>goodbye $(foo)</esi:vars>";
        let bytes = Bytes::from_static(input);
        let (rest, x) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(
            x,
            [
                Element::Content(Bytes::from_static(b"hello $(foo)")),
                Element::Content(Bytes::from_static(b"goodbye ")),
                Element::Expr(Expr::Variable("foo".to_string(), None, None)),
            ]
        );
    }
    #[test]
    fn test_parse_examples() {
        let input = include_bytes!("../../examples/esi_vars_example/src/index.html");
        let bytes = Bytes::from_static(input);
        let (rest, _) = parse_complete(&bytes).unwrap();
        // just make sure it parsed the whole thing
        assert_eq!(rest.len(), 0);
    }

    #[test]
    fn test_parse_equality_operators() {
        let input = b"$(foo) == 'bar'";
        let (rest, result) = expr(input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            result,
            Expr::Comparison {
                operator: Operator::Equals,
                ..
            }
        ));

        let input2 = b"$(foo) != 'bar'";
        let (rest, result) = expr(input2).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            result,
            Expr::Comparison {
                operator: Operator::NotEquals,
                ..
            }
        ));
    }

    #[test]
    fn test_parse_comparison_operators() {
        // Test via parsing complete ESI documents with esi:when test attributes
        // which internally use parse_expression() for complete input handling

        let input1 = b"<esi:choose><esi:when test=\"$(count) < 10\">yes</esi:when></esi:choose>";
        let bytes1 = Bytes::from_static(input1);
        let result1 = parse_complete(&bytes1);
        assert!(
            result1.is_ok(),
            "Should parse < operator: {:?}",
            result1.err()
        );

        let input2 = b"<esi:choose><esi:when test=\"$(count) >= 5\">yes</esi:when></esi:choose>";
        let bytes2 = Bytes::from_static(input2);
        let result2 = parse_complete(&bytes2);
        assert!(
            result2.is_ok(),
            "Should parse >= operator: {:?}",
            result2.err()
        );

        // Test has operator
        let input3 = b"<esi:choose><esi:when test=\"$(USER_AGENT) has 'Mobile'\">yes</esi:when></esi:choose>";
        let bytes3 = Bytes::from_static(input3);
        let result3 = parse_complete(&bytes3);
        assert!(
            result3.is_ok(),
            "Should parse 'has' operator: {:?}",
            result3.err()
        );

        // Test has_i operator
        let input4 =
            b"<esi:choose><esi:when test=\"$(COOKIE) has_i 'sam'\">yes</esi:when></esi:choose>";
        let bytes4 = Bytes::from_static(input4);
        let result4 = parse_complete(&bytes4);
        assert!(
            result4.is_ok(),
            "Should parse 'has_i' operator: {:?}",
            result4.err()
        );
    }

    #[test]
    fn test_parse_logical_operators() {
        // With parentheses to enforce correct precedence
        let input = b"($(foo) == 'bar') & ($(baz) == 'qux')";
        let (rest, result) = expr(input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            result,
            Expr::Comparison {
                operator: Operator::And,
                ..
            }
        ));

        let input2 = b"($(foo) == 'bar') | ($(baz) == 'qux')";
        let (rest, result) = expr(input2).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            result,
            Expr::Comparison {
                operator: Operator::Or,
                ..
            }
        ));
    }

    #[test]
    fn test_parse_negation() {
        let input = b"!$(flag)";
        let (rest, result) = expr(input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(result, Expr::Not(_)));

        // Test negation with comparison
        let input2 = b"!($(foo) == 'bar')";
        let (rest, result) = expr(input2).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(result, Expr::Not(_)));
    }

    #[test]
    fn test_parse_grouped_expressions() {
        let input = b"($(foo) == 'bar')";
        let (rest, result) = expr(input).unwrap();
        assert_eq!(rest.len(), 0);
        assert!(matches!(
            result,
            Expr::Comparison {
                operator: Operator::Equals,
                ..
            }
        ));
    }

    #[test]
    fn test_single_quoted_attributes() {
        // Test single-quoted attributes
        let input = b"<esi:include src='http://example.com/fragment' />";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0, "Should parse completely");
        assert_eq!(elements.len(), 1);
        if let Element::Esi(Tag::Include { attrs, .. }) = &elements[0] {
            assert!(
                matches!(&attrs.src, Expr::String(Some(s)) if s == &Bytes::from("http://example.com/fragment"))
            );
        } else {
            panic!("Expected Include tag");
        }

        // Test mixed quotes
        let input2 = b"<esi:assign name='foo' value=\"bar\" />";
        let bytes2 = Bytes::from_static(input2);
        let (rest, elements) = parse_complete(&bytes2).unwrap();
        assert_eq!(rest.len(), 0, "Should parse completely");
        assert_eq!(elements.len(), 1);
        if let Element::Esi(Tag::Assign {
            name,
            subscript: _,
            value,
        }) = &elements[0]
        {
            assert_eq!(name, "foo");
            assert_eq!(value, &Expr::String(Some(Bytes::from("bar"))));
        } else {
            panic!("Expected Assign tag");
        }
    }

    #[test]
    fn test_assign_valid_variable_names() {
        // Valid names
        let valid_cases: Vec<&[u8]> = vec![
            b"<esi:assign name=\"valid_name\" value=\"test\"/>",
            b"<esi:assign name=\"a\" value=\"test\"/>",
            b"<esi:assign name=\"Z\" value=\"test\"/>",
            b"<esi:assign name=\"var123\" value=\"test\"/>",
            b"<esi:assign name=\"my_var_123\" value=\"test\"/>",
            b"<esi:assign name=\"CamelCase\" value=\"test\"/>",
        ];

        for input in valid_cases {
            let bytes = Bytes::copy_from_slice(input);
            let result = parse_complete(&bytes);
            assert!(
                result.is_ok(),
                "Should parse valid name: {:?}",
                std::str::from_utf8(input)
            );
            let (_, elements) = result.unwrap();
            let has_assign = elements
                .iter()
                .any(|e| matches!(e, Element::Esi(Tag::Assign { .. })));
            assert!(
                has_assign,
                "Should have Assign tag for: {:?}",
                std::str::from_utf8(input)
            );
        }
    }

    #[test]
    fn test_assign_invalid_variable_names() {
        // Invalid names should be rejected (treated as empty/skipped)
        let invalid_cases: Vec<&[u8]> = vec![
            b"<esi:assign name=\"$invalid\" value=\"test\"/>", // starts with $
            b"<esi:assign name=\"123invalid\" value=\"test\"/>", // starts with digit
            b"<esi:assign name=\"_invalid\" value=\"test\"/>", // starts with underscore
            b"<esi:assign name=\"invalid-name\" value=\"test\"/>", // contains dash
            b"<esi:assign name=\"invalid.name\" value=\"test\"/>", // contains dot
            b"<esi:assign name=\"invalid name\" value=\"test\"/>", // contains space
            b"<esi:assign name=\"\" value=\"test\"/>",         // empty name
        ];

        for input in invalid_cases {
            let bytes = Bytes::copy_from_slice(input);
            let result = parse_complete(&bytes);
            assert!(
                result.is_ok(),
                "Should parse (but skip invalid): {:?}",
                std::str::from_utf8(input)
            );
            let (_, elements) = result.unwrap();
            let has_assign = elements
                .iter()
                .any(|e| matches!(e, Element::Esi(Tag::Assign { .. })));
            assert!(
                !has_assign,
                "Should NOT have Assign tag for invalid name: {:?}",
                std::str::from_utf8(input)
            );
        }
    }

    #[test]
    fn test_assign_name_length_limit() {
        // Test 256 character limit
        let valid_256 = format!(r#"<esi:assign name="a{}" value="test"/>"#, "b".repeat(255));
        let bytes = Bytes::from(valid_256.clone());
        let result = parse_complete(&bytes);
        assert!(result.is_ok(), "Should parse 256 char name");
        let (_, elements) = result.unwrap();
        let has_assign = elements
            .iter()
            .any(|e| matches!(e, Element::Esi(Tag::Assign { .. })));
        assert!(has_assign, "Should have Assign tag for 256 char name");

        // Test 257 characters (should be invalid)
        let invalid_257 = format!(r#"<esi:assign name="a{}" value="test"/>"#, "b".repeat(256));
        let bytes = Bytes::from(invalid_257);
        let result = parse_complete(&bytes);
        assert!(result.is_ok(), "Should parse (but skip)");
        let (_, elements) = result.unwrap();
        let has_assign = elements
            .iter()
            .any(|e| matches!(e, Element::Esi(Tag::Assign { .. })));
        assert!(!has_assign, "Should NOT have Assign tag for 257 char name");
    }

    #[test]
    fn test_assign_long_form_invalid_name() {
        // Long form with invalid name should also be rejected
        let input = b"<esi:assign name=\"$invalid\">test value</esi:assign>";
        let bytes = Bytes::copy_from_slice(input);
        let result = parse_complete(&bytes);
        assert!(result.is_ok(), "Should parse");
        let (_, elements) = result.unwrap();
        let has_assign = elements
            .iter()
            .any(|e| matches!(e, Element::Esi(Tag::Assign { .. })));
        assert!(
            !has_assign,
            "Should NOT have Assign tag for invalid name in long form"
        );
    }

    #[test]
    fn test_assign_with_subscript() {
        // Test subscript assignment parsing with bare identifier
        let input = b"<esi:assign name=\"ages{joan}\" value=\"28\"/>";
        let bytes = Bytes::copy_from_slice(input);
        let result = parse_complete(&bytes);
        assert!(result.is_ok(), "Should parse");
        let (_, elements) = result.unwrap();
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Assign {
                name,
                subscript,
                value,
            }) => {
                assert_eq!(name, "ages");
                assert!(subscript.is_some(), "Should have subscript");
                if let Some(sub) = subscript {
                    // Should be a string literal "joan"
                    assert!(matches!(sub, Expr::String(Some(s)) if s == &Bytes::from("joan")));
                }
                assert!(matches!(value, Expr::Integer(28)));
            }
            _ => panic!("Expected Assign tag"),
        }

        // Test with another bare identifier
        let input2 = b"<esi:assign name=\"ages{bob}\" value=\"34\"/>";
        let bytes2 = Bytes::copy_from_slice(input2);
        let result2 = parse_complete(&bytes2);
        assert!(result2.is_ok(), "Should parse");
        let (_, elements2) = result2.unwrap();
        assert_eq!(elements2.len(), 1);

        match &elements2[0] {
            Element::Esi(Tag::Assign {
                name,
                subscript,
                value,
            }) => {
                assert_eq!(name, "ages");
                assert!(subscript.is_some(), "Should have subscript");
                if let Some(sub) = subscript {
                    // Should be a string literal "bob"
                    assert!(
                        matches!(sub, Expr::String(Some(s)) if s == &Bytes::from("bob")),
                        "Subscript should be 'bob', got {:?}",
                        sub
                    );
                }
                assert!(matches!(value, Expr::Integer(34)));
            }
            _ => panic!("Expected Assign tag"),
        }
    }

    #[test]
    fn test_assign_with_quoted_subscript() {
        // Test ESI spec-compliant subscript with quoted strings in assignment
        let input = b"<esi:assign name=\"ages{'joan'}\" value=\"28\"/>";
        let bytes = Bytes::copy_from_slice(input);
        let result = parse_complete(&bytes);

        assert!(
            result.is_ok(),
            "Should parse spec-compliant quoted subscript"
        );
        let (_, elements) = result.unwrap();
        assert_eq!(elements.len(), 1, "Should have exactly 1 element");

        match &elements[0] {
            Element::Esi(Tag::Assign {
                name,
                subscript,
                value,
            }) => {
                assert_eq!(name, "ages");
                assert!(subscript.is_some(), "Should have subscript");
                if let Some(sub) = subscript {
                    // Should be a string literal "joan"
                    assert!(
                        matches!(sub, Expr::String(Some(s)) if s == "joan"),
                        "Subscript should be 'joan', got {:?}",
                        sub
                    );
                }
                assert!(matches!(value, Expr::Integer(28)));
            }
            other => panic!("Expected Assign tag, got {:?}", other),
        }

        // Test with multiple quoted subscripts
        let input2 = b"<esi:assign name=\"data{'key1'}\" value=\"${'value1'}\"/>";
        let bytes2 = Bytes::copy_from_slice(input2);
        let result2 = parse_complete(&bytes2);
        assert!(
            result2.is_ok(),
            "Should parse assignment with quoted subscript and quoted value"
        );
    }

    #[test]
    fn test_unclosed_script_tag() {
        // Unclosed script tag - should handle gracefully
        let input = b"<script>content without closing";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();

        // In complete mode, unclosed script becomes text
        assert_eq!(rest.len(), 0, "Should consume all input");
        assert_eq!(elements.len(), 1);
        // The whole thing becomes text since script tag couldn't be fully parsed
        assert!(matches!(&elements[0], Element::Content(_)));
    }
    #[test]
    fn test_partial_esi_tag() {
        // Partial ESI tag - streaming should return Incomplete
        let input = b"<esi:inclu";
        let bytes = Bytes::from_static(input);
        let result = parse(&bytes);

        // Should return Incomplete in streaming mode
        assert!(matches!(result, Err(nom::Err::Incomplete(_))));
    }

    #[test]
    fn test_partial_esi_tag_with_prefix() {
        // Text followed by partial ESI tag
        let input = b"hello <esi:inclu";
        let bytes = Bytes::from_static(input);
        let result = parse(&bytes);

        // Should return the text and indicate more data needed
        match result {
            Ok((rest, elements)) => {
                // Should have parsed "hello " as text
                assert_eq!(elements.len(), 1);
                assert!(matches!(&elements[0], Element::Content(t) if t.as_ref() == b"hello "));
                // Remaining should be the partial tag
                assert_eq!(rest, b"<esi:inclu");
            }
            Err(nom::Err::Incomplete(_)) => {
                // This is also acceptable - couldn't parse anything
            }
            Err(e) => panic!("Unexpected error: {:?}", e),
        }
    }
    #[test]
    fn test_html_comment() {
        let input = b"<!-- this is a comment -->";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);
        // Should return full comment including delimiters
        assert!(matches!(
            &elements[0],
            Element::Html(h) if h.as_ref() == b"<!-- this is a comment -->"
        ));
    }

    #[test]
    fn test_parse_foreach() {
        let input = b"<esi:foreach collection=\"$(items)\" item=\"x\">Item: $(x)</esi:foreach>";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Foreach {
                collection,
                item,
                content,
            }) => {
                assert!(matches!(collection, Expr::Variable(name, None, None) if name == "items"));
                assert_eq!(item.as_deref(), Some("x"));
                assert!(!content.is_empty());
            }
            other => panic!("Expected Foreach tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_foreach_no_item() {
        let input = b"<esi:foreach collection=\"$(mylist)\">Value: $(item)</esi:foreach>";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Foreach {
                collection,
                item,
                content,
            }) => {
                assert!(matches!(collection, Expr::Variable(name, None, None) if name == "mylist"));
                assert_eq!(item, &None);
                assert!(!content.is_empty());
            }
            other => panic!("Expected Foreach tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_break() {
        let input = b"<esi:break />";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);
        assert!(matches!(&elements[0], Element::Esi(Tag::Break)));
    }

    #[test]
    fn test_parse_foreach_with_break() {
        let input = b"<esi:foreach collection=\"$(items)\"><esi:break /></esi:foreach>";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Foreach {
                collection,
                content,
                ..
            }) => {
                assert!(matches!(collection, Expr::Variable(name, None, None) if name == "items"));
                assert_eq!(content.len(), 1);
                assert!(matches!(&content[0], Element::Esi(Tag::Break)));
            }
            other => panic!("Expected Foreach tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_function() {
        let input = b"<esi:function name=\"greet\">Hello $(name)</esi:function>";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Function { name, body }) => {
                assert_eq!(name, "greet");
                assert!(!body.is_empty());
            }
            other => panic!("Expected Function tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_function_with_return() {
        let input =
            b"<esi:function name=\"add\"><esi:return value=\"$(a) + $(b)\" /></esi:function>";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Function { name, body }) => {
                assert_eq!(name, "add");
                assert_eq!(body.len(), 1);
                match &body[0] {
                    Element::Esi(Tag::Return { value }) => {
                        // Return should have a valid expression (Comparison for + operator)
                        assert!(matches!(value, Expr::Comparison { .. }));
                    }
                    other => panic!("Expected Return tag in function body, got {:?}", other),
                }
            }
            other => panic!("Expected Function tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_return() {
        let input = b"<esi:return value=\"42\" />";
        let bytes = Bytes::from_static(input);
        let (rest, elements) = parse_complete(&bytes).unwrap();
        assert_eq!(rest.len(), 0);
        assert_eq!(elements.len(), 1);

        match &elements[0] {
            Element::Esi(Tag::Return { value }) => {
                assert!(matches!(value, Expr::Integer(42)));
            }
            other => panic!("Expected Return tag, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_dict_literal() {
        let input = b"{1:'apple',2:'orange'}";
        let result = dict_literal(input);
        assert!(result.is_ok(), "Dict literal should parse: {:?}", result);
        let (rest, expr) = result.unwrap();
        assert_eq!(rest, b"");
        assert!(matches!(expr, Expr::DictLiteral(_)));
    }

    #[test]
    fn test_left_to_right_evaluation() {
        // Test 1: Left-to-right evaluation per ESI spec
        // $(a) & $(b) | $(c) should parse as ($(a) & $(b)) | $(c)
        let input = b"$(a) & $(b) | $(c)";
        let result = expr(input);
        assert!(
            result.is_ok(),
            "Failed to parse '$(a) & $(b) | $(c)': {:?}",
            result
        );
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have OR at the top level (last operator evaluated)
        match parsed {
            Expr::Comparison {
                operator: Operator::Or,
                left,
                right,
            } => {
                // Left should be: $(a) & $(b) (evaluated first, left-to-right)
                match *left {
                    Expr::Comparison {
                        operator: Operator::And,
                        ..
                    } => {}
                    _ => panic!("Expected AND on left side, got {:?}", left),
                }
                // Right should be: $(c)
                match *right {
                    Expr::Variable(name, None, None) if name == "c" => {}
                    _ => panic!("Expected variable 'c' on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected OR at top level, got {:?}", parsed),
        }

        // Test 2: $(a) | $(b) & $(c) should parse as ($(a) | $(b)) & $(c) [left-to-right]
        let input = b"$(a) | $(b) & $(c)";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '$(a) | $(b) & $(c)'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have AND at the top level (last operator, left-to-right)
        match parsed {
            Expr::Comparison {
                operator: Operator::And,
                left,
                right,
            } => {
                // Left should be: $(a) | $(b) (evaluated first)
                match *left {
                    Expr::Comparison {
                        operator: Operator::Or,
                        ..
                    } => {}
                    _ => panic!("Expected OR on left side, got {:?}", left),
                }
                // Right should be: $(c)
                match *right {
                    Expr::Variable(name, None, None) if name == "c" => {}
                    _ => panic!("Expected variable 'c' on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected AND at top level, got {:?}", parsed),
        }

        // Test 3: Unary NOT binds tighter than binary operators
        // !$(a) & $(b) should parse as (!$(a)) & $(b)
        let input = b"!$(a) & $(b)";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '!$(a) & $(b)'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have AND at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::And,
                left,
                right,
            } => {
                // Left should be: !$(a)
                match *left {
                    Expr::Not(_) => {}
                    _ => panic!("Expected NOT on left side, got {:?}", left),
                }
                // Right should be: $(b)
                match *right {
                    Expr::Variable(name, None, None) if name == "b" => {}
                    _ => panic!("Expected variable 'b' on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected AND at top level, got {:?}", parsed),
        }

        // Test 4: Left-to-right with multiple operators
        // $(a) == $(b) | $(c) should parse as ($(a) == $(b)) | $(c)
        let input = b"$(a) == $(b) | $(c)";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '$(a) == $(b) | $(c)'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have OR at the top level (last operator)
        match parsed {
            Expr::Comparison {
                operator: Operator::Or,
                left,
                right,
            } => {
                // Left should be: $(a) == $(b)
                match *left {
                    Expr::Comparison {
                        operator: Operator::Equals,
                        ..
                    } => {}
                    _ => panic!("Expected EQUALS on left side, got {:?}", left),
                }
                // Right should be: $(c)
                match *right {
                    Expr::Variable(name, None, None) if name == "c" => {}
                    _ => panic!("Expected variable 'c' on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected OR at top level, got {:?}", parsed),
        }

        // Test 5: Parentheses override left-to-right evaluation
        // $(a) & ($(b) | $(c)) should respect the parentheses
        let input = b"$(a) & ($(b) | $(c))";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '$(a) & ($(b) | $(c))'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have AND at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::And,
                left,
                right,
            } => {
                // Left should be: $(a)
                match *left {
                    Expr::Variable(name, None, None) if name == "a" => {}
                    _ => panic!("Expected variable 'a' on left side, got {:?}", left),
                }
                // Right should be: $(b) | $(c) (grouped by parentheses)
                match *right {
                    Expr::Comparison {
                        operator: Operator::Or,
                        ..
                    } => {}
                    _ => panic!("Expected OR on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected AND at top level, got {:?}", parsed),
        }
    }

    #[test]
    fn test_arithmetic_left_to_right() {
        // Test 1: Per ESI spec, left-to-right evaluation
        // 2 + 3 * 4 should parse as (2 + 3) * 4 = 20 (not 14 like traditional math)
        let input = b"2 + 3 * 4";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '2 + 3 * 4': {:?}", result);
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have * at the top level (last operator, left-to-right)
        match parsed {
            Expr::Comparison {
                operator: Operator::Multiply,
                left,
                right,
            } => {
                // Left should be: 2 + 3 (evaluated first)
                match *left {
                    Expr::Comparison {
                        operator: Operator::Add,
                        ..
                    } => {}
                    _ => panic!("Expected ADD on left side, got {:?}", left),
                }
                // Right should be: 4
                match *right {
                    Expr::Integer(4) => {}
                    _ => panic!("Expected integer 4 on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected MULTIPLY at top level, got {:?}", parsed),
        }

        // Test 2: Subtraction and division
        // 10 - 2 / 2 should parse as (10 - 2) / 2 = 4 (not 9)
        let input = b"10 - 2 / 2";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '10 - 2 / 2'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have / at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::Divide,
                left,
                right,
            } => {
                // Left should be: 10 - 2
                match *left {
                    Expr::Comparison {
                        operator: Operator::Subtract,
                        ..
                    } => {}
                    _ => panic!("Expected SUBTRACT on left side, got {:?}", left),
                }
                // Right should be: 2
                match *right {
                    Expr::Integer(2) => {}
                    _ => panic!("Expected integer 2 on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected DIVIDE at top level, got {:?}", parsed),
        }

        // Test 3: Modulo
        // 7 + 3 % 2 should parse as (7 + 3) % 2 = 0
        let input = b"7 + 3 % 2";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '7 + 3 % 2'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have % at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::Modulo,
                ..
            } => {}
            _ => panic!("Expected MODULO at top level, got {:?}", parsed),
        }

        // Test 4: Parentheses override left-to-right
        // 2 + (3 * 4) should respect parentheses = 2 + 12 = 14
        let input = b"2 + (3 * 4)";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '2 + (3 * 4)'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have + at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::Add,
                left,
                right,
            } => {
                // Left should be: 2
                match *left {
                    Expr::Integer(2) => {}
                    _ => panic!("Expected integer 2 on left side, got {:?}", left),
                }
                // Right should be: 3 * 4 (grouped by parentheses)
                match *right {
                    Expr::Comparison {
                        operator: Operator::Multiply,
                        ..
                    } => {}
                    _ => panic!("Expected MULTIPLY on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected ADD at top level, got {:?}", parsed),
        }

        // Test 5: Parentheses override left-to-right
        // 2 + (3 * 4) should respect parentheses = 2 + 12 = 14
        let input = b"2 + (3 * 4)";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '2 + (3 * 4)'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have + at the top level
        match parsed {
            Expr::Comparison {
                operator: Operator::Add,
                left,
                right,
            } => {
                // Left should be: 2
                match *left {
                    Expr::Integer(2) => {}
                    _ => panic!("Expected integer 2 on left side, got {:?}", left),
                }
                // Right should be: 3 * 4 (grouped by parentheses)
                match *right {
                    Expr::Comparison {
                        operator: Operator::Multiply,
                        ..
                    } => {}
                    _ => panic!("Expected MULTIPLY on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected ADD at top level, got {:?}", parsed),
        }

        // Test 6: Arithmetic mixed with comparison
        // 5 + 3 > 7 should parse as (5 + 3) > 7 = true
        let input = b"5 + 3 > 7";
        let result = expr(input);
        assert!(result.is_ok(), "Failed to parse '5 + 3 > 7'");
        let (rest, parsed) = result.unwrap();
        assert_eq!(rest, b"");

        // Should have > at the top level (last operator)
        match parsed {
            Expr::Comparison {
                operator: Operator::GreaterThan,
                left,
                right,
            } => {
                // Left should be: 5 + 3
                match *left {
                    Expr::Comparison {
                        operator: Operator::Add,
                        ..
                    } => {}
                    _ => panic!("Expected ADD on left side, got {:?}", left),
                }
                // Right should be: 7
                match *right {
                    Expr::Integer(7) => {}
                    _ => panic!("Expected integer 7 on right side, got {:?}", right),
                }
            }
            _ => panic!("Expected GREATER_THAN at top level, got {:?}", parsed),
        }
    }

    // --- Backslash escape tests ---

    #[test]
    fn test_single_quoted_string_escape_quote() {
        // 'it\'s' should parse as: it's
        let input = br"'it\'s'";
        let (rest, result) = single_quoted_string(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(result.as_ref(), b"it's");
    }

    #[test]
    fn test_single_quoted_string_escape_backslash() {
        // 'a\\b' should parse as: a\b
        let input = br"'a\\b'";
        let (rest, result) = single_quoted_string(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(result.as_ref(), b"a\\b");
    }

    #[test]
    fn test_single_quoted_string_escape_arbitrary() {
        // 'a\nb' — \n is not a special sequence, just literal n
        let input = br"'a\nb'";
        let (rest, result) = single_quoted_string(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(result.as_ref(), b"anb");
    }

    #[test]
    fn test_single_quoted_string_no_escapes() {
        let input = b"'hello'";
        let (rest, result) = single_quoted_string(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(result.as_ref(), b"hello");
    }

    #[test]
    fn test_interpolated_content_escape() {
        // Backslash escape in attribute value: hello\<world → hello<world
        let input_bytes = Bytes::from_static(br"hello\<world");
        let (rest, elements) = interpolated_content(&input_bytes).unwrap();
        assert!(
            rest.is_empty(),
            "remaining: {:?}",
            String::from_utf8_lossy(rest)
        );
        // Should have: Content("hello"), Content("<"), Content("world")
        let text: Vec<u8> = elements
            .iter()
            .filter_map(|e| match e {
                Element::Content(b) => Some(b.as_ref().to_vec()),
                _ => None,
            })
            .flatten()
            .collect();
        assert_eq!(text, b"hello<world");
    }

    #[test]
    fn test_interpolated_content_escape_backslash() {
        // \\\\ in source → two backslashes: \\
        let input_bytes = Bytes::from_static(br"a\\b");
        let (rest, elements) = interpolated_content(&input_bytes).unwrap();
        assert!(rest.is_empty());
        let text: Vec<u8> = elements
            .iter()
            .filter_map(|e| match e {
                Element::Content(b) => Some(b.as_ref().to_vec()),
                _ => None,
            })
            .flatten()
            .collect();
        assert_eq!(text, b"a\\b");
    }

    #[test]
    fn test_interpolated_content_escape_dollar() {
        // \$ should produce literal $, not start a variable
        let input_bytes = Bytes::from_static(br"\$notavar");
        let (rest, elements) = interpolated_content(&input_bytes).unwrap();
        assert!(
            rest.is_empty(),
            "remaining: {:?}",
            String::from_utf8_lossy(rest)
        );
        let text: Vec<u8> = elements
            .iter()
            .filter_map(|e| match e {
                Element::Content(b) => Some(b.as_ref().to_vec()),
                _ => None,
            })
            .flatten()
            .collect();
        assert_eq!(text, b"$notavar");
    }

    #[test]
    fn test_parse_content_complete_backslash_escape() {
        // Test backslash escaping in esi:assign body context
        let input_bytes = Bytes::from_static(br"hello\$world");
        let elements = parse_content_complete(&input_bytes, input_bytes.as_ref());
        let text: Vec<u8> = elements
            .iter()
            .filter_map(|e| match e {
                Element::Content(b) => Some(b.as_ref().to_vec()),
                _ => None,
            })
            .flatten()
            .collect();
        assert_eq!(text, b"hello$world");
    }
}