rumdl 0.1.51

A fast Markdown linter written in Rust (Ru(st) MarkDown Linter)
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
//!
//! Rule MD033: No HTML tags
//!
//! See [docs/md033.md](../../docs/md033.md) for full documentation, configuration, and examples.

use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
use crate::utils::regex_cache::*;
use std::collections::HashSet;

mod md033_config;
use md033_config::{MD033Config, MD033FixMode};

#[derive(Clone)]
pub struct MD033NoInlineHtml {
    config: MD033Config,
    allowed: HashSet<String>,
    disallowed: HashSet<String>,
    drop_attributes: HashSet<String>,
    strip_wrapper_elements: HashSet<String>,
}

impl Default for MD033NoInlineHtml {
    fn default() -> Self {
        let config = MD033Config::default();
        let allowed = config.allowed_set();
        let disallowed = config.disallowed_set();
        let drop_attributes = config.drop_attributes_set();
        let strip_wrapper_elements = config.strip_wrapper_elements_set();
        Self {
            config,
            allowed,
            disallowed,
            drop_attributes,
            strip_wrapper_elements,
        }
    }
}

impl MD033NoInlineHtml {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_allowed(allowed_vec: Vec<String>) -> Self {
        let config = MD033Config {
            allowed: allowed_vec.clone(),
            disallowed: Vec::new(),
            fix: false,
            ..MD033Config::default()
        };
        let allowed = config.allowed_set();
        let disallowed = config.disallowed_set();
        let drop_attributes = config.drop_attributes_set();
        let strip_wrapper_elements = config.strip_wrapper_elements_set();
        Self {
            config,
            allowed,
            disallowed,
            drop_attributes,
            strip_wrapper_elements,
        }
    }

    pub fn with_disallowed(disallowed_vec: Vec<String>) -> Self {
        let config = MD033Config {
            allowed: Vec::new(),
            disallowed: disallowed_vec.clone(),
            fix: false,
            ..MD033Config::default()
        };
        let allowed = config.allowed_set();
        let disallowed = config.disallowed_set();
        let drop_attributes = config.drop_attributes_set();
        let strip_wrapper_elements = config.strip_wrapper_elements_set();
        Self {
            config,
            allowed,
            disallowed,
            drop_attributes,
            strip_wrapper_elements,
        }
    }

    /// Create a new rule with auto-fix enabled
    pub fn with_fix(fix: bool) -> Self {
        let config = MD033Config {
            allowed: Vec::new(),
            disallowed: Vec::new(),
            fix,
            ..MD033Config::default()
        };
        let allowed = config.allowed_set();
        let disallowed = config.disallowed_set();
        let drop_attributes = config.drop_attributes_set();
        let strip_wrapper_elements = config.strip_wrapper_elements_set();
        Self {
            config,
            allowed,
            disallowed,
            drop_attributes,
            strip_wrapper_elements,
        }
    }

    pub fn from_config_struct(config: MD033Config) -> Self {
        let allowed = config.allowed_set();
        let disallowed = config.disallowed_set();
        let drop_attributes = config.drop_attributes_set();
        let strip_wrapper_elements = config.strip_wrapper_elements_set();
        Self {
            config,
            allowed,
            disallowed,
            drop_attributes,
            strip_wrapper_elements,
        }
    }

    // Efficient check for allowed tags using HashSet (case-insensitive)
    #[inline]
    fn is_tag_allowed(&self, tag: &str) -> bool {
        if self.allowed.is_empty() {
            return false;
        }
        // Remove angle brackets and slashes, then split by whitespace or '>'
        let tag = tag.trim_start_matches('<').trim_start_matches('/');
        let tag_name = tag
            .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
            .next()
            .unwrap_or("");
        self.allowed.contains(&tag_name.to_lowercase())
    }

    /// Check if a tag is in the disallowed set (for disallowed-only mode)
    #[inline]
    fn is_tag_disallowed(&self, tag: &str) -> bool {
        if self.disallowed.is_empty() {
            return false;
        }
        // Remove angle brackets and slashes, then split by whitespace or '>'
        let tag = tag.trim_start_matches('<').trim_start_matches('/');
        let tag_name = tag
            .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
            .next()
            .unwrap_or("");
        self.disallowed.contains(&tag_name.to_lowercase())
    }

    /// Check if operating in disallowed-only mode
    #[inline]
    fn is_disallowed_mode(&self) -> bool {
        self.config.is_disallowed_mode()
    }

    // Check if a tag is an HTML comment
    #[inline]
    fn is_html_comment(&self, tag: &str) -> bool {
        tag.starts_with("<!--") && tag.ends_with("-->")
    }

    /// Check if a tag name is a valid HTML element or custom element.
    /// Returns false for placeholder syntax like `<NAME>`, `<resource>`, `<actual>`.
    ///
    /// Per HTML spec, custom elements must contain a hyphen (e.g., `<my-component>`).
    #[inline]
    fn is_html_element_or_custom(tag_name: &str) -> bool {
        // Sorted for binary search — must remain sorted when adding elements
        const HTML_ELEMENTS: &[&str] = &[
            "a",
            "abbr",
            "acronym",
            "address",
            "applet",
            "area",
            "article",
            "aside",
            "audio",
            "b",
            "base",
            "basefont",
            "bdi",
            "bdo",
            "big",
            "blockquote",
            "body",
            "br",
            "button",
            "canvas",
            "caption",
            "center",
            "cite",
            "code",
            "col",
            "colgroup",
            "data",
            "datalist",
            "dd",
            "del",
            "details",
            "dfn",
            "dialog",
            "dir",
            "div",
            "dl",
            "dt",
            "em",
            "embed",
            "fieldset",
            "figcaption",
            "figure",
            "font",
            "footer",
            "form",
            "frame",
            "frameset",
            "h1",
            "h2",
            "h3",
            "h4",
            "h5",
            "h6",
            "head",
            "header",
            "hgroup",
            "hr",
            "html",
            "i",
            "iframe",
            "img",
            "input",
            "ins",
            "isindex",
            "kbd",
            "label",
            "legend",
            "li",
            "link",
            "main",
            "map",
            "mark",
            "marquee",
            "math",
            "menu",
            "meta",
            "meter",
            "nav",
            "noembed",
            "noframes",
            "noscript",
            "object",
            "ol",
            "optgroup",
            "option",
            "output",
            "p",
            "param",
            "picture",
            "plaintext",
            "pre",
            "progress",
            "q",
            "rp",
            "rt",
            "ruby",
            "s",
            "samp",
            "script",
            "search",
            "section",
            "select",
            "slot",
            "small",
            "source",
            "span",
            "strike",
            "strong",
            "style",
            "sub",
            "summary",
            "sup",
            "svg",
            "table",
            "tbody",
            "td",
            "template",
            "textarea",
            "tfoot",
            "th",
            "thead",
            "time",
            "title",
            "tr",
            "track",
            "tt",
            "u",
            "ul",
            "var",
            "video",
            "wbr",
            "xmp",
        ];

        let lower = tag_name.to_ascii_lowercase();
        if HTML_ELEMENTS.binary_search(&lower.as_str()).is_ok() {
            return true;
        }
        // Custom elements must contain a hyphen per HTML spec
        tag_name.contains('-')
    }

    // Check if a tag is likely a programming type annotation rather than HTML
    #[inline]
    fn is_likely_type_annotation(&self, tag: &str) -> bool {
        // Sorted for binary search — must remain sorted when adding elements
        const COMMON_TYPES: &[&str] = &[
            "any",
            "apiresponse",
            "array",
            "bigint",
            "config",
            "data",
            "date",
            "e",
            "element",
            "error",
            "function",
            "generator",
            "item",
            "iterator",
            "k",
            "map",
            "node",
            "null",
            "number",
            "options",
            "params",
            "promise",
            "regexp",
            "request",
            "response",
            "result",
            "set",
            "string",
            "symbol",
            "t",
            "u",
            "undefined",
            "userdata",
            "v",
            "void",
            "weakmap",
            "weakset",
        ];

        let tag_content = tag
            .trim_start_matches('<')
            .trim_end_matches('>')
            .trim_start_matches('/');
        let tag_name = tag_content
            .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
            .next()
            .unwrap_or("");

        // Check if it's a simple tag (no attributes) with a common type name
        if !tag_content.contains(' ') && !tag_content.contains('=') {
            let lower = tag_name.to_ascii_lowercase();
            COMMON_TYPES.binary_search(&lower.as_str()).is_ok()
        } else {
            false
        }
    }

    // Check if a tag is actually an email address in angle brackets
    #[inline]
    fn is_email_address(&self, tag: &str) -> bool {
        let content = tag.trim_start_matches('<').trim_end_matches('>');
        // Simple email pattern: contains @ and has reasonable structure
        content.contains('@')
            && content.chars().all(|c| c.is_alphanumeric() || "@.-_+".contains(c))
            && content.split('@').count() == 2
            && content.split('@').all(|part| !part.is_empty())
    }

    // Check if a tag has the markdown attribute (MkDocs/Material for MkDocs)
    #[inline]
    fn has_markdown_attribute(&self, tag: &str) -> bool {
        // Check for various forms of markdown attribute
        // Examples: <div markdown>, <div markdown="1">, <div class="result" markdown>
        tag.contains(" markdown>") || tag.contains(" markdown=") || tag.contains(" markdown ")
    }

    /// Check if a tag contains JSX-specific attributes that indicate it's JSX, not HTML
    /// JSX uses different attribute names than HTML:
    /// - `className` instead of `class`
    /// - `htmlFor` instead of `for`
    /// - camelCase event handlers (`onClick`, `onChange`, `onSubmit`, etc.)
    /// - JSX expression syntax `={...}` for dynamic values
    #[inline]
    fn has_jsx_attributes(tag: &str) -> bool {
        // JSX-specific attribute names (HTML uses class, for, onclick, etc.)
        tag.contains("className")
            || tag.contains("htmlFor")
            || tag.contains("dangerouslySetInnerHTML")
            // camelCase event handlers (JSX uses onClick, HTML uses onclick)
            || tag.contains("onClick")
            || tag.contains("onChange")
            || tag.contains("onSubmit")
            || tag.contains("onFocus")
            || tag.contains("onBlur")
            || tag.contains("onKeyDown")
            || tag.contains("onKeyUp")
            || tag.contains("onKeyPress")
            || tag.contains("onMouseDown")
            || tag.contains("onMouseUp")
            || tag.contains("onMouseEnter")
            || tag.contains("onMouseLeave")
            // JSX expression syntax: ={expression} or ={ expression }
            || tag.contains("={")
    }

