html-to-markdown-rs 3.8.3

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

use crate::converter::tier1::bail::BailReason;
use crate::converter::tier1::parse;
use crate::converter::tier1::spec_rules;
use crate::converter::tier1::state::{EscapeCtx, OpenTag, Tier1State};
use crate::converter::tier1::tags::{ListKind, TagKind, TagSpec};
use crate::converter::tier1::{self};
use crate::converter::utility::attributes::NAV_KEYWORDS;
use crate::options::ConversionOptions;

use memchr::{memchr2, memchr3};

/// Maximum byte length of a tag name lowercased into a stack buffer.
///
/// Names longer than this are silently truncated and will not match any
/// entry in the spec table, causing an `UnknownCustomElement` bail.
const MAX_TAG_NAME_BYTES: usize = 32;

/// Maximum byte length scanned when looking for a `;` to close an entity.
///
/// Entities longer than this are treated as bare `&` literals.
const MAX_ENTITY_NAME_BYTES: usize = 32;

/// Minimum number of dashes in a GFM separator cell.
///
/// Matches Tier-2's `col_widths.get(i).unwrap_or(0).max(MIN_SEPARATOR_DASHES)`.
const MIN_SEPARATOR_DASHES: usize = 3;

/// Static `TagSpec` used for all unknown custom elements (tag names containing
/// `-`, e.g. `<x-foo>`, `<my-component>`).
///
/// Tier-2 treats unknown custom elements as generic block containers and emits
/// their inner content as plain text.  Using a `Block` spec here produces
/// byte-identical output to Tier-2 for the common cases where custom-element
/// content is plain text or standard HTML children.
///
/// The static reference `&CUSTOM_ELEMENT_BLOCK_SPEC` is used anywhere the
/// scanner needs a `&'static TagSpec` for a custom element open/close tag.
static CUSTOM_ELEMENT_BLOCK_SPEC: TagSpec = TagSpec {
    kind: TagKind::Block,
    is_void: false,
    is_block: true,
    optional_close: None,
    is_rawtext: false,
};

/// ATX heading prefixes indexed by level − 1 (0 = `h1`, 5 = `h6`).
const HEADING_PREFIXES: [&str; 6] = ["# ", "## ", "### ", "#### ", "##### ", "###### "];

/// List-item indentation strings indexed by depth (0 = top-level, no indent).
///
/// Depths beyond the table size fall back to a runtime allocation.
const LIST_ITEM_INDENTS: [&str; 8] = [
    "",
    "  ",
    "    ",
    "      ",
    "        ",
    "          ",
    "            ",
    "              ",
];

/// Successful output of the Tier-1 scanner.
#[derive(Debug, Clone, Default)]
pub struct ScanOutput {
    /// Accumulated Markdown body.
    pub body: String,
    /// Byte range of `<head>…</head>` content (if a `<head>` was seen) in
    /// the input the scanner walked.  Forwarded by `tier1::run` to
    /// `head_metadata::extract_frontmatter` so the YAML frontmatter step
    /// works without a `PrescanReport`.
    pub head_range: Option<std::ops::Range<usize>>,
}

/// Entry point for the Tier-1 scanner.
pub fn scan(html: &str, options: &ConversionOptions) -> Result<ScanOutput, BailReason> {
    let bytes = html.as_bytes();
    let mut state = Tier1State::new(html.len());
    // ~keep Phase DD: Tier-2 runs an html5ever roundtrip when custom-element
    // ~keep tags are present in the source, which canonicalizes attribute
    // ~keep entities.  Mirror that for byte-equality.
    state.canonicalize_attr_entities = crate::converter::main_helpers::has_custom_element_tags(html);
    let mut pos = 0usize;
    let mut text_start = 0usize;

    while pos < bytes.len() {
        match bytes[pos] {
            b'<' => {
                if text_start < pos {
                    flush_text(&mut state, &html[text_start..pos], text_start)?;
                }

                let next = bytes.get(pos + 1).copied().unwrap_or(0);

                if next == b'!' {
                    if html[pos..].starts_with("<![CDATA[") {
                        return Err(BailReason::Cdata { offset: pos });
                    }
                    pos = skip_bang(bytes, pos)?;
                    text_start = pos;
                    continue;
                }

                // ~keep `<?` — processing instruction.  Tier-2 handles these
                // ~keep inconsistently depending on whether html5ever-repair
                // ~keep ran (it rewrites bogus comments) and how tl chooses
                // ~keep to parse the run.  Either way the byte shape
                // ~keep downstream differs from the simple skip Tier-1 could
                // ~keep perform, so bail and let the Tier-2 fallback produce
                // ~keep the authoritative output.
                if next == b'?' {
                    return Err(BailReason::Classifier);
                }

                if next == b'/' {
                    let name_start = pos + 2;
                    let name_end = parse::scan_tag_name(bytes, name_start);
                    if name_end == name_start {
                        // ~keep `</>` or similar — bail
                        return Err(BailReason::LiteralLt { offset: pos });
                    }
                    let close_bracket =
                        parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;

                    let tag_name_bytes = &bytes[name_start..name_end];
                    emit_close(&mut state, tag_name_bytes, options)?;

                    pos = close_bracket.0 + 1;
                    text_start = pos;
                    continue;
                }

                // ~keep Not a tag-name-start byte → literal `<` in text. Tier-2
                // ~keep emits these verbatim (html5ever/astral-tl both parse a
                // ~keep bare `<x` as a text node). Emit the `<` and continue so
                // ~keep we don't bail on commonly-unescaped source like `x < 5`.
                if !parse::is_tag_name_start(next) {
                    flush_text(&mut state, "<", pos)?;
                    pos += 1;
                    text_start = pos;
                    continue;
                }

                let name_start = pos + 1;
                let name_end = parse::scan_tag_name(bytes, name_start);
                let tag_name_bytes = &bytes[name_start..name_end];

                let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
                let name_lower = lowercase_into(tag_name_bytes, &mut name_buf);

                // ~keep Phase I: `<svg>` — emit as base64 data URI matching Tier-2's
                // ~keep `handle_svg` output.  The entire subtree (open tag through
                // ~keep `</svg>`) is consumed here; the scanner skips past it without
                // ~keep pushing anything on the open-tag stack.
                // ~keep
                // ~keep `tl::parse` is called on just the SVG fragment to normalize
                // ~keep attribute order via `serialize_element` (which sorts attrs
                // ~keep alphabetically — raw source bytes differ, so slicing alone is
                // ~keep not byte-identical with Tier-2 output).
                if name_lower == b"svg" {
                    let tag_open_start = pos;
                    let Some((close_pos, is_self_closing)) = parse::find_tag_close(bytes, name_end) else {
                        // ~keep Unclosed SVG open tag — skip to end; Tier-2 handles it.
                        pos = bytes.len();
                        text_start = pos;
                        continue;
                    };
                    let open_tag_end = close_pos + 1;

                    let svg_end = if is_self_closing {
                        // ~keep `<svg ... />` — self-closing, no children.
                        open_tag_end
                    } else {
                        // ~keep Find matching `</svg>` with depth tracking.
                        find_svg_close(bytes, open_tag_end).unwrap_or(bytes.len())
                    };

                    let svg_slice = &html[tag_open_start..svg_end];

                    emit_svg_from_slice(svg_slice, tag_open_start, &mut state, options)?;

                    pos = svg_end;
                    text_start = pos;
                    continue;
                }

                // ~keep Phase N: `<template>` — inert script container; Tier-2 drops
                // ~keep its content (see plain_text.rs SKIP_TAGS).  Skip the entire
                // ~keep subtree without emitting anything.  Self-closing form is rare
                // ~keep but handled.
                if name_lower == b"template" {
                    let Some((close_pos, is_self_closing)) = parse::find_tag_close(bytes, name_end) else {
                        pos = bytes.len();
                        text_start = pos;
                        continue;
                    };
                    let open_tag_end = close_pos + 1;
                    pos = if is_self_closing {
                        open_tag_end
                    } else {
                        find_balanced_close(bytes, open_tag_end, b"template").unwrap_or(bytes.len())
                    };
                    text_start = pos;
                    continue;
                }

                // ~keep Resolve the tag spec.  Custom elements (names containing `-`)
                // ~keep are not in the static TAGS table but are treated as generic
                // ~keep block containers — Tier-2 emits their inner content as plain
                // ~keep block text, which matches `TagKind::Block` behaviour.  All
                // ~keep other unknown tags are still bailed immediately.
                let spec: &'static TagSpec = if name_lower.contains(&b'-') {
                    &CUSTOM_ELEMENT_BLOCK_SPEC
                } else {
                    match tier1::lookup(name_lower) {
                        Some(s) => s,
                        None => {
                            return Err(BailReason::UnknownCustomElement {
                                name: bytes_to_string(tag_name_bytes).into(),
                                offset: pos,
                            });
                        }
                    }
                };

                // ~keep Raw-text "ignored" tags (`<script>`, `<style>`): their
                // ~keep spec is `TagKind::Ignored` with `is_rawtext = true` (see
                // ~keep tags.rs `rawtext_ignored`).  Prescan also strips their
                // ~keep content (STRIP_CONTENT_TAGS); Tier-2 does the same.  Skip
                // ~keep them inline so we don't bail to Tier-2 just because a page
                // ~keep contains an empty `<script></script>` left over from
                // ~keep prescan.  Other `RawText` kinds (textarea / title / xmp /
                // ~keep iframe / noscript / noembed / noframes) keep their text
                // ~keep content in Tier-2 and must continue to bail until Tier-1
                // ~keep learns to emit it correctly.
                if matches!(spec.kind, TagKind::Ignored) && spec.is_rawtext {
                    let open_end = match parse::find_tag_close(bytes, name_end) {
                        Some(close) => close.0 + 1,
                        None => bytes.len(),
                    };
                    pos = find_raw_text_close(bytes, open_end, name_lower).unwrap_or(bytes.len());
                    text_start = pos;
                    // ~keep Tier-2 observed behaviour (medium_python "walrus operator"
                    // ~keep case): after walking through a `<style>` block whose
                    // ~keep content emits nothing, the subsequent inline sibling
                    // ~keep emission gets a separating space inserted (matching the
                    // ~keep `<style></style><span>X</span>` → `" X"` pattern).
                    // ~keep Mirror this here: when the output buffer's tail looks
                    // ~keep like inline text content (no trailing whitespace, no
                    // ~keep `<br>` sentinel), push a single space.
                    if name_lower == b"style" {
                        let dest = state.cell_or_output_mut();
                        let ends_with_word = !dest.is_empty()
                            && !dest.ends_with(' ')
                            && !dest.ends_with('\t')
                            && !dest.ends_with('\n')
                            && !dest.ends_with('<')
                            && !dest.ends_with("<br>");
                        if ends_with_word {
                            dest.push(' ');
                        }
                    }
                    continue;
                }

                // ~keep Non-rawtext `Ignored` tags (`<head>`, `<meta>`, `<link>`):
                // ~keep Tier-2 does not emit any markdown from their bodies — head
                // ~keep is consumed by metadata extraction; meta/link are void.
                // ~keep Silent-skip them here so Tier-1 can be invoked on inputs
                // ~keep that contain a `<head>` (the common case for full HTML
                // ~keep documents) without bailing.  For non-void `<head>`, capture
                // ~keep the content range on `state.head_range` so `tier1::run` can
                // ~keep hand it to `head_metadata::extract_frontmatter` when
                // ~keep metadata extraction is enabled.
                if matches!(spec.kind, TagKind::Ignored) {
                    let open_end = match parse::find_tag_close(bytes, name_end) {
                        Some(close) => close.0 + 1,
                        None => bytes.len(),
                    };
                    if spec.is_void {
                        pos = open_end;
                        text_start = pos;
                        continue;
                    }
                    let (close_start, close_end) = match find_close_tag_range(bytes, open_end, name_lower) {
                        Some(pair) => pair,
                        None => (bytes.len(), bytes.len()),
                    };
                    if state.head_range.is_none() {
                        state.head_range = Some(open_end..close_start);
                    }
                    pos = close_end;
                    text_start = pos;
                    continue;
                }

                // ~keep Bail on unsupported tag kinds for M3c
                bail_unsupported(spec, pos)?;

                // ~keep Phase D': mirror Tier-2's preprocessing pipeline <nav> /
                // ~keep nav-hinted <header> / <footer> / <aside> / <form> strip.
                // ~keep When the user's preprocessing options request the strip,
                // ~keep jump past the matching close tag without pushing any frame.
                // ~keep Matches Tier-2's should_drop_for_preprocessing
                // ~keep (preprocessing_helpers.rs:115).
                if is_preprocessing_skip_candidate(name_lower) {
                    let close = parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;
                    let attrs_end = if close.1 { close.0.saturating_sub(1) } else { close.0 };
                    let skip_attrs = parse::collect_attrs(bytes, name_end, attrs_end);
                    if should_skip_preprocessing(name_lower, &skip_attrs, options) {
                        let open_end = close.0 + 1;
                        if close.1 {
                            pos = open_end;
                        } else {
                            pos = find_balanced_close(bytes, open_end, name_lower).unwrap_or(bytes.len());
                        }
                        text_start = pos;
                        continue;
                    }
                }

                // ~keep Bail on <pre> when code_block_style is not Indented.
                // ~keep Phase Q.4: Tier-1 supports Indented (4-space) and
                // ~keep Backticks (`` ``` ``-fenced) code blocks via open_pre /
                // ~keep close_pre.  Tildes still require Tier-2's fence emitter.
                if matches!(spec.kind, TagKind::Pre)
                    && options.code_block_style == crate::options::CodeBlockStyle::Tildes
                {
                    return Err(BailReason::Classifier);
                }

                let close = parse::find_tag_close(bytes, name_end).ok_or(BailReason::LiteralLt { offset: pos })?;

                let attrs_end = if close.1 { close.0.saturating_sub(1) } else { close.0 };
                // ~keep Most tag kinds (headings, paragraphs, emphasis, code, etc.) do
                // ~keep not read attributes during emit.  Skip the allocation in the
                // ~keep common case; only collect for the kinds whose emit paths
                // ~keep actually consult attributes.  `<abbr>` is `TagKind::Inline`
                // ~keep but its `title` attribute is read at open time to mirror
                // ~keep Tier-2's `handle_abbr` — include it in the collect-set.
                let needs_attrs = matches!(
                    spec.kind,
                    TagKind::Link
                        | TagKind::Image
                        | TagKind::List(ListKind::Ordered)
                        | TagKind::TableCell { .. }
                        | TagKind::Pre
                        | TagKind::Code
                ) || name_lower == b"abbr";
                let attrs: Vec<(&[u8], Option<&[u8]>)> = if needs_attrs {
                    parse::collect_attrs(bytes, name_end, attrs_end)
                } else {
                    Vec::new()
                };

                pos = close.0 + 1;

                if spec.is_void || close.1 {
                    emit_void(&mut state, spec, &attrs, html, options)?;
                    text_start = pos;
                    continue;
                }

                // ~keep Phase HH: nested tables are NO LONGER bailed here.  An inner
                // ~keep table is opened with `inline_mode = true` (set inside
                // ~keep `open_table`), and on `</table>` the rendered GFM markdown
                // ~keep is written into the parent cell buffer rather than
                // ~keep `state.output`.  The parent cell's newline-collapse step
                // ~keep then flattens the inner table to a single inline run,
                // ~keep matching Tier-2's behaviour.

                // ~keep M4: HTML5 implicit-close transitions.
                // ~keep Run BEFORE the block-in-cell check so that structural table
                // ~keep elements like `<tr>` correctly close any open `<td>`/`<th>`
                // ~keep before the block check evaluates `in_table_cell()`.  Without
                // ~keep this ordering, `<th>h1<tr>` would fire the bail even though
                // ~keep `<tr>` is not a content element inside the cell.
                while let Some(top) = state.stack.last() {
                    if !spec_rules::should_close_for_new_tag(top.spec, spec) {
                        break;
                    }
                    emit_close_for_implicit(&mut state, options)?;
                }

                // ~keep M9: Block-in-cell bail.
                // ~keep Evaluated AFTER M4 implicit closes so that table-structural
                // ~keep elements (e.g. a `<tr>` following an unclosed `<th>`) correctly
                // ~keep collapse the cell state before the check runs.
                // ~keep
                // ~keep Allow `<p>`, `<div>/<section>/…` (TagKind::Block), `<ul>/<ol>`,
                // ~keep and `<h1>-<h6>` inside cells — each has cell-aware open/close
                // ~keep helpers that redirect their output to the cell accumulator and
                // ~keep match Tier-2's `cell_text_content` normalisation
                // ~keep (`text.replace('\n', " ")` when `br_in_tables` is false).
                // ~keep
                // ~keep All other block kinds (blockquote, pre, etc.) still bail because
                // ~keep they produce multi-line content that would diverge from Tier-2's
                // ~keep cell normalisation.
                if state.in_table_cell() && spec.is_block {
                    let inlineable = matches!(
                        spec.kind,
                        TagKind::Paragraph
                            | TagKind::Block
                            | TagKind::Summary
                            | TagKind::Figcaption
                            | TagKind::Blockquote
                            | TagKind::Pre
                            | TagKind::List(_)
                            | TagKind::ListItem
                            | TagKind::Heading(_)
                            | TagKind::DefinitionTerm
                            | TagKind::DefinitionDescription
                            | TagKind::Table
                    );
                    if !inlineable {
                        return Err(BailReason::TableBlockChildInCell);
                    }
                }

                let prev_ctx = state.escape_ctx;
                let ol_start = if matches!(spec.kind, TagKind::List(ListKind::Ordered)) {
                    extract_ol_start(&attrs)
                } else {
                    1
                };
                if matches!(spec.kind, TagKind::Link) {
                    let (href, title) = extract_link_attrs(&attrs)?;
                    state.link_stack.push((href, title));
                }
                // ~keep Mirror Tier-2's `semantic/attributes.rs::handle_abbr`:
                // ~keep capture the abbreviation's `title` attribute and emit
                // ~keep `" (title)"` after the abbr's text content at close time.
                if name_lower == b"abbr" {
                    let title = find_attr(&attrs, b"title")
                        .and_then(|b| std::str::from_utf8(b).ok())
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .map(str::to_owned);
                    state.abbr_titles.push(title);
                }

                emit_open(&mut state, spec, &attrs)?;

                // ~keep Record the content-start position AFTER emit_open so that
                // ~keep close-side post-processing operates on the correct slice.
                // ~keep When inside a table cell the position is in the cell buffer;
                // ~keep otherwise it is in the main output buffer.
                let output_content_start = state.cell_or_output_mut().len();

                let list_index = 0u16;

                state.stack.push(OpenTag {
                    spec,
                    content_start: output_content_start,
                    prev_escape_ctx: prev_ctx,
                    list_index,
                    ol_start,
                    name_range: name_start..name_end,
                });

                apply_open_escape_ctx(&mut state, spec);

                text_start = pos;
            }
            _ => {
                // ~keep Batch ASCII fast-path: skip forward to the next `<` or `&`
                // ~keep (the only two bytes that require special handling) in one
                // ~keep memchr2 call instead of advancing one byte at a time.
                // ~keep flush_text handles entity decoding and whitespace collapsing
                // ~keep for whatever raw slice [text_start..pos] we hand it, so it
                // ~keep is correct to jump pos all the way to the next special byte.
                // ~keep This is safe across every context (<pre>, table cells, etc.)
                // ~keep because:
                // ~keep   • `<` still triggers the tag-dispatch path above.
                // ~keep   • `&` is preserved in the slice passed to flush_text, which
                // ~keep     entity-decodes it correctly regardless of context.
                // ~keep   • Raw-text elements (script/style/textarea/…) bail before
                // ~keep     reaching this arm, so we never skip inside them.
                match memchr2(b'<', b'&', &bytes[pos..]) {
                    Some(offset) if offset > 0 => pos += offset,
                    Some(_) => pos += 1,
                    None => pos = bytes.len(),
                }
            }
        }
    }

    if text_start < pos {
        flush_text(&mut state, &html[text_start..pos], text_start)?;
    }

    // ~keep Phase N2: implicitly close all remaining open elements at EOF.
    // ~keep HTML5 parsers (html5ever and tl) close every open element when input
    // ~keep ends, so Tier-2 produces output even for malformed input like
    // ~keep `<p>hello <b>world` (no `</b>`, no `</p>`).  Mirror that here by
    // ~keep running emit_close_for_implicit on every remaining frame, regardless
    // ~keep of whether it has an OptionalCloseRule.
    // ~keep
    // ~keep Before closing, trim trailing inline whitespace (spaces, tabs, newlines)
    // ~keep from the output buffer.  In well-formed HTML the close tag arrives
    // ~keep before the file's trailing newline; the inline close-marker emission
    // ~keep (e.g. `**` for `</strong>`) lands flush against the content.  At EOF
    // ~keep any trailing newline is between the implicit close and the file end,
    // ~keep not inside the inline body, so we trim it before pushing the close
    // ~keep marker to match Tier-2's `world**` instead of `world\n**`.
    while !state.stack.is_empty() {
        let buf = &mut state.output;
        while matches!(buf.as_bytes().last(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            buf.pop();
        }
        emit_close_for_implicit(&mut state, options)?;
    }

    // ~keep Collapse runs of 3+ consecutive newlines to exactly 2, matching Tier-2's
    // ~keep `collapse_excess_blank_lines` post-processing step.
    if state.output.contains("\n\n\n") {
        collapse_excess_blank_lines(&mut state.output);
    }

    // ~keep Normalise trailing newlines to match Tier-2's final-output contract:
    // ~keep   `format!("{}\n", output.trim_end_matches('\n'))`
    // ~keep Tier-2 strips all trailing newlines and appends exactly one.  We mirror
    // ~keep that here so paragraphs (which emit "\n\n") don't leave an extra blank
    // ~keep line at the end.
    if !state.output.is_empty() {
        let trimmed_end = state.output.trim_end_matches('\n');
        if trimmed_end.is_empty() {
            state.output.clear();
        } else {
            let trimmed_len = trimmed_end.len();
            state.output.truncate(trimmed_len);
            state.output.push('\n');
        }
    }

    Ok(ScanOutput {
        body: state.output,
        head_range: state.head_range,
    })
}

// ~keep ── Bail guard ────────────────────────────────────────────────────────────────

/// Return `Err(BailReason::Classifier)` for tag kinds not supported in M9.
///
/// Table-related tags are now handled by the scanner (M9); they are no longer
/// bailed here.  Table-specific bail reasons are emitted by the table-handling
/// code in `emit_open` and `emit_close`.
/// Locate the matching close tag for `tag_name` starting at `open_end`.
///
/// Returns `Some((close_start, close_end))` where `close_start` is the byte
/// index of the `<` opening the `</tag>` close and `close_end` is the byte
/// index immediately after its `>`.  `None` when no matching close exists.
///
/// Used by `<head>` silent-skip to record the content slice
/// (`open_end..close_start`) for metadata extraction while advancing past the
/// entire `<head>…</head>` block.
fn find_close_tag_range(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<(usize, usize)> {
    let len = bytes.len();
    let mut idx = open_end;
    while idx < len {
        match memchr3(b'<', b'<', b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 2 < len && bytes[idx + 1] == b'/' {
            let after_slash = idx + 2;
            if after_slash + tag_name.len() <= len
                && bytes[after_slash..after_slash + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let post_name = after_slash + tag_name.len();
                if matches!(bytes.get(post_name), Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r')) {
                    let mut j = post_name;
                    while j < len && bytes[j] != b'>' {
                        j += 1;
                    }
                    if j < len {
                        return Some((idx, j + 1));
                    }
                    return None;
                }
            }
        }
        idx += 1;
    }
    None
}

// ~keep ── SVG helpers ───────────────────────────────────────────────────────────────

/// Find the byte offset immediately after the matching `</svg>` close tag,
/// starting from `open_end` (the byte after the `>` of the opening `<svg ...>`).
///
/// Tracks nesting depth so nested `<svg>` elements (valid in SVG 1.1) are
/// handled correctly.  Returns `None` when no matching close is found.
fn find_svg_close(bytes: &[u8], open_end: usize) -> Option<usize> {
    find_balanced_close(bytes, open_end, b"svg")
}

/// Find the byte offset immediately after the matching close tag for
/// `tag_name`, starting from `open_end` (the byte after the `>` of the
/// opening tag).  Tracks nesting depth so nested same-name elements are
/// handled correctly.  Returns `None` when no matching close is found.
fn find_balanced_close(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut idx = open_end;
    let mut depth = 1usize;
    while idx < len {
        match memchr::memchr(b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 1 < len && bytes[idx + 1] == b'/' {
            let name_start = idx + 2;
            if name_start + tag_name.len() <= len
                && bytes[name_start..name_start + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let after = name_start + tag_name.len();
                if matches!(
                    bytes.get(after),
                    Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') | None
                ) {
                    depth -= 1;
                    if depth == 0 {
                        let mut j = after;
                        while j < len && bytes[j] != b'>' {
                            j += 1;
                        }
                        return Some(j + 1);
                    }
                }
            }
        } else if idx + 1 < len {
            let name_start = idx + 1;
            if name_start + tag_name.len() <= len
                && bytes[name_start..name_start + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let after = name_start + tag_name.len();
                if matches!(
                    bytes.get(after),
                    Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r') | None
                ) {
                    let mut j = after;
                    let mut in_q: Option<u8> = None;
                    let tag_end = loop {
                        if j >= len {
                            break len;
                        }
                        match bytes[j] {
                            b'"' | b'\'' => {
                                if let Some(q) = in_q {
                                    if q == bytes[j] {
                                        in_q = None;
                                    }
                                } else {
                                    in_q = Some(bytes[j]);
                                }
                            }
                            b'>' if in_q.is_none() => {
                                break j + 1;
                            }
                            _ => {}
                        }
                        j += 1;
                    };
                    let is_self_closing = tag_end >= 2 && bytes[tag_end - 2] == b'/';
                    if !is_self_closing {
                        depth += 1;
                    }
                }
            }
        }
        idx += 1;
    }
    None
}

/// Emit a `<svg>` element as a Markdown base64 data URI, matching Tier-2's
/// `handle_svg` output byte-for-byte.
///
/// `svg_slice` is the raw HTML source bytes for the entire `<svg…>…</svg>`
/// element.  We re-parse it with `tl::parse` to get the canonical attribute
/// order that `serialize_element` produces (it sorts attributes alphabetically,
/// so raw-source slicing would diverge from Tier-2).
///
/// Mirrors Tier-2's `media/svg.rs::handle_svg`:
/// - Walks children for a `<title>` tag → alt text.  Default: "SVG Image".
/// - Calls `serialize_element` on the root SVG node.
/// - Base64-encodes (STANDARD engine) the serialized bytes.
/// - Emits `![{title}](data:image/svg+xml;base64,{b64})`.
/// - When `options.skip_images` → emits nothing (matches Tier-2 skip).
fn emit_svg_from_slice(
    svg_slice: &str,
    svg_start_offset: usize,
    state: &mut Tier1State,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    // ~keep CDATA inside SVG cannot be processed correctly without the prescan's
    // ~keep entity-escaping transformation.  Bail to Tier-2 so it sees the
    // ~keep prescan-normalized form (where `<![CDATA[` is escaped to `&lt;![CDATA[`).
    if svg_slice.contains("<![CDATA[") {
        return Err(BailReason::Cdata {
            offset: svg_start_offset,
        });
    }

    if options.skip_images {
        return Ok(());
    }

    use crate::converter::media::svg::serialize_element;
    use base64::{Engine as _, engine::general_purpose::STANDARD};

    // ~keep Re-parse just the SVG fragment.  Wrap it in a minimal document so
    // ~keep tl has proper context — the same pattern used by head_metadata.rs.
    let wrapped = format!("<html><body>{svg_slice}</body></html>");
    let dom = match tl::parse(&wrapped, tl::ParserOptions::default()) {
        Ok(d) => d,
        Err(_) => {
            // ~keep Parse failure: emit nothing rather than bail — matches
            // ~keep Tier-2's silent skip on serialization failure.
            return Ok(());
        }
    };
    let parser = dom.parser();

    // ~keep Locate the first `<svg>` node in the parsed fragment.
    let svg_handle = dom.nodes().iter().enumerate().find_map(|(i, node)| {
        if let tl::Node::Tag(tag) = node {
            if tag.name().as_utf8_str().as_ref().eq_ignore_ascii_case("svg") {
                Some(tl::NodeHandle::new(i as u32))
            } else {
                None
            }
        } else {
            None
        }
    });

    let Some(handle) = svg_handle else {
        return Ok(());
    };

    // ~keep Extract title from a direct `<title>` child, mirroring Tier-2.
    let title = if let Some(tl::Node::Tag(svg_tag)) = handle.get(parser) {
        let mut found = String::from("SVG Image");
        for child_handle in svg_tag.children().top().iter() {
            if let Some(tl::Node::Tag(child)) = child_handle.get(parser) {
                if child.name().as_utf8_str().as_ref().eq_ignore_ascii_case("title") {
                    let mut text = String::new();
                    for grandchild in child.children().top().iter() {
                        if let Some(tl::Node::Raw(raw)) = grandchild.get(parser) {
                            text.push_str(&raw.as_utf8_str());
                        }
                    }
                    let trimmed = text.trim().to_owned();
                    if !trimmed.is_empty() {
                        found = trimmed;
                    }
                    break;
                }
            }
        }
        found
    } else {
        String::from("SVG Image")
    };

    let svg_html = serialize_element(&handle, parser);
    let base64_svg = STANDARD.encode(svg_html.as_bytes());

    let dest = state.cell_or_output_mut();
    dest.push_str("![");
    dest.push_str(&title);
    dest.push_str("](data:image/svg+xml;base64,");
    dest.push_str(&base64_svg);
    dest.push(')');

    Ok(())
}

/// Skip the body of a raw-text element (script/style/textarea/iframe/…).
///
/// `open_end` is the byte index immediately after the tag's `>`.  `tag_name`
/// is the lowercased open-tag name.  Returns the byte index after the
/// matching `</tag>` close, or `None` if no matching close tag exists in the
/// remainder of the input.
///
/// Mirrors the prescan's STRIP_CONTENT_TAGS handling: content is discarded,
/// only the position advances.  Matches Tier-2's behaviour byte-for-byte
/// because Tier-2 sees this content already stripped by the prescan.
fn find_raw_text_close(bytes: &[u8], open_end: usize, tag_name: &[u8]) -> Option<usize> {
    let len = bytes.len();
    let mut idx = open_end;
    while idx < len {
        match memchr3(b'<', b'<', b'<', &bytes[idx..]) {
            Some(off) => idx += off,
            None => return None,
        }
        if idx + 2 < len && bytes[idx + 1] == b'/' {
            let after_slash = idx + 2;
            if after_slash + tag_name.len() <= len
                && bytes[after_slash..after_slash + tag_name.len()].eq_ignore_ascii_case(tag_name)
            {
                let post_name = after_slash + tag_name.len();
                if matches!(bytes.get(post_name), Some(b'>' | b'/' | b' ' | b'\t' | b'\n' | b'\r')) {
                    let mut j = post_name;
                    while j < len && bytes[j] != b'>' {
                        j += 1;
                    }
                    if j < len {
                        return Some(j + 1);
                    }
                    return None;
                }
            }
        }
        idx += 1;
    }
    None
}

#[inline]
const fn bail_unsupported(spec: &TagSpec, _offset: usize) -> Result<(), BailReason> {
    match spec.kind {
        // ~keep Raw-text content tags are handled inline by the main scan loop
        // ~keep (see find_raw_text_close).  They never reach this point in practice;
        // ~keep listed here only to make the match exhaustive over TagKind::RawText.
        TagKind::RawText(_) => Err(BailReason::Classifier),

        // ~keep `Ignored` tags (head/meta/link/script/style) are now handled inline
        // ~keep by the main scan loop (see the dispatch above `bail_unsupported`).
        // ~keep The match arm is kept for exhaustiveness — it cannot fire in
        // ~keep practice.
        TagKind::Ignored => Err(BailReason::Classifier),

        _ => Ok(()),
    }
}

fn emit_open(
    state: &mut Tier1State,
    spec: &'static TagSpec,
    attrs: &[(&[u8], Option<&[u8]>)],
) -> Result<(), BailReason> {
    // ~keep Phase V: when a block-level tag opens inside a link, bail.  Tier-2's
    // ~keep link handler collapses block children (img alt, paragraph text) into
    // ~keep an inline link label; replicating that in Tier-1 requires content
    // ~keep capture similar to Phase R's summary buffer.  Until that lands, bail
    // ~keep so Tier-2's fallback handles the collapse.
    if matches!(
        spec.kind,
        TagKind::Block
            | TagKind::Paragraph
            | TagKind::Heading(_)
            | TagKind::Blockquote
            | TagKind::Pre
            | TagKind::List(_)
            | TagKind::Table
    ) && state.stack.iter().any(|f| matches!(f.spec.kind, TagKind::Link))
    {
        return Err(BailReason::Classifier);
    }
    match spec.kind {
        TagKind::Paragraph => open_paragraph(state),
        TagKind::Heading(_) => open_heading(state),
        TagKind::Blockquote => open_blockquote(state),
        TagKind::Pre => open_pre(state, attrs),
        TagKind::List(ListKind::Definition) => open_dl(state),
        TagKind::List(kind) => open_list(state, kind),
        TagKind::ListItem => open_list_item(state),
        TagKind::DefinitionTerm => open_dt(state),
        TagKind::DefinitionDescription => open_dd(state),
        TagKind::Strong => {
            // ~keep Inside a <summary> accumulation buffer, Tier-2 processes
            // ~keep children with `in_strong: true` which suppresses nested
            // ~keep strong markers.  Mirror that by not pushing `**` when inside
            // ~keep a summary, so `<strong>b</strong>` inside `<summary>` emits
            // ~keep just `b` instead of `**b**`.
            // ~keep Phase FF-2: figcaption uses the same buffer stack but
            // ~keep Tier-2 does NOT set in_strong for figcaption children, so
            // ~keep emit `**` normally when the topmost wrap-buf is a
            // ~keep figcaption (or there's no wrap-buf at all).
            if !state.summary_at_top() {
                state.cell_or_output_mut().push_str("**");
            }
        }
        TagKind::Emphasis => {
            state.cell_or_output_mut().push('*');
        }
        TagKind::Strikethrough => {
            // ~keep Tier-2's handle_strikethrough suppresses the `~~` wrapping
            // ~keep when inside `<code>`/`<pre>` (in_code).  Mirror via EscapeCtx.
            if !state.escape_ctx.contains(EscapeCtx::CODE) && !state.escape_ctx.contains(EscapeCtx::PRE) {
                state.cell_or_output_mut().push_str("~~");
            }
        }
        TagKind::Inserted => {
            // ~keep Tier-2's handle_inserted emits `==` markers unconditionally for
            // ~keep <ins>.  Mirror Strikethrough's in-code/pre suppression for
            // ~keep consistency (no `==` inside backtick spans / fenced blocks).
            if !state.escape_ctx.contains(EscapeCtx::CODE) && !state.escape_ctx.contains(EscapeCtx::PRE) {
                state.cell_or_output_mut().push_str("==");
            }
        }
        // ~keep Phase CC: defer the open backtick marker — close_code does
        // ~keep smart escaping based on the content (mirrors Tier-2's
        // ~keep render_code_with_escaping at inline/code.rs:260).  Inside an
        // ~keep outer <code> or <pre>, the inner code is transparent.
        TagKind::Code if !state.escape_ctx.contains(EscapeCtx::PRE) && !state.escape_ctx.contains(EscapeCtx::CODE) => {}
        TagKind::Code if state.pre_lang.is_none() && state.escape_ctx.contains(EscapeCtx::PRE) => {
            if let Some(lang) = extract_language_from_class(attrs) {
                state.pre_lang = Some(lang);
            }
        }
        TagKind::Link => open_link(state),
        TagKind::Table => open_table(state),
        TagKind::TableCaption => open_table_caption(state),
        TagKind::TableHead => open_table_head(state)?,
        TagKind::TableBody => open_table_body(state)?,
        TagKind::TableFoot => open_table_foot(state),
        TagKind::TableRow => open_table_row(state),
        TagKind::TableCell { is_header } => open_table_cell(state, attrs, is_header)?,
        // ~keep Block containers: emit a leading blank-line separator when there's
        // ~keep already preceding content.  Mirrors Tier-2's div/sectioning handlers
        // ~keep (block/div.rs:88, semantic/sectioning.rs:71) which prefix block
        // ~keep content with `\n\n` to separate from siblings.
        // ~keep
        // ~keep Inside a table cell, Tier-2's div.rs:60 treats a sibling-div as a
        // ~keep "table continuation" and emits `"  \n"` (two-space + newline) when
        // ~keep the cell already has non-`|`/non-`<br>` content.  After
        // ~keep `close_table_cell`'s `replace('\n', ' ')` step, this becomes a 3-space
        // ~keep run between sibling divs — matching Tier-2's lists_timeline cell
        // ~keep layout `[link]   [other-link]`.  Without this, Tier-1 emits 1 space.
        TagKind::Block => {
            if state.in_table_cell() {
                let cell_buf = state.cell_or_output_mut();
                if !cell_buf.is_empty()
                    && !cell_buf.ends_with('|')
                    && !cell_buf.ends_with("<br>")
                    && !cell_buf.ends_with("  \n")
                {
                    while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
                        cell_buf.pop();
                    }
                    cell_buf.push_str("  \n");
                }
            } else {
                state.ensure_blank_line();
            }
        }
        // ~keep Summary: push accumulation buffer so children redirect into it (Phase R).
        TagKind::Summary => open_summary(state),
        // ~keep Figcaption: same buffer mechanism as summary (Phase FF-2); the
        // ~keep wrap delimiter differs (`*…*` vs `**…**`) and is emitted by
        // ~keep close_figcaption.
        TagKind::Figcaption => open_figcaption(state),
        // ~keep Button: no leading separator (matches Tier-2 handle_button which
        // ~keep does nothing on open).  Close-side `\n\n` is emitted by close_button.
        TagKind::Button => {}
        TagKind::Inline => {}
        _ => {}
    }

    Ok(())
}

fn open_paragraph(state: &mut Tier1State) {
    // ~keep When inside a table cell, treat `<p>` as a transparent container.
    // ~keep Tier-2's paragraph.rs emits `<br>` when `in_table_cell` and there is
    // ~keep already cell content; we mirror that behaviour so the cell buffer stays
    // ~keep on one logical line (no `\n` in cell output to collapse later).
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        if !cell_buf.is_empty() && !cell_buf.ends_with("<br>") {
            cell_buf.push_str("<br>");
        }
        return;
    }
    // ~keep Mirrors Tier-2: when output is non-empty and doesn't already end
    // ~keep with "\n\n", push "\n\n" (may produce three newlines total when
    // ~keep output ends with a single "\n", e.g. right after a table row or
    // ~keep an `<hr>`).
    let dest = state.cell_or_output_mut();
    // ~keep Phase EE: when the paragraph is the first child of a list-item
    // ~keep (output ends with a freshly-emitted bullet like `- ` or `1. `),
    // ~keep the paragraph content joins the bullet inline.  Tier-2's
    // ~keep paragraph.rs achieves this by checking the parent and skipping
    // ~keep the leading `\n\n` for the first block child.  Check BEFORE
    // ~keep `trim_trailing_horizontal`, which would strip the trailing
    // ~keep space from the bullet.
    if dest.ends_with("- ") || dest.ends_with("* ") || dest.ends_with("+ ") || ends_with_ordered_marker(dest) {
        return;
    }
    // ~keep Drop trailing horizontal whitespace from inter-tag preservation
    // ~keep (Phase U-2) before the block separator.
    crate::converter::tier1::state::trim_trailing_horizontal(dest);
    if !dest.is_empty() && !dest.ends_with("\n\n") {
        dest.push_str("\n\n");
    }
}

fn open_heading(state: &mut Tier1State) {
    // ~keep When inside a table cell, Tier-2 does NOT add a leading separator before
    // ~keep the heading (`needs_leading_sep = false` when `in_table_cell`).  The
    // ~keep heading text is emitted directly into the cell accumulator with no `#`
    // ~keep prefix and no surrounding newlines.
    if state.in_table_cell() {
        return;
    }
    state.ensure_blank_line();
}

fn open_blockquote(state: &mut Tier1State) {
    state.ensure_blank_line();
}

fn open_pre(state: &mut Tier1State, attrs: &[(&[u8], Option<&[u8]>)]) {
    state.ensure_blank_line();
    if let Some(lang) = extract_language_from_class(attrs) {
        state.pre_lang = Some(lang);
    }
}

/// Extract the language tag from a `class` attribute matching `language-X`
/// or `lang-X`.  Mirrors Tier-2's `extract_language_from_pre`.
fn extract_language_from_class(attrs: &[(&[u8], Option<&[u8]>)]) -> Option<String> {
    let class_bytes = find_attr(attrs, b"class")?;
    let class = std::str::from_utf8(class_bytes).ok()?;
    for cls in class.split_ascii_whitespace() {
        if let Some(rest) = cls.strip_prefix("language-") {
            return Some(rest.to_owned());
        }
        if let Some(rest) = cls.strip_prefix("lang-") {
            return Some(rest.to_owned());
        }
    }
    None
}

fn open_list(state: &mut Tier1State, kind: ListKind) {
    // ~keep When inside a table cell, mirror Tier-2's `add_list_leading_separator`:
    // ~keep push `<br>` if there is already cell content (but not if it already ends
    // ~keep with `|`, ` `, or `<br>`).  Do not touch `state.output`.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        if !cell_buf.is_empty() && !cell_buf.ends_with('|') && !cell_buf.ends_with(' ') && !cell_buf.ends_with("<br>") {
            cell_buf.push_str("<br>");
        }
        state.list_depth = state.list_depth.saturating_add(1);
        if matches!(kind, ListKind::Unordered) {
            state.ul_depth = state.ul_depth.saturating_add(1);
        }
        return;
    }
    let current_list_depth = state.list_depth;
    {
        let dest = state.cell_or_output_mut();
        // ~keep Drop trailing horizontal whitespace from inter-tag preservation
        // ~keep (Phase U-2) before the block separator.
        crate::converter::tier1::state::trim_trailing_horizontal(dest);
        if !dest.is_empty() {
            if current_list_depth == 0 {
                if !dest.ends_with("\n\n") {
                    if dest.ends_with('\n') {
                        dest.push('\n');
                    } else {
                        dest.push_str("\n\n");
                    }
                }
            } else {
                if !dest.ends_with('\n') {
                    dest.push('\n');
                }
            }
        }
    }
    state.list_depth = state.list_depth.saturating_add(1);
    if matches!(kind, ListKind::Unordered) {
        state.ul_depth = state.ul_depth.saturating_add(1);
    }
}