    // Check if a tag is actually a URL in angle brackets
    #[inline]
    fn is_url_in_angle_brackets(&self, tag: &str) -> bool {
        let content = tag.trim_start_matches('<').trim_end_matches('>');
        // Check for common URL schemes
        content.starts_with("http://")
            || content.starts_with("https://")
            || content.starts_with("ftp://")
            || content.starts_with("ftps://")
            || content.starts_with("mailto:")
    }

    #[inline]
    fn is_relaxed_fix_mode(&self) -> bool {
        self.config.fix_mode == MD033FixMode::Relaxed
    }

    #[inline]
    fn is_droppable_attribute(&self, attr_name: &str) -> bool {
        // Event handler attributes (onclick, onload, etc.) are never droppable
        // because they can execute arbitrary JavaScript.
        if attr_name.starts_with("on") && attr_name.len() > 2 {
            return false;
        }
        self.drop_attributes.contains(attr_name)
            || (attr_name.starts_with("data-")
                && (self.drop_attributes.contains("data-*") || self.drop_attributes.contains("data-")))
    }

    #[inline]
    fn is_strippable_wrapper(&self, tag_name: &str) -> bool {
        self.is_relaxed_fix_mode() && self.strip_wrapper_elements.contains(tag_name)
    }

    /// Check whether `byte_offset` sits directly inside a top-level strippable
    /// wrapper element (e.g. `<p>`).  Returns `true` only when:
    ///  1. The nearest unclosed opening tag before the offset is a configured
    ///     wrapper element, AND
    ///  2. That wrapper is itself NOT nested inside another HTML element.
    ///
    /// Condition 2 prevents converting inner content when the wrapper cannot
    /// be stripped (e.g. `<div><p><img/></p></div>` -- stripping `<p>` is
    /// blocked because it is nested, so converting `<img>` would leave
    /// markdown inside an HTML block where it won't render).
    fn is_inside_strippable_wrapper(&self, content: &str, byte_offset: usize) -> bool {
        if byte_offset == 0 {
            return false;
        }
        let before = content[..byte_offset].trim_end();
        if !before.ends_with('>') || before.ends_with("->") {
            return false;
        }
        if let Some(last_lt) = before.rfind('<') {
            let potential_tag = &before[last_lt..];
            if potential_tag.starts_with("</") || potential_tag.starts_with("<!--") {
                return false;
            }
            let parent_name = potential_tag
                .trim_start_matches('<')
                .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
                .next()
                .unwrap_or("")
                .to_lowercase();
            if !self.strip_wrapper_elements.contains(&parent_name) {
                return false;
            }
            // Verify the wrapper itself is not nested inside another element.
            let wrapper_before = before[..last_lt].trim_end();
            if wrapper_before.ends_with('>')
                && !wrapper_before.ends_with("->")
                && let Some(outer_lt) = wrapper_before.rfind('<')
                && let outer_tag = &wrapper_before[outer_lt..]
                && !outer_tag.starts_with("</")
                && !outer_tag.starts_with("<!--")
            {
                return false;
            }
            return true;
        }
        false
    }

    /// Convert paired HTML tags to their Markdown equivalents.
    /// Returns None if the tag cannot be safely converted (has nested tags, HTML entities, etc.)
    fn convert_to_markdown(tag_name: &str, inner_content: &str) -> Option<String> {
        // Skip if content contains nested HTML tags
        if inner_content.contains('<') {
            return None;
        }
        // Skip if content contains HTML entities (e.g., &vert;, &amp;, &lt;)
        // These need HTML context to render correctly; markdown won't process them
        if inner_content.contains('&') && inner_content.contains(';') {
            // Check for common HTML entity patterns
            let has_entity = inner_content
                .split('&')
                .skip(1)
                .any(|part| part.split(';').next().is_some_and(|e| !e.is_empty() && e.len() < 10));
            if has_entity {
                return None;
            }
        }
        match tag_name {
            "em" | "i" => Some(format!("*{inner_content}*")),
            "strong" | "b" => Some(format!("**{inner_content}**")),
            "code" => {
                // Handle backticks in content by using double backticks with padding
                if inner_content.contains('`') {
                    Some(format!("`` {inner_content} ``"))
                } else {
                    Some(format!("`{inner_content}`"))
                }
            }
            _ => None,
        }
    }

    /// Convert self-closing HTML tags to their Markdown equivalents.
    fn convert_self_closing_to_markdown(&self, tag_name: &str, opening_tag: &str) -> Option<String> {
        match tag_name {
            "br" => match self.config.br_style {
                md033_config::BrStyle::TrailingSpaces => Some("  \n".to_string()),
                md033_config::BrStyle::Backslash => Some("\\\n".to_string()),
            },
            "hr" => Some("\n---\n".to_string()),
            "img" => self.convert_img_to_markdown(opening_tag),
            _ => None,
        }
    }

    /// Parse all attributes from an HTML tag into a list of (name, value) pairs.
    /// This provides proper attribute parsing instead of naive string matching.
    fn parse_attributes(tag: &str) -> Vec<(String, Option<String>)> {
        let mut attrs = Vec::new();

        // Remove < and > and tag name
        let tag_content = tag.trim_start_matches('<').trim_end_matches('>').trim_end_matches('/');

        // Find first whitespace to skip tag name
        let attr_start = tag_content
            .find(|c: char| c.is_whitespace())
            .map(|i| i + 1)
            .unwrap_or(tag_content.len());

        if attr_start >= tag_content.len() {
            return attrs;
        }

        let attr_str = &tag_content[attr_start..];
        let mut chars = attr_str.chars().peekable();

        while chars.peek().is_some() {
            // Skip whitespace
            while chars.peek().is_some_and(|c| c.is_whitespace()) {
                chars.next();
            }

            if chars.peek().is_none() {
                break;
            }

            // Read attribute name
            let mut attr_name = String::new();
            while let Some(&c) = chars.peek() {
                if c.is_whitespace() || c == '=' || c == '>' || c == '/' {
                    break;
                }
                attr_name.push(c);
                chars.next();
            }

            if attr_name.is_empty() {
                break;
            }

            // Skip whitespace before =
            while chars.peek().is_some_and(|c| c.is_whitespace()) {
                chars.next();
            }

            // Check for = and value
            if chars.peek() == Some(&'=') {
                chars.next(); // consume =

                // Skip whitespace after =
                while chars.peek().is_some_and(|c| c.is_whitespace()) {
                    chars.next();
                }

                // Read value
                let mut value = String::new();
                if let Some(&quote) = chars.peek() {
                    if quote == '"' || quote == '\'' {
                        chars.next(); // consume opening quote
                        for c in chars.by_ref() {
                            if c == quote {
                                break;
                            }
                            value.push(c);
                        }
                    } else {
                        // Unquoted value
                        while let Some(&c) = chars.peek() {
                            if c.is_whitespace() || c == '>' || c == '/' {
                                break;
                            }
                            value.push(c);
                            chars.next();
                        }
                    }
                }
                attrs.push((attr_name.to_ascii_lowercase(), Some(value)));
            } else {
                // Boolean attribute (no value)
                attrs.push((attr_name.to_ascii_lowercase(), None));
            }
        }

        attrs
    }

    /// Extract an HTML attribute value from a tag string.
    /// Handles double quotes, single quotes, and unquoted values.
    /// Returns None if the attribute is not found.
    fn extract_attribute(tag: &str, attr_name: &str) -> Option<String> {
        let attrs = Self::parse_attributes(tag);
        let attr_lower = attr_name.to_ascii_lowercase();

        attrs
            .into_iter()
            .find(|(name, _)| name == &attr_lower)
            .and_then(|(_, value)| value)
    }

    /// Check if an HTML tag has extra attributes beyond the specified allowed ones.
    /// Uses proper attribute parsing to avoid false positives from string matching.
    fn has_extra_attributes(&self, tag: &str, allowed_attrs: &[&str]) -> bool {
        let attrs = Self::parse_attributes(tag);

        // All event handlers (on*) are dangerous
        // Plus common attributes that would be lost in markdown conversion
        const DANGEROUS_ATTR_PREFIXES: &[&str] = &["on"]; // onclick, onload, onerror, etc.
        const DANGEROUS_ATTRS: &[&str] = &[
            "class",
            "id",
            "style",
            "target",
            "rel",
            "download",
            "referrerpolicy",
            "crossorigin",
            "loading",
            "decoding",
            "fetchpriority",
            "sizes",
            "srcset",
            "usemap",
            "ismap",
            "width",
            "height",
            "name",   // anchor names
            "data-*", // data attributes (checked separately)
        ];

        for (attr_name, _) in attrs {
            // Skip allowed attributes (list is small, linear scan is efficient)
            if allowed_attrs.iter().any(|a| a.to_ascii_lowercase() == attr_name) {
                continue;
            }

            if self.is_relaxed_fix_mode() {
                if self.is_droppable_attribute(&attr_name) {
                    continue;
                }
                return true;
            }

            // Check for event handlers (on*)
            for prefix in DANGEROUS_ATTR_PREFIXES {
                if attr_name.starts_with(prefix) && attr_name.len() > prefix.len() {
                    return true;
                }
            }

            // Check for data-* attributes
            if attr_name.starts_with("data-") {
                return true;
            }

            // Check for other dangerous attributes
            if DANGEROUS_ATTRS.contains(&attr_name.as_str()) {
                return true;
            }
        }

        false
    }