/// Cycle through the canonical default `options.bullets` value (`"-*+"`) by
/// `<ul>` nesting depth.  The router (`router.rs::classify`) gates Tier-1 to
/// the literal default, so this hardcoded cycle reproduces Tier-2 byte-for-byte.
const TIER1_BULLETS: [u8; 3] = [b'-', b'*', b'+'];

fn open_list_item(state: &mut Tier1State) {
    // ~keep When inside a table cell, Tier-2 does NOT emit bullet/number prefixes
    // ~keep for list items (see list/item.rs: `if !ctx.in_table_cell { ... bullet ... }`).
    // ~keep The cell accumulator already receives the raw text; separators are handled
    // ~keep by the `\n` → ` ` replacement at cell-close time.
    if state.in_table_cell() {
        if find_parent_list_kind(&state.stack) == Some(ListKind::Ordered) {
            increment_ol_counter(&mut state.stack);
        }
        return;
    }
    let parent_kind = find_parent_list_kind(&state.stack);
    let indent_depth = state.list_depth.saturating_sub(1);
    if parent_kind == Some(ListKind::Ordered) {
        let counter = increment_ol_counter(&mut state.stack);
        let start = find_ol_start(&state.stack);
        let index = start.saturating_sub(1) + counter;
        push_list_item_indent(&mut state.output, indent_depth);
        #[allow(clippy::format_push_string)]
        state.output.push_str(&format!("{index}. "));
    } else {
        push_list_item_indent(&mut state.output, indent_depth);
        let bullet_idx = state.ul_depth.saturating_sub(1) as usize % TIER1_BULLETS.len();
        state.output.push(TIER1_BULLETS[bullet_idx] as char);
        state.output.push(' ');
    }
}

fn open_link(state: &mut Tier1State) {
    // ~keep Track link count inside tables for layout-table detection.
    if let Some(ts) = state.table_stack.last_mut() {
        ts.link_count += 1;
    }
    state.cell_or_output_mut().push('[');
}

fn open_table(state: &mut Tier1State) {
    // ~keep Phase HH: nested tables are no longer a bail; an inner table inherits
    // ~keep `inline_mode = true` so its final GFM rendering writes into the parent
    // ~keep cell buffer rather than `state.output`.  The parent cell's newline
    // ~keep collapse then flattens the inner table to a single inline run.
    let inline_mode = !state.table_stack.is_empty();
    state.table_stack.push(crate::converter::tier1::state::TableState {
        inline_mode,
        ..Default::default()
    });
}

fn open_table_caption(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.caption_buf.clear();
        ts.in_caption = true;
    }
}

fn open_table_head(state: &mut Tier1State) -> Result<(), BailReason> {
    if let Some(ts) = state.table_stack.last_mut() {
        if ts.seen_tbody_close || ts.seen_tfoot {
            return Err(BailReason::TableSectionOrder);
        }
        ts.in_thead = true;
    }
    Ok(())
}

fn open_table_body(state: &mut Tier1State) -> Result<(), BailReason> {
    if let Some(ts) = state.table_stack.last_mut() {
        if ts.seen_tfoot {
            return Err(BailReason::TableSectionOrder);
        }
    }
    Ok(())
}

fn open_table_foot(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.seen_tfoot = true;
    }
}

fn open_table_row(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.current_row.clear();
    }
}

fn open_table_cell(
    state: &mut Tier1State,
    attrs: &[(&[u8], Option<&[u8]>)],
    is_header: bool,
) -> Result<(), BailReason> {
    // ~keep rowspan: accepted but not expanded (lossy — a spanned cell renders once,
    // ~keep matching mdream).  colspan: expanded by `close_table_cell` adding
    // ~keep `(colspan - 1)` empty cells so Tier-2's column-count expectations are
    // ~keep met (without this, infobox-style `<th colspan="2">` rows trigger Tier-2's
    // ~keep layout-table fallback in close_table on what should be a normal GFM table).
    let colspan = find_attr(attrs, b"colspan")
        .and_then(|b| std::str::from_utf8(b).ok())
        .and_then(|s| s.parse::<u16>().ok())
        .unwrap_or(1)
        .max(1);
    if let Some(ts) = state.table_stack.last_mut() {
        ts.current_cell.clear();
        ts.in_cell = true;
        ts.current_cell_colspan = colspan;
        if is_header {
            ts.has_th = true;
        }
    }
    Ok(())
}

/// Emit a void element (no closing tag).
fn emit_void(
    state: &mut Tier1State,
    spec: &'static TagSpec,
    attrs: &[(&[u8], Option<&[u8]>)],
    html: &str,
    options: &ConversionOptions,
) -> Result<(), BailReason> {
    match spec.kind {
        TagKind::Hr => {
            {
                let dest = state.cell_or_output_mut();
                if !dest.is_empty() && !dest.ends_with("\n\n") {
                    if dest.ends_with('\n') {
                        dest.push('\n');
                    } else {
                        dest.push_str("\n\n");
                    }
                }
            }
            state.cell_or_output_mut().push_str("---\n");
        }

        TagKind::LineBreak => {
            // ~keep `<br>` outside any block context emits nothing (Tier-2 behaviour).
            // ~keep Three context-dependent emissions:
            // ~keep   - Inside a link (anywhere): one space.  Tier-2's
            // ~keep     `normalize_link_label` (utility/content.rs ~145) collapses
            // ~keep     whitespace runs in link labels, so multiple spaces or
            // ~keep     `  \n` would normalize back to one space.
            // ~keep   - Inside a table cell (not in a link): emit a single sentinel
            // ~keep     `\u{0001}`.  `close_table_cell` collapses whitespace runs
            // ~keep     before normalising the sentinel to three spaces — matches
            // ~keep     Tier-2 walking `<br>` to `"  \n"` and `replace('\n', ' ')`
            // ~keep     producing `"   "` (three spaces).
            // ~keep   - Inside a regular block (paragraph, div, etc.): `"  \n"`.
            let in_link = state.stack.iter().any(|f| matches!(f.spec.kind, TagKind::Link));
            if in_link {
                state.cell_or_output_mut().push(' ');
            } else if state.in_table_cell() {
                state.cell_or_output_mut().push('\u{0001}');
            } else if state.stack.is_empty() {
                // ~keep bare `<br>` at top level — Tier-2 emits nothing
            } else {
                state.cell_or_output_mut().push_str("  \n");
            }
        }

        TagKind::Image => {
            let src = find_attr(attrs, b"src").unwrap_or_default();
            let alt = find_attr(attrs, b"alt").unwrap_or_default();
            let title = find_attr(attrs, b"title");

            // ~keep Phase DD: src gets entity-decoding (URL semantics).
            // ~keep For alt/title:
            // ~keep   • With custom-element tags → T2 ran html5ever roundtrip
            // ~keep     and canonicalized entities; decode + re-encode the
            // ~keep     special set to match.
            // ~keep   • Without → T2 just yields tl's raw attribute bytes;
            // ~keep     keep entities verbatim.
            let src = decode_attr(src)?;
            let canonicalize = state.canonicalize_attr_entities;
            let alt_owned;
            let alt: &str = if canonicalize {
                alt_owned = canonicalize_attr_entities(&decode_attr(alt)?).into_owned();
                &alt_owned
            } else {
                std::str::from_utf8(alt).map_err(|_| BailReason::Classifier)?
            };

            let keep_as_markdown = should_keep_image_as_markdown(html, &state.stack, options);

            let dest = state.cell_or_output_mut();
            if keep_as_markdown {
                if let Some(title_bytes) = title {
                    let title_owned;
                    let title_str: &str = if canonicalize {
                        title_owned = canonicalize_attr_entities(&decode_attr(title_bytes)?).into_owned();
                        &title_owned
                    } else {
                        std::str::from_utf8(title_bytes).map_err(|_| BailReason::Classifier)?
                    };
                    #[allow(clippy::format_push_string)]
                    dest.push_str(&format!("![{alt}]({src} \"{title_str}\")"));
                } else {
                    #[allow(clippy::format_push_string)]
                    dest.push_str(&format!("![{alt}]({src})"));
                }
            } else {
                // ~keep Strip to alt-text only — mirrors Tier-2 behaviour when the image
                // ~keep is in a heading whose tag is not in `keep_inline_images_in`.
                dest.push_str(alt);
            }
        }

        TagKind::Ignored | TagKind::Inline | TagKind::Block => {}

        _ => {}
    }
    Ok(())
}

/// Decide whether an `<img>` should be emitted as `![alt](src)` markdown.
///
/// When the `inline-images` feature is disabled, images are always kept as
/// markdown (original Tier-1 behaviour).
///
/// When the feature is enabled this mirrors the Tier-2 logic in
/// `converter.rs`:
/// - `keep_inline_images_in` empty → always emit markdown image.
/// - `keep_inline_images_in` non-empty → emit markdown only when the image
///   has a heading ancestor (`h1`–`h6`) whose (lowercased) tag name is in the
///   list; otherwise emit alt-text only.
///
/// Ancestor matching is ASCII-case-insensitive so callers may supply "H1" or
/// "h1" interchangeably.
#[inline]
#[allow(clippy::missing_const_for_fn)]
fn should_keep_image_as_markdown(html: &str, stack: &[OpenTag], options: &ConversionOptions) -> bool {
    #[cfg(feature = "inline-images")]
    {
        keep_inline_image_for_ancestors(html.as_bytes(), stack, &options.keep_inline_images_in)
    }
    #[cfg(not(feature = "inline-images"))]
    {
        let _ = html;
        let _ = stack;
        let _ = options;
        true
    }
}

/// Return `true` when the `<img>` should be emitted as `![alt](src)` markdown.
///
/// Mirrors the Tier-2 logic in `converter.rs`: images are kept as markdown
/// unconditionally when `keep_inline_images_in` is empty.  When the list is
/// non-empty, an image is kept only when it has a heading ancestor (`h1`–`h6`)
/// whose (lowercased) tag name appears in the list; otherwise the caller should
/// emit alt-text only.
///
/// The comparison is ASCII-case-insensitive on both the stack name bytes and the
/// user-supplied strings, so callers may supply "H1" or "h1" interchangeably.
#[cfg(feature = "inline-images")]
fn keep_inline_image_for_ancestors(input: &[u8], stack: &[OpenTag], keep: &[String]) -> bool {
    if keep.is_empty() {
        // ~keep No restriction — always emit markdown image (Tier-2 default).
        return true;
    }
    for frame in stack.iter().rev() {
        if matches!(frame.spec.kind, TagKind::Heading(_)) {
            let name = &input[frame.name_range.clone()];
            for keep_name in keep {
                if eq_ascii_ignore_case(name, keep_name.as_bytes()) {
                    return true;
                }
            }
            return false;
        }
    }
    // ~keep No heading ancestor at all: no restriction applies — emit markdown image.
    // ~keep This matches Tier-2 behaviour: the `keep_inline_images_in` guard only
    // ~keep fires when `ctx.in_heading` is true.
    true
}

/// Byte-level ASCII case-insensitive comparison — no allocation.
#[cfg(feature = "inline-images")]
fn eq_ascii_ignore_case(a: &[u8], b: &[u8]) -> bool {
    a.eq_ignore_ascii_case(b)
}

fn emit_close(state: &mut Tier1State, tag_name_bytes: &[u8], options: &ConversionOptions) -> Result<(), BailReason> {
    let mut name_buf = [0u8; MAX_TAG_NAME_BYTES];
    let name_lower = lowercase_into(tag_name_bytes, &mut name_buf);

    // ~keep Custom element close tags (e.g. `</x-foo>`) use the same static Block
    // ~keep spec as their corresponding open tag.  All other unknown close tags bail.
    let spec: &'static TagSpec = if name_lower.contains(&b'-') {
        &CUSTOM_ELEMENT_BLOCK_SPEC
    } else {
        match tier1::lookup(name_lower) {
            Some(s) => s,
            None => {
                return Err(BailReason::UnknownCustomElement {
                    name: bytes_to_string(tag_name_bytes).into(),
                    offset: 0,
                });
            }
        }
    };

    while let Some(top) = state.stack.last() {
        if kinds_match(&top.spec.kind, &spec.kind) {
            break;
        }
        if top.spec.optional_close.is_some() {
            emit_close_for_implicit(state, options)?;
        } else {
            break;
        }
    }

    // ~keep Pop the matching frame from the open-tag stack.
    // ~keep Tier-2 is lenient about mismatched tags; for M3c we bail.
    let actual_depth = state.stack.len() as u8;
    let frame = pop_matching_frame(&mut state.stack, spec).ok_or_else(|| BailReason::DepthMismatch {
        tag: bytes_to_string(name_lower),
        expected: 1,
        actual: actual_depth,
    })?;

    state.escape_ctx = frame.prev_escape_ctx;

    match spec.kind {
        TagKind::Paragraph => close_paragraph(state),
        TagKind::Heading(n) => close_heading(state, &frame, n, false)?,
        TagKind::Blockquote => close_blockquote(state, &frame),
        TagKind::Pre => close_pre(state, &frame, options),
        // ~keep Strong: suppress close marker when inside summary (see open strong guard).
        TagKind::Strong if state.summary_at_top() => {}
        TagKind::Strong => close_inline_marker(state, &frame, "**"),
        TagKind::Emphasis => close_inline_marker(state, &frame, "*"),
        TagKind::Strikethrough
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strikethrough => close_inline_marker(state, &frame, "~~"),
        TagKind::Inserted
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Inserted => close_inline_marker(state, &frame, "=="),
        TagKind::Code => close_code(state, &frame),
        TagKind::Link => close_link(state, &frame),
        TagKind::List(ListKind::Definition) => close_dl(state, &frame),
        TagKind::List(kind) => close_list(state, kind),
        TagKind::ListItem => close_list_item(state, &frame),
        TagKind::DefinitionTerm => close_dt(state),
        TagKind::DefinitionDescription => close_dd(state),
        TagKind::Hr => {}
        TagKind::Table => close_table(state)?,
        TagKind::TableHead => close_table_head(state),
        TagKind::TableBody => close_table_body(state),
        TagKind::TableFoot => {}
        TagKind::TableRow => close_table_row(state),
        TagKind::TableCell { .. } => close_table_cell(state, false)?,
        TagKind::TableCaption => close_table_caption(state),
        // ~keep Generic block container close: when it produced visible content,
        // ~keep ensure a paragraph-break separator follows so the next sibling
        // ~keep doesn't run together with this div's last byte.  Mirrors Tier-2's
        // ~keep `div::handle` post-children block: `output.push_str("\n\n")` when
        // ~keep `has_content` (see block/div.rs around line 124-130).
        TagKind::Block => close_block_container(state, &frame),
        // ~keep Summary: pop accumulation buffer, trim, emit `**…**\n\n` (Phase R).
        TagKind::Summary => close_summary(state, &frame),
        // ~keep Figcaption: pop accumulation buffer, trim, emit `*…*\n\n` (Phase FF-2).
        TagKind::Figcaption => close_figcaption(state, &frame),
        // ~keep Button (Phase T): emit `\n\n` when content was produced — mirrors
        // ~keep Tier-2 `form/elements.rs:592-594`.  No leading separator on open.
        TagKind::Button => close_button(state, &frame),
        TagKind::Inline => {
            if name_lower == b"abbr" {
                if let Some(Some(title)) = state.abbr_titles.pop() {
                    let dest = state.cell_or_output_mut();
                    dest.push_str(" (");
                    dest.push_str(&title);
                    dest.push(')');
                }
            }
        }
        TagKind::LineBreak | TagKind::Image => {}
        TagKind::RawText(_) | TagKind::Ignored => {}
    }

    Ok(())
}

/// Append a paragraph-break separator after a generic block container close
/// (`<div>`, `<section>`, etc.) when it produced visible content.
///
/// Without this Tier-1 emits adjacent block content with no separator
/// (e.g. `[image-link](href)EN` instead of `[image-link](href)\n\nEN`),
/// diverging from Tier-2 which always emits `\n\n` after a block-with-content
/// close (see Tier-2 `block/div.rs`).  Skipped inside table cells and inline
/// contexts where the surrounding code already handles spacing.
fn close_block_container(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let buf = state.cell_or_output_mut();
    if buf.len() <= frame.content_start {
        return;
    }
    // ~keep Drop trailing horizontal whitespace (left over from inter-tag whitespace
    // ~keep preservation) before emitting the block separator.  Same rationale as
    // ~keep `ensure_blank_line` (Phase U-2).
    while buf.ends_with(' ') || buf.ends_with('\t') {
        buf.pop();
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

// ~keep ── Summary strong-wrap (Phase R) ────────────────────────────────────────────

/// Open a `<summary>` element.
///
/// Push a fresh accumulation buffer so all child text collects here instead
/// of in the outer destination (main output, table cell, or caption).
/// The summary buffer has the highest priority in `cell_or_output_mut`, so
/// even when inside a table cell the children write to this buffer rather
/// than the cell buffer.  This matches Tier-2's `handle_summary` which
/// always processes children into a local `content` buffer then wraps with
/// `**…**\n\n` before writing to the outer output.
///
/// No leading separator is emitted on open; deferred to `close_summary`
/// once we know whether the content is non-empty.
fn open_summary(state: &mut Tier1State) {
    state.push_summary_buf(crate::converter::tier1::state::WrapKind::Summary);
}

/// Close a `<summary>` element.
///
/// Pops the accumulation buffer (if any), trims it, and emits
/// `**{trimmed}**\n\n` into the parent destination (main output, an outer
/// summary buffer, a table cell, or a caption).
///
/// Mirrors Tier-2's `handle_summary` (semantic/summary.rs:138–249):
/// - collect children with `in_strong: true` (block children render inline)
/// - trim
/// - emit `**…**\n\n`
fn close_summary(state: &mut Tier1State, _frame: &OpenTag) {
    // ~keep Pop the buffer we pushed in open_summary.
    let buf = match state.pop_summary_buf() {
        Some(b) => b,
        None => return,
    };
    let trimmed = buf.trim();
    if trimmed.is_empty() {
        return;
    }
    // ~keep Acquire the parent destination.  Because we already popped the buffer
    // ~keep above, cell_or_output_mut now returns the next-outer target — which may
    // ~keep be the table cell buffer (when the summary was inside a <td>), an outer
    // ~keep summary buffer, or the main output.
    // ~keep
    // ~keep Check whether we're emitting into a table cell BEFORE borrowing `dest`,
    // ~keep so we can decide whether to add a leading separator without conflicting
    // ~keep with the mutable borrow.
    let writing_to_cell = state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Ensure a blank-line separator before the summary block when there is
    // ~keep preceding content and we're NOT writing to a table cell (cells are
    // ~keep rendered to a single line; block separators would be collapsed anyway).
    if !writing_to_cell && !dest.is_empty() && !dest.ends_with("\n\n") {
        if dest.ends_with('\n') {
            dest.push('\n');
        } else {
            dest.push_str("\n\n");
        }
    }
    dest.push_str("**");
    dest.push_str(trimmed);
    dest.push_str("**\n\n");
}

// ~keep ── Figcaption italic-wrap (Phase FF-2) ──────────────────────────────────────

/// Open a `<figcaption>` element.
///
/// Reuses the summary accumulation buffer stack — children write into it,
/// `close_figcaption` pops + wraps with `*…*\n\n` (vs Summary's `**…**`).
fn open_figcaption(state: &mut Tier1State) {
    state.push_summary_buf(crate::converter::tier1::state::WrapKind::Figcaption);
}

/// Close a `<figcaption>` element.
///
/// Mirrors Tier-2's `semantic/figure.rs::handle_figcaption`:
/// - collect children into a local buffer
/// - trim
/// - prepend single-space-or-blank-line separator
/// - emit `*{trimmed}*\n\n`
///
/// An empty/whitespace-only caption emits nothing (Tier-2 returns early).
fn close_figcaption(state: &mut Tier1State, _frame: &OpenTag) {
    let buf = match state.pop_summary_buf() {
        Some(b) => b,
        None => return,
    };
    let trimmed = buf.trim();
    if trimmed.is_empty() {
        return;
    }
    let writing_to_cell = state.in_table_cell();
    let dest = state.cell_or_output_mut();
    // ~keep Phase FF-2: trim trailing horizontal whitespace introduced by
    // ~keep Phase U-2's inter-tag-whitespace preservation, so the block
    // ~keep separator (\n\n) doesn't sit after a stray space.  Tier-2 does
    // ~keep not emit that space when the figcaption follows inline content.
    while dest.ends_with(' ') || dest.ends_with('\t') {
        dest.pop();
    }
    if !writing_to_cell && !dest.is_empty() && !dest.ends_with("\n\n") {
        if dest.ends_with('\n') {
            dest.push('\n');
        } else {
            dest.push_str("\n\n");
        }
    }
    dest.push('*');
    dest.push_str(trimmed);
    dest.push_str("*\n\n");
}

/// Close a `<button>` (Phase T).  When the button produced visible content,
/// emit `\n\n` after.  Skipped in table cells (cells stay one logical line).
///
/// Mirrors Tier-2 `form/elements.rs:592-594`:
/// ```text
/// if !ctx.convert_as_inline && output.len() > start_len {
///     output.push_str("\n\n");
/// }
/// ```
fn close_button(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let dest = state.cell_or_output_mut();
    if dest.len() <= frame.content_start {
        return;
    }
    // ~keep Drop trailing horizontal whitespace from the inter-tag fix before the
    // ~keep block separator (Phase U-2).
    while dest.ends_with(' ') || dest.ends_with('\t') {
        dest.pop();
    }
    if dest.ends_with("\n\n") {
        return;
    }
    if dest.ends_with('\n') {
        dest.push('\n');
    } else {
        dest.push_str("\n\n");
    }
}

/// Close an inline emphasis-style element (`<strong>`, `<em>`, `<b>`, `<i>`).
///
/// When the element produced no visible content (the source had `<strong></strong>`
/// or `<i>   </i>`), erase the open marker too instead of emitting an empty
/// `**` / `*` pair.  Tier-2's DOM walker reaches the same result by emitting
/// nothing for an empty inline node; the byte-equality oracle requires us to
/// match that.
fn close_inline_marker(state: &mut Tier1State, frame: &OpenTag, marker: &str) {
    let buf = state.cell_or_output_mut();
    let body_is_empty = buf.len() <= frame.content_start
        || buf[frame.content_start..]
            .bytes()
            .all(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r'));
    if body_is_empty {
        let open_marker_start = frame.content_start.saturating_sub(marker.len());
        buf.truncate(open_marker_start);
        return;
    }

    // ~keep Mirror Tier-2's `chomp_inline` (utility/content.rs:31): leading/trailing
    // ~keep whitespace (including Unicode whitespace like NBSP `\u{a0}`) inside the
    // ~keep strong/emphasis markers gets pushed OUTSIDE them so `**\u{a0}X**` becomes
    // ~keep `\u{a0}**X**`.  Required for byte-equality on Wikipedia fixtures with
    // ~keep `<b><span>&nbsp;</span>X</b>` patterns.
    let content_str = &buf[frame.content_start..];
    let leading_len = content_str.len() - content_str.trim_start().len();
    if leading_len > 0 {
        let leading: String = content_str[..leading_len].to_owned();
        buf.replace_range(frame.content_start..frame.content_start + leading_len, "");
        let marker_start = frame.content_start.saturating_sub(marker.len());
        buf.insert_str(marker_start, &leading);
    }

    buf.push_str(marker);
}

/// Implicitly close the top-of-stack frame without a matching `</tag>` in the
/// input.  Called by the M4 implicit-close loop when HTML5 optional-tag rules
/// require an open element to be closed before the next tag is pushed.
///
/// Mirrors `emit_close` but skips the stack-pop search (we always close the
/// literal top frame) and skips the tag-name lookup (we use the frame's spec
/// directly).
fn emit_close_for_implicit(state: &mut Tier1State, options: &ConversionOptions) -> Result<(), BailReason> {
    let frame = state.stack.pop().ok_or_else(|| BailReason::DepthMismatch {
        tag: String::from("(implicit)"),
        expected: 1,
        actual: 0,
    })?;
    let spec = frame.spec;

    state.escape_ctx = frame.prev_escape_ctx;

    match spec.kind {
        TagKind::Paragraph => close_paragraph(state),
        TagKind::Heading(n) => close_heading(state, &frame, n, true)?,
        TagKind::Blockquote => close_blockquote(state, &frame),
        TagKind::Pre => close_pre(state, &frame, options),
        // ~keep Strong: suppress close marker when inside summary (see open strong guard).
        TagKind::Strong if state.summary_at_top() => {}
        TagKind::Strong => close_inline_marker(state, &frame, "**"),
        TagKind::Emphasis => close_inline_marker(state, &frame, "*"),
        TagKind::Strikethrough
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Strikethrough => close_inline_marker(state, &frame, "~~"),
        TagKind::Inserted
            if state.escape_ctx.contains(EscapeCtx::CODE) || state.escape_ctx.contains(EscapeCtx::PRE) => {}
        TagKind::Inserted => close_inline_marker(state, &frame, "=="),
        TagKind::Code => close_code(state, &frame),
        TagKind::Link => close_link(state, &frame),
        TagKind::List(ListKind::Definition) => close_dl(state, &frame),
        TagKind::List(kind) => close_list(state, kind),
        TagKind::ListItem => close_list_item(state, &frame),
        TagKind::DefinitionTerm => close_dt(state),
        TagKind::DefinitionDescription => close_dd(state),
        TagKind::TableCell { .. } => close_table_cell(state, true)?,
        TagKind::TableRow => close_table_row(state),
        // ~keep Summary: pop accumulation buffer, trim, emit `**…**\n\n` (Phase R).
        TagKind::Summary => close_summary(state, &frame),
        // ~keep Figcaption: pop accumulation buffer, trim, emit `*…*\n\n` (Phase FF-2).
        TagKind::Figcaption => close_figcaption(state, &frame),
        // ~keep Button (Phase T): emit `\n\n` on EOF close just like explicit close.
        TagKind::Button => close_button(state, &frame),
        TagKind::Block | TagKind::Inline => {}
        TagKind::LineBreak
        | TagKind::Image
        | TagKind::Hr
        | TagKind::Table
        | TagKind::TableHead
        | TagKind::TableBody
        | TagKind::TableFoot
        | TagKind::TableCaption
        | TagKind::RawText(_)
        | TagKind::Ignored => {}
    }

    Ok(())
}

fn close_paragraph(state: &mut Tier1State) {
    // ~keep When inside a table cell, `<p>` is transparent — no block separators.
    // ~keep Any inter-paragraph separators were already added as `<br>` at open time
    // ~keep by `open_paragraph`; `close_paragraph` does nothing in this context.
    if state.in_table_cell() {
        return;
    }
    // ~keep Tier-2 appends "\n\n" after paragraph content (always two newlines).
    // ~keep Matching this precisely is required for byte-equal output.
    trim_trailing_inline_whitespace(state);
    state.cell_or_output_mut().push_str("\n\n");
}

/// Close a heading element.
///
/// When `is_implicit` is true the empty-heading guard is skipped: implicitly
/// closed headings have already had their content flushed through the normal
/// path, so we just prepend the prefix unconditionally.
fn close_heading(state: &mut Tier1State, frame: &OpenTag, n: u8, is_implicit: bool) -> Result<(), BailReason> {
    // ~keep When inside a table cell, Tier-2 emits the heading text directly into
    // ~keep the cell accumulator — no `#` prefix, no block separators.  The
    // ~keep `frame.content_start` is a position in the CELL buffer (set by
    // ~keep `cell_or_output_mut().len()` at emit_open time), so all position
    // ~keep arithmetic must use the cell buffer, not `state.output`.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
            cell_buf.pop();
        }
        if !is_implicit {
            let content = &state.cell_or_output_mut()[frame.content_start..];
            if content.trim().is_empty() {
                let len = frame.content_start;
                state.cell_or_output_mut().truncate(len);
            }
        }
        return Ok(());
    }

    trim_trailing_inline_whitespace(state);

    if !is_implicit {
        let content = &state.output[frame.content_start..];
        if content.trim().is_empty() {
            // ~keep Empty heading: Tier-2 emits nothing. Roll back to before
            // ~keep the heading's block separator was added.
            state.output.truncate(frame.content_start);
            let trimmed_len = state.output.trim_end_matches('\n').len();
            if trimmed_len > 0 {
                state.output.truncate(trimmed_len);
                state.output.push('\n');
            } else {
                state.output.clear();
            }
            return Ok(());
        }
    }

    // ~keep Normalize whitespace in the heading body: Tier-2's heading.rs walks
    // ~keep children with `convert_as_inline: true` which routes text through
    // ~keep text-node normalization, folding `\n + indent` runs to a single space.
    // ~keep Mirror that here so `<h3>Mozilla\n   sponsorship</h3>` emits
    // ~keep `### Mozilla sponsorship` rather than `### Mozilla\n  sponsorship`.
    if state.output[frame.content_start..].contains('\n') {
        let content = state.output[frame.content_start..].to_owned();
        let mut normalized = String::with_capacity(content.len());
        let mut prev_was_space = false;
        for ch in content.chars() {
            let is_ws = ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
            if is_ws {
                if !prev_was_space {
                    normalized.push(' ');
                    prev_was_space = true;
                }
            } else {
                normalized.push(ch);
                prev_was_space = false;
            }
        }
        state.output.truncate(frame.content_start);
        state.output.push_str(normalized.trim_end());
    }

    let prefix = heading_prefix(n);
    state.output.insert_str(frame.content_start, prefix);
    // ~keep Tier-2 leaves a blank line ("\n\n") after a heading. A
    // ~keep following paragraph's "\n\n" guard then finds it already and appends
    // ~keep nothing, yielding the expected single blank line.
    state.ensure_blank_line();
    Ok(())
}

fn close_blockquote(state: &mut Tier1State, frame: &OpenTag) {
    // ~keep Phase GG follow-up: inside a table cell `frame.content_start` indexes
    // ~keep into the cell buffer, not `state.output`.  Don't prefix `> ` — Tier-2
    // ~keep also collapses blockquote inside cells to plain inline text.
    if state.in_table_cell() {
        return;
    }
    let content = state.output[frame.content_start..].to_owned();
    let prefixed = prefix_blockquote_lines(&content);
    state.output.truncate(frame.content_start);
    // ~keep Mirror Tier-2 blockquote.rs: when the output ends with "\n\n"
    // ~keep before the blockquote, remove one "\n" (heading-then-blockquote
    // ~keep produces only a single newline separator, not a blank line).
    if state.output.ends_with("\n\n") {
        state.output.pop();
    }
    state.output.push_str(&prefixed);
}

fn close_pre(state: &mut Tier1State, frame: &OpenTag, options: &ConversionOptions) {
    use crate::options::CodeBlockStyle;
    // ~keep Phase GG follow-up: when `<pre>` opened inside a table cell, its content
    // ~keep was accumulated into `current_cell` (the cell buffer), not `state.output`.
    // ~keep The frame's `content_start` indexes into the cell buffer.  Don't emit a
    // ~keep code fence — Tier-2 also collapses pre inside cells to plain inline text
    // ~keep (the cell's `replace('\n', ' ')` step does the rest).
    if state.in_table_cell() {
        return;
    }
    let raw = state.output[frame.content_start..].to_owned();
    state.output.truncate(frame.content_start);
    match options.code_block_style {
        CodeBlockStyle::Indented => {
            let indented = indent_pre_lines(&raw);
            state.output.push_str(&indented);
        }
        CodeBlockStyle::Backticks => {
            state.output.push_str("```");
            if let Some(lang) = state.pre_lang.take() {
                state.output.push_str(&lang);
            } else if !options.code_language.is_empty() {
                state.output.push_str(&options.code_language);
            }
            state.output.push('\n');
            // ~keep Strip a single leading + trailing newline from raw so neither
            // ~keep fence sits next to a blank line.  Tier-2 emits
            // ~keep `\ncontent\n` (single newlines flanking content).
            let raw = raw.strip_prefix('\n').unwrap_or(&raw);
            let raw = raw.strip_suffix('\n').unwrap_or(raw);
            state.output.push_str(raw);
            state.output.push('\n');
            state.output.push_str("```\n");
        }
        CodeBlockStyle::Tildes => {
            let indented = indent_pre_lines(&raw);
            state.output.push_str(&indented);
        }
    }
    state.pre_lang = None;
}

fn close_code(state: &mut Tier1State, frame: &OpenTag) {
    if state.escape_ctx.contains(EscapeCtx::PRE) || state.escape_ctx.contains(EscapeCtx::CODE) {
        return;
    }
    // ~keep Phase CC: smart backtick escaping (mirrors inline/code.rs:260).
    // ~keep Open emitted nothing; content from `frame.content_start` to buf
    // ~keep end is the raw code content.  Choose num_backticks + delimiter
    // ~keep spaces from that slice, then truncate and re-emit wrapped.
    let buf = state.cell_or_output_mut();
    let content_start = frame.content_start.min(buf.len());
    if content_start >= buf.len() {
        // ~keep No content emitted between open and close — Tier-2 emits
        // ~keep nothing for empty <code></code>.
        return;
    }

    let contains_backtick = buf[content_start..].contains('`');

    let (needs_spaces, num_backticks) = {
        let content = &buf[content_start..];
        let first_char = content.chars().next();
        let last_char = content.chars().last();
        let starts_with_space = first_char == Some(' ');
        let ends_with_space = last_char == Some(' ');
        let starts_with_backtick = first_char == Some('`');
        let ends_with_backtick = last_char == Some('`');
        let all_spaces = content.chars().all(|c| c == ' ');

        let needs_delimiter_spaces = all_spaces
            || starts_with_backtick
            || ends_with_backtick
            || (starts_with_space && ends_with_space && contains_backtick);

        let num_backticks = if contains_backtick {
            let max_consecutive = content
                .chars()
                .fold((0usize, 0usize), |(max, current), c| {
                    if c == '`' {
                        let new_current = current + 1;
                        (max.max(new_current), new_current)
                    } else {
                        (max, 0)
                    }
                })
                .0;
            if max_consecutive == 1 { 2 } else { 1 }
        } else {
            1
        };
        (needs_delimiter_spaces, num_backticks)
    };

    let mut prefix = String::with_capacity(num_backticks + 1);
    for _ in 0..num_backticks {
        prefix.push('`');
    }
    if needs_spaces {
        prefix.push(' ');
    }
    buf.insert_str(content_start, &prefix);
    if needs_spaces {
        buf.push(' ');
    }
    for _ in 0..num_backticks {
        buf.push('`');
    }
}

fn close_link(state: &mut Tier1State, frame: &OpenTag) {
    // ~keep Close the link: `](href "title")` or `](href)`
    // ~keep If no href, just emit the text as-is (Tier-2 behaviour: no link markup).
    // ~keep Link state was pushed to state.link_stack at open; pop it now.
    let (href, title) = state.link_stack.pop().unwrap_or((None, None));
    let dest = state.cell_or_output_mut();
    // ~keep Trim trailing whitespace inside the link label so `[text  ](url)`
    // ~keep collapses to `[text](url)` — matches Tier-2's normalize_link_label
    // ~keep at utility/content.rs:145 (kimbrain.html and similar source HTML
    // ~keep with whitespace before </a>).
    let trim_start = frame.content_start.min(dest.len());
    let trimmed_end = dest[trim_start..].trim_end_matches(|c: char| c.is_whitespace()).len();
    dest.truncate(trim_start + trimmed_end);
    // ~keep Mirror Tier-2's `normalize_whitespace_cow` step inside
    // ~keep `normalize_link_label` (utility/content.rs:144): any Unicode whitespace
    // ~keep in the link label (notably NBSP `\u{00a0}`) collapses to a single ASCII
    // ~keep space.  Tier-1 otherwise emits `[Designed\u{a0}by](url)` where Tier-2
    // ~keep emits `[Designed by](url)`.
    if dest[trim_start..].contains('\u{00a0}') {
        let normalised: String = dest[trim_start..]
            .chars()
            .map(|c| if c == '\u{00a0}' { ' ' } else { c })
            .collect();
        dest.truncate(trim_start);
        dest.push_str(&normalised);
    }
    // ~keep Wikipedia back-reference normalisation (Tier-2 `handlers/link.rs:208`):
    // ~keep a label of exactly `^` paired with an `#anchor` href is rewritten to
    // ~keep `↑` so it does not look like Markdown's footnote syntax.
    if let Some(href_str) = href.as_deref() {
        if href_str.starts_with('#') && dest.len() == trim_start + 1 && dest.as_bytes()[trim_start] == b'^' {
            dest.truncate(trim_start);
            dest.push('');
        }
    }
    if let Some(href) = href {
        if let Some(title) = title {
            // ~keep Tier-2 in production HTML fixtures HTML-encodes a literal `"`
            // ~keep in the title attribute to `&quot;` (rather than the
            // ~keep `replace('"', "\\\"")` shown in `inline/link.rs:482-484`).  The
            // ~keep backslash-escape branch of link.rs appears unreachable in
            // ~keep practice for the title attribute path on these fixtures.
            // ~keep Mirror the observed fixture behaviour to match expected output.
            let escaped_title;
            let title_out: &str = if title.contains('"') {
                escaped_title = title.replace('"', "&quot;");
                &escaped_title
            } else {
                &title
            };
            #[allow(clippy::format_push_string)]
            dest.push_str(&format!("]({href} \"{title_out}\")"));
        } else {
            #[allow(clippy::format_push_string)]
            dest.push_str(&format!("]({href})"));
        }
    } else {
        if let Some(bracket_pos) = dest[..frame.content_start].rfind('[') {
            dest.remove(bracket_pos);
        }
    }
}

fn close_list(state: &mut Tier1State, kind: ListKind) {
    state.list_depth = state.list_depth.saturating_sub(1);
    if matches!(kind, ListKind::Unordered) {
        state.ul_depth = state.ul_depth.saturating_sub(1);
    }
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // ~keep the list — the cell accumulator handles any separators via the
    // ~keep `\n → space` replacement at cell-close time.
    if state.in_table_cell() {
        return;
    }
    let dest = state.cell_or_output_mut();
    if !dest.ends_with('\n') {
        dest.push('\n');
    }
}

fn close_list_item(state: &mut Tier1State, frame: &OpenTag) {
    // ~keep When inside a table cell, Tier-2 does NOT add a trailing newline after
    // ~keep each list item (see list/item.rs: `if !ctx.in_table_cell { ... \n ... }`).
    // ~keep Items are concatenated directly in the cell accumulator.
    if state.in_table_cell() {
        let cell_buf = state.cell_or_output_mut();
        while cell_buf.ends_with(' ') || cell_buf.ends_with('\t') {
            cell_buf.pop();
        }
        return;
    }
    trim_trailing_inline_whitespace(state);
    let dest = state.cell_or_output_mut();
    // ~keep Phase EE: loose-list separator.  When this item had block-level
    // ~keep children (its content range contains a `\n\n` block separator),
    // ~keep mirror Tier-2's `handle_li` ensure_trailing_blank_line behaviour
    // ~keep so the next sibling `<li>` starts after a blank line.  Plain text
    // ~keep items still get the tight `\n` terminator.
    let had_block_children = {
        let start = frame.content_start.min(dest.len());
        dest[start..].contains("\n\n")
    };
    if had_block_children {
        if !dest.ends_with("\n\n") {
            if dest.ends_with('\n') {
                dest.push('\n');
            } else {
                dest.push_str("\n\n");
            }
        }
    } else if !dest.is_empty() && !dest.ends_with('\n') {
        dest.push('\n');
    }
}

// ~keep ── Definition-list helpers ───────────────────────────────────────────────────
// ~keep
// ~keep Tier-2 reference: crates/html-to-markdown/src/converter/list/definition.rs.
// ~keep Tier-2 builds the full <dl> content in a buffer, trims it, then emits with
// ~keep "\n\n" boundaries. <dt> emits trimmed term + "\n"; <dd> emits trimmed
// ~keep description + "\n\n". Tier-1 streams the same shape by:
// ~keep   - open_dl: ensure blank line; record content_start on the frame
// ~keep   - close_dt: trim trailing whitespace, push "\n"
// ~keep   - close_dd: trim trailing whitespace, push "\n\n"
// ~keep   - close_dl: trim leading/trailing whitespace inside the dl range, then
// ~keep               normalise the trailing separator to "\n\n"
// ~keep
// ~keep Bails on dl/dt/dd are removed (see bail_unsupported). Implicit close of an
// ~keep open dt/dd when a sibling dt/dd opens is wired via OptionalCloseRule::
// ~keep CloseSiblingDtDd in spec_rules.rs and runs the same close_dt/close_dd path
// ~keep through emit_close_for_implicit.

fn open_dl(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    state.ensure_blank_line();
}

const fn open_dt(_state: &mut Tier1State) {}

const fn open_dd(_state: &mut Tier1State) {}

fn close_dt(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() || buf.ends_with('\n') {
        return;
    }
    buf.push('\n');
}

fn close_dd(state: &mut Tier1State) {
    if state.in_table_cell() {
        return;
    }
    trim_trailing_inline_whitespace(state);
    let buf = state.cell_or_output_mut();
    if buf.is_empty() {
        return;
    }
    if buf.ends_with("\n\n") {
        return;
    }
    if buf.ends_with('\n') {
        buf.push('\n');
    } else {
        buf.push_str("\n\n");
    }
}

fn close_dl(state: &mut Tier1State, frame: &OpenTag) {
    if state.in_table_cell() {
        return;
    }
    let buf = state.cell_or_output_mut();
    // ~keep Empty dl: emit nothing (matches Tier-2 which skips when trimmed content
    // ~keep is empty).
    if buf.len() <= frame.content_start {
        return;
    }
    // ~keep Tier-2 trims the dl's accumulated content, so any trailing whitespace
    // ~keep from the last dt/dd close should collapse to a single "\n\n" separator.
    while buf.len() > frame.content_start {
        let last = buf.as_bytes()[buf.len() - 1];
        if matches!(last, b' ' | b'\t' | b'\n' | b'\r') {
            buf.pop();
        } else {
            break;
        }
    }
    if buf.len() == frame.content_start {
        return;
    }
    buf.push_str("\n\n");
}

fn close_table(state: &mut Tier1State) -> Result<(), BailReason> {
    // ~keep Pop the table state and (if safe) emit the GFM table to main output.
    let Some(ts) = state.table_stack.pop() else {
        return Ok(());
    };

    // ~keep Safety checks: ensure Tier-2 would also use the GFM path.
    // ~keep
    // ~keep Tier-2 uses the layout (non-GFM) path when ALL of these hold:
    // ~keep   (a) no <th> anywhere in the table, AND
    // ~keep   (b) no <caption>, AND
    // ~keep   (c) looks_like_layout || is_blank || (row_count<=2 && link_count>=3)
    // ~keep
    // ~keep Where looks_like_layout covers nested tables (already bailed),
    // ~keep colspan/rowspan (already bailed), and inconsistent column counts.
    // ~keep
    // ~keep If those conditions could apply to this table, we bail rather than
    // ~keep emit a GFM table that Tier-2 would have rendered differently.
    // ~keep
    // ~keep When a <caption> is present, Tier-2 always takes the GFM path
    // ~keep regardless of <th> presence (has_caption short-circuits the layout check).
    let has_caption = ts.caption_text.is_some();
    if !ts.has_th && !has_caption {
        // ~keep No <th> and no <caption>: check if Tier-2 would take the layout path.
        let row_count = ts.rows.len();

        // ~keep Inconsistent column counts → layout table in Tier-2.
        // ~keep Compare colspan-expanded column counts (sum of cell colspans per row)
        // ~keep because Tier-2 computes column counts post-colspan expansion.
        let expanded_cols = |row: &Vec<(String, u16)>| -> usize { row.iter().map(|(_, c)| usize::from(*c)).sum() };
        let inconsistent_cols = {
            let first = ts.first_row_col_count.unwrap_or(0);
            ts.rows.iter().any(|r| expanded_cols(r) != first)
        };

        // ~keep Link-heavy with few rows → layout table in Tier-2.
        let link_heavy = row_count <= 2 && ts.link_count >= 3;

        // ~keep Blank table → Tier-2 emits nothing (not a bail case).
        let is_blank = ts.rows.is_empty() || ts.rows.iter().all(|r| r.iter().all(|(c, _)| c.trim().is_empty()));

        if inconsistent_cols || link_heavy || is_blank {
            // ~keep Tier-2 would not emit a GFM table here.  Bail so the fallback
            // ~keep produces the correct layout output.  Phase L's full layout
            // ~keep emit deferred — needs more careful per-cell content tracking
            // ~keep to mirror Tier-2's walker exactly.
            return Err(BailReason::Classifier);
        }
    }
    // ~keep Phase HH: a nested table writes its GFM rendering into the parent
    // ~keep cell buffer; the parent's `close_table_cell` then collapses the
    // ~keep resulting newlines to spaces.  An outer table writes to the main
    // ~keep output buffer as before.
    if ts.inline_mode {
        if let Some(outer) = state.table_stack.last_mut() {
            outer.had_nested_table = true;
        }
        let target = state.cell_or_output_mut();
        emit_gfm_table(target, ts);
    } else {
        emit_gfm_table(&mut state.output, ts);
    }
    Ok(())
}

fn close_table_head(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.in_thead = false;
    }
}