    /// Convert `<a href="url">text</a>` to `[text](url)` or `[text](url "title")`
    /// Returns None if conversion is not safe.
    fn convert_a_to_markdown(&self, opening_tag: &str, inner_content: &str) -> Option<String> {
        // Extract href attribute
        let href = Self::extract_attribute(opening_tag, "href")?;

        // Check URL is safe
        if !MD033Config::is_safe_url(&href) {
            return None;
        }

        // Check for nested HTML tags in content
        if inner_content.contains('<') {
            return None;
        }

        // Check for HTML entities that wouldn't render correctly in markdown
        if inner_content.contains('&') && inner_content.contains(';') {
            let has_entity = inner_content
                .split('&')
                .skip(1)
                .any(|part| part.split(';').next().is_some_and(|e| !e.is_empty() && e.len() < 10));
            if has_entity {
                return None;
            }
        }

        // Extract optional title attribute
        let title = Self::extract_attribute(opening_tag, "title");

        // Check for extra dangerous attributes (title is allowed)
        if self.has_extra_attributes(opening_tag, &["href", "title"]) {
            return None;
        }

        // If inner content is exactly a markdown image (from a prior <img> fix),
        // use it directly without bracket escaping to produce valid [![alt](src)](href).
        // Must verify the entire content is a single image — not mixed content like
        // "![](url) extra [text]" where trailing brackets still need escaping.
        let trimmed_inner = inner_content.trim();
        let is_markdown_image =
            trimmed_inner.starts_with("![") && trimmed_inner.contains("](") && trimmed_inner.ends_with(')') && {
                // Verify the closing ](url) accounts for the rest of the content
                // by finding the image's ]( and checking nothing follows the final )
                if let Some(bracket_close) = trimmed_inner.rfind("](") {
                    let after_paren = &trimmed_inner[bracket_close + 2..];
                    // The rest should be just "url)" — find the matching close paren
                    after_paren.ends_with(')')
                        && after_paren.chars().filter(|&c| c == ')').count()
                            >= after_paren.chars().filter(|&c| c == '(').count()
                } else {
                    false
                }
            };
        let escaped_text = if is_markdown_image {
            trimmed_inner.to_string()
        } else {
            // Escape special markdown characters in link text
            // Brackets need escaping to avoid breaking the link syntax
            inner_content.replace('[', r"\[").replace(']', r"\]")
        };

        // Escape parentheses in URL
        let escaped_url = href.replace('(', "%28").replace(')', "%29");

        // Format with or without title
        if let Some(title_text) = title {
            // Escape quotes in title
            let escaped_title = title_text.replace('"', r#"\""#);
            Some(format!("[{escaped_text}]({escaped_url} \"{escaped_title}\")"))
        } else {
            Some(format!("[{escaped_text}]({escaped_url})"))
        }
    }

    /// Convert `<img src="url" alt="text">` to `![alt](src)` or `![alt](src "title")`
    /// Returns None if conversion is not safe.
    fn convert_img_to_markdown(&self, tag: &str) -> Option<String> {
        // Extract src attribute (required)
        let src = Self::extract_attribute(tag, "src")?;

        // Check URL is safe
        if !MD033Config::is_safe_url(&src) {
            return None;
        }

        // Extract alt attribute (optional, default to empty)
        let alt = Self::extract_attribute(tag, "alt").unwrap_or_default();

        // Extract optional title attribute
        let title = Self::extract_attribute(tag, "title");

        // Check for extra dangerous attributes (title is allowed)
        if self.has_extra_attributes(tag, &["src", "alt", "title"]) {
            return None;
        }

        // Escape special markdown characters in alt text
        let escaped_alt = alt.replace('[', r"\[").replace(']', r"\]");

        // Escape parentheses in URL
        let escaped_url = src.replace('(', "%28").replace(')', "%29");

        // Format with or without title
        if let Some(title_text) = title {
            // Escape quotes in title
            let escaped_title = title_text.replace('"', r#"\""#);
            Some(format!("![{escaped_alt}]({escaped_url} \"{escaped_title}\")"))
        } else {
            Some(format!("![{escaped_alt}]({escaped_url})"))
        }
    }

    /// Check if an HTML tag has attributes that would make conversion unsafe
    fn has_significant_attributes(opening_tag: &str) -> bool {
        // Tags with just whitespace or empty are fine
        let tag_content = opening_tag
            .trim_start_matches('<')
            .trim_end_matches('>')
            .trim_end_matches('/');

        // Split by whitespace; if there's more than the tag name, it has attributes
        let parts: Vec<&str> = tag_content.split_whitespace().collect();
        parts.len() > 1
    }

    /// Check if a tag appears to be nested inside another HTML element
    /// by looking at the surrounding context (e.g., `<code><em>text</em></code>`)
    fn is_nested_in_html(content: &str, tag_byte_start: usize, tag_byte_end: usize) -> bool {
        // Check if there's a `>` immediately before this tag (indicating inside another element)
        if tag_byte_start > 0 {
            let before = &content[..tag_byte_start];
            let before_trimmed = before.trim_end();
            if before_trimmed.ends_with('>') && !before_trimmed.ends_with("->") {
                // Check it's not a closing tag or comment
                if let Some(last_lt) = before_trimmed.rfind('<') {
                    let potential_tag = &before_trimmed[last_lt..];
                    // Skip if it's a closing tag (</...>) or comment (<!--)
                    if !potential_tag.starts_with("</") && !potential_tag.starts_with("<!--") {
                        return true;
                    }
                }
            }
        }
        // Check if there's a `<` immediately after the closing tag (indicating inside another element)
        if tag_byte_end < content.len() {
            let after = &content[tag_byte_end..];
            let after_trimmed = after.trim_start();
            if after_trimmed.starts_with("</") {
                return true;
            }
        }
        false
    }

    /// Calculate fix to remove HTML tags while keeping content.
    ///
    /// For self-closing tags like `<br/>`, returns a single fix to remove the tag.
    /// For paired tags like `<span>text</span>`, returns the replacement text (just the content).
    ///
    /// Returns (range, replacement_text) where range is the bytes to replace
    /// and replacement_text is what to put there (content without tags, or empty for self-closing).
    ///
    /// When `in_html_block` is true, returns None in conservative mode.  In
    /// relaxed mode two exceptions apply:
    /// - Strippable wrapper elements (e.g. `<p>`) bypass the block guard so
    ///   they can be stripped even though they ARE the HTML block.
    /// - Self-closing tags whose direct parent is a strippable wrapper also
    ///   bypass the guard so inner content can be converted first.
    fn calculate_fix(
        &self,
        content: &str,
        opening_tag: &str,
        tag_byte_start: usize,
        in_html_block: bool,
    ) -> Option<(std::ops::Range<usize>, String)> {
        // Extract tag name from opening tag
        let tag_name = opening_tag
            .trim_start_matches('<')
            .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
            .next()?
            .to_lowercase();

        // Check if it's a self-closing tag (ends with /> or is a void element like <br>)
        let is_self_closing =
            opening_tag.ends_with("/>") || matches!(tag_name.as_str(), "br" | "hr" | "img" | "input" | "meta" | "link");

        if is_self_closing {
            // When fix is enabled, try to convert to Markdown equivalent.
            // Skip tags inside HTML blocks (would break structure), UNLESS we
            // are in relaxed mode and the containing block is a strippable
            // wrapper -- this lets the inner element be converted first so the
            // wrapper can be stripped on a subsequent pass.
            let block_ok = !in_html_block
                || (self.is_relaxed_fix_mode() && self.is_inside_strippable_wrapper(content, tag_byte_start));
            if self.config.fix
                && MD033Config::is_safe_fixable_tag(&tag_name)
                && block_ok
                && let Some(markdown) = self.convert_self_closing_to_markdown(&tag_name, opening_tag)
            {
                return Some((tag_byte_start..tag_byte_start + opening_tag.len(), markdown));
            }
            // Can't convert this self-closing tag to Markdown, don't provide a fix
            // (e.g., <input>, <meta> - these have no Markdown equivalent without the new img support)
            return None;
        }

        // Search for the closing tag after the opening tag (case-insensitive)
        let search_start = tag_byte_start + opening_tag.len();
        let search_slice = &content[search_start..];

        // Find closing tag case-insensitively
        let closing_tag_lower = format!("</{tag_name}>");
        let closing_pos = search_slice.to_ascii_lowercase().find(&closing_tag_lower);

        if let Some(closing_pos) = closing_pos {
            // Get actual closing tag from original content to get correct byte length
            let closing_tag_len = closing_tag_lower.len();
            let closing_byte_start = search_start + closing_pos;
            let closing_byte_end = closing_byte_start + closing_tag_len;

            // Extract the content between tags
            let inner_content = &content[search_start..closing_byte_start];

            // In relaxed mode, check wrapper stripping BEFORE the in_html_block
            // guard because the wrapper element itself IS the HTML block. We only
            // strip when:
            //  - the wrapper is not nested inside another HTML element
            //  - the inner content no longer contains HTML tags (prevents
            //    overlapping byte-range replacements within a single fix pass)
            if self.config.fix && self.is_strippable_wrapper(&tag_name) {
                if Self::is_nested_in_html(content, tag_byte_start, closing_byte_end) {
                    return None;
                }
                if inner_content.contains('<') {
                    return None;
                }
                return Some((tag_byte_start..closing_byte_end, inner_content.trim().to_string()));
            }

            // Skip auto-fix if inside an HTML block (like <pre>, <div>, etc.)
            // Converting tags inside HTML blocks would break the intended structure
            if in_html_block {
                return None;
            }

            // Skip auto-fix if this tag is nested inside another HTML element
            // e.g., <code><em>text</em></code> - don't convert the inner <em>
            if Self::is_nested_in_html(content, tag_byte_start, closing_byte_end) {
                return None;
            }

            // When fix is enabled and tag is safe to convert, try markdown conversion
            if self.config.fix && MD033Config::is_safe_fixable_tag(&tag_name) {
                // Handle <a> tags specially - they require attribute extraction
                if tag_name == "a" {
                    if let Some(markdown) = self.convert_a_to_markdown(opening_tag, inner_content) {
                        return Some((tag_byte_start..closing_byte_end, markdown));
                    }
                    // convert_a_to_markdown returned None - unsafe URL, nested HTML, etc.
                    return None;
                }

                // For simple tags (em, strong, code, etc.) - no attributes allowed
                if Self::has_significant_attributes(opening_tag) {
                    // Don't provide a fix for tags with attributes
                    // User may want to keep the attributes, so leave as-is
                    return None;
                }
                if let Some(markdown) = Self::convert_to_markdown(&tag_name, inner_content) {
                    return Some((tag_byte_start..closing_byte_end, markdown));
                }
                // convert_to_markdown returned None, meaning content has nested tags or
                // HTML entities that shouldn't be converted - leave as-is
                return None;
            }

            // For non-fixable tags, don't provide a fix
            // (e.g., <div>content</div>, <span>text</span>)
            return None;
        }

        // If no closing tag found, don't provide a fix (malformed HTML)
        None
    }
}

impl Rule for MD033NoInlineHtml {
    fn name(&self) -> &'static str {
        "MD033"
    }

    fn description(&self) -> &'static str {
        "Inline HTML is not allowed"
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let content = ctx.content;

        // Early return: if no HTML tags at all, skip processing
        if content.is_empty() || !ctx.likely_has_html() {
            return Ok(Vec::new());
        }

        // Quick check for HTML tag pattern before expensive processing
        if !HTML_TAG_QUICK_CHECK.is_match(content) {
            return Ok(Vec::new());
        }

        let mut warnings = Vec::new();

        // Use centralized HTML parser to get all HTML tags (including multiline)
        let html_tags = ctx.html_tags();

        for html_tag in html_tags.iter() {
            // Skip closing tags (only warn on opening tags)
            if html_tag.is_closing {
                continue;
            }

            let line_num = html_tag.line;
            let tag_byte_start = html_tag.byte_offset;

            // Reconstruct tag string from byte offsets
            let tag = &content[html_tag.byte_offset..html_tag.byte_end];

            // Skip tags in code blocks, PyMdown blocks, and block IALs
            if ctx
                .line_info(line_num)
                .is_some_and(|info| info.in_code_block || info.in_pymdown_block || info.is_kramdown_block_ial)
            {
                continue;
            }

            // Skip HTML tags inside HTML comments
            if ctx.is_in_html_comment(tag_byte_start) {
                continue;
            }

            // Skip HTML comments themselves
            if self.is_html_comment(tag) {
                continue;
            }

            // Skip angle brackets inside link reference definition titles
            // e.g., [ref]: url "Title with <angle brackets>"
            if ctx.is_in_link_title(tag_byte_start) {
                continue;
            }

            // Skip JSX components in MDX files (e.g., <Chart />, <MyComponent>)
            if ctx.flavor.supports_jsx() && html_tag.tag_name.chars().next().is_some_and(|c| c.is_uppercase()) {
                continue;
            }

            // Skip JSX fragments in MDX files (<> and </>)
            if ctx.flavor.supports_jsx() && (html_tag.tag_name.is_empty() || tag == "<>" || tag == "</>") {
                continue;
            }

            // Skip elements with JSX-specific attributes in MDX files
            // e.g., <div className="...">, <button onClick={handler}>
            if ctx.flavor.supports_jsx() && Self::has_jsx_attributes(tag) {
                continue;
            }

            // Skip non-HTML elements (placeholder syntax like <NAME>, <resource>)
            if !Self::is_html_element_or_custom(&html_tag.tag_name) {
                continue;
            }

            // Skip likely programming type annotations
            if self.is_likely_type_annotation(tag) {
                continue;
            }

            // Skip email addresses in angle brackets
            if self.is_email_address(tag) {
                continue;
            }

            // Skip URLs in angle brackets
            if self.is_url_in_angle_brackets(tag) {
                continue;
            }

            // Skip tags inside code spans (use byte offset for reliable multi-line span detection)
            if ctx.is_byte_offset_in_code_span(tag_byte_start) {
                continue;
            }

            // Determine whether to report this tag based on mode:
            // - Disallowed mode: only report tags in the disallowed list
            // - Default mode: report all tags except those in the allowed list
            if self.is_disallowed_mode() {
                // In disallowed mode, skip tags NOT in the disallowed list
                if !self.is_tag_disallowed(tag) {
                    continue;
                }
            } else {
                // In default mode, skip allowed tags
                if self.is_tag_allowed(tag) {
                    continue;
                }
            }

            // Skip tags with markdown attribute in MkDocs mode
            if ctx.flavor == crate::config::MarkdownFlavor::MkDocs && self.has_markdown_attribute(tag) {
                continue;
            }

            // Check if we're inside an HTML block (like <pre>, <div>, etc.)
            let in_html_block = ctx.is_in_html_block(line_num);

            // Calculate fix to remove HTML tags but keep content
            let fix = self
                .calculate_fix(content, tag, tag_byte_start, in_html_block)
                .map(|(range, replacement)| Fix { range, replacement });

            // Calculate actual end line and column for multiline tags
            // Use byte_end - 1 to get the last character position of the tag
            let (end_line, end_col) = if html_tag.byte_end > 0 {
                ctx.offset_to_line_col(html_tag.byte_end - 1)
            } else {
                (line_num, html_tag.end_col + 1)
            };

            // Report the HTML tag
            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line: line_num,
                column: html_tag.start_col + 1, // Convert to 1-indexed
                end_line,                       // Actual end line for multiline tags
                end_column: end_col + 1,        // Actual end column
                message: format!("Inline HTML found: {tag}"),
                severity: Severity::Warning,
                fix,
            });
        }

        Ok(warnings)
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        // Auto-fix is opt-in: only apply if explicitly enabled in config
        if !self.config.fix {
            return Ok(ctx.content.to_string());
        }

        // Get warnings with their inline fixes
        let warnings = self.check(ctx)?;
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());

        // If no warnings with fixes, return original content
        if warnings.is_empty() || !warnings.iter().any(|w| w.fix.is_some()) {
            return Ok(ctx.content.to_string());
        }

        // Collect all fixes and sort by range start (descending) to apply from end to beginning
        let mut fixes: Vec<_> = warnings
            .iter()
            .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
            .collect();
        fixes.sort_by(|a, b| b.0.cmp(&a.0));

        // Apply fixes from end to beginning to preserve byte offsets
        let mut result = ctx.content.to_string();
        for (start, end, replacement) in fixes {
            if start < result.len() && end <= result.len() && start <= end {
                result.replace_range(start..end, replacement);
            }
        }

        Ok(result)
    }

    fn fix_capability(&self) -> crate::rule::FixCapability {
        if self.config.fix {
            crate::rule::FixCapability::FullyFixable
        } else {
            crate::rule::FixCapability::Unfixable
        }
    }

    /// Get the category of this rule for selective processing
    fn category(&self) -> RuleCategory {
        RuleCategory::Html
    }

    /// Check if this rule should be skipped
    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        ctx.content.is_empty() || !ctx.likely_has_html()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn default_config_section(&self) -> Option<(String, toml::Value)> {
        let json_value = serde_json::to_value(&self.config).ok()?;
        Some((
            self.name().to_string(),
            crate::rule_config_serde::json_to_toml_value(&json_value)?,
        ))
    }

    fn config_aliases(&self) -> Option<std::collections::HashMap<String, String>> {
        let mut aliases = std::collections::HashMap::new();
        // Shorthand aliases for allowed-elements/disallowed-elements
        aliases.insert("allowed".to_string(), "allowed-elements".to_string());
        aliases.insert("disallowed".to_string(), "disallowed-elements".to_string());
        Some(aliases)
    }

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD033Config>(config);
        Box::new(Self::from_config_struct(rule_config))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lint_context::LintContext;
    use crate::rule::Rule;

    fn relaxed_fix_rule() -> MD033NoInlineHtml {
        let config = MD033Config {
            fix: true,
            fix_mode: MD033FixMode::Relaxed,
            ..MD033Config::default()
        };
        MD033NoInlineHtml::from_config_struct(config)
    }

    #[test]
    fn test_md033_basic_html() {
        let rule = MD033NoInlineHtml::default();
        let content = "<div>Some content</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only reports opening tags, not closing tags
        assert_eq!(result.len(), 1); // Only <div>, not </div>
        assert!(result[0].message.starts_with("Inline HTML found: <div>"));
    }

    #[test]
    fn test_md033_case_insensitive() {
        let rule = MD033NoInlineHtml::default();
        let content = "<DiV>Some <B>content</B></dIv>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only reports opening tags, not closing tags
        assert_eq!(result.len(), 2); // <DiV>, <B> (not </B>, </dIv>)
        assert_eq!(result[0].message, "Inline HTML found: <DiV>");
        assert_eq!(result[1].message, "Inline HTML found: <B>");
    }

    #[test]
    fn test_md033_allowed_tags() {
        let rule = MD033NoInlineHtml::with_allowed(vec!["div".to_string(), "br".to_string()]);
        let content = "<div>Allowed</div><p>Not allowed</p><br/>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only warnings for non-allowed opening tags (<p> only, div and br are allowed)
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].message, "Inline HTML found: <p>");

        // Test case-insensitivity of allowed tags
        let content2 = "<DIV>Allowed</DIV><P>Not allowed</P><BR/>";
        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
        let result2 = rule.check(&ctx2).unwrap();
        assert_eq!(result2.len(), 1); // Only <P> flagged
        assert_eq!(result2[0].message, "Inline HTML found: <P>");
    }

    #[test]
    fn test_md033_html_comments() {
        let rule = MD033NoInlineHtml::default();
        let content = "<!-- This is a comment --> <p>Not a comment</p>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should detect warnings for HTML opening tags (comments are skipped, closing tags not reported)
        assert_eq!(result.len(), 1); // Only <p>
        assert_eq!(result[0].message, "Inline HTML found: <p>");
    }

    #[test]
    fn test_md033_tags_in_links() {
        let rule = MD033NoInlineHtml::default();
        let content = "[Link](http://example.com/<div>)";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // The <div> in the URL should be detected as HTML (not skipped)
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].message, "Inline HTML found: <div>");

        let content2 = "[Link <a>text</a>](url)";
        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
        let result2 = rule.check(&ctx2).unwrap();
        // Only reports opening tags
        assert_eq!(result2.len(), 1); // Only <a>
        assert_eq!(result2[0].message, "Inline HTML found: <a>");
    }

    #[test]
    fn test_md033_fix_escaping() {
        let rule = MD033NoInlineHtml::default();
        let content = "Text with <div> and <br/> tags.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed_content = rule.fix(&ctx).unwrap();
        // No fix for HTML tags; output should be unchanged
        assert_eq!(fixed_content, content);
    }

    #[test]
    fn test_md033_in_code_blocks() {
        let rule = MD033NoInlineHtml::default();
        let content = "```html\n<div>Code</div>\n```\n<div>Not code</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Only reports opening tags outside code block
        assert_eq!(result.len(), 1); // Only <div> outside code block
        assert_eq!(result[0].message, "Inline HTML found: <div>");
    }

    #[test]
    fn test_md033_in_code_spans() {
        let rule = MD033NoInlineHtml::default();
        let content = "Text with `<p>in code</p>` span. <br/> Not in span.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should detect <br/> outside code span, but not tags inside code span
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].message, "Inline HTML found: <br/>");
    }

    #[test]
    fn test_md033_issue_90_code_span_with_diff_block() {
        // Test for issue #90: inline code span followed by diff code block
        let rule = MD033NoInlineHtml::default();
        let content = r#"# Heading

`<env>`

```diff
- this
+ that
```"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        // Should NOT detect <env> as HTML since it's inside backticks
        assert_eq!(result.len(), 0, "Should not report HTML tags inside code spans");
    }

    #[test]
    fn test_md033_multiple_code_spans_with_angle_brackets() {
        // Test multiple code spans on same line
        let rule = MD033NoInlineHtml::default();
        let content = "`<one>` and `<two>` and `<three>` are all code spans";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 0, "Should not report HTML tags inside any code spans");
    }

    #[test]
    fn test_md033_nested_angle_brackets_in_code_span() {
        // Test nested angle brackets
        let rule = MD033NoInlineHtml::default();
        let content = "Text with `<<nested>>` brackets";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 0, "Should handle nested angle brackets in code spans");
    }

    #[test]
    fn test_md033_code_span_at_end_before_code_block() {
        // Test code span at end of line before code block
        let rule = MD033NoInlineHtml::default();
        let content = "Testing `<test>`\n```\ncode here\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 0, "Should handle code span before code block");
    }

    #[test]
    fn test_md033_quick_fix_inline_tag() {
        // Test that non-fixable tags (like <span>) do NOT get a fix
        // Only safe fixable tags (em, i, strong, b, code, br, hr) with fix=true get fixes
        let rule = MD033NoInlineHtml::default();
        let content = "This has <span>inline text</span> that should keep content.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // <span> is NOT a safe fixable tag, so no fix should be provided
        assert!(
            result[0].fix.is_none(),
            "Non-fixable tags like <span> should not have a fix"
        );
    }

    #[test]
    fn test_md033_quick_fix_multiline_tag() {
        // HTML block elements like <div> are intentionally NOT auto-fixed
        // Removing them would change document structure significantly
        let rule = MD033NoInlineHtml::default();
        let content = "<div>\nBlock content\n</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // HTML block elements should NOT have auto-fix
        assert!(result[0].fix.is_none(), "HTML block elements should NOT have auto-fix");
    }

    #[test]
    fn test_md033_quick_fix_self_closing_tag() {
        // Test that self-closing tags with fix=false (default) do NOT get a fix
        let rule = MD033NoInlineHtml::default();
        let content = "Self-closing: <br/>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // Default config has fix=false, so no fix should be provided
        assert!(
            result[0].fix.is_none(),
            "Self-closing tags should not have a fix when fix config is false"
        );
    }

    #[test]
    fn test_md033_quick_fix_multiple_tags() {
        // Test that multiple tags without fix=true do NOT get fixes
        // <span> is not a safe fixable tag, <strong> is but fix=false by default
        let rule = MD033NoInlineHtml::default();
        let content = "<span>first</span> and <strong>second</strong>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 2, "Should find two HTML tags");
        // Neither should have a fix: <span> is not fixable, <strong> is but fix=false
        assert!(result[0].fix.is_none(), "Non-fixable <span> should not have a fix");
        assert!(
            result[1].fix.is_none(),
            "<strong> should not have a fix when fix config is false"
        );
    }

    #[test]
    fn test_md033_skip_angle_brackets_in_link_titles() {
        // Angle brackets inside link reference definition titles should not be flagged as HTML
        let rule = MD033NoInlineHtml::default();
        let content = r#"# Test

[example]: <https://example.com> "Title with <Angle Brackets> inside"

Regular text with <div>content</div> HTML tag.
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only flag <div>, not <Angle Brackets> in the title (not a valid HTML element)
        // Opening tag only (markdownlint behavior)
        assert_eq!(result.len(), 1, "Should find opening div tag");
        assert!(
            result[0].message.contains("<div>"),
            "Should flag <div>, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_md033_skip_angle_brackets_in_link_title_single_quotes() {
        // Test with single-quoted title
        let rule = MD033NoInlineHtml::default();
        let content = r#"[ref]: url 'Title <Help Wanted> here'

<span>text</span> here
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // <Help Wanted> is not a valid HTML element, so only <span> is flagged
        // Opening tag only (markdownlint behavior)
        assert_eq!(result.len(), 1, "Should find opening span tag");
        assert!(
            result[0].message.contains("<span>"),
            "Should flag <span>, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_md033_multiline_tag_end_line_calculation() {
        // Test that multiline HTML tags report correct end_line
        let rule = MD033NoInlineHtml::default();
        let content = "<div\n  class=\"test\"\n  id=\"example\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // Tag starts on line 1
        assert_eq!(result[0].line, 1, "Start line should be 1");
        // Tag ends on line 3 (where the closing > is)
        assert_eq!(result[0].end_line, 3, "End line should be 3");
    }

    #[test]
    fn test_md033_single_line_tag_same_start_end_line() {
        // Test that single-line HTML tags have same start and end line
        let rule = MD033NoInlineHtml::default();
        let content = "Some text <div class=\"test\"> more text";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        assert_eq!(result[0].line, 1, "Start line should be 1");
        assert_eq!(result[0].end_line, 1, "End line should be 1 for single-line tag");
    }

    #[test]
    fn test_md033_multiline_tag_with_many_attributes() {
        // Test multiline tag spanning multiple lines
        let rule = MD033NoInlineHtml::default();
        let content =
            "Text\n<div\n  data-attr1=\"value1\"\n  data-attr2=\"value2\"\n  data-attr3=\"value3\">\nMore text";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // Tag starts on line 2 (first line is "Text")
        assert_eq!(result[0].line, 2, "Start line should be 2");
        // Tag ends on line 5 (where the closing > is)
        assert_eq!(result[0].end_line, 5, "End line should be 5");
    }

    #[test]
    fn test_md033_disallowed_mode_basic() {
        // Test disallowed mode: only flags tags in the disallowed list
        let rule = MD033NoInlineHtml::with_disallowed(vec!["script".to_string(), "iframe".to_string()]);
        let content = "<div>Safe content</div><script>alert('xss')</script>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only flag <script>, not <div>
        assert_eq!(result.len(), 1, "Should only flag disallowed tags");
        assert!(result[0].message.contains("<script>"), "Should flag script tag");
    }

    #[test]
    fn test_md033_disallowed_gfm_security_tags() {
        // Test GFM security tags expansion
        let rule = MD033NoInlineHtml::with_disallowed(vec!["gfm".to_string()]);
        let content = r#"
<div>Safe</div>
<title>Bad title</title>
<textarea>Bad textarea</textarea>
<style>.bad{}</style>
<iframe src="evil"></iframe>
<script>evil()</script>
<plaintext>old tag</plaintext>
<span>Safe span</span>
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag: title, textarea, style, iframe, script, plaintext
        // Should NOT flag: div, span
        assert_eq!(result.len(), 6, "Should flag 6 GFM security tags");

        let flagged_tags: Vec<&str> = result
            .iter()
            .filter_map(|w| w.message.split("<").nth(1))
            .filter_map(|s| s.split(">").next())
            .filter_map(|s| s.split_whitespace().next())
            .collect();

        assert!(flagged_tags.contains(&"title"), "Should flag title");
        assert!(flagged_tags.contains(&"textarea"), "Should flag textarea");
        assert!(flagged_tags.contains(&"style"), "Should flag style");
        assert!(flagged_tags.contains(&"iframe"), "Should flag iframe");
        assert!(flagged_tags.contains(&"script"), "Should flag script");
        assert!(flagged_tags.contains(&"plaintext"), "Should flag plaintext");
        assert!(!flagged_tags.contains(&"div"), "Should NOT flag div");
        assert!(!flagged_tags.contains(&"span"), "Should NOT flag span");
    }

    #[test]
    fn test_md033_disallowed_case_insensitive() {
        // Test that disallowed check is case-insensitive
        let rule = MD033NoInlineHtml::with_disallowed(vec!["script".to_string()]);
        let content = "<SCRIPT>alert('xss')</SCRIPT><Script>alert('xss')</Script>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag both <SCRIPT> and <Script>
        assert_eq!(result.len(), 2, "Should flag both case variants");
    }

    #[test]
    fn test_md033_disallowed_with_attributes() {
        // Test that disallowed mode works with tags that have attributes
        let rule = MD033NoInlineHtml::with_disallowed(vec!["iframe".to_string()]);
        let content = r#"<iframe src="https://evil.com" width="100" height="100"></iframe>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should flag iframe with attributes");
        assert!(result[0].message.contains("iframe"), "Should flag iframe");
    }

    #[test]
    fn test_md033_disallowed_all_gfm_tags() {
        // Verify all GFM disallowed tags are covered
        use md033_config::GFM_DISALLOWED_TAGS;
        let rule = MD033NoInlineHtml::with_disallowed(vec!["gfm".to_string()]);

        for tag in GFM_DISALLOWED_TAGS {
            let content = format!("<{tag}>content</{tag}>");
            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();

            assert_eq!(result.len(), 1, "GFM tag <{tag}> should be flagged");
        }
    }

    #[test]
    fn test_md033_disallowed_mixed_with_custom() {
        // Test mixing "gfm" with custom disallowed tags
        let rule = MD033NoInlineHtml::with_disallowed(vec![
            "gfm".to_string(),
            "marquee".to_string(), // Custom disallowed tag
        ]);
        let content = r#"<script>bad</script><marquee>annoying</marquee><div>ok</div>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag script (gfm) and marquee (custom)
        assert_eq!(result.len(), 2, "Should flag both gfm and custom tags");
    }

    #[test]
    fn test_md033_disallowed_empty_means_default_mode() {
        // Empty disallowed list means default mode (flag all HTML)
        let rule = MD033NoInlineHtml::with_disallowed(vec![]);
        let content = "<div>content</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag <div> in default mode
        assert_eq!(result.len(), 1, "Empty disallowed = default mode");
    }

    #[test]
    fn test_md033_jsx_fragments_in_mdx() {
        // JSX fragments (<> and </>) should not trigger warnings in MDX
        let rule = MD033NoInlineHtml::default();
        let content = r#"# MDX Document

<>
  <Heading />
  <Content />
</>

<div>Regular HTML should still be flagged</div>
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
        let result = rule.check(&ctx).unwrap();

        // Should only flag <div>, not the fragments or JSX components
        assert_eq!(result.len(), 1, "Should only find one HTML tag (the div)");
        assert!(
            result[0].message.contains("<div>"),
            "Should flag <div>, not JSX fragments"
        );
    }

    #[test]
    fn test_md033_jsx_components_in_mdx() {
        // JSX components (capitalized) should not trigger warnings in MDX
        let rule = MD033NoInlineHtml::default();
        let content = r#"<CustomComponent prop="value">
  Content
</CustomComponent>

<MyButton onClick={handler}>Click</MyButton>
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
        let result = rule.check(&ctx).unwrap();

        // No warnings - all are JSX components
        assert_eq!(result.len(), 0, "Should not flag JSX components in MDX");
    }

    #[test]
    fn test_md033_jsx_not_skipped_in_standard_markdown() {
        // In standard markdown, capitalized tags should still be flagged if they're valid HTML
        let rule = MD033NoInlineHtml::default();
        let content = "<Script>alert(1)</Script>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag <Script> in standard markdown (it's a valid HTML element)
        assert_eq!(result.len(), 1, "Should flag <Script> in standard markdown");
    }

    #[test]
    fn test_md033_jsx_attributes_in_mdx() {
        // Elements with JSX-specific attributes should not trigger warnings in MDX
        let rule = MD033NoInlineHtml::default();
        let content = r#"# MDX with JSX Attributes

<div className="card big">Content</div>

<button onClick={handleClick}>Click me</button>

<label htmlFor="input-id">Label</label>

<input onChange={handleChange} />

<div class="html-class">Regular HTML should be flagged</div>
"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::MDX, None);
        let result = rule.check(&ctx).unwrap();

        // Should only flag the div with regular HTML "class" attribute
        assert_eq!(
            result.len(),
            1,
            "Should only flag HTML element without JSX attributes, got: {result:?}"
        );
        assert!(
            result[0].message.contains("<div class="),
            "Should flag the div with HTML class attribute"
        );
    }

    #[test]
    fn test_md033_jsx_attributes_not_skipped_in_standard() {
        // In standard markdown, JSX attributes should still be flagged
        let rule = MD033NoInlineHtml::default();
        let content = r#"<div className="card">Content</div>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should flag in standard markdown
        assert_eq!(result.len(), 1, "Should flag JSX-style elements in standard markdown");
    }

    // Auto-fix tests for MD033

    #[test]
    fn test_md033_fix_disabled_by_default() {
        // Auto-fix should be disabled by default
        let rule = MD033NoInlineHtml::default();
        assert!(!rule.config.fix, "Fix should be disabled by default");
        assert_eq!(rule.fix_capability(), crate::rule::FixCapability::Unfixable);
    }

    #[test]
    fn test_md033_fix_enabled_em_to_italic() {
        // When fix is enabled, <em>text</em> should convert to *text*
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <em>emphasized text</em> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has *emphasized text* here.");
    }

    #[test]
    fn test_md033_fix_enabled_i_to_italic() {
        // <i>text</i> should convert to *text*
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <i>italic text</i> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has *italic text* here.");
    }

    #[test]
    fn test_md033_fix_enabled_strong_to_bold() {
        // <strong>text</strong> should convert to **text**
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <strong>bold text</strong> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has **bold text** here.");
    }

    #[test]
    fn test_md033_fix_enabled_b_to_bold() {
        // <b>text</b> should convert to **text**
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <b>bold text</b> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has **bold text** here.");
    }

    #[test]
    fn test_md033_fix_enabled_code_to_backticks() {
        // <code>text</code> should convert to `text`
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <code>inline code</code> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has `inline code` here.");
    }

    #[test]
    fn test_md033_fix_enabled_code_with_backticks() {
        // <code>text with `backticks`</code> should use double backticks
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <code>text with `backticks`</code> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has `` text with `backticks` `` here.");
    }

    #[test]
    fn test_md033_fix_enabled_br_trailing_spaces() {
        // <br> should convert to two trailing spaces + newline (default)
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "First line<br>Second line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "First line  \nSecond line");
    }

    #[test]
    fn test_md033_fix_enabled_br_self_closing() {
        // <br/> and <br /> should also convert
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "First<br/>second<br />third";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "First  \nsecond  \nthird");
    }

    #[test]
    fn test_md033_fix_enabled_br_backslash_style() {
        // With br_style = backslash, <br> should convert to backslash + newline
        let config = MD033Config {
            allowed: Vec::new(),
            disallowed: Vec::new(),
            fix: true,
            br_style: md033_config::BrStyle::Backslash,
            ..MD033Config::default()
        };
        let rule = MD033NoInlineHtml::from_config_struct(config);
        let content = "First line<br>Second line";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "First line\\\nSecond line");
    }

    #[test]
    fn test_md033_fix_enabled_hr() {
        // <hr> should convert to horizontal rule
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Above<hr>Below";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Above\n---\nBelow");
    }

    #[test]
    fn test_md033_fix_enabled_hr_self_closing() {
        // <hr/> should also convert
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Above<hr/>Below";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Above\n---\nBelow");
    }

    #[test]
    fn test_md033_fix_skips_nested_tags() {
        // Tags with nested HTML - outer tags may not be fully fixed due to overlapping ranges
        // The inner tags are processed first, which can invalidate outer tag ranges
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <em>text with <strong>nested</strong> tags</em> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Inner <strong> is converted to markdown, outer <em> range becomes invalid
        // This is expected behavior - user should run fix multiple times for nested tags
        assert_eq!(fixed, "This has <em>text with **nested** tags</em> here.");
    }

    #[test]
    fn test_md033_fix_skips_tags_with_attributes() {
        // Tags with attributes should NOT be fixed at all - leave as-is
        // User may want to keep the attributes (e.g., class="highlight" for styling)
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <em class=\"highlight\">emphasized</em> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Content should remain unchanged - we don't know if attributes matter
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_disabled_no_changes() {
        // When fix is disabled, original content should be returned
        let rule = MD033NoInlineHtml::default(); // fix is false by default
        let content = "This has <em>emphasized text</em> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Should return original content when fix is disabled");
    }

    #[test]
    fn test_md033_fix_capability_enabled() {
        let rule = MD033NoInlineHtml::with_fix(true);
        assert_eq!(rule.fix_capability(), crate::rule::FixCapability::FullyFixable);
    }

    #[test]
    fn test_md033_fix_multiple_tags() {
        // Test fixing multiple HTML tags in one document
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Here is <em>italic</em> and <strong>bold</strong> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Here is *italic* and **bold** text.");
    }

    #[test]
    fn test_md033_fix_uppercase_tags() {
        // HTML tags are case-insensitive
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <EM>emphasized</EM> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This has *emphasized* text.");
    }

    #[test]
    fn test_md033_fix_unsafe_tags_not_modified() {
        // Tags without safe markdown equivalents should NOT be modified
        // Only safe fixable tags (em, i, strong, b, code, br, hr) get converted
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This has <div>a div</div> content.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // <div> is not a safe fixable tag, so content should be unchanged
        assert_eq!(fixed, "This has <div>a div</div> content.");
    }

    #[test]
    fn test_md033_fix_img_tag_converted() {
        // <img> tags with simple src/alt attributes are converted to markdown images
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Image: <img src=\"photo.jpg\" alt=\"My Photo\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // <img> is converted to ![alt](src) format
        assert_eq!(fixed, "Image: ![My Photo](photo.jpg)");
    }

    #[test]
    fn test_md033_fix_img_tag_with_extra_attrs_not_converted() {
        // <img> tags with width/height/style attributes are NOT converted
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Image: <img src=\"photo.jpg\" alt=\"My Photo\" width=\"100\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Has width attribute - not safe to convert
        assert_eq!(fixed, "Image: <img src=\"photo.jpg\" alt=\"My Photo\" width=\"100\">");
    }

    #[test]
    fn test_md033_fix_relaxed_a_with_target_is_converted() {
        let rule = relaxed_fix_rule();
        let content = "Link: <a href=\"https://example.com\" target=\"_blank\">Example</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Link: [Example](https://example.com)");
    }

    #[test]
    fn test_md033_fix_relaxed_img_with_width_is_converted() {
        let rule = relaxed_fix_rule();
        let content = "Image: <img src=\"photo.jpg\" alt=\"My Photo\" width=\"100\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Image: ![My Photo](photo.jpg)");
    }

    #[test]
    fn test_md033_fix_relaxed_rejects_unknown_extra_attributes() {
        let rule = relaxed_fix_rule();
        let content = "Image: <img src=\"photo.jpg\" alt=\"My Photo\" aria-label=\"hero\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Unknown attributes should not be dropped by default");
    }

    #[test]
    fn test_md033_fix_relaxed_still_blocks_unsafe_schemes() {
        let rule = relaxed_fix_rule();
        let content = "Link: <a href=\"javascript:alert(1)\" target=\"_blank\">Example</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Unsafe URL schemes must never be converted");
    }

    #[test]
    fn test_md033_fix_relaxed_wrapper_strip_requires_second_pass_for_nested_html() {
        let rule = relaxed_fix_rule();
        let content = "<p align=\"center\">\n  <img src=\"logo.svg\" alt=\"Logo\" width=\"120\" />\n</p>";
        let ctx1 = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed_once = rule.fix(&ctx1).unwrap();
        assert!(
            fixed_once.contains("<p"),
            "First pass should keep wrapper when inner HTML is still present: {fixed_once}"
        );
        assert!(
            fixed_once.contains("![Logo](logo.svg)"),
            "Inner image should be converted on first pass: {fixed_once}"
        );

        let ctx2 = LintContext::new(&fixed_once, crate::config::MarkdownFlavor::Standard, None);
        let fixed_twice = rule.fix(&ctx2).unwrap();
        assert!(
            !fixed_twice.contains("<p"),
            "Second pass should strip configured wrapper: {fixed_twice}"
        );
        assert!(fixed_twice.contains("![Logo](logo.svg)"));
    }

    #[test]
    fn test_md033_fix_relaxed_multiple_droppable_attrs() {
        let rule = relaxed_fix_rule();
        let content = "<a href=\"https://example.com\" target=\"_blank\" rel=\"noopener\" class=\"btn\">Click</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "[Click](https://example.com)");
    }

    #[test]
    fn test_md033_fix_relaxed_img_multiple_droppable_attrs() {
        let rule = relaxed_fix_rule();
        let content = "<img src=\"logo.png\" alt=\"Logo\" width=\"120\" height=\"40\" style=\"border:none\" />";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "![Logo](logo.png)");
    }

    #[test]
    fn test_md033_fix_relaxed_event_handler_never_dropped() {
        let rule = relaxed_fix_rule();
        let content = "<a href=\"https://example.com\" onclick=\"track()\">Link</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Event handler attributes must block conversion");
    }

    #[test]
    fn test_md033_fix_relaxed_event_handler_even_with_custom_config() {
        // Even if someone adds on* to drop-attributes, event handlers must be rejected
        let config = MD033Config {
            fix: true,
            fix_mode: MD033FixMode::Relaxed,
            drop_attributes: vec!["on*".to_string(), "target".to_string()],
            ..MD033Config::default()
        };
        let rule = MD033NoInlineHtml::from_config_struct(config);
        let content = "<a href=\"https://example.com\" onclick=\"alert(1)\">Link</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "on* event handlers must never be dropped");
    }

    #[test]
    fn test_md033_fix_relaxed_custom_drop_attributes() {
        let config = MD033Config {
            fix: true,
            fix_mode: MD033FixMode::Relaxed,
            drop_attributes: vec!["loading".to_string()],
            ..MD033Config::default()
        };
        let rule = MD033NoInlineHtml::from_config_struct(config);
        // "loading" is in the custom list, "width" is NOT
        let content = "<img src=\"x.jpg\" alt=\"\" loading=\"lazy\">";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "![](x.jpg)", "Custom drop-attributes should be respected");

        let content2 = "<img src=\"x.jpg\" alt=\"\" width=\"100\">";
        let ctx2 = LintContext::new(content2, crate::config::MarkdownFlavor::Standard, None);
        let fixed2 = rule.fix(&ctx2).unwrap();
        assert_eq!(
            fixed2, content2,
            "Attributes not in custom list should block conversion"
        );
    }

    #[test]
    fn test_md033_fix_relaxed_custom_strip_wrapper() {
        let config = MD033Config {
            fix: true,
            fix_mode: MD033FixMode::Relaxed,
            strip_wrapper_elements: vec!["div".to_string()],
            ..MD033Config::default()
        };
        let rule = MD033NoInlineHtml::from_config_struct(config);
        let content = "<div>Some text content</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Some text content");
    }

    #[test]
    fn test_md033_fix_relaxed_wrapper_with_plain_text() {
        let rule = relaxed_fix_rule();
        let content = "<p align=\"center\">Just some text</p>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Just some text");
    }

    #[test]
    fn test_md033_fix_relaxed_data_attr_with_wildcard() {
        let config = MD033Config {
            fix: true,
            fix_mode: MD033FixMode::Relaxed,
            drop_attributes: vec!["data-*".to_string(), "target".to_string()],
            ..MD033Config::default()
        };
        let rule = MD033NoInlineHtml::from_config_struct(config);
        let content = "<a href=\"https://example.com\" data-tracking=\"abc\" target=\"_blank\">Link</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "[Link](https://example.com)");
    }

    #[test]
    fn test_md033_fix_relaxed_mixed_droppable_and_blocking_attrs() {
        let rule = relaxed_fix_rule();
        // "target" is droppable, "aria-label" is not in the default list
        let content = "<a href=\"https://example.com\" target=\"_blank\" aria-label=\"nav\">Link</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Non-droppable attribute should block conversion");
    }

    #[test]
    fn test_md033_fix_relaxed_badge_pattern() {
        // Common GitHub README badge pattern
        let rule = relaxed_fix_rule();
        let content = "<a href=\"https://crates.io/crates/rumdl\" target=\"_blank\"><img src=\"https://img.shields.io/crates/v/rumdl.svg\" alt=\"Crate\" width=\"120\" /></a>";
        let ctx1 = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed_once = rule.fix(&ctx1).unwrap();
        // First pass should convert the inner <img>
        assert!(
            fixed_once.contains("![Crate](https://img.shields.io/crates/v/rumdl.svg)"),
            "Inner img should be converted: {fixed_once}"
        );

        // Second pass converts the <a> wrapper
        let ctx2 = LintContext::new(&fixed_once, crate::config::MarkdownFlavor::Standard, None);
        let fixed_twice = rule.fix(&ctx2).unwrap();
        assert!(
            fixed_twice
                .contains("[![Crate](https://img.shields.io/crates/v/rumdl.svg)](https://crates.io/crates/rumdl)"),
            "Badge should produce nested markdown image link: {fixed_twice}"
        );
    }

    #[test]
    fn test_md033_fix_relaxed_conservative_mode_unchanged() {
        // Verify conservative mode (default) is unaffected by the relaxed logic
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<a href=\"https://example.com\" target=\"_blank\">Link</a>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, content, "Conservative mode should not drop target attribute");
    }

    #[test]
    fn test_md033_fix_relaxed_img_inside_pre_not_converted() {
        // <img> inside <pre> must NOT be converted, even in relaxed mode
        let rule = relaxed_fix_rule();
        let content = "<pre>\n  <img src=\"diagram.png\" alt=\"d\" width=\"100\" />\n</pre>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(fixed.contains("<img"), "img inside pre must not be converted: {fixed}");
    }

    #[test]
    fn test_md033_fix_relaxed_wrapper_nested_inside_div_not_stripped() {
        // <p> nested inside <div> should not be stripped
        let rule = relaxed_fix_rule();
        let content = "<div><p>text</p></div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("<p>text</p>") || fixed.contains("<p>"),
            "Nested <p> inside <div> should not be stripped: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_relaxed_img_inside_nested_wrapper_not_converted() {
        // <img> inside <div><p>...</p></div> must NOT be converted because the
        // <p> wrapper can't be stripped (it's nested), so the markdown would be
        // stuck inside an HTML block where it won't render.
        let rule = relaxed_fix_rule();
        let content = "<div><p><img src=\"x.jpg\" alt=\"pic\" width=\"100\" /></p></div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert!(
            fixed.contains("<img"),
            "img inside nested wrapper must not be converted: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_mixed_safe_tags() {
        // All tags are now safe fixable (em, img, strong)
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<em>italic</em> and <img src=\"x.jpg\"> and <strong>bold</strong>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // All are converted
        assert_eq!(fixed, "*italic* and ![](x.jpg) and **bold**");
    }

    #[test]
    fn test_md033_fix_multiple_tags_same_line() {
        // Multiple tags on the same line should all be fixed correctly
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "Regular text <i>italic</i> and <b>bold</b> here.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "Regular text *italic* and **bold** here.");
    }

    #[test]
    fn test_md033_fix_multiple_em_tags_same_line() {
        // Multiple em/strong tags on the same line
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<em>first</em> and <strong>second</strong> and <code>third</code>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "*first* and **second** and `third`");
    }

    #[test]
    fn test_md033_fix_skips_tags_inside_pre() {
        // Tags inside <pre> blocks should NOT be fixed (would break structure)
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<pre><code><em>VALUE</em></code></pre>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // The <em> inside <pre><code> should NOT be converted
        // Only the outer structure might be changed
        assert!(
            !fixed.contains("*VALUE*"),
            "Tags inside <pre> should not be converted to markdown. Got: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_skips_tags_inside_div() {
        // Tags inside HTML block elements should not be fixed
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<div>\n<em>emphasized</em>\n</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // The <em> inside <div> should not be converted to *emphasized*
        assert!(
            !fixed.contains("*emphasized*"),
            "Tags inside HTML blocks should not be converted. Got: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_outside_html_block() {
        // Tags outside HTML blocks should still be fixed
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<div>\ncontent\n</div>\n\nOutside <em>emphasized</em> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // The <em> outside the div should be converted
        assert!(
            fixed.contains("*emphasized*"),
            "Tags outside HTML blocks should be converted. Got: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_with_id_attribute() {
        // Tags with id attributes should not be fixed (id might be used for anchors)
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "See <em id=\"important\">this note</em> for details.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should remain unchanged - id attribute matters for linking
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_with_style_attribute() {
        // Tags with style attributes should not be fixed
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This is <strong style=\"color: red\">important</strong> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should remain unchanged - style attribute provides formatting
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_mixed_with_and_without_attributes() {
        // Mix of tags with and without attributes
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<em>normal</em> and <em class=\"special\">styled</em> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Only the tag without attributes should be fixed
        assert_eq!(fixed, "*normal* and <em class=\"special\">styled</em> text.");
    }

    #[test]
    fn test_md033_quick_fix_tag_with_attributes_no_fix() {
        // Quick fix should not be provided for tags with attributes
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<em class=\"test\">emphasized</em>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should find one HTML tag");
        // No fix should be provided for tags with attributes
        assert!(
            result[0].fix.is_none(),
            "Should NOT have a fix for tags with attributes"
        );
    }

    #[test]
    fn test_md033_fix_skips_html_entities() {
        // Tags containing HTML entities should NOT be fixed
        // HTML entities need HTML context to render; markdown won't process them
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<code>&vert;</code>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should remain unchanged - converting would break rendering
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_skips_multiple_html_entities() {
        // Multiple HTML entities should also be skipped
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<code>&lt;T&gt;</code>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should remain unchanged
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_allows_ampersand_without_entity() {
        // Content with & but no semicolon should still be fixed
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<code>a & b</code>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should be converted since & is not part of an entity
        assert_eq!(fixed, "`a & b`");
    }

    #[test]
    fn test_md033_fix_em_with_entities_skipped() {
        // <em> with entities should also be skipped
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<em>&nbsp;text</em>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should remain unchanged
        assert_eq!(fixed, content);
    }

    #[test]
    fn test_md033_fix_skips_nested_em_in_code() {
        // Tags nested inside other HTML elements should NOT be fixed
        // e.g., <code><em>n</em></code> - the <em> should not be converted
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "<code><em>n</em></code>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // The inner <em> should NOT be converted to *n* because it's nested
        // The whole structure should be left as-is (or outer code converted, but not inner)
        assert!(
            !fixed.contains("*n*"),
            "Nested <em> should not be converted to markdown. Got: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_skips_nested_in_table() {
        // Tags nested in HTML structures in tables should not be fixed
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "| <code>><em>n</em></code> | description |";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        // Should not convert nested <em> to *n*
        assert!(
            !fixed.contains("*n*"),
            "Nested tags in table should not be converted. Got: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_standalone_em_still_converted() {
        // Standalone (non-nested) <em> should still be converted
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = "This is <em>emphasized</em> text.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(fixed, "This is *emphasized* text.");
    }

    // ==========================================================================
    // Obsidian Templater Plugin Syntax Tests
    //
    // Templater is a popular Obsidian plugin that uses `<% ... %>` syntax for
    // template interpolation. The `<%` pattern is NOT captured by the HTML tag
    // parser because `%` is not a valid HTML tag name character (tags must start
    // with a letter). This behavior is documented here with comprehensive tests.
    //
    // Reference: https://silentvoid13.github.io/Templater/
    // ==========================================================================

    #[test]
    fn test_md033_templater_basic_interpolation_not_flagged() {
        // Basic Templater interpolation: <% expr %>
        // Should NOT be flagged because `%` is not a valid HTML tag character
        let rule = MD033NoInlineHtml::default();
        let content = "Today is <% tp.date.now() %> which is nice.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater basic interpolation should not be flagged as HTML. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_file_functions_not_flagged() {
        // Templater file functions: <% tp.file.* %>
        let rule = MD033NoInlineHtml::default();
        let content = "File: <% tp.file.title %>\nCreated: <% tp.file.creation_date() %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater file functions should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_with_arguments_not_flagged() {
        // Templater with function arguments
        let rule = MD033NoInlineHtml::default();
        let content = r#"Date: <% tp.date.now("YYYY-MM-DD") %>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater with arguments should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_javascript_execution_not_flagged() {
        // Templater JavaScript execution block: <%* code %>
        let rule = MD033NoInlineHtml::default();
        let content = "<%* const today = tp.date.now(); tR += today; %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater JS execution block should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_dynamic_execution_not_flagged() {
        // Templater dynamic/preview execution: <%+ expr %>
        let rule = MD033NoInlineHtml::default();
        let content = "Dynamic: <%+ tp.date.now() %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater dynamic execution should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_whitespace_trim_all_not_flagged() {
        // Templater whitespace control - trim all: <%_ expr _%>
        let rule = MD033NoInlineHtml::default();
        let content = "<%_ tp.date.now() _%>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater trim-all whitespace should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_whitespace_trim_newline_not_flagged() {
        // Templater whitespace control - trim newline: <%- expr -%>
        let rule = MD033NoInlineHtml::default();
        let content = "<%- tp.date.now() -%>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater trim-newline should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_combined_modifiers_not_flagged() {
        // Templater combined whitespace and execution modifiers
        let rule = MD033NoInlineHtml::default();
        let contents = [
            "<%-* const x = 1; -%>",  // trim + JS execution
            "<%_+ tp.date.now() _%>", // trim-all + dynamic
            "<%- tp.file.title -%>",  // trim-newline only
            "<%_ tp.file.title _%>",  // trim-all only
        ];
        for content in contents {
            let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
            let result = rule.check(&ctx).unwrap();
            assert!(
                result.is_empty(),
                "Templater combined modifiers should not be flagged: {content}. Got: {result:?}"
            );
        }
    }

    #[test]
    fn test_md033_templater_multiline_block_not_flagged() {
        // Multi-line Templater JavaScript block
        let rule = MD033NoInlineHtml::default();
        let content = r#"<%*
const x = 1;
const y = 2;
tR += x + y;
%>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater multi-line block should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_with_angle_brackets_in_condition_not_flagged() {
        // Templater with angle brackets in JavaScript condition
        // This is a key edge case: `<` inside Templater should not trigger HTML detection
        let rule = MD033NoInlineHtml::default();
        let content = "<%* if (x < 5) { tR += 'small'; } %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater with angle brackets in conditions should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_mixed_with_html_only_html_flagged() {
        // Templater syntax mixed with actual HTML - only HTML should be flagged
        let rule = MD033NoInlineHtml::default();
        let content = "<% tp.date.now() %> is today's date. <div>This is HTML</div>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert_eq!(result.len(), 1, "Should only flag the HTML div tag");
        assert!(
            result[0].message.contains("<div>"),
            "Should flag <div>, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_md033_templater_in_heading_not_flagged() {
        // Templater in markdown heading
        let rule = MD033NoInlineHtml::default();
        let content = "# <% tp.file.title %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater in heading should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_multiple_on_same_line_not_flagged() {
        // Multiple Templater blocks on same line
        let rule = MD033NoInlineHtml::default();
        let content = "From <% tp.date.now() %> to <% tp.date.tomorrow() %> we have meetings.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Multiple Templater blocks should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_in_code_block_not_flagged() {
        // Templater syntax in code blocks should not be flagged (code blocks are skipped)
        let rule = MD033NoInlineHtml::default();
        let content = "```\n<% tp.date.now() %>\n```";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater in code block should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_in_inline_code_not_flagged() {
        // Templater syntax in inline code span should not be flagged
        let rule = MD033NoInlineHtml::default();
        let content = "Use `<% tp.date.now() %>` for current date.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater in inline code should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_also_works_in_standard_flavor() {
        // Templater syntax should also not be flagged in Standard flavor
        // because the HTML parser doesn't recognize `<%` as a valid tag
        let rule = MD033NoInlineHtml::default();
        let content = "<% tp.date.now() %> works everywhere.";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater should not be flagged even in Standard flavor. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_empty_tag_not_flagged() {
        // Empty Templater tags
        let rule = MD033NoInlineHtml::default();
        let content = "<%>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Empty Templater-like tag should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_unclosed_not_flagged() {
        // Unclosed Templater tags - these are template errors, not HTML
        let rule = MD033NoInlineHtml::default();
        let content = "<% tp.date.now() without closing tag";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Unclosed Templater should not be flagged as HTML. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_with_newlines_inside_not_flagged() {
        // Templater with newlines inside the expression
        let rule = MD033NoInlineHtml::default();
        let content = r#"<% tp.date.now("YYYY") +
"-" +
tp.date.now("MM") %>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Templater with internal newlines should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_erb_style_tags_not_flagged() {
        // ERB/EJS style tags (similar to Templater) are also not HTML
        // This documents the general principle that `<%` is not valid HTML
        let rule = MD033NoInlineHtml::default();
        let content = "<%= variable %> and <% code %> and <%# comment %>";
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "ERB/EJS style tags should not be flagged as HTML. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_templater_complex_expression_not_flagged() {
        // Complex Templater expression with multiple function calls
        let rule = MD033NoInlineHtml::default();
        let content = r#"<%*
const file = tp.file.title;
const date = tp.date.now("YYYY-MM-DD");
const folder = tp.file.folder();
tR += `# ${file}\n\nCreated: ${date}\nIn: ${folder}`;
%>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, None);
        let result = rule.check(&ctx).unwrap();
        assert!(
            result.is_empty(),
            "Complex Templater expression should not be flagged. Got: {result:?}"
        );
    }

    #[test]
    fn test_md033_percent_sign_variations_not_flagged() {
        // Various patterns starting with <% that should all be safe
        let rule = MD033NoInlineHtml::default();
        let patterns = [
            "<%=",  // ERB output
            "<%#",  // ERB comment
            "<%%",  // Double percent
            "<%!",  // Some template engines
            "<%@",  // JSP directive
            "<%--", // JSP comment
        ];
        for pattern in patterns {
            let content = format!("{pattern} content %>");
            let ctx = LintContext::new(&content, crate::config::MarkdownFlavor::Standard, None);
            let result = rule.check(&ctx).unwrap();
            assert!(
                result.is_empty(),
                "Pattern {pattern} should not be flagged. Got: {result:?}"
            );
        }
    }

    // ───── Bug #3: Bracket escaping in image-inside-link conversion ─────
    //
    // When <a> wraps already-converted markdown image text, the bracket escaping
    // must be skipped to produce valid [![alt](url)](href) instead of !\[\](url)

    #[test]
    fn test_md033_fix_a_wrapping_markdown_image_no_escaped_brackets() {
        // When <a> wraps a markdown image (from a prior fix iteration),
        // the result should be [![](url)](href) — no escaped brackets
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = r#"<a href="https://example.com">![](https://example.com/image.png)</a>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "[![](https://example.com/image.png)](https://example.com)",);
        assert!(!fixed.contains(r"\["), "Must not escape brackets: {fixed}");
        assert!(!fixed.contains(r"\]"), "Must not escape brackets: {fixed}");
    }

    #[test]
    fn test_md033_fix_a_wrapping_markdown_image_with_alt() {
        // <a> wrapping ![alt](url) preserves alt text in linked image
        let rule = MD033NoInlineHtml::with_fix(true);
        let content =
            r#"<a href="https://github.com/repo">![Contributors](https://contrib.rocks/image?repo=org/repo)</a>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(
            fixed,
            "[![Contributors](https://contrib.rocks/image?repo=org/repo)](https://github.com/repo)"
        );
    }

    #[test]
    fn test_md033_fix_img_without_alt_produces_empty_alt() {
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = r#"<img src="photo.jpg" />"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert_eq!(fixed, "![](photo.jpg)");
    }

    #[test]
    fn test_md033_fix_a_with_plain_text_still_escapes_brackets() {
        // Plain text brackets inside <a> SHOULD be escaped
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = r#"<a href="https://example.com">text with [brackets]</a>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        assert!(
            fixed.contains(r"\[brackets\]"),
            "Plain text brackets should be escaped: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_a_with_image_plus_extra_text_escapes_brackets() {
        // Mixed content: image followed by bracketed text — brackets must be escaped
        // The image detection must NOT match partial content
        let rule = MD033NoInlineHtml::with_fix(true);
        let content = r#"<a href="/link">![](img.png) see [docs]</a>"#;
        let ctx = LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let fixed = rule.fix(&ctx).unwrap();

        // "see [docs]" brackets should be escaped since inner content is mixed
        assert!(
            fixed.contains(r"\[docs\]"),
            "Brackets in mixed image+text content should be escaped: {fixed}"
        );
    }

    #[test]
    fn test_md033_fix_img_in_a_end_to_end() {
        // End-to-end: verify that iterative fixing of <a><img></a>
        // produces the correct final result through the fix coordinator
        use crate::config::Config;
        use crate::fix_coordinator::FixCoordinator;

        let rule = MD033NoInlineHtml::with_fix(true);
        let rules: Vec<Box<dyn crate::rule::Rule>> = vec![Box::new(rule)];

        let mut content =
            r#"<a href="https://github.com/org/repo"><img src="https://contrib.rocks/image?repo=org/repo" /></a>"#
                .to_string();
        let config = Config::default();
        let coordinator = FixCoordinator::new();

        let result = coordinator
            .apply_fixes_iterative(&rules, &[], &mut content, &config, 10, None)
            .unwrap();

        assert_eq!(
            content, "[![](https://contrib.rocks/image?repo=org/repo)](https://github.com/org/repo)",
            "End-to-end: <a><img></a> should become valid linked image"
        );
        assert!(result.converged);
        assert!(!content.contains(r"\["), "No escaped brackets: {content}");
    }

    #[test]
    fn test_md033_fix_img_in_a_with_alt_end_to_end() {
        use crate::config::Config;
        use crate::fix_coordinator::FixCoordinator;

        let rule = MD033NoInlineHtml::with_fix(true);
        let rules: Vec<Box<dyn crate::rule::Rule>> = vec![Box::new(rule)];

        let mut content =
            r#"<a href="https://github.com/org/repo"><img src="https://contrib.rocks/image" alt="Contributors" /></a>"#
                .to_string();
        let config = Config::default();
        let coordinator = FixCoordinator::new();

        let result = coordinator
            .apply_fixes_iterative(&rules, &[], &mut content, &config, 10, None)
            .unwrap();

        assert_eq!(
            content,
            "[![Contributors](https://contrib.rocks/image)](https://github.com/org/repo)",
        );
        assert!(result.converged);
    }
}