fn close_table_body(state: &mut Tier1State) {
    if let Some(ts) = state.table_stack.last_mut() {
        ts.seen_tbody_close = true;
    }
}

/// Finalise a `<caption>` element.
///
/// Mirrors Tier-2's `builder.rs` caption handling: trim the collected text,
/// replace `-` with `\-` to prevent Markdown table-separator interpretation,
/// and store the result in `ts.caption_text` for emission before the table body.
fn close_table_caption(state: &mut Tier1State) {
    let Some(ts) = state.table_stack.last_mut() else {
        return;
    };
    ts.in_caption = false;
    let raw = std::mem::take(&mut ts.caption_buf);
    let trimmed = raw.trim();
    if !trimmed.is_empty() {
        ts.caption_text = Some(trimmed.replace('-', r"\-"));
    }
}

fn close_table_row(state: &mut Tier1State) {
    let Some(ts) = state.table_stack.last_mut() else {
        return;
    };
    if ts.current_row.is_empty() {
        return;
    }
    // ~keep Track first-row column count for consistency checking — use the
    // ~keep colspan-expanded count so Tier-2's heuristic compares the same numbers.
    let col_count: usize = ts.current_row.iter().map(|(_, c)| usize::from(*c)).sum();
    if ts.first_row_col_count.is_none() {
        ts.first_row_col_count = Some(col_count);
    }
    let row = std::mem::take(&mut ts.current_row);
    ts.rows.push(row);
}

/// Close a table cell (`<td>` or `<th>`).
///
/// `is_implicit` skips the pipe-escape bail that only applies when the cell
/// was explicitly closed (implicit closes happen during row/table teardown
/// where we've already committed to the data we have).
fn close_table_cell(state: &mut Tier1State, is_implicit: bool) -> Result<(), BailReason> {
    let Some(ts) = state.table_stack.last_mut() else {
        return Ok(());
    };
    ts.in_cell = false;
    // ~keep Trim the accumulated cell text (matches Tier-2 `text.trim()`).
    let cell_text_raw = ts.current_cell.trim().to_owned();
    // ~keep Replace newlines with spaces — mirrors Tier-2's `cell_text_content`
    // ~keep which calls `text.replace('\n', " ")` when `br_in_tables` is false.
    let cell_text = if cell_text_raw.contains('\n') {
        cell_text_raw.replace('\n', " ")
    } else {
        cell_text_raw
    };
    // ~keep Expand the `<br>` sentinel `\u{0001}` to three literal spaces — Tier-2
    // ~keep emits `<br>` as `"  \n"` and the cell-level `replace('\n', ' ')` yields
    // ~keep `"   "` (three spaces).  Using a sentinel keeps multi-space runs from
    // ~keep inter-tag whitespace distinguishable from `<br>`-derived padding.
    let cell_text = if cell_text.contains('\u{0001}') {
        cell_text.replace('\u{0001}', "   ")
    } else {
        cell_text
    };
    let cell_text = cell_text.trim().to_owned();
    // ~keep Bail if the cell contains a pipe: Tier-2 escapes `|` → `\|`
    // ~keep which changes the cell width computation; Tier-1 does not
    // ~keep implement pipe escaping.  Implicit closes skip this check because
    // ~keep they are triggered during structural teardown, not fresh cell data.
    // ~keep
    // ~keep Phase HH exception: when a nested table emitted GFM markdown into
    // ~keep this cell, the literal pipes are part of the inner table's
    // ~keep rendering — Tier-2 does NOT escape them either.  `had_nested_table`
    // ~keep gates the skip; reset it so subsequent cells in the same row are
    // ~keep still pipe-checked.
    let allow_pipes = ts.had_nested_table;
    ts.had_nested_table = false;
    if !is_implicit && !allow_pipes && cell_text.contains('|') {
        return Err(BailReason::TableBlockChildInCell);
    }
    // ~keep Phase L-prep: store (text, colspan) so emit_gfm_table can mirror
    // ~keep Tier-2's `for _ in 0..colspan { output.push_str(" |") }` (cell.rs:248)
    // ~keep and the layout-heuristic uses the colspan-expanded column count.
    let colspan = ts.current_cell_colspan;
    ts.current_row.push((cell_text, colspan));
    ts.current_cell.clear();
    ts.current_cell_colspan = 1;
    Ok(())
}

/// Flush a raw HTML text segment into the output (or current cell buffer),
/// decoding entities and collapsing whitespace (unless inside `<pre>`).
///
/// `base_offset` is the byte offset of `raw` within the original HTML input;
/// it is forwarded to the entity decoder so that `BailReason::UnknownEntity`
/// carries an accurate position.
///
/// Returns `Err(BailReason::UnknownEntity)` if an unrecognised entity is found.
/// True when `s` ends with an ordered-list marker (`<digit(s)>. ` or `<digit(s)>) `).
///
/// Used by the inter-block whitespace strip to recognise that the scanner just
/// emitted a list-item marker and the next text would be the item content;
/// leading whitespace from the source HTML indentation should be dropped.
fn ends_with_ordered_marker(s: &str) -> bool {
    let bytes = s.as_bytes();
    let len = bytes.len();
    if len < 3 || bytes[len - 1] != b' ' {
        return false;
    }
    let punct = bytes[len - 2];
    if punct != b'.' && punct != b')' {
        return false;
    }
    let mut i = len - 2;
    while i > 0 && bytes[i - 1].is_ascii_digit() {
        i -= 1;
    }
    i < len - 2 && (i == 0 || !bytes[i - 1].is_ascii_digit())
}

/// Returns `true` when the output tail is an explicit inline-element close
/// marker emitted by Tier-1.  These markers signal that the next whitespace
/// text node is between two inline siblings and should collapse to a single
/// space — even when the whitespace run contains a newline (Phase U-2).
///
/// Recognised markers:
/// - `**` — `</strong>` / `</b>` close
/// - `*` — `</em>` / `</i>` close (only a lone `*`, not part of `**`)
/// - `` ` `` — `</code>` close
/// - `)` — `</a>` (link) close, e.g. `](href)`
///
/// Block edges (`\n`, empty output, trailing space) are explicitly excluded.
fn output_ends_with_inline_close_marker(output: &str) -> bool {
    if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
        return false;
    }
    if output.ends_with("**") || output.ends_with('`') || output.ends_with(')') {
        return true;
    }
    output.ends_with('*') && !output.ends_with("**")
}

/// Returns `true` when the output tail is a non-marker text character —
/// e.g. ending in a letter, digit, or punctuation other than the inline-
/// close markers.  Text-tail preservation only fires for *horizontal*
/// whitespace runs (no `\n`/`\r`) because we cannot tell at flush time
/// whether the next tag is inline or block; preserving a space across a
/// newline-bearing run risks `text \n\n<list>` regressions.
fn output_ends_with_inline_text(output: &str) -> bool {
    if output.is_empty() || output.ends_with('\n') || output.ends_with(' ') || output.ends_with('\t') {
        return false;
    }
    !output_ends_with_inline_close_marker(output)
}

fn flush_text(state: &mut Tier1State, raw: &str, base_offset: usize) -> Result<(), BailReason> {
    if raw.is_empty() {
        return Ok(());
    }

    // ~keep Inside a table but outside a cell or caption: discard text (whitespace
    // ~keep between structural tags like <table>...<tr> or <tr>...<td>).
    // ~keep Tier-2 processes only tag children explicitly, ignoring text nodes at
    // ~keep this level.  Caption content is the exception — Tier-2 walks caption
    // ~keep children and accumulates their text into the caption output.
    if !state.table_stack.is_empty() && !state.in_table_cell() && !state.in_table_caption() {
        return Ok(());
    }

    let in_pre = state.escape_ctx.contains(EscapeCtx::PRE);
    // ~keep Phase EE: inside `<code>` text is verbatim — Tier-2's handle_code
    // ~keep walks children and pushes their text without normalize_whitespace,
    // ~keep so `\n` and runs of spaces inside `<code>` survive into the
    // ~keep wrapped span.  Treat as `in_pre` for the no-collapse path.
    let in_code = state.escape_ctx.contains(EscapeCtx::CODE);

    // ~keep Phase NN: text containing Unicode whitespace (NBSP `\u{00A0}`, hair
    // ~keep space `\u{200A}`, etc., or their entity forms) folds those to ASCII
    // ~keep space — but only when the chunk has non-whitespace content.
    // ~keep Mirrors Tier-2 `text_node.rs:124` and `:154` which run
    // ~keep `normalize_whitespace_cow` on text outside `<code>`/`<pre>` (folding
    // ~keep Unicode space chars).  The whitespace-only branch at `:80-112`
    // ~keep preserves a pure-NBSP text node between inline siblings as-is (e.g.
    // ~keep `<a>X</a>&nbsp;<a>Y</a>` keeps the NBSP).  Without this rule,
    // ~keep `First<NBSP>appeared` reaches the buffer verbatim where Tier-2 outputs
    // ~keep `First appeared`.
    // ~keep Common Unicode-whitespace entity forms: named + numeric (decimal +
    // ~keep hex).  Tier-2's `normalize_whitespace_cow` folds the decoded chars;
    // ~keep Tier-1's flush_text runs BEFORE entity decode, so the patterns must
    // ~keep be listed explicitly.
    const UNICODE_WS_ENTITIES: &[&str] = &[
        "&nbsp;", "&#160;", "&#xa0;", "&#xA0;", "&ensp;", "&#8194;", "&#x2002;", "&emsp;", "&#8195;", "&#x2003;",
        "&thinsp;", "&#8201;", "&#x2009;", "&hairsp;", "&#8202;", "&#x200a;", "&#x200A;",
    ];
    let raw_owned_nbsp;
    let raw: &str = if !in_pre && !in_code {
        let has_ws_entity = UNICODE_WS_ENTITIES.iter().any(|p| raw.contains(p));
        let has_unicode_ws_literal = raw.bytes().any(|b| b >= 0x80)
            && raw
                .chars()
                .any(|c| c.is_whitespace() && c != ' ' && c != '\t' && c != '\n' && c != '\r');
        if has_ws_entity || has_unicode_ws_literal {
            let mut stripped = raw.to_owned();
            for p in UNICODE_WS_ENTITIES {
                if stripped.contains(p) {
                    stripped = stripped.replace(p, "");
                }
            }
            let is_logically_whitespace = stripped.chars().all(char::is_whitespace);
            if is_logically_whitespace {
                raw
            } else {
                let mut after_entities = raw.to_owned();
                for p in UNICODE_WS_ENTITIES {
                    if after_entities.contains(p) {
                        after_entities = after_entities.replace(p, " ");
                    }
                }
                let mut tmp = String::with_capacity(after_entities.len());
                for c in after_entities.chars() {
                    if c.is_whitespace() && c != ' ' && c != '\t' && c != '\n' && c != '\r' {
                        tmp.push(' ');
                    } else {
                        tmp.push(c);
                    }
                }
                raw_owned_nbsp = tmp;
                raw_owned_nbsp.as_str()
            }
        } else {
            raw
        }
    } else {
        raw
    };

    // ~keep Inter-block whitespace strip: in a block-edge context (output empty,
    // ~keep ends with a newline, or ends with a list-item marker like "- " /
    // ~keep "1. "), whitespace-only text between adjacent elements (the
    // ~keep indentation in pretty-printed HTML) is not meaningful and must be
    // ~keep discarded.  Tier-2's DOM walker gets this for free because the
    // ~keep parser yields text nodes separately from tag nodes and the walker
    // ~keep skips whitespace-only text at block-level boundaries.  Skipped when
    // ~keep inside `<pre>` (verbatim) or inside a table cell (caller is
    // ~keep accumulating cell text).
    // ~keep
    // ~keep We also treat "the current open frame is a link/emphasis frame whose
    // ~keep body is still empty" as a block-edge: text appearing immediately
    // ~keep after `<a>` → `[`, `<strong>` → `**`, etc. inherits leading
    // ~keep whitespace from the source HTML's indentation and Tier-2 trims it
    // ~keep when building the inline label.  This catches cases like
    // ~keep `<a href>\n   <span>EN</span>\n</a>` where the whitespace after
    // ~keep `<a>` would otherwise leak into the link label as `[ EN]`.
    // ~keep
    // ~keep Plain `<p>`/`<div>`/`<h1>` frames are NOT in this set — Tier-2 keeps
    // ~keep the leading whitespace inside the very first paragraph of a document
    // ~keep (it becomes the single space after `normalize_whitespace`).  Only
    // ~keep post-content paragraphs see "\n\n" before them, which the
    // ~keep `output.ends_with('\n')` check above already handles.
    // ~keep Phase R-3: inside `<summary>`, any tag's body-start is also an inline
    // ~keep frame edge.  Tier-2's handle_summary collects all children with
    // ~keep text-normalization in effect; leading whitespace inside `<span>`,
    // ~keep `<div>`, `<p>` (etc.) bodies gets stripped just like inside `<a>`.
    let in_summary_snapshot = state.in_summary();
    let at_inline_frame_start = match state.stack.last() {
        Some(frame) => {
            let cs = frame.content_start;
            let kind = frame.spec.kind;
            let buf_len = state.cell_or_output_mut().len();
            cs >= buf_len
                && (matches!(
                    kind,
                    TagKind::Link | TagKind::Strong | TagKind::Emphasis | TagKind::Code
                ) || (in_summary_snapshot
                    && matches!(
                        kind,
                        TagKind::Inline | TagKind::Block | TagKind::Paragraph | TagKind::Heading(_)
                    )))
        }
        None => false,
    };
    // ~keep Determine whether the current active output position is at a "block
    // ~keep edge" (empty or after a newline / list marker).  When inside a summary
    // ~keep accumulation buffer, consult that buffer rather than state.output so
    // ~keep that inter-element spaces inside the summary are preserved correctly.
    // ~keep Snap the relevant properties to local booleans before releasing the
    // ~keep borrow to avoid conflicts with subsequent state reads.
    let (active_empty, active_ends_newline, active_ends_list_marker, active_ends_ordered) = {
        let buf: &str = state.cell_or_output_mut();
        (
            buf.is_empty(),
            buf.ends_with('\n'),
            buf.ends_with("- ") || buf.ends_with("* ") || buf.ends_with("+ "),
            ends_with_ordered_marker(buf),
        )
    };
    let is_block_edge =
        active_empty || active_ends_newline || active_ends_list_marker || active_ends_ordered || at_inline_frame_start;
    let raw_is_whitespace = raw.bytes().all(|b| b == b' ' || b == b'\t' || b == b'\n' || b == b'\r');
    if !in_pre && is_block_edge && raw_is_whitespace {
        // ~keep Drop block-edge whitespace anywhere — including inside table cells.
        // ~keep A cell-open `<td>`/`<th>` produces a fresh empty buffer; the
        // ~keep pretty-printer's inter-tag whitespace before the first child would
        // ~keep otherwise leak as a leading space into the cell, breaking the
        // ~keep 3-space gap heuristic (`  \n` from `<div>` open becomes 4 spaces
        // ~keep instead of 3 after `replace('\n', ' ')`).
        return Ok(());
    }
    // ~keep Tier-2 text_node.rs:100-113 collapses whitespace-only text nodes
    // ~keep between adjacent inline siblings to a single space — including
    // ~keep inside table cells where the surrounding `<a>`/`<span>` siblings are
    // ~keep inline.  Mirror that here so `<a>x</a>\n  <a>y</a>` inside a `<td>`
    // ~keep emits `[x] [y]` (single space) instead of `[x]\n [y]` which the
    // ~keep cell-close `replace('\n', ' ')` would turn into two spaces.  Skip
    // ~keep when at a block edge (cell just opened) so the cell doesn't start
    // ~keep with a stray space.
    if !in_pre && state.in_table_cell() && raw_is_whitespace && !is_block_edge {
        // ~keep Tier-2's text_node.rs:80-98 drops whitespace text between non-inline
        // ~keep siblings: when the parent is a list (`<ul>`/`<ol>`/`<dl>`), the
        // ~keep inter-`<li>` whitespace returns without pushing because the next
        // ~keep sibling `<li>` is a block, not inline.  Mirror that here so adjacent
        // ~keep `<li>` siblings in a cell concatenate without separation
        // ~keep (`[v](u1)[t](u2)` not `[v](u1) [t](u2)`).  For inline parents
        // ~keep (`<span>`/`<a>`/`<td>` direct inline-sibling case), keep the
        // ~keep single-space fold.
        if matches!(state.stack.last().map(|f| f.spec.kind), Some(TagKind::List(_))) {
            return Ok(());
        }
        let dest = state.cell_or_output_mut();
        if !dest.is_empty() && !dest.ends_with(' ') && !dest.ends_with('\n') {
            dest.push(' ');
        }
        return Ok(());
    }
    // ~keep Whitespace-only text outside any inline element (link / strong / em /
    // ~keep code) and outside `<pre>` / table cells is structural indentation
    // ~keep between block siblings (e.g. between `</div>` and the next `<div>`).
    // ~keep Tier-2 emits a single ASCII space here when the surrounding context
    // ~keep is inline, but otherwise the DOM walker treats it as a no-op.  For
    // ~keep Tier-1's heuristic we collapse it to nothing — matches Tier-2 for
    // ~keep the common block-between-blocks case and the inline cases are caught
    // ~keep by the inline-frame check above.
    // ~keep
    // ~keep Exception (Phase U + U-2): when the output tail is inline content
    // ~keep (text or `**`/`*`/`` ` ``/`)` close markers) AND we're NOT at a
    // ~keep block edge, a whitespace-only text node between siblings must
    // ~keep become a single space.  Without this `</strong> <em>` would emit
    // ~keep `**a***b*` and `<span>Open Search Bar</span>\n<button>` would lose
    // ~keep the space before the button's content.
    // ~keep
    // ~keep Phase U-2 dropped the original "horizontal whitespace only" guard:
    // ~keep a newline-bearing whitespace run between two inline siblings still
    // ~keep collapses to a single space in Tier-2.  The "what if next tag is a
    // ~keep block?" regression is now handled later in `ensure_blank_line` and
    // ~keep `close_block_container`, which trim trailing horizontal whitespace
    // ~keep before emitting `\n\n`.
    if !in_pre && !state.in_table_cell() && raw_is_whitespace {
        // ~keep When inside a <summary> accumulation buffer, treat the context as
        // ~keep inline (like strong/emphasis): inter-element spaces must be
        // ~keep preserved so `<span>a</span> <span>b</span>` collects "a b" not "ab".
        let inside_inline = state.in_summary()
            || state.stack.iter().any(|frame| {
                matches!(
                    frame.spec.kind,
                    TagKind::Link | TagKind::Strong | TagKind::Emphasis | TagKind::Code
                )
            });
        if !inside_inline {
            // ~keep Use the active buffer (summary buf or main output) for the
            // ~keep tail check so spaces between adjacent inline elements inside
            // ~keep a summary are preserved correctly.
            let active_tail: &str = state.cell_or_output_mut();
            if output_ends_with_inline_close_marker(active_tail) || output_ends_with_inline_text(active_tail) {
                let dest = state.cell_or_output_mut();
                dest.push(' ');
            }
            return Ok(());
        }
        // ~keep Inside an inline frame (`<a>`/`<strong>`/`<em>`/`<code>`) or summary
        // ~keep accumulation: a whitespace-only text node (often the indent run
        // ~keep between two inline siblings like `</span>\n  <a>`) must collapse to
        // ~keep a single ASCII space — Tier-2's text-node normalize_whitespace folds
        // ~keep any `\n` + spaces run into one space.  Without this, Tier-1 falls
        // ~keep through to `decode_and_collapse_into` which preserves the `\n` and
        // ~keep emits `*[a](x)\n [b](y)*` where Tier-2 has `*[a](x) [b](y)*`.
        let active_tail: &str = state.cell_or_output_mut();
        if !active_tail.is_empty() && !active_tail.ends_with(' ') && !active_tail.ends_with('\n') {
            let dest = state.cell_or_output_mut();
            dest.push(' ');
        }
        return Ok(());
    }
    // ~keep Even when the text is not entirely whitespace, strip its LEADING
    // ~keep whitespace when:
    // ~keep   - we're at the start of an open inline element's body (`<a>`,
    // ~keep     `<strong>`, etc.), OR
    // ~keep   - the output ends with a block separator (`\n\n`) or a list-item
    // ~keep     marker — Tier-2's text-node `skip_prefix` logic does the same.
    // ~keep
    // ~keep Not when output is empty (first paragraph of a document keeps its
    // ~keep leading whitespace per Tier-2's behaviour).
    let block_separator_after = {
        let active: &str = state.cell_or_output_mut();
        active.ends_with("\n\n")
            || active.ends_with("- ")
            || active.ends_with("* ")
            || active.ends_with("+ ")
            || ends_with_ordered_marker(active)
    };
    let raw = if !in_pre && !state.in_table_cell() && (at_inline_frame_start || block_separator_after) {
        raw.trim_start_matches([' ', '\t', '\n', '\r'])
    } else {
        raw
    };
    if raw.is_empty() {
        return Ok(());
    }

    let has_entities = raw.contains('&');

    if in_pre || in_code {
        if has_entities {
            let dest = state.cell_or_output_mut();
            decode_entities_into(dest, raw, base_offset)?;
        } else {
            state.cell_or_output_mut().push_str(raw);
        }
        return Ok(());
    }

    // ~keep Inside an `<a>` link frame, Tier-2's `normalize_link_label` replaces
    // ~keep newlines with spaces before whitespace collapsing.  Mirror that here so
    // ~keep text spanning `\n` inside an `<a>` (e.g. `<a>Skip to main\n  content</a>`)
    // ~keep collapses to `[Skip to main content]` instead of leaking the newline.
    // ~keep `<strong>`/`<em>` do NOT normalize newlines in Tier-2 — only links do.
    // ~keep
    // ~keep `<summary>` is treated the same as `<a>` here (Phase R-3): Tier-2's
    // ~keep handle_summary collects children into a local content buffer and
    // ~keep wraps in `**...**\n\n`; the surrounding text-normalization layer
    // ~keep collapses internal newline runs to single spaces before emission.
    // ~keep Without this, summary content with multi-line inline children leaks
    // ~keep `\n  \n  ` between text runs.
    let inside_inline = state.in_summary() || state.stack.iter().any(|frame| matches!(frame.spec.kind, TagKind::Link));

    // ~keep Phase Y: text-node chomp.  Tier-2's text_node.rs runs `chomp()` on
    // ~keep every text node and substitutes the leading and trailing whitespace
    // ~keep runs with simpler stand-ins:
    // ~keep   prefix → `" "` if the run had any leading whitespace, else `""`
    // ~keep   suffix → `"\n\n"` if trailing run contained `\n\n`,
    // ~keep          → `" "`   if trailing run had space/tab (folding any `\n`),
    // ~keep          → `""`    if trailing run was `\n` only.
    // ~keep Without this, Tier-1 keeps the literal `\n  ` in text like
    // ~keep "The number of\n  " and emits `of\n ` while Tier-2 emits `of `,
    // ~keep and likewise the leading whitespace case `</em>\n  baz` produces
    // ~keep `*bar*\n baz` instead of `*bar* baz`.
    // ~keep
    // ~keep Applied only outside inline frames (which call
    // ~keep `decode_and_collapse_into_inline` and handle `\n` collapse already),
    // ~keep outside `<pre>` (verbatim), and outside table cells (which run
    // ~keep `normalize_whitespace_cow` directly).
    let raw_owned;
    let raw = if !inside_inline && !state.in_table_cell() {
        let trim_chars: &[char] = &['\n', '\r', ' ', '\t'];
        let after_lead = raw.trim_start_matches(trim_chars);
        let leading_len = raw.len() - after_lead.len();
        let lead_has_nl = leading_len > 0 && raw.as_bytes()[..leading_len].iter().any(|&b| b == b'\n' || b == b'\r');
        let trimmed_len = raw.trim_end_matches(trim_chars).len();
        let trailing_len = raw.len() - trimmed_len;
        let trail_has_nl = trailing_len > 0 && raw.as_bytes()[trimmed_len..].iter().any(|&b| b == b'\n' || b == b'\r');
        if lead_has_nl || trail_has_nl {
            let core_start = leading_len;
            let core_end = trimmed_len;
            if core_start >= core_end {
                // ~keep Whitespace-only text node — already handled by the
                // ~keep earlier whitespace-only branches; skip Phase Y here.
                raw
            } else {
                let core = &raw[core_start..core_end];
                let trailing = &raw[core_end..];
                let prefix = if leading_len > 0 { " " } else { "" };
                let suffix = if trailing.contains("\n\n") {
                    "\n\n"
                } else if trailing.bytes().any(|b| b == b' ' || b == b'\t') {
                    " "
                } else if trail_has_nl {
                    ""
                } else {
                    trailing
                };
                raw_owned = format!("{prefix}{core}{suffix}");
                raw_owned.as_str()
            }
        } else {
            raw
        }
    } else {
        raw
    };
    if raw.is_empty() {
        return Ok(());
    }
    let has_entities = raw.contains('&');

    if !has_entities {
        let needle_present = if inside_inline {
            memchr3(b' ', b'\t', b'\n', raw.as_bytes()).is_some()
        } else {
            memchr::memchr2(b' ', b'\t', raw.as_bytes()).is_some()
        };
        if !needle_present {
            state.cell_or_output_mut().push_str(raw);
            return Ok(());
        }
        let dest = state.cell_or_output_mut();
        return if inside_inline {
            decode_and_collapse_into_inline(dest, raw, false, base_offset)
        } else {
            decode_and_collapse_into(dest, raw, false, base_offset)
        };
    }

    let dest = state.cell_or_output_mut();
    if inside_inline {
        decode_and_collapse_into_inline(dest, raw, has_entities, base_offset)
    } else {
        decode_and_collapse_into(dest, raw, has_entities, base_offset)
    }
}

/// Decode HTML entities directly into `out` (no intermediate allocation).
///
/// `base_offset` is the byte offset of `s` within the original HTML input and
/// is used to report the position of any unrecognised entity in the bail reason.
///
/// Uses memchr to quickly find the next `&` and bulk-copies non-entity runs.
///
/// Returns `Err(BailReason::UnknownEntity)` when an entity cannot be decoded.
fn decode_entities_into(out: &mut String, s: &str, base_offset: usize) -> Result<(), BailReason> {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if let Some(pos) = memchr::memchr(b'&', &bytes[i..]) {
            let amp_pos = i + pos;
            if amp_pos > i {
                out.push_str(&s[i..amp_pos]);
            }
            i = decode_entity_at(bytes, s, amp_pos, out, base_offset)?;
        } else {
            if i < bytes.len() {
                out.push_str(&s[i..]);
            }
            break;
        }
    }
    Ok(())
}

/// Decode entities AND collapse spaces/tabs in one pass, directly into `out`.
///
/// `base_offset` is the byte offset of `s` within the original HTML input and
/// is used to report the position of any unrecognised entity in the bail reason.
///
/// Uses memchr3 to quickly find the next special byte (space/tab/&), then
/// bulk-copies the run in one `push_str` to avoid per-byte overhead.
///
/// Returns `Err(BailReason::UnknownEntity)` when an entity cannot be decoded.
fn decode_and_collapse_into(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
) -> Result<(), BailReason> {
    decode_and_collapse_into_inner(out, s, has_entities, base_offset, false)
}

/// Collapse like `decode_and_collapse_into` but treat `\n`/`\r` as collapsible
/// whitespace too.  Used for text inside `<a>`/`<strong>`/`<em>` frames where
/// Tier-2's `normalize_link_label` first replaces newlines with spaces, then
/// runs whitespace normalization.
fn decode_and_collapse_into_inline(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
) -> Result<(), BailReason> {
    decode_and_collapse_into_inner(out, s, has_entities, base_offset, true)
}

fn decode_and_collapse_into_inner(
    out: &mut String,
    s: &str,
    has_entities: bool,
    base_offset: usize,
    collapse_newlines: bool,
) -> Result<(), BailReason> {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut prev_was_space = false;
    while i < bytes.len() {
        let next_special = match (has_entities, collapse_newlines) {
            (true, true) => {
                let s_pos = memchr3(b' ', b'\t', b'\n', &bytes[i..]).map(|pos| i + pos);
                let e_pos = memchr::memchr(b'&', &bytes[i..]).map(|pos| i + pos);
                match (s_pos, e_pos) {
                    (Some(a), Some(b)) => Some(a.min(b)),
                    (Some(a), None) | (None, Some(a)) => Some(a),
                    (None, None) => None,
                }
            }
            (true, false) => memchr3(b' ', b'\t', b'&', &bytes[i..]).map(|pos| i + pos),
            (false, true) => memchr3(b' ', b'\t', b'\n', &bytes[i..]).map(|pos| i + pos),
            (false, false) => memchr::memchr2(b' ', b'\t', &bytes[i..]).map(|pos| i + pos),
        };

        if let Some(pos) = next_special {
            if pos > i {
                out.push_str(&s[i..pos]);
                prev_was_space = false;
            }
            match bytes[pos] {
                b' ' | b'\t' => {
                    if !prev_was_space {
                        out.push(' ');
                    }
                    prev_was_space = true;
                    i = pos + 1;
                }
                b'\n' if collapse_newlines => {
                    if !prev_was_space {
                        out.push(' ');
                    }
                    prev_was_space = true;
                    i = pos + 1;
                }
                b'&' => {
                    prev_was_space = false;
                    i = decode_entity_at(bytes, s, pos, out, base_offset)?;
                }
                _ => unreachable!(),
            }
        } else {
            if i < bytes.len() {
                out.push_str(&s[i..]);
            }
            break;
        }
    }
    Ok(())
}

/// Scan and decode a single HTML entity starting at `amp_pos` (the `&` byte).
///
/// Looks for a matching `;` within 32 bytes, then dispatches to
/// `decode_entity_into` or `decode_numeric_entity_into`.
///
/// Returns the position immediately after the entity (i.e. after the `;`), or
/// after the bare `&` when no valid entity boundary is found.
///
/// Emits `Err(BailReason::UnknownEntity)` when an `&name;` sequence is found
/// but the name is not in the decode table.
fn decode_entity_at(
    bytes: &[u8],
    s: &str,
    amp_pos: usize,
    out: &mut String,
    _base_offset: usize,
) -> Result<usize, BailReason> {
    let amp = amp_pos;
    let mut end = amp + 1;
    while end < bytes.len() && end - amp <= MAX_ENTITY_NAME_BYTES && bytes[end] != b';' {
        end += 1;
    }
    if end < bytes.len() && bytes[end] == b';' && end > amp + 1 {
        let entity = &s[amp + 1..end];
        if decode_entity_into(out, entity) {
            return Ok(end + 1);
        }
        // ~keep Phase N3: entity name (`&name;`) not in Tier-1's decode table.
        // ~keep Tier-2 and mdream pass these through verbatim instead of decoding.
        // ~keep Push the raw `&name;` and advance past it.
        out.push_str(&s[amp..=end]);
        return Ok(end + 1);
    }
    out.push('&');
    Ok(amp + 1)
}

/// Apply the escape-context bits for an opening tag.
///
/// The close path restores `state.escape_ctx` directly from `frame.prev_escape_ctx`
/// so a symmetric `remove_open_escape_ctx` is not needed.
#[inline]
fn apply_open_escape_ctx(state: &mut Tier1State, spec: &TagSpec) {
    if spec.kind == TagKind::Pre {
        state.escape_ctx |= EscapeCtx::PRE | EscapeCtx::CODE;
        return;
    }

    let bit = match spec.kind {
        TagKind::Code => EscapeCtx::CODE,
        TagKind::Link => EscapeCtx::LINK,
        TagKind::Blockquote => EscapeCtx::BLOCKQUOTE,
        TagKind::Heading(_) => EscapeCtx::HEADING,
        _ => return,
    };

    state.escape_ctx |= bit;
}

/// Find an attribute value by (lowercase) key name.
fn find_attr<'a>(attrs: &[(&'a [u8], Option<&'a [u8]>)], key: &[u8]) -> Option<&'a [u8]> {
    for (k, v) in attrs {
        if k.eq_ignore_ascii_case(key) {
            return *v;
        }
    }
    None
}

/// Returns true when `name_lower` is a tag that *may* need preprocessing-skip
/// evaluation.  All other tags skip the more expensive `should_skip_preprocessing`
/// check entirely.
fn is_preprocessing_skip_candidate(name_lower: &[u8]) -> bool {
    matches!(name_lower, b"nav" | b"header" | b"footer" | b"aside" | b"form")
}

/// Mirrors `should_drop_for_preprocessing` (preprocessing_helpers.rs:115) for
/// the Tier-1 byte scanner.
///
/// Called only for tags that passed [`is_preprocessing_skip_candidate`].
/// Uses the raw attribute byte slices collected by [`parse::collect_attrs`]
/// instead of the Tier-2 `tl::HTMLTag` DOM node.
fn should_skip_preprocessing(name_lower: &[u8], attrs: &[(&[u8], Option<&[u8]>)], options: &ConversionOptions) -> bool {
    use crate::options::PreprocessingPreset;

    if !options.preprocessing.enabled {
        return false;
    }

    if options.preprocessing.preset == PreprocessingPreset::Minimal {
        return false;
    }

    if options.preprocessing.remove_forms && name_lower == b"form" {
        return true;
    }

    if !options.preprocessing.remove_navigation {
        return false;
    }

    if name_lower == b"nav" {
        return true;
    }

    // ~keep <header> / <footer> / <aside> — drop only when navigation hints present.
    // ~keep (Aggressive would drop footer/aside unconditionally, but Aggressive routes
    // ~keep through Tier-2 via the existing router gate so Tier-1 only needs the
    // ~keep Standard-preset behaviour: nav-hint check.)
    if matches!(name_lower, b"header" | b"footer" | b"aside") {
        return byte_attrs_have_navigation_hint(attrs);
    }

    false
}

/// Byte-level equivalent of `element_has_navigation_hint` for use in the
/// Tier-1 scanner where attributes are raw `&[u8]` slices rather than a
/// parsed `tl::HTMLTag`.
fn byte_attrs_have_navigation_hint(attrs: &[(&[u8], Option<&[u8]>)]) -> bool {
    if let Some(role) = find_attr(attrs, b"role") {
        let role_lc = role.to_ascii_lowercase();
        if matches!(role_lc.as_slice(), b"navigation" | b"menubar" | b"tablist" | b"toolbar") {
            return true;
        }
    }

    if let Some(label) = find_attr(attrs, b"aria-label") {
        let label_lc = label.to_ascii_lowercase();
        const ARIA_SUBSTRINGS: &[&[u8]] = &[b"navigation", b"menu", b"contents", b"table of contents", b"toc"];
        if ARIA_SUBSTRINGS
            .iter()
            .any(|sub| label_lc.windows(sub.len()).any(|w| w == *sub))
        {
            return true;
        }
    }

    for attr_name in [b"class".as_slice(), b"id".as_slice()] {
        if let Some(value) = find_attr(attrs, attr_name) {
            if byte_value_has_nav_keyword(value) {
                return true;
            }
        }
    }

    false
}

/// Tokenize a raw attribute byte value and return true when any token matches
/// a keyword in [`NAV_KEYWORDS`].
///
/// Tokens are split on ASCII whitespace.  Each token is normalised by
/// replacing `_`, `:`, `.`, `/` with `-` and lowercasing before comparison.
fn byte_value_has_nav_keyword(value: &[u8]) -> bool {
    let mut start = 0;
    let len = value.len();
    loop {
        while start < len && value[start].is_ascii_whitespace() {
            start += 1;
        }
        if start >= len {
            break;
        }
        let mut end = start;
        while end < len && !value[end].is_ascii_whitespace() {
            end += 1;
        }
        let token_bytes = &value[start..end];
        let mut buf = [0u8; 64];
        let normalised: &[u8] = if token_bytes.len() <= buf.len() {
            let n = token_bytes.len();
            for (i, &b) in token_bytes.iter().enumerate() {
                buf[i] = match b {
                    b'_' | b':' | b'.' | b'/' => b'-',
                    _ => b.to_ascii_lowercase(),
                };
            }
            &buf[..n]
        } else {
            start = end;
            continue;
        };

        if NAV_KEYWORDS.iter().any(|kw| kw.as_bytes() == normalised) {
            return true;
        }

        start = end;
    }
    false
}

/// Extract `href` and `title` from the attribute list for a link.
fn extract_link_attrs(attrs: &[(&[u8], Option<&[u8]>)]) -> Result<(Option<String>, Option<String>), BailReason> {
    let href = find_attr(attrs, b"href").map(decode_attr).transpose()?;
    // ~keep Mirror Tier-2's `inline/link.rs:82` which captures the title attribute
    // ~keep via tl::parse's `as_utf8_str()` — tl decodes numeric entities
    // ~keep (`&#039;` → `'`) but preserves named entities (`&amp;`, `&quot;`,
    // ~keep `&lt;`).  Use a partial-decode pass for titles to match.
    let title = find_attr(attrs, b"title").map(decode_title_attr).transpose()?;
    Ok((href, title))
}

/// Decode a link-title attribute: numeric entities (`&#NNN;`, `&#xNNN;`)
/// resolve to characters, named entities (`&amp;`, `&quot;`, etc.) survive
/// as-is.  Mirrors tl::parse's `as_utf8_str()` behaviour on attribute values.
/// Decode a link-title attribute: numeric entities (`&#NNN;`, `&#xNNN;`)
/// resolve to characters, named entities (`&amp;`, `&quot;`, etc.) survive
/// as-is.  Mirrors Tier-2's observed behaviour on link titles: it decodes
/// `&#039;` → `'` but preserves `&amp;`/`&quot;` literally.
fn decode_title_attr(bytes: &[u8]) -> Result<String, BailReason> {
    let s = std::str::from_utf8(bytes).map_err(|_| BailReason::Classifier)?;
    if !s.contains("&#") {
        return Ok(s.to_owned());
    }
    let mut out = String::with_capacity(s.len());
    let bytes_s = s.as_bytes();
    let mut i = 0;
    while i < bytes_s.len() {
        let Some(rel) = memchr::memchr(b'&', &bytes_s[i..]) else {
            out.push_str(&s[i..]);
            break;
        };
        let amp_pos = i + rel;
        if amp_pos > i {
            out.push_str(&s[i..amp_pos]);
        }
        if amp_pos + 1 >= bytes_s.len() || bytes_s[amp_pos + 1] != b'#' {
            out.push('&');
            i = amp_pos + 1;
            continue;
        }
        let mut j = amp_pos + 2;
        while j < bytes_s.len() && bytes_s[j] != b';' {
            j += 1;
        }
        if j >= bytes_s.len() {
            out.push_str(&s[amp_pos..]);
            break;
        }
        let body = &s[amp_pos + 2..j];
        let cp_opt = if let Some(hex) = body.strip_prefix(['x', 'X']) {
            u32::from_str_radix(hex, 16).ok()
        } else {
            body.parse::<u32>().ok()
        };
        if let Some(cp) = cp_opt {
            if let Some(ch) = char::from_u32(cp) {
                out.push(ch);
                i = j + 1;
                continue;
            }
        }
        out.push_str(&s[amp_pos..=j]);
        i = j + 1;
    }
    Ok(out)
}

/// Extract `start` attribute from `<ol>` (defaults to 1).
fn extract_ol_start(attrs: &[(&[u8], Option<&[u8]>)]) -> u16 {
    find_attr(attrs, b"start")
        .and_then(|b| std::str::from_utf8(b).ok())
        .and_then(|s| s.parse::<u16>().ok())
        .unwrap_or(1)
}

/// Decode an attribute value: entity-decode and convert to a String.
///
/// Returns `Err(BailReason::Classifier)` when the value is not valid UTF-8
/// (malformed bytes in attributes cannot be decoded faithfully).
/// Returns `Err(BailReason::UnknownEntity)` when the value contains an entity
/// that Tier-1 cannot decode (Tier-2 would decode it differently).
fn decode_attr(bytes: &[u8]) -> Result<String, BailReason> {
    let s = std::str::from_utf8(bytes).map_err(|_| BailReason::Classifier)?;
    if !s.contains('&') {
        return Ok(s.to_owned());
    }
    let mut out = String::with_capacity(s.len());
    decode_entities_into(&mut out, s, 0)?;
    Ok(out)
}

/// Canonicalize the special-character set in an attribute value to match
/// the output produced by html5ever's serializer (which Tier-2 runs on
/// HTML containing custom elements).  Numeric forms like `&#x22;` decode
/// to `"` and re-encode to the canonical named form `&quot;`; literal
/// special chars are also escaped.  Matches the set in
/// `html5ever::serialize::escape_for_attribute`.
fn canonicalize_attr_entities(input: &str) -> std::borrow::Cow<'_, str> {
    let needs_escape = input
        .bytes()
        .any(|b| matches!(b, b'&' | b'<' | b'>' | b'"') || b == 0xC2);
    if !needs_escape {
        return std::borrow::Cow::Borrowed(input);
    }
    let mut out = String::with_capacity(input.len() + 8);
    for c in input.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\u{a0}' => out.push_str("&nbsp;"),
            _ => out.push(c),
        }
    }
    std::borrow::Cow::Owned(out)
}

/// Pop the topmost frame whose spec matches `spec`.
/// Tier-2 is lenient about close tags; we are strict in M3c: only pop the
/// Pop the topmost frame whose spec matches `spec`.
///
/// We compare by checking if the `TagKind` on the top frame maps to the same
/// "semantic group" as the spec being closed.  We are strict in M3c: only the
/// top frame is checked to avoid mismatched-close-tag complexity.
fn pop_matching_frame(stack: &mut Vec<OpenTag>, spec: &'static TagSpec) -> Option<OpenTag> {
    let top = stack.last()?;
    if kinds_match(&top.spec.kind, &spec.kind) {
        stack.pop()
    } else {
        None
    }
}

/// Return `true` if two `TagKind` values are the "same" for close-tag matching.
///
/// Uses pointer equality on the `&'static TagSpec` where possible for speed.
/// For kinds with inner data (`List`, `Heading`, `TableCell`) we use a
/// coarser match that still prevents cross-kind confusion:
/// - `List(Ordered)` only matches `List(Ordered)`, etc.
/// - `Heading(n)` matches `Heading(m)` for any n, m (HTML allows `</h3>` to
///   close `<h2>` in some parsers; we are lenient for headings since they
///   do not nest in practice).
fn kinds_match(a: &TagKind, b: &TagKind) -> bool {
    match (a, b) {
        (TagKind::List(la), TagKind::List(lb)) => la == lb,
        (TagKind::Heading(_), TagKind::Heading(_)) => true,
        (TagKind::TableCell { is_header: a_h }, TagKind::TableCell { is_header: b_h }) => a_h == b_h,
        _ => std::mem::discriminant(a) == std::mem::discriminant(b),
    }
}

/// Find the nearest enclosing list kind by walking the stack top-to-bottom.
fn find_parent_list_kind(stack: &[OpenTag]) -> Option<ListKind> {
    for frame in stack.iter().rev() {
        if let TagKind::List(kind) = frame.spec.kind {
            return Some(kind);
        }
    }
    None
}

/// Increment the ordered-list counter on the nearest `List(Ordered)` frame.
/// Returns the new counter value (1-based).
fn increment_ol_counter(stack: &mut [OpenTag]) -> u16 {
    for frame in stack.iter_mut().rev() {
        if frame.spec.kind == TagKind::List(ListKind::Ordered) {
            frame.list_index = frame.list_index.saturating_add(1);
            return frame.list_index;
        }
    }
    1
}

/// Get the `ol_start` value from the nearest `List(Ordered)` frame.
fn find_ol_start(stack: &[OpenTag]) -> u16 {
    for frame in stack.iter().rev() {
        if frame.spec.kind == TagKind::List(ListKind::Ordered) {
            return frame.ol_start;
        }
    }
    1
}

/// Return the ATX heading prefix for level `n` (1–6).
///
/// Uses the `HEADING_PREFIXES` table — no allocation.
fn heading_prefix(n: u8) -> &'static str {
    let idx = (n as usize).saturating_sub(1).min(5);
    HEADING_PREFIXES[idx]
}

/// Push the list-item indentation for `depth` into `out`.
///
/// Depth 0 → no indent; each level adds two spaces (matches the router's
/// `list_indent_width == 2` gate).  Depths 0–7 use the static `LIST_ITEM_INDENTS`
/// table; deeper nesting (rare) falls back to a runtime loop.
fn push_list_item_indent(out: &mut String, depth: u16) {
    let idx = depth as usize;
    if idx < LIST_ITEM_INDENTS.len() {
        out.push_str(LIST_ITEM_INDENTS[idx]);
    } else {
        out.reserve(idx * 2);
        for _ in 0..idx {
            out.push_str("  ");
        }
    }
}

/// Add `> ` prefix to every non-empty line of `content`, and `>` to empty
/// lines that are between non-empty ones (Tier-2 behaviour for multi-paragraph
/// blockquotes).
fn prefix_blockquote_lines(content: &str) -> String {
    let content = content.trim_end_matches('\n');
    if content.is_empty() {
        return String::new();
    }

    let lines: Vec<&str> = content.split('\n').collect();
    let mut result = String::with_capacity(content.len() + lines.len() * 2);

    for (i, line) in lines.iter().enumerate() {
        if line.is_empty() {
            result.push('>');
        } else {
            result.push_str("> ");
            result.push_str(line);
        }
        if i < lines.len() - 1 {
            result.push('\n');
        }
    }
    result.push('\n');
    result
}

/// Indent each line of a pre block by 4 spaces, after dedenting common leading whitespace.
///
/// Mirrors Tier-2's `dedent_code_block` + 4-space indent logic.
fn indent_pre_lines(raw: &str) -> String {
    let raw = raw.strip_prefix('\n').unwrap_or(raw);
    let raw = raw.trim_end_matches('\n');
    if raw.is_empty() {
        return String::new();
    }

    let min_indent = raw
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
        .min()
        .unwrap_or(0);

    let mut result = String::with_capacity(raw.len() + raw.lines().count() * 4);
    for line in raw.lines() {
        if line.trim().is_empty() {
            // ~keep Empty / whitespace-only line: emit as a bare `\n` (no 4-space
            // ~keep indent prefix).  Tier-2's `block/code.rs` also skips the indent
            // ~keep for blank lines inside indented code blocks — without this,
            // ~keep round-tripped CommonMark `    code\n    \n    code` would
            // ~keep render with stray trailing spaces in the blank gap.
        } else {
            result.push_str("    ");
            // ~keep Convert char-count `min_indent` into a byte offset by walking
            // ~keep `char_indices`.  Indexing `line[min_indent..]` directly panics
            // ~keep when the leading whitespace contains multibyte characters such
            // ~keep as `\u{a0}` (NBSP).  Mirrors Tier-2's `dedent_code_block`
            // ~keep (text/processing.rs:38-50).
            let mut remaining = min_indent;
            let mut cut = 0;
            for (idx, ch) in line.char_indices() {
                if remaining == 0 {
                    break;
                }
                if ch.is_whitespace() {
                    remaining -= 1;
                    cut = idx + ch.len_utf8();
                } else {
                    break;
                }
            }
            result.push_str(&line[cut..]);
        }
        result.push('\n');
    }
    result
}

// ~keep ── GFM table emission ────────────────────────────────────────────────────────

/// Emit a completed table as GFM markdown, appending to `state.output`.
///
/// Format must match Tier-2 `convert_table_row` byte-for-byte:
/// - Each row: `|` + ` cell |` per cell → `| c1 | c2 |`
/// - After row 0: separator `| --- | --- |` (one `---` per column)
///
/// # Panics
///
/// Never — empty-table guard returns early.
fn emit_gfm_table(target: &mut String, ts: crate::converter::tier1::state::TableState) {
    // ~keep Emit caption (if any) BEFORE the table body.
    // ~keep
    // ~keep Mirrors Tier-2 builder.rs caption handling: `*escaped_text*\n\n`.
    // ~keep Tier-2 emits the caption as part of the table child loop, which runs
    // ~keep before the rows are rendered, so the caption appears even when there
    // ~keep are no table rows.  The caption text has already been trimmed and
    // ~keep hyphen-escaped when `</caption>` was processed.
    if let Some(ref caption) = ts.caption_text {
        if !caption.is_empty() {
            if !target.is_empty() && !target.ends_with("\n\n") {
                if target.ends_with('\n') {
                    target.push('\n');
                } else {
                    target.push_str("\n\n");
                }
            }
            target.push('*');
            target.push_str(caption);
            target.push_str("*\n\n");
        }
    }

    if ts.rows.is_empty() {
        return;
    }

    // ~keep Pre-table separator: mirrors Tier-2's `convert_table` logic exactly.
    // ~keep Tier-2 (block/table/mod.rs): `if !output.is_empty() && !output.ends_with("\n\n")`
    // ~keep — only adds separator when there is existing output (no leading blank lines).
    if !target.is_empty() && !target.ends_with("\n\n") {
        if target.ends_with('\n') {
            target.push('\n');
        } else {
            target.push_str("\n\n");
        }
    }

    // ~keep Pre-compute max column widths across ALL rows (mirrors Tier-2's pre-pass).
    // ~keep Tier-2: separator dashes = max(col_content_char_count_across_all_rows, 3).
    // ~keep col_count is the colspan-expanded column count (sum of colspans per row).
    let col_count = ts
        .rows
        .iter()
        .map(|r| r.iter().map(|(_, c)| usize::from(*c)).sum::<usize>())
        .max()
        .unwrap_or(0);
    let mut col_widths: Vec<usize> = vec![0; col_count];
    for row in &ts.rows {
        let mut col = 0usize;
        for (cell, span) in row {
            let w = cell.chars().count();
            // ~keep Only the cell's anchor column owns the width — spanned columns
            // ~keep contribute zero (matches Tier-2's per-cell pad calculation).
            if col < col_widths.len() && w > col_widths[col] {
                col_widths[col] = w;
            }
            col += usize::from(*span);
        }
    }

    for (row_index, row) in ts.rows.iter().enumerate() {
        // ~keep Row: `|` then each cell as ` text |` (padded to col_width like Tier-2).
        target.push('|');
        let mut col = 0usize;
        for (cell, span) in row {
            target.push(' ');
            target.push_str(cell);
            // ~keep Pad to column width (mirrors Tier-2 cell.rs padding logic).
            let cell_len = cell.chars().count();
            let col_w = col_widths.get(col).copied().unwrap_or(0);
            for _ in cell_len..col_w {
                target.push(' ');
            }
            // ~keep Tier-2 (cell.rs:248): `for _ in 0..colspan { output.push_str(" |") }`.
            // ~keep colspan trailing ` |` separators per cell — produces `| Header | | |`
            // ~keep for `<th colspan="3">Header</th>` instead of `| Header |  |  |`.
            for _ in 0..*span {
                target.push_str(" |");
            }
            col += usize::from(*span);
        }
        target.push('\n');

        // ~keep After row 0 (the header row), emit the separator row.
        // ~keep Tier-2: col_widths.get(i).unwrap_or(0).max(MIN_SEPARATOR_DASHES).
        if row_index == 0 {
            target.push_str("| ");
            for i in 0..col_count.max(1) {
                if i > 0 {
                    target.push_str(" | ");
                }
                let dash_count = col_widths.get(i).copied().unwrap_or(0).max(MIN_SEPARATOR_DASHES);
                for _ in 0..dash_count {
                    target.push('-');
                }
            }
            target.push_str(" |\n");
        }
    }
}

/// Trim trailing spaces and tabs from the end of the output (used before
/// closing block elements that trim trailing whitespace in Tier-2).
fn trim_trailing_inline_whitespace(state: &mut Tier1State) {
    let buf = state.cell_or_output_mut();
    while buf.ends_with(' ') || buf.ends_with('\t') {
        buf.pop();
    }
}

/// Collapse runs of 3+ consecutive newlines down to 2, matching Tier-2's
/// `collapse_excess_blank_lines` post-processing step.
fn collapse_excess_blank_lines(output: &mut String) {
    let mut consecutive = 0usize;
    output.retain(|c| {
        if c == '\n' {
            consecutive += 1;
            consecutive <= 2
        } else {
            consecutive = 0;
            true
        }
    });
}

/// Decode a single HTML entity name (without `&` or `;`) directly into `out`.
///
/// Returns `true` when the entity was recognized and written; `false` when the
/// name didn't match any known entity (caller emits the literal `&...;`).
///
/// All named entities are static strings; numeric references emit a single
/// `char`. No `String` is allocated.
fn decode_entity_into(out: &mut String, name: &str) -> bool {
    let s: &str = match name {
        "amp" => "&",
        "lt" => "<",
        "gt" => ">",
        "quot" => "\"",
        "apos" => "'",
        "nbsp" => "\u{00A0}",
        "copy" => "\u{00A9}",
        "reg" => "\u{00AE}",
        "trade" => "\u{2122}",
        "mdash" => "\u{2014}",
        "ndash" => "\u{2013}",
        "hellip" => "\u{2026}",
        "laquo" => "\u{00AB}",
        "raquo" => "\u{00BB}",
        "lsquo" => "\u{2018}",
        "rsquo" => "\u{2019}",
        "ldquo" => "\u{201C}",
        "rdquo" => "\u{201D}",
        "prime" => "\u{2032}",
        "Prime" => "\u{2033}",
        "bull" => "\u{2022}",
        "middot" => "\u{00B7}",
        "deg" => "\u{00B0}",
        "plusmn" => "\u{00B1}",
        "times" => "\u{00D7}",
        "divide" => "\u{00F7}",
        "frac12" => "\u{00BD}",
        "frac14" => "\u{00BC}",
        "frac34" => "\u{00BE}",
        "euro" => "\u{20AC}",
        "pound" => "\u{00A3}",
        "yen" => "\u{00A5}",
        "cent" => "\u{00A2}",
        "larr" => "\u{2190}",
        "rarr" => "\u{2192}",
        "uarr" => "\u{2191}",
        "darr" => "\u{2193}",
        "harr" => "\u{2194}",
        "infin" => "\u{221E}",
        "alpha" => "\u{03B1}",
        "beta" => "\u{03B2}",
        "gamma" => "\u{03B3}",
        "delta" => "\u{03B4}",
        "pi" => "\u{03C0}",
        "sigma" => "\u{03C3}",
        "omega" => "\u{03C9}",
        // ~keep Latin-1 Supplement (U+00A0–U+00FF) — html5ever's Tier-2 backend
        // ~keep decodes the full HTML5 named entity table; mirror the Latin-1
        // ~keep block here so Tier-1 byte-equality holds for accented Western
        // ~keep text without bailing.  Entries already defined above (`nbsp`,
        // ~keep `copy`, `reg`, `laquo`, `raquo`, `frac12`, etc.) are not repeated.
        "iexcl" => "\u{00A1}",
        "brvbar" => "\u{00A6}",
        "sect" => "\u{00A7}",
        "uml" => "\u{00A8}",
        "ordf" => "\u{00AA}",
        "not" => "\u{00AC}",
        "shy" => "\u{00AD}",
        "macr" => "\u{00AF}",
        "sup2" => "\u{00B2}",
        "sup3" => "\u{00B3}",
        "acute" => "\u{00B4}",
        "micro" => "\u{00B5}",
        "para" => "\u{00B6}",
        "cedil" => "\u{00B8}",
        "sup1" => "\u{00B9}",
        "ordm" => "º",
        "iquest" => "\u{00BF}",
        "Agrave" => "\u{00C0}",
        "Aacute" => "\u{00C1}",
        "Acirc" => "\u{00C2}",
        "Atilde" => "\u{00C3}",
        "Auml" => "\u{00C4}",
        "Aring" => "\u{00C5}",
        "AElig" => "\u{00C6}",
        "Ccedil" => "\u{00C7}",
        "Egrave" => "\u{00C8}",
        "Eacute" => "\u{00C9}",
        "Ecirc" => "\u{00CA}",
        "Euml" => "\u{00CB}",
        "Igrave" => "\u{00CC}",
        "Iacute" => "\u{00CD}",
        "Icirc" => "\u{00CE}",
        "Iuml" => "\u{00CF}",
        "ETH" => "\u{00D0}",
        "Ntilde" => "\u{00D1}",
        "Ograve" => "\u{00D2}",
        "Oacute" => "\u{00D3}",
        "Ocirc" => "\u{00D4}",
        "Otilde" => "\u{00D5}",
        "Ouml" => "\u{00D6}",
        "Oslash" => "\u{00D8}",
        "Ugrave" => "\u{00D9}",
        "Uacute" => "\u{00DA}",
        "Ucirc" => "\u{00DB}",
        "Uuml" => "\u{00DC}",
        "Yacute" => "\u{00DD}",
        "THORN" => "\u{00DE}",
        "szlig" => "\u{00DF}",
        "agrave" => "\u{00E0}",
        "aacute" => "\u{00E1}",
        "acirc" => "\u{00E2}",
        "atilde" => "\u{00E3}",
        "auml" => "\u{00E4}",
        "aring" => "\u{00E5}",
        "aelig" => "\u{00E6}",
        "ccedil" => "\u{00E7}",
        "egrave" => "\u{00E8}",
        "eacute" => "\u{00E9}",
        "ecirc" => "\u{00EA}",
        "euml" => "\u{00EB}",
        "igrave" => "\u{00EC}",
        "iacute" => "\u{00ED}",
        "icirc" => "\u{00EE}",
        "iuml" => "\u{00EF}",
        "eth" => "\u{00F0}",
        "ntilde" => "\u{00F1}",
        "ograve" => "\u{00F2}",
        "oacute" => "\u{00F3}",
        "ocirc" => "\u{00F4}",
        "otilde" => "\u{00F5}",
        "ouml" => "\u{00F6}",
        "oslash" => "\u{00F8}",
        "ugrave" => "\u{00F9}",
        "uacute" => "\u{00FA}",
        "ucirc" => "\u{00FB}",
        "uuml" => "\u{00FC}",
        "yacute" => "\u{00FD}",
        "thorn" => "\u{00FE}",
        "yuml" => "\u{00FF}",
        _ => return decode_numeric_entity_into(out, name),
    };
    out.push_str(s);
    true
}

fn decode_numeric_entity_into(out: &mut String, name: &str) -> bool {
    let Some(rest) = name.strip_prefix('#') else {
        return false;
    };
    let code_point = if rest.starts_with('x') || rest.starts_with('X') {
        match u32::from_str_radix(&rest[1..], 16) {
            Ok(n) => n,
            Err(_) => return false,
        }
    } else {
        match rest.parse::<u32>() {
            Ok(n) => n,
            Err(_) => return false,
        }
    };
    match char::from_u32(code_point) {
        Some(ch) => {
            out.push(ch);
            true
        }
        None => false,
    }
}

/// Skip `<!--...-->`, `<!DOCTYPE...>`, or any `<!...>` construct.
/// Returns the position immediately after the closing `>`.
///
/// On failure returns `Err(BailReason::LiteralLt)`.
fn skip_bang(bytes: &[u8], pos: usize) -> Result<usize, BailReason> {
    let start = pos + 2;

    if bytes.get(start) == Some(&b'-') && bytes.get(start + 1) == Some(&b'-') {
        let comment_start = start + 2;
        let mut i = comment_start;
        while i + 2 < bytes.len() {
            if bytes[i] == b'-' && bytes[i + 1] == b'-' && bytes[i + 2] == b'>' {
                return Ok(i + 3);
            }
            i += 1;
        }
        // ~keep Unclosed comment — bail
        return Err(BailReason::LiteralLt { offset: pos });
    }

    let mut i = start;
    while i < bytes.len() {
        if bytes[i] == b'>' {
            return Ok(i + 1);
        }
        i += 1;
    }
    Err(BailReason::LiteralLt { offset: pos })
}

/// Convert tag name bytes to lowercase in a fixed-size stack buffer.
/// Returns a slice into `buf`.  If the name is longer than `buf`, it is
/// truncated (names > `MAX_TAG_NAME_BYTES` won't appear in the spec table and
/// will be rejected as unknown).
fn lowercase_into<'b>(bytes: &[u8], buf: &'b mut [u8; MAX_TAG_NAME_BYTES]) -> &'b [u8] {
    let len = bytes.len().min(MAX_TAG_NAME_BYTES);
    for (i, &b) in bytes[..len].iter().enumerate() {
        buf[i] = b.to_ascii_lowercase();
    }
    &buf[..len]
}

/// Convert a byte slice to an owned `String` (lossy UTF-8).
fn bytes_to_string(b: &[u8]) -> String {
    String::from_utf8_lossy(b).into_owned()
}