guidebook 0.1.71

HonKit/GitBook compatible static book generator
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
use pulldown_cmark::{html, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use std::path::Path;

/// Table of Contents item
#[derive(Debug, Clone)]
pub struct TocItem {
    pub level: u8,
    pub text: String,
    pub id: String,
}

/// Extract headings from markdown content for TOC generation
pub fn extract_headings(content: &str) -> Vec<TocItem> {
    let content = fix_fullwidth_heading_spaces(content);

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_HEADING_ATTRIBUTES);

    let parser = Parser::new_ext(&content, options);

    let mut headings = Vec::new();
    let mut in_heading: Option<HeadingLevel> = None;
    let mut heading_text = String::new();
    let mut custom_heading_id: Option<String> = None;
    // Must mirror the slug assignment in render_markdown_internal exactly
    // (dedup counters consume slugs for ALL heading levels, not just h2-h4)
    let mut used_slugs: std::collections::HashMap<String, usize> = std::collections::HashMap::new();

    for event in parser {
        match &event {
            Event::Start(Tag::Heading { level, id, .. }) => {
                in_heading = Some(*level);
                heading_text.clear();
                custom_heading_id = id.as_ref().map(|s| s.to_string());
            }
            Event::Text(text) if in_heading.is_some() => {
                heading_text.push_str(text);
            }
            Event::End(TagEnd::Heading(level)) if in_heading.is_some() => {
                let level_num = heading_level_to_num(*level);
                let id = custom_heading_id
                    .take()
                    .unwrap_or_else(|| dedupe_slug(slugify(&heading_text), &mut used_slugs));
                // Only include h2, h3, h4 in TOC (skip h1 which is page title)
                if (2..=4).contains(&level_num) {
                    headings.push(TocItem {
                        level: level_num,
                        text: heading_text.clone(),
                        id,
                    });
                }
                in_heading = None;
            }
            _ => {}
        }
    }

    headings
}

/// Render markdown content to HTML with Mermaid support
/// current_path: the path of the current markdown file (e.g., "Customer/AssetStatus/PortfolioTop.md")
/// hardbreaks: when true, treat single newlines as hard breaks (<br>)
pub fn render_markdown_with_path(
    content: &str,
    current_path: Option<&str>,
    hardbreaks: bool,
) -> String {
    // Normalize CRLF/CR to LF for consistent line handling
    let content = content.replace("\r\n", "\n").replace("\r", "\n");
    let html = render_markdown_internal(&content, hardbreaks);

    // If we have a current path, convert relative links to absolute
    if let Some(path) = current_path {
        convert_relative_links_to_absolute(&html, path)
    } else {
        html
    }
}

/// Render markdown content to HTML (backward compatible)
pub fn render_markdown(content: &str) -> String {
    // Normalize CRLF/CR to LF for consistent line handling
    let content = content.replace("\r\n", "\n").replace("\r", "\n");
    render_markdown_internal(&content, false)
}

/// Render markdown content to HTML with hardbreaks option
pub fn render_markdown_with_hardbreaks(content: &str, hardbreaks: bool) -> String {
    // Normalize CRLF/CR to LF for consistent line handling
    let content = content.replace("\r\n", "\n").replace("\r", "\n");
    render_markdown_internal(&content, hardbreaks)
}

fn render_markdown_internal(content: &str, hardbreaks: bool) -> String {
    // Strip all UTF-8 BOM characters (fixes reference link parsing issues)
    // BOM can appear at start of file or in concatenated content from @import
    let content = content.replace('\u{FEFF}', "");
    // Preprocess: fix full-width spaces after heading markers
    let content = fix_fullwidth_heading_spaces(&content);
    // Preprocess: fix image paths with spaces
    let content = fix_image_paths_with_spaces(&content);
    // Preprocess: fix multi-line footnotes without proper indentation
    let content = fix_multiline_footnotes(&content);
    // Preprocess: fix malformed table separator rows
    let content = fix_table_separator_columns(&content);

    // Convert footnote definitions to inline format (preserve original position)
    let content = convert_footnote_definitions_inline(&content, hardbreaks);

    // Convert footnote references [^n] to placeholders BEFORE markdown parsing
    // This prevents [A][^1] from being interpreted as a markdown link reference
    let content = convert_footnote_references_to_placeholder(&content);

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    // Don't use pulldown-cmark's footnote processing - we handle it ourselves
    // options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_HEADING_ATTRIBUTES);

    let parser = Parser::new_ext(&content, options);

    // Process events to handle mermaid code blocks and heading IDs
    let mut in_mermaid = false;
    let mut mermaid_content = String::new();
    let mut in_heading: Option<HeadingLevel> = None;
    let mut heading_text = String::new();
    let mut custom_heading_id: Option<String> = None; // Store custom ID from {#id} syntax
                                                      // Track used slugs so duplicate headings get unique ids (-1, -2, ...)
    let mut used_slugs: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    let mut events: Vec<Event> = Vec::new();

    for event in parser {
        match &event {
            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(lang))) => {
                let lang_str = lang.as_ref();
                if lang_str == "mermaid" || lang_str.starts_with("mermaid") {
                    in_mermaid = true;
                    mermaid_content.clear();
                    continue;
                }
            }
            Event::End(TagEnd::CodeBlock) if in_mermaid => {
                // Output mermaid div instead of code block
                let mermaid_html = format!(
                    r#"<div class="mermaid">{}</div>"#,
                    html_escape(&mermaid_content)
                );
                events.push(Event::Html(mermaid_html.into()));
                in_mermaid = false;
                continue;
            }
            Event::Text(text) if in_mermaid => {
                mermaid_content.push_str(text);
                continue;
            }
            // Track heading start and capture custom ID from {#id} syntax
            Event::Start(Tag::Heading { level, id, .. }) => {
                in_heading = Some(*level);
                heading_text.clear();
                // Capture custom ID if provided via {#custom-id} syntax
                custom_heading_id = id.as_ref().map(|s| s.to_string());
                events.push(event.clone());
                continue;
            }
            // Capture heading text
            Event::Text(text) if in_heading.is_some() => {
                heading_text.push_str(text);
                events.push(event.clone());
                continue;
            }
            // End of heading: inject ID
            Event::End(TagEnd::Heading(level)) if in_heading.is_some() => {
                // Use custom ID if provided, otherwise generate from heading text
                // (deduplicated: same text yields id, id-1, id-2, ...)
                let id = custom_heading_id
                    .take()
                    .unwrap_or_else(|| dedupe_slug(slugify(&heading_text), &mut used_slugs));
                let level_num = heading_level_to_num(*level);
                // Pop the heading content and rebuild with ID
                let mut heading_events = Vec::new();
                while let Some(ev) = events.pop() {
                    if matches!(ev, Event::Start(Tag::Heading { .. })) {
                        break;
                    }
                    heading_events.push(ev);
                }
                heading_events.reverse();

                // Push heading with ID as raw HTML
                let open_tag = format!(r#"<h{} id="{}">"#, level_num, id);
                events.push(Event::Html(open_tag.into()));
                events.extend(heading_events);
                events.push(Event::Html(format!("</h{}>", level_num).into()));

                in_heading = None;
                continue;
            }
            // Convert soft breaks to hard breaks when hardbreaks option is enabled
            Event::SoftBreak if hardbreaks => {
                events.push(Event::HardBreak);
                continue;
            }
            _ => {}
        }
        events.push(event);
    }

    let mut html_output = String::new();
    html::push_html(&mut html_output, events.into_iter());

    // Fix relative links: convert .md to .html
    html_output = fix_relative_links(&html_output);

    // Note: Root-relative links (starting with /) are handled in convert_relative_links_to_absolute()
    // which has access to the current file path and can calculate the correct relative path

    // Auto-link URLs that are not already linked
    html_output = autolink_urls(&html_output);

    // Add target="_blank" to external links (Markdown-style links like [text](https://...))
    html_output = add_target_blank_to_external_links(&html_output);

    // Convert any remaining markdown images inside HTML blocks to <img> tags
    html_output = convert_remaining_markdown_images(&html_output);

    // Convert footnote placeholders to HTML
    html_output = convert_footnote_placeholders_to_html(&html_output);

    html_output
}

fn heading_level_to_num(level: HeadingLevel) -> u8 {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

/// Generate a URL-safe slug from text (matching github-slugger / HonKit behavior)
fn slugify(text: &str) -> String {
    text.to_lowercase()
        .chars()
        .filter_map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                Some(c)
            } else if c.is_whitespace() {
                Some('-')
            } else if c > '\x7F' {
                // Keep non-ASCII characters (Japanese, etc.)
                Some(c)
            } else {
                // Remove other special characters (/, ., etc.) to match github-slugger
                None
            }
        })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

/// Deduplicate a slug against previously used ones (github-slugger behavior:
/// "foo", "foo-1", "foo-2", ...). Skips suffixes that collide with slugs
/// that literally occurred earlier.
fn dedupe_slug(slug: String, used: &mut std::collections::HashMap<String, usize>) -> String {
    if !used.contains_key(&slug) {
        used.insert(slug.clone(), 0);
        return slug;
    }

    let mut n = used[&slug] + 1;
    let mut candidate = format!("{}-{}", slug, n);
    while used.contains_key(&candidate) {
        n += 1;
        candidate = format!("{}-{}", slug, n);
    }
    used.insert(slug, n);
    used.insert(candidate.clone(), 0);
    candidate
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Collect reference link definitions from markdown content
/// Returns a map of label -> url
fn collect_reference_links(content: &str) -> std::collections::HashMap<String, String> {
    let mut links = std::collections::HashMap::new();

    for line in content.lines() {
        let trimmed = line.trim();
        // Match [label]: url pattern (but not footnote definitions [^n]:)
        if trimmed.starts_with('[') && !trimmed.starts_with("[^") {
            if let Some(bracket_end) = trimmed.find("]:") {
                let label = &trimmed[1..bracket_end];
                let url = trimmed[bracket_end + 2..].trim();
                if !label.is_empty() && !url.is_empty() {
                    // Remove optional angle brackets around URL
                    let url = url.trim_start_matches('<').trim_end_matches('>');
                    links.insert(label.to_lowercase(), url.to_string());
                }
            }
        }
    }

    links
}

/// Resolve reference links in text (e.g., [A] -> <a href="url">A</a>)
/// Handles both shortcut style [label] and full style [text][ref]
fn resolve_reference_links(
    text: &str,
    reference_links: &std::collections::HashMap<String, String>,
) -> String {
    let mut result = String::new();
    let mut chars = text.char_indices().peekable();

    while let Some((i, c)) = chars.next() {
        if c == '[' {
            // Check for [label] or [text][ref] pattern
            let rest = &text[i + c.len_utf8()..];
            if let Some(end_byte) = rest.find(']') {
                let first_label = &rest[..end_byte];
                let after_bracket = &rest[end_byte + 1..];

                // Check for full reference link [text][ref]
                if let Some(after_second_open) = after_bracket.strip_prefix('[') {
                    // Find the second closing bracket
                    if let Some(second_end_byte) = after_second_open.find(']') {
                        let ref_label = &after_second_open[..second_end_byte];
                        // Look up the reference (use ref_label, or first_label if ref is empty)
                        let lookup_key = if ref_label.is_empty() {
                            first_label.to_lowercase()
                        } else {
                            ref_label.to_lowercase()
                        };
                        if let Some(url) = reference_links.get(&lookup_key) {
                            result.push_str(&format!("<a href=\"{}\">{}</a>", url, first_label));
                            // Skip past [text][ref] - count characters (not bytes) to skip
                            // Pattern: [text][ref] - we need to skip: text + ] + [ + ref + ]
                            let chars_to_skip =
                                first_label.chars().count() + 1 + 1 + ref_label.chars().count() + 1;
                            for _ in 0..chars_to_skip {
                                chars.next();
                            }
                            continue;
                        }
                    }
                }

                // Check for inline link [text](url) - skip these, pulldown-cmark handles them
                if after_bracket.starts_with('(') {
                    result.push(c);
                    continue;
                }

                // This is a shortcut reference link [label]
                if let Some(url) = reference_links.get(&first_label.to_lowercase()) {
                    result.push_str(&format!("<a href=\"{}\">{}</a>", url, first_label));
                    // Skip past the [label] - count characters to skip: label + ]
                    let chars_to_skip = first_label.chars().count() + 1;
                    for _ in 0..chars_to_skip {
                        chars.next();
                    }
                    continue;
                }
            }
        }
        result.push(c);
    }

    result
}

/// Convert footnote definitions in-place to HTML (preserve original position)
fn convert_footnote_definitions_inline(content: &str, hardbreaks: bool) -> String {
    // Collect reference link definitions for resolving within footnotes
    let reference_links = collect_reference_links(content);

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

    while i < lines.len() {
        let line = lines[i];
        // Check if this line starts a footnote definition [^n]:
        if let Some(captures) = parse_footnote_def_start(line) {
            let (number, first_line_content) = captures;
            // Trim trailing whitespace from first line (for hardbreaks consistency)
            let first_line_content = first_line_content.trim_end();

            // Resolve reference links in the first line content
            let first_line_resolved = resolve_reference_links(first_line_content, &reference_links);

            let mut continuation_lines: Vec<String> = Vec::new();

            // Collect continuation lines (indented or list items until next footnote/heading/blank)
            i += 1;
            while i < lines.len() {
                let next_line = lines[i];
                let trimmed = next_line.trim_start();

                // Stop if: empty line, new footnote, heading
                if trimmed.is_empty() {
                    break;
                }
                if trimmed.starts_with("[^") && trimmed.contains("]:") {
                    break;
                }
                if trimmed.starts_with('#') {
                    break;
                }

                // This is a continuation line - resolve reference links
                let resolved_line = resolve_reference_links(next_line, &reference_links);
                continuation_lines.push(resolved_line);
                i += 1;
            }

            // Convert to inline HTML at original position (HonKit style)
            // First line goes inline with number, return link right after first line
            // Then continuation content (lists, etc.) follows
            let return_link = format!(
                "<a href=\"#reffn_{}\" title=\"Jump back to footnote [{}] in the text.\"> ↩</a>",
                number, number
            );

            if continuation_lines.is_empty() {
                // Single-line footnote: <blockquote><sup>n</sup>. content ↩</blockquote>
                // Use blockquote to match HonKit styling (left border)
                result_lines.push(format!(
                    "<blockquote id=\"fn_{}\"><sup>{}</sup>. {}{}</blockquote>",
                    number, number, first_line_resolved, return_link
                ));
            } else {
                // Multi-line footnote: first line in blockquote, continuation outside
                // This matches HonKit behavior: blockquote has border, continuation doesn't
                let continuation_content = continuation_lines.join("\n");
                let continuation_html =
                    render_footnote_continuation(&continuation_content, hardbreaks);
                result_lines.push(format!(
                    "<blockquote id=\"fn_{}\"><sup>{}</sup>. {}{}</blockquote>\n{}",
                    number, number, first_line_resolved, return_link, continuation_html
                ));
            }
        } else {
            result_lines.push(line.to_string());
            i += 1;
        }
    }

    result_lines.join("\n")
}

/// Convert footnote references [^n] to placeholder (before parsing)
/// Placeholder format: %%FNREF_n%% - will be converted to HTML after markdown parsing
///
/// Skips fenced code blocks and inline code spans so that literal text like
/// the regex character class `[^abc]` is not turned into a footnote reference.
fn convert_footnote_references_to_placeholder(content: &str) -> String {
    let mut result = String::new();
    // (fence_char, fence_length) while inside a fenced code block
    let mut in_fence: Option<(char, usize)> = None;

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

        if let Some((fence_char, fence_len)) = in_fence {
            // Closing fence: a run of the same char, at least as long, alone on the line
            let run = trimmed.chars().take_while(|&c| c == fence_char).count();
            if run >= fence_len && trimmed.trim_end().chars().all(|c| c == fence_char) {
                in_fence = None;
            }
            result.push_str(line);
            result.push('\n');
            continue;
        }

        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
            let fence_char = trimmed.chars().next().unwrap();
            let fence_len = trimmed.chars().take_while(|&c| c == fence_char).count();
            in_fence = Some((fence_char, fence_len));
            result.push_str(line);
            result.push('\n');
            continue;
        }

        result.push_str(&convert_footnote_refs_in_line(line));
        result.push('\n');
    }

    // lines() drops the trailing newline info; restore original ending
    if !content.ends_with('\n') && result.ends_with('\n') {
        result.pop();
    }

    result
}

/// Convert footnote references in a single line, leaving inline code spans untouched
fn convert_footnote_refs_in_line(line: &str) -> String {
    let mut result = String::new();
    let mut rest = line;

    loop {
        match find_inline_code_span(rest) {
            Some((start, end)) => {
                result.push_str(&convert_footnote_refs_in_text(&rest[..start]));
                result.push_str(&rest[start..end]); // code span verbatim
                rest = &rest[end..];
            }
            None => {
                result.push_str(&convert_footnote_refs_in_text(rest));
                break;
            }
        }
    }

    result
}

/// Find the next inline code span (a run of N backticks closed by an
/// equal-length run, per CommonMark). Returns the byte range including
/// the backticks, or None if no closed span exists.
fn find_inline_code_span(s: &str) -> Option<(usize, usize)> {
    let bytes = s.as_bytes();
    let mut open = s.find('`')?;

    loop {
        let open_len = bytes[open..].iter().take_while(|&&b| b == b'`').count();
        // Search for a closing run of exactly open_len backticks
        let mut idx = open + open_len;
        while idx < bytes.len() {
            if bytes[idx] == b'`' {
                let run_start = idx;
                while idx < bytes.len() && bytes[idx] == b'`' {
                    idx += 1;
                }
                if idx - run_start == open_len {
                    return Some((open, idx));
                }
            } else {
                idx += 1;
            }
        }
        // This opener never closes; try the next backtick run after it
        let next = s[open + open_len..].find('`')?;
        open = open + open_len + next;
    }
}

/// Convert footnote references [^n] to placeholders in plain (non-code) text
fn convert_footnote_refs_in_text(content: &str) -> String {
    let mut result = String::new();
    let mut chars = content.char_indices().peekable();

    while let Some((i, c)) = chars.next() {
        if c == '[' && content[i..].starts_with("[^") {
            // Find the closing ]
            let rest = &content[i + 2..];
            if let Some(end) = rest.find(']') {
                let number = &rest[..end];
                // Make sure it's a reference (not a definition - no : after ])
                let after = &rest[end + 1..];
                if !after.starts_with(':')
                    && !number.is_empty()
                    && number.chars().all(|c| c.is_alphanumeric())
                {
                    // This is a reference, convert to placeholder
                    result.push_str(&format!("%%FNREF_{}%%", number));
                    // Skip past the reference: ^number]
                    // We already consumed '[', so skip: ^ + number + ]
                    for _ in 0..(1 + end + 1) {
                        chars.next();
                    }
                    continue;
                }
            }
        }
        result.push(c);
    }

    result
}

/// Convert footnote placeholders to HTML (after markdown parsing)
fn convert_footnote_placeholders_to_html(html: &str) -> String {
    let mut result = html.to_string();
    // Find all %%FNREF_n%% patterns and replace with HTML
    let re_pattern = "%%FNREF_";
    while let Some(start) = result.find(re_pattern) {
        let after_prefix = &result[start + re_pattern.len()..];
        if let Some(end) = after_prefix.find("%%") {
            let number = &after_prefix[..end];
            let replacement = format!(
                "<sup><a href=\"#fn_{}\" id=\"reffn_{}\">{}</a></sup>",
                number, number, number
            );
            let full_placeholder = format!("%%FNREF_{}%%", number);
            result = result.replacen(&full_placeholder, &replacement, 1);
        } else {
            break;
        }
    }
    result
}

/// Parse a footnote definition start line, returns (number, rest_of_line)
fn parse_footnote_def_start(line: &str) -> Option<(&str, &str)> {
    let trimmed = line.trim_start();
    if !trimmed.starts_with("[^") {
        return None;
    }

    // Find the closing ]
    let after_bracket = &trimmed[2..];
    let end_bracket = after_bracket.find("]:")?;
    let number = &after_bracket[..end_bracket];

    // Get the content after ]:
    let rest = &after_bracket[end_bracket + 2..].trim_start();
    Some((number, rest))
}

/// Render footnote continuation content (lists, paragraphs after first line)
fn render_footnote_continuation(content: &str, hardbreaks: bool) -> String {
    // Find minimum indentation (excluding empty lines) to preserve relative indentation
    let min_indent = content
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.len() - line.trim_start().len())
        .min()
        .unwrap_or(0);

    // Remove only the common leading indentation, preserving relative structure
    let dedented: String = content
        .lines()
        .map(|line| {
            if line.len() >= min_indent {
                &line[min_indent..]
            } else {
                line.trim_start()
            }
        })
        .collect::<Vec<_>>()
        .join("\n");

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);

    let parser = Parser::new_ext(&dedented, options);

    // Apply hardbreaks conversion if enabled
    let events: Vec<Event> = parser
        .map(|event| {
            if hardbreaks {
                match event {
                    Event::SoftBreak => Event::HardBreak,
                    _ => event,
                }
            } else {
                event
            }
        })
        .collect();

    let mut html = String::new();
    html::push_html(&mut html, events.into_iter());

    html.trim().to_string()
}

/// Fix multi-line footnotes without proper indentation
/// Adds 4 spaces to ALL continuation lines to preserve relative indentation structure
fn fix_multiline_footnotes(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut result = Vec::new();
    let mut in_footnote = false;

    for line in lines {
        // Check if this line starts a new footnote definition
        if line.starts_with("[^") && line.contains("]:") {
            in_footnote = true;
            result.push(line.to_string());
        } else if in_footnote {
            let trimmed = line.trim_start();

            if trimmed.is_empty() {
                // Empty line ends the footnote
                in_footnote = false;
                result.push(line.to_string());
            } else if trimmed.starts_with("[^") && trimmed.contains("]:") {
                // New footnote starts
                in_footnote = true;
                result.push(line.to_string());
            } else if trimmed.starts_with('#') {
                // Heading starts - end of footnotes section
                in_footnote = false;
                result.push(line.to_string());
            } else {
                // Continuation line - add 4 spaces to ALL lines to preserve relative structure
                result.push(format!("    {}", line));
            }
        } else {
            result.push(line.to_string());
        }
    }

    result.join("\n")
}

/// Fix malformed table rows:
/// - Add missing trailing | to header rows
/// - Fix separator rows where column count doesn't match header
fn fix_table_separator_columns(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut result = Vec::new();
    let mut i = 0;

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

        // Check if this line looks like a table row (starts with |)
        if trimmed.starts_with('|') {
            // Check if next line is a separator row
            if i + 1 < lines.len() {
                let next_line = lines[i + 1];
                if is_table_separator_row(next_line) {
                    // This is a header row - fix missing trailing pipe if needed
                    let fixed_header = fix_table_row_trailing_pipe(line);
                    let header_cols = count_table_columns(&fixed_header);

                    let separator_cols = count_table_columns(next_line);

                    // Push the fixed header
                    result.push(fixed_header);
                    i += 1;

                    // If column counts don't match, fix the separator row
                    if header_cols > 0 && separator_cols != header_cols {
                        let fixed_separator = generate_separator_row(header_cols, next_line);
                        result.push(fixed_separator);
                    } else {
                        result.push(next_line.to_string());
                    }
                    i += 1;
                    continue;
                }
            }
        }

        result.push(line.to_string());
        i += 1;
    }

    result.join("\n")
}

/// Add trailing pipe to table row if missing
fn fix_table_row_trailing_pipe(line: &str) -> String {
    let trimmed = line.trim();
    if trimmed.starts_with('|') && !trimmed.ends_with('|') {
        format!("{}|", line)
    } else {
        line.to_string()
    }
}

/// Count the number of columns in a table row
fn count_table_columns(line: &str) -> usize {
    let trimmed = line.trim();
    if !trimmed.starts_with('|') {
        return 0;
    }

    // Count the | characters, accounting for leading/trailing pipes
    let pipe_count = trimmed.chars().filter(|&c| c == '|').count();

    // Number of columns = pipes - 1 (for |col1|col2|col3| format)
    pipe_count.saturating_sub(1)
}

/// Check if a line is a table separator row (contains only |, -, :, and whitespace)
fn is_table_separator_row(line: &str) -> bool {
    let trimmed = line.trim();
    if !trimmed.starts_with('|') || !trimmed.ends_with('|') {
        return false;
    }

    // Must contain at least one dash
    if !trimmed.contains('-') {
        return false;
    }

    // All characters must be |, -, :, or whitespace
    trimmed
        .chars()
        .all(|c| c == '|' || c == '-' || c == ':' || c.is_whitespace())
}

/// Generate a separator row with the specified number of columns
/// Preserves per-column alignment from the original separator
fn generate_separator_row(col_count: usize, original: &str) -> String {
    // Parse alignments from original separator row
    let trimmed = original.trim();
    let original_alignments: Vec<&str> = trimmed
        .trim_start_matches('|')
        .trim_end_matches('|')
        .split('|')
        .map(|cell| {
            let cell = cell.trim();
            if cell.starts_with(':') && cell.ends_with(':') {
                ":--:" // center
            } else if cell.starts_with(':') {
                ":--" // left (explicit)
            } else if cell.ends_with(':') {
                "--:" // right
            } else {
                "--" // left (default)
            }
        })
        .collect();

    // Build new separator with correct number of columns
    // Use original alignments where available, default to "--" for extra columns
    let cols: Vec<&str> = (0..col_count)
        .map(|i| {
            if i < original_alignments.len() {
                original_alignments[i]
            } else {
                "--" // default alignment for extra columns
            }
        })
        .collect();

    format!("|{}|", cols.join("|"))
}

/// Fix full-width spaces after heading markers (common mistake in Japanese documents)
/// Converts "## 見出し" to "## 見出し"
fn fix_fullwidth_heading_spaces(content: &str) -> String {
    content
        .lines()
        .map(|line| {
            // Check if line starts with heading markers followed by full-width space
            let trimmed = line.trim_start();
            if trimmed.starts_with('#') {
                // Find where the # sequence ends
                let hash_count = trimmed.chars().take_while(|&c| c == '#').count();
                if hash_count > 0 && hash_count <= 6 {
                    let after_hashes = &trimmed[hash_count..];
                    // Check if followed by full-width space (U+3000)
                    if after_hashes.starts_with('\u{3000}') {
                        // Replace full-width space with half-width space
                        let leading_whitespace = &line[..line.len() - trimmed.len()];
                        let rest = &after_hashes['\u{3000}'.len_utf8()..];
                        return format!(
                            "{}{} {}",
                            leading_whitespace,
                            "#".repeat(hash_count),
                            rest
                        );
                    }
                }
            }
            line.to_string()
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Fix image paths that contain spaces by wrapping them in angle brackets
/// Converts ![alt](path with space.png) to ![alt](<path with space.png>)
fn fix_image_paths_with_spaces(content: &str) -> String {
    let mut result = String::new();
    let mut chars = content.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '!' {
            // Check for image syntax: ![...](...)
            if chars.peek() == Some(&'[') {
                // Collect the entire potential image syntax
                let mut img_str = String::from("!");
                img_str.push(chars.next().unwrap()); // '['

                // Read alt text until ']'
                let mut bracket_depth = 1;
                while let Some(&ch) = chars.peek() {
                    img_str.push(chars.next().unwrap());
                    if ch == '[' {
                        bracket_depth += 1;
                    } else if ch == ']' {
                        bracket_depth -= 1;
                        if bracket_depth == 0 {
                            break;
                        }
                    }
                }

                // Check for '(' after ']'
                if chars.peek() == Some(&'(') {
                    img_str.push(chars.next().unwrap()); // '('

                    // Read URL until ')'
                    let mut url = String::new();
                    let mut paren_depth = 1;
                    while let Some(&ch) = chars.peek() {
                        if ch == '(' {
                            paren_depth += 1;
                            url.push(chars.next().unwrap());
                        } else if ch == ')' {
                            paren_depth -= 1;
                            if paren_depth == 0 {
                                chars.next(); // consume ')'
                                break;
                            }
                            url.push(chars.next().unwrap());
                        } else {
                            url.push(chars.next().unwrap());
                        }
                    }

                    // Check if URL contains spaces and doesn't already use angle brackets
                    if url.contains(' ') && !url.starts_with('<') {
                        img_str.push('<');
                        img_str.push_str(&url);
                        img_str.push('>');
                    } else {
                        img_str.push_str(&url);
                    }
                    img_str.push(')');
                }

                result.push_str(&img_str);
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }

    result
}

fn fix_relative_links(html: &str) -> String {
    // Replace .md links with .html, but ONLY inside href attribute values.
    // A blind string replace would also rewrite occurrences in visible text,
    // e.g. `chapter1.md#section` inside <code>.
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();
    let mut in_tag = false;

    while let Some((_, c)) = chars.next() {
        result.push(c);

        if c == '<' {
            in_tag = true;
            continue;
        }
        if c == '>' {
            in_tag = false;
            continue;
        }

        // Attribute values only exist inside tags; this keeps literal text
        // like href="x.md" inside <code> untouched
        if in_tag && (c == '"' || c == '\'') {
            let quote_char = c;
            // Check if this quote opens an href attribute value
            // (look at the 5 chars just before the quote we pushed)
            let before_quote = &result[..result.len() - quote_char.len_utf8()];
            let suffix: String = before_quote
                .chars()
                .rev()
                .take(5)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            if suffix.eq_ignore_ascii_case("href=") {
                // Collect the URL up to the closing quote
                let mut url = String::new();
                let mut closed = false;
                for (_, ch) in chars.by_ref() {
                    if ch == quote_char {
                        result.push_str(&fix_md_extension(&url));
                        result.push(quote_char);
                        closed = true;
                        break;
                    }
                    url.push(ch);
                }
                if !closed {
                    // Unterminated attribute: emit what we collected as-is
                    result.push_str(&url);
                }
            }
        }
    }

    // Normalize backslashes to forward slashes in href attributes
    normalize_path_separators(&result)
}

/// Convert a `.md` extension in a URL to `.html` (also handles `.md#anchor`)
fn fix_md_extension(url: &str) -> String {
    if let Some(stripped) = url.strip_suffix(".md") {
        format!("{}.html", stripped)
    } else if let Some(pos) = url.find(".md#") {
        format!("{}.html{}", &url[..pos], &url[pos + 3..])
    } else {
        url.to_string()
    }
}

/// True when the quote just pushed onto `result` opens an href/src attribute
/// value. The quote itself must be excluded before checking — including it
/// makes the ends_with() check structurally impossible to match.
fn quote_opens_link_attr(result: &str, quote_char: char) -> bool {
    let before = &result[..result.len() - quote_char.len_utf8()];
    let tail: String = before
        .chars()
        .rev()
        .take(5)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    let tail = tail.to_ascii_lowercase();
    tail.ends_with("href=") || tail.ends_with("src=")
}

/// Rewrite the value of every href/src attribute with `f`.
/// Unterminated attribute values are emitted unchanged.
fn map_link_attr_values(html: &str, f: impl Fn(String) -> String) -> String {
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();

    while let Some((_, c)) = chars.next() {
        result.push(c);

        if (c == '"' || c == '\'') && quote_opens_link_attr(&result, c) {
            let quote_char = c;
            let mut url = String::new();
            let mut closed = false;
            for (_, ch) in chars.by_ref() {
                if ch == quote_char {
                    result.push_str(&f(url.clone()));
                    result.push(quote_char);
                    closed = true;
                    break;
                }
                url.push(ch);
            }
            if !closed {
                result.push_str(&url);
            }
        }
    }

    result
}

/// Remove leading slashes from internal links
/// Converts href="/path/to/file" → href="path/to/file"
/// Skips protocol-relative URLs (//example.com) and external links
fn remove_leading_slash_from_links(html: &str) -> String {
    map_link_attr_values(html, |url| {
        if url.starts_with('/') && !url.starts_with("//") {
            let lower = url.to_lowercase();
            if !lower.starts_with("/http://") && !lower.starts_with("/https://") {
                return url.chars().skip(1).collect();
            }
        }
        url
    })
}

/// Convert backslashes to forward slashes in href and src attributes
/// Handles Windows-style paths like href="path\to\file" → href="path/to/file"
fn normalize_path_separators(html: &str) -> String {
    map_link_attr_values(html, |url| url.replace('\\', "/"))
}

/// Add target="_blank" rel="noopener noreferrer" to external links that don't have target attribute
/// This handles Markdown-style links [text](https://...) that were converted to <a href="...">
fn add_target_blank_to_external_links(html: &str) -> String {
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();

    while let Some((i, c)) = chars.next() {
        if c == '<' && html[i..].starts_with("<a ") {
            // Found an anchor tag start
            let mut tag_content = String::from("<a ");
            // Skip past "<a "
            chars.next(); // 'a'
            chars.next(); // ' '

            // Collect the entire tag until '>'
            for (_, ch) in chars.by_ref() {
                tag_content.push(ch);
                if ch == '>' {
                    break;
                }
            }

            // Check if this is an external link without target attribute
            let tag_lower = tag_content.to_lowercase();
            let has_target = tag_lower.contains("target=");
            let is_external = tag_lower.contains("href=\"http://")
                || tag_lower.contains("href=\"https://")
                || tag_lower.contains("href='http://")
                || tag_lower.contains("href='https://");

            if is_external && !has_target {
                // Insert target="_blank" rel="noopener noreferrer" before the closing >
                let without_close = tag_content.trim_end_matches('>');
                result.push_str(without_close);
                result.push_str(" target=\"_blank\" rel=\"noopener noreferrer\">");
            } else {
                result.push_str(&tag_content);
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Auto-link URLs that are not already inside anchor tags or code blocks
/// Converts bare URLs like https://example.com to <a href="..." target="_blank">...</a>
fn autolink_urls(html: &str) -> String {
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();
    let mut in_code = false; // Track if we're inside <code> or <pre>

    while let Some((i, c)) = chars.next() {
        // Check if we're inside an HTML tag
        if c == '<' {
            result.push(c);

            // Collect the tag
            let mut tag_content = String::new();
            for (_, ch) in chars.by_ref() {
                result.push(ch);
                if ch == '>' {
                    break;
                }
                tag_content.push(ch);
            }

            // Check for code/pre tags
            let tag_lower = tag_content.to_lowercase();
            if tag_lower.starts_with("code") || tag_lower.starts_with("pre") {
                in_code = true;
            } else if tag_lower.starts_with("/code") || tag_lower.starts_with("/pre") {
                in_code = false;
            }
            continue;
        }

        // Skip auto-linking if inside code block
        if in_code {
            result.push(c);
            continue;
        }

        // Check for http:// or https://
        if c == 'h' && html[i..].starts_with("http://") || html[i..].starts_with("https://") {
            // Check if this URL is already inside an href=""
            if result.ends_with("href=\"") || result.ends_with("src=\"") {
                // Already in an href, just copy normally
                result.push(c);
                continue;
            }

            // Extract the URL
            let url_start = i;
            let mut url_end = i + 1;

            // Continue consuming URL characters
            while let Some(&(next_i, next_c)) = chars.peek() {
                // URL ends at whitespace, <, >, ", '
                if next_c.is_whitespace()
                    || next_c == '<'
                    || next_c == '>'
                    || next_c == '"'
                    || next_c == '\''
                {
                    break;
                }
                url_end = next_i + next_c.len_utf8();
                chars.next();
            }

            let mut url = &html[url_start..url_end];

            // Remove trailing punctuation that's likely not part of URL
            while url.ends_with('.')
                || url.ends_with(',')
                || url.ends_with(';')
                || url.ends_with(':')
                || url.ends_with(')')
                || url.ends_with('!')
                || url.ends_with('?')
            {
                url = &url[..url.len() - 1];
            }

            // Create the link with target="_blank"
            result.push_str(&format!(r#"<a href="{}" target="_blank">{}</a>"#, url, url));

            // If we trimmed trailing punctuation, add it back
            let trimmed_len = url_end - url_start - url.len();
            if trimmed_len > 0 {
                result.push_str(&html[url_start + url.len()..url_end]);
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Convert remaining markdown image syntax ![alt](url) to <img> tags
/// This handles images inside raw HTML blocks that pulldown-cmark doesn't parse
/// Skips content inside <code> and <pre> tags
fn convert_remaining_markdown_images(html: &str) -> String {
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();
    let mut in_code = false; // Track if we're inside <code> or <pre>

    while let Some((_, c)) = chars.next() {
        // Check if we're inside an HTML tag
        if c == '<' {
            result.push(c);

            // Collect the tag
            let mut tag_content = String::new();
            for (_, ch) in chars.by_ref() {
                result.push(ch);
                if ch == '>' {
                    break;
                }
                tag_content.push(ch);
            }

            // Check for code/pre tags
            let tag_lower = tag_content.to_lowercase();
            if tag_lower.starts_with("code") || tag_lower.starts_with("pre") {
                in_code = true;
            } else if tag_lower.starts_with("/code") || tag_lower.starts_with("/pre") {
                in_code = false;
            }
            continue;
        }

        // Skip image conversion if inside code block
        if in_code {
            result.push(c);
            continue;
        }

        if c == '!' && chars.peek().map(|(_, ch)| *ch) == Some('[') {
            chars.next(); // consume '['

            // Collect alt text until ']'
            let mut alt = String::new();
            let mut bracket_depth = 1;
            for (_, ch) in chars.by_ref() {
                if ch == '[' {
                    bracket_depth += 1;
                    alt.push(ch);
                } else if ch == ']' {
                    bracket_depth -= 1;
                    if bracket_depth == 0 {
                        break;
                    }
                    alt.push(ch);
                } else {
                    alt.push(ch);
                }
            }

            // Check for '(' after ']'
            if chars.peek().map(|(_, ch)| *ch) == Some('(') {
                chars.next(); // consume '('

                // Collect URL until ')'
                let mut url = String::new();
                let mut paren_depth = 1;
                for (_, ch) in chars.by_ref() {
                    if ch == '(' {
                        paren_depth += 1;
                        url.push(ch);
                    } else if ch == ')' {
                        paren_depth -= 1;
                        if paren_depth == 0 {
                            break;
                        }
                        url.push(ch);
                    } else {
                        url.push(ch);
                    }
                }

                // Output as <img> tag (escape quotes so alt/url text cannot
                // break out of the attribute value)
                result.push_str(&format!(
                    r#"<img src="{}" alt="{}">"#,
                    html_escape(&url),
                    html_escape(&alt)
                ));
            } else {
                // Not an image, output as-is
                result.push('!');
                result.push('[');
                result.push_str(&alt);
                result.push(']');
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Convert internal links to proper relative paths from current file
///
/// Handles two cases:
/// 1. Root-relative links (starting with /): e.g., "/api-docs/" → "../../api-docs/" (at depth 2)
/// 2. Root-relative links without slash: e.g., "Customer/AssetStatus/File.html" → "../../Customer/AssetStatus/File.html"
///
/// current_path: e.g., "Customer/AssetStatus/PortfolioTop.md"
fn convert_relative_links_to_absolute(html: &str, current_path: &str) -> String {
    let result = html.to_string();

    // Calculate the depth (number of directories from root)
    // e.g., "Customer/AssetStatus/PortfolioTop.md" -> depth 2
    let depth = Path::new(current_path)
        .parent()
        .map(|p| {
            let dir = p.to_string_lossy();
            if dir.is_empty() {
                0
            } else {
                dir.matches('/').count() + 1
            }
        })
        .unwrap_or(0);

    // Create the prefix to go back to root (e.g., "../../" for depth 2)
    let root_prefix: String = "../".repeat(depth);

    // href: root-relative AND bare directory paths are book-root-relative
    let result = adjust_attribute_urls(&result, r#"href=""#, &root_prefix, depth, true);
    // src: only root-relative paths (/assets/x.png). Page-relative image
    // paths (images/foo.png) are correct as written and must not be rewritten
    adjust_attribute_urls(&result, r#"src=""#, &root_prefix, depth, false)
}

/// Adjust URLs in one attribute type (href="..." / src="...") for page depth
fn adjust_attribute_urls(
    html: &str,
    attr_pattern: &str,
    root_prefix: &str,
    depth: usize,
    convert_bare_dir_paths: bool,
) -> String {
    let result = html;
    let mut new_result = String::new();
    let mut last_end = 0;
    let mut search_start = 0;

    while let Some(attr_pos) = result[search_start..].find(attr_pattern) {
        let abs_attr_pos = search_start + attr_pos;
        let url_start = abs_attr_pos + attr_pattern.len();

        // Find the closing quote
        if let Some(url_end_offset) = result[url_start..].find('"') {
            let url_end = url_start + url_end_offset;
            let url = &result[url_start..url_end];

            // Check if this is a root-relative link (starts with /)
            // Convert "/api-docs/" to "../../api-docs/" based on depth
            let is_root_relative = url.starts_with('/')
                && !url.starts_with("//")  // Skip protocol-relative URLs
                && !url.to_lowercase().starts_with("/http://")
                && !url.to_lowercase().starts_with("/https://");

            if is_root_relative {
                // Copy everything up to the URL
                new_result.push_str(&result[last_end..url_start]);
                // Add the root prefix + URL without leading slash
                new_result.push_str(root_prefix);
                new_result.push_str(&url[1..]); // Skip the leading /
                last_end = url_end;
                search_start = url_end + 1;
                continue;
            }

            // Check if this is an internal link that needs conversion (no leading /)
            // Skip: external links (http/https), anchor-only (#), already relative (../ or ./), data URIs
            // Skip: same-directory links (no "/" in path) - these are already correct relative links
            let needs_conversion = convert_bare_dir_paths
                && !url.is_empty()
                && url.contains('/')  // Only convert links with directory paths
                && !url.starts_with("http://")
                && !url.starts_with("https://")
                && !url.starts_with('#')
                && !url.starts_with("../")
                && !url.starts_with("./")
                && !url.starts_with('/')
                && !url.starts_with("mailto:")
                && !url.starts_with("javascript:")
                && !url.starts_with("data:")
                && depth > 0;

            if needs_conversion {
                // Copy everything up to the URL
                new_result.push_str(&result[last_end..url_start]);
                // Add the root prefix + original URL
                new_result.push_str(root_prefix);
                new_result.push_str(url);
                last_end = url_end;
            }

            search_start = url_end + 1;
        } else {
            search_start = url_start + 1;
        }
    }

    // Copy the remaining part
    new_result.push_str(&result[last_end..]);

    new_result
}

// =============================================================================
// AsciiDoc Rendering
// =============================================================================

/// Render AsciiDoc content to HTML
/// Applies the same post-processing as markdown (target="_blank", link normalization, etc.)
pub fn render_asciidoc(content: &str) -> String {
    render_asciidoc_internal(content)
}

/// Render AsciiDoc content to HTML with path for relative link conversion
pub fn render_asciidoc_with_path(content: &str, current_path: Option<&str>) -> String {
    let html = render_asciidoc_internal(content);

    // If we have a current path, convert relative links to absolute
    if let Some(path) = current_path {
        convert_relative_links_to_absolute(&html, path)
    } else {
        html
    }
}

/// Extract headings from AsciiDoc content for TOC generation
pub fn extract_headings_from_asciidoc(content: &str) -> Vec<TocItem> {
    let mut headings = Vec::new();

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

        // AsciiDoc headings: == Level 1, === Level 2, ==== Level 3, etc.
        if trimmed.starts_with("==") && !trimmed.starts_with("====") {
            // Count the equals signs
            let eq_count = trimmed.chars().take_while(|&c| c == '=').count();

            // Level mapping: == is h2, === is h3, ==== is h4
            // (= is h1 which is typically the document title)
            if (2..=5).contains(&eq_count) {
                let level = eq_count as u8; // 2 = h2, 3 = h3, etc.
                let text = trimmed[eq_count..].trim().to_string();

                // Only include h2, h3, h4 in TOC (skip h1 which is page title)
                if (2..=4).contains(&level) && !text.is_empty() {
                    let id = slugify(&text);
                    headings.push(TocItem { level, text, id });
                }
            }
        }
    }

    headings
}

fn render_asciidoc_internal(content: &str) -> String {
    // Normalize CRLF/CR to LF for consistent line handling
    let content = content.replace("\r\n", "\n").replace("\r", "\n");

    // Strip all UTF-8 BOM characters
    let content = content.replace('\u{FEFF}', "");

    // Use asciidocr to convert to HTML
    // 1. Create a Scanner to tokenize the content
    let scanner = asciidocr::scanner::Scanner::new(&content);

    // 2. Create a Parser and parse the tokens (parser expects iterator of Result<Token, ScannerError>)
    let mut parser = asciidocr::parser::Parser::new(std::path::PathBuf::from("."));

    match parser.parse(scanner) {
        Ok(asg) => {
            // 3. Render the ASG to HTMLBook
            match asciidocr::backends::htmls::render_htmlbook(&asg) {
                Ok(html) => {
                    // Extract just the body content (asciidocr outputs full HTML document)
                    let html = extract_body_content(&html);

                    // Apply the same post-processing as markdown
                    let html = fix_asciidoc_relative_links(&html);
                    let html = remove_leading_slash_from_links(&html);
                    let html = autolink_urls(&html);

                    add_target_blank_to_external_links(&html)
                }
                Err(e) => {
                    eprintln!("  Warning: AsciiDoc conversion error: {:?}", e);
                    format!("<p>{}</p>", html_escape(&content))
                }
            }
        }
        Err(e) => {
            eprintln!("  Warning: AsciiDoc parsing error: {:?}", e);
            // Return the content wrapped in a simple paragraph as fallback
            format!("<p>{}</p>", html_escape(&content))
        }
    }
}

/// Extract body content from full HTML document
/// asciidocr outputs full HTML with <!DOCTYPE>, <html>, <head>, <body>
/// We only need the content inside <body>
fn extract_body_content(html: &str) -> String {
    // Try to find <body> and </body> tags
    if let Some(body_start) = html.find("<body>") {
        let content_start = body_start + 6; // length of "<body>"
        if let Some(body_end) = html.find("</body>") {
            return html[content_start..body_end].trim().to_string();
        }
    }
    // If no body tags found, return as-is
    html.to_string()
}

/// Fix relative links in AsciiDoc output
/// Converts .adoc and .asciidoc links to .html
fn fix_asciidoc_relative_links(html: &str) -> String {
    let mut result = html.to_string();

    // Replace .adoc and .asciidoc links with .html
    let patterns = [
        (r#".adoc""#, r#".html""#),
        (r#".adoc#"#, r#".html#"#),
        (r#".adoc'"#, r#".html'"#),
        (r#".asciidoc""#, r#".html""#),
        (r#".asciidoc#"#, r#".html#"#),
        (r#".asciidoc'"#, r#".html'"#),
        // Also handle .md links for mixed content
        (r#".md""#, r#".html""#),
        (r#".md#"#, r#".html#"#),
        (r#".md'"#, r#".html'"#),
    ];

    for (from, to) in patterns {
        result = result.replace(from, to);
    }

    // Normalize backslashes to forward slashes in href attributes
    result = normalize_path_separators(&result);

    result
}

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

    #[test]
    fn test_render_basic_markdown() {
        let md = "# Hello\n\nThis is a **test**.";
        let html = render_markdown(md);
        // Heading now includes ID attribute
        assert!(
            html.contains("<h1 id=\"hello\">Hello</h1>"),
            "HTML: {}",
            html
        );
        assert!(html.contains("<strong>test</strong>"));
    }

    #[test]
    fn test_render_table() {
        let md = r#"
| Header 1 | Header 2 |
|----------|----------|
| Cell 1   | Cell 2   |
"#;
        let html = render_markdown(md);
        assert!(html.contains("<table>"));
        assert!(html.contains("<th>Header 1</th>"));
    }

    #[test]
    fn test_render_mermaid() {
        let md = r#"
```mermaid
sequenceDiagram
    A->>B: Hello
```
"#;
        let html = render_markdown(md);
        assert!(html.contains(r#"<div class="mermaid">"#));
        assert!(html.contains("sequenceDiagram"));
    }

    #[test]
    fn test_fix_relative_links() {
        let html = r#"<a href="chapter1.md">Link</a>"#;
        let fixed = fix_relative_links(html);
        assert!(fixed.contains(r#"href="chapter1.html""#));
    }

    #[test]
    fn test_image_in_table() {
        let md = r#"
| Col1 | Col2 |
|:--:|:--:|
|![](test.png)|text|
"#;
        let html = render_markdown(md);
        println!("Generated HTML: {}", html);
        assert!(
            html.contains("<img"),
            "Image tag should be generated: {}",
            html
        );
    }

    #[test]
    fn test_image_in_table_japanese() {
        let md = r#"## デザイン
|該当するタイムラインがある場合|該当するタイムラインがない場合|
|:--:|:--:|
|![](../../../assets/Customer/TimeLine/B-0-8-Timeline Information Page.png)|![](../../../assets/Customer/TimeLine/B-0-8-Timeline Information Page0件.png)|
## 項目一覧"#;
        let html = render_markdown(md);
        println!("Generated HTML: {}", html);
        assert!(
            html.contains("<img"),
            "Image tag should be generated: {}",
            html
        );
    }

    #[test]
    fn test_image_with_space_in_filename() {
        // Test: space in filename
        let md = r#"|![](test file.png)|"#;
        let html = render_markdown(md);
        println!("With space: {}", html);

        // Test: no space in filename
        let md2 = r#"|![](testfile.png)|"#;
        let html2 = render_markdown(md2);
        println!("No space: {}", html2);
    }

    #[test]
    fn test_autolink_urls() {
        // Test: bare URL should become a link
        let md = "Guide Git:https://github.com/guide-inc-org/kcmsr-member-site-spec";
        let html = render_markdown(md);
        println!("Autolink result: {}", html);
        assert!(html.contains(r#"<a href="https://github.com/guide-inc-org/kcmsr-member-site-spec" target="_blank">"#),
            "URL should be auto-linked: {}", html);
    }

    #[test]
    fn test_autolink_does_not_double_link() {
        // Test: already linked URL should not be double-linked
        let md = "[Link](https://example.com)";
        let html = render_markdown(md);
        println!("Already linked result: {}", html);
        // Should have exactly one href for the URL
        let count = html.matches("https://example.com").count();
        assert_eq!(count, 1, "URL should appear only once: {}", html);
    }

    #[test]
    fn test_multiline_footnotes() {
        let md = r#"Text with footnote[^1].

[^1]: First line
- Second line
- Third line
[^2]: Another footnote"#;
        let html = render_markdown(md);
        println!("Footnote HTML: {}", html);
        // The footnote should be properly rendered with list items inside
        assert!(
            html.contains("<li>"),
            "Footnote should contain list items: {}",
            html
        );
    }

    #[test]
    fn test_fix_multiline_footnotes_preprocessing() {
        let input = r#"[^1]: First line
- Second line
- Third line
[^2]: Another"#;
        let output = fix_multiline_footnotes(input);
        println!("Preprocessed:\n{}", output);
        assert!(
            output.contains("    - Second line"),
            "Second line should be indented: {}",
            output
        );
        assert!(
            output.contains("    - Third line"),
            "Third line should be indented: {}",
            output
        );
        assert!(
            !output.contains("    [^2]"),
            "New footnote should not be indented: {}",
            output
        );
    }

    #[test]
    fn test_slugify_matches_github_slugger() {
        // Test that slugify matches github-slugger / HonKit behavior
        // Special characters like / should be removed, not converted to hyphens
        assert_eq!(
            slugify("/auth/verification-email/resend"),
            "authverification-emailresend"
        );
        assert_eq!(slugify("Hello World"), "hello-world");
        assert_eq!(slugify("A.B.C"), "abc"); // Periods removed
        assert_eq!(slugify("日本語テスト"), "日本語テスト"); // Japanese preserved
        assert_eq!(slugify("test_underscore"), "test_underscore"); // Underscores preserved
        assert_eq!(slugify("a--b"), "a-b"); // Multiple hyphens collapsed
    }

    #[test]
    fn test_duplicate_heading_ids_are_deduplicated() {
        // Regression: identical headings produced identical ids
        let md = "## 概要\n\n本文A\n\n## 概要\n\n本文B\n\n## 概要\n\n本文C\n";
        let html = render_markdown(md);
        assert!(html.contains(r#"<h2 id="概要">"#), "html: {}", html);
        assert!(html.contains(r#"<h2 id="概要-1">"#), "html: {}", html);
        assert!(html.contains(r#"<h2 id="概要-2">"#), "html: {}", html);
    }

    #[test]
    fn test_toc_ids_match_rendered_heading_ids_for_duplicates() {
        let md = "## 概要\n\n本文A\n\n### 詳細\n\n## 概要\n\n本文B\n";
        let html = render_markdown(md);
        let toc = extract_headings(md);
        for item in &toc {
            assert!(
                html.contains(&format!(r#"id="{}""#, item.id)),
                "TOC id {} not found in rendered html: {}",
                item.id,
                html
            );
        }
        // The two 概要 entries must have distinct ids
        let ids: Vec<&str> = toc.iter().map(|t| t.id.as_str()).collect();
        assert_eq!(ids.iter().filter(|i| **i == "概要").count(), 1);
        assert!(ids.contains(&"概要-1"));
    }

    #[test]
    fn test_md_link_in_inline_code_not_rewritten() {
        // Regression: blind .md# replacement rewrote text inside <code>
        let md = "詳細は `chapter1.md#section` を参照。\n\n[link](other.md#anchor)\n";
        let html = render_markdown(md);
        assert!(
            html.contains("<code>chapter1.md#section</code>"),
            "inline code must be untouched: {}",
            html
        );
        assert!(
            html.contains(r##"href="other.html#anchor""##),
            "real links must still be converted: {}",
            html
        );
    }

    #[test]
    fn test_md_link_in_code_block_not_rewritten() {
        let md = "```\nsee chapter1.md#section and \"file.md\"\n```\n";
        let html = render_markdown(md);
        assert!(
            html.contains("chapter1.md#section"),
            "code block must be untouched: {}",
            html
        );
        assert!(!html.contains("chapter1.html"), "html: {}", html);
    }

    #[test]
    fn test_normalize_path_separators_fires() {
        // Regression: the href=/src= detection included the just-pushed quote
        // in the suffix check, so it never matched and backslashes survived
        let html =
            r#"<a href="docs\sub\file.html">x</a> <img src="img\pic.png"> and text\with\backslash"#;
        let fixed = normalize_path_separators(html);
        assert!(fixed.contains(r#"href="docs/sub/file.html""#), "{}", fixed);
        assert!(fixed.contains(r#"src="img/pic.png""#), "{}", fixed);
        // Backslashes outside attributes stay untouched
        assert!(fixed.contains(r"text\with\backslash"), "{}", fixed);
    }

    #[test]
    fn test_remove_leading_slash_fires() {
        // Same regression shape as normalize_path_separators
        let html = r#"<a href="/guide/page.html">x</a><img src="/assets/pic.png"><a href="//cdn.example.com/x">y</a>"#;
        let fixed = remove_leading_slash_from_links(html);
        assert!(fixed.contains(r#"href="guide/page.html""#), "{}", fixed);
        assert!(fixed.contains(r#"src="assets/pic.png""#), "{}", fixed);
        // Protocol-relative URL untouched
        assert!(fixed.contains(r#"href="//cdn.example.com/x""#), "{}", fixed);
    }

    #[test]
    fn test_root_relative_img_src_depth_adjusted() {
        // Regression: only href was depth-adjusted; root-relative <img src>
        // stayed absolute and 404'd on nested pages / subpath hosting
        let md = "![img](/assets/pic.png)\n\n[link](/api-docs/)\n";
        let html = render_markdown_with_path(md, Some("Guide/Sub/Page.md"), false);
        assert!(
            html.contains(r#"src="../../assets/pic.png""#),
            "src must be depth-adjusted: {}",
            html
        );
        assert!(
            html.contains(r#"href="../../api-docs/""#),
            "href behavior unchanged: {}",
            html
        );
    }

    #[test]
    fn test_page_relative_img_src_untouched() {
        // Page-relative image paths are correct as written — the bare-dir
        // conversion applied to href must NOT be applied to src
        let md = "![img](images/pic.png)\n";
        let html = render_markdown_with_path(md, Some("Guide/Sub/Page.md"), false);
        assert!(
            html.contains(r#"src="images/pic.png""#),
            "page-relative src must stay as written: {}",
            html
        );
    }

    #[test]
    fn test_remaining_markdown_image_escapes_quotes() {
        let html = r#"<div>![weather "sunny"](icon.png)</div>"#;
        let fixed = convert_remaining_markdown_images(html);
        assert!(
            fixed.contains(r#"alt="weather &quot;sunny&quot;""#),
            "quotes in alt must be escaped: {}",
            fixed
        );
    }

    #[test]
    fn test_href_like_text_outside_tag_not_rewritten() {
        // Raw HTML passes through markdown unescaped; href= appearing as
        // visible text (not inside a tag) must not be treated as a link
        let html = r#"<p>example: href="a.md" is the syntax. <a href="b.md">real</a></p>"#;
        let fixed = fix_relative_links(html);
        assert!(fixed.contains(r#"href="a.md" is the syntax"#), "{}", fixed);
        assert!(fixed.contains(r#"<a href="b.html">"#), "{}", fixed);
    }

    #[test]
    fn test_footnote_ref_in_inline_code_not_converted() {
        // Regression: the regex character class [^abc] inside inline code
        // was converted to a footnote reference
        let md = "正規表現 `[^abc]` は abc 以外にマッチする。[^1]\n\n[^1]: 実際の脚注\n";
        let html = render_markdown(md);
        assert!(
            html.contains("<code>[^abc]</code>"),
            "inline code must be untouched: {}",
            html
        );
        assert!(
            !html.contains("reffn_abc"),
            "no footnote must be generated from code: {}",
            html
        );
        // The real footnote reference still works
        assert!(html.contains("reffn_1"), "html: {}", html);
    }

    #[test]
    fn test_footnote_ref_in_fenced_code_not_converted() {
        let md = "```\nmatch = re.compile(r\"[^abc]\")\n```\n\n本文[^2]です。\n\n[^2]: 脚注\n";
        let html = render_markdown(md);
        assert!(
            !html.contains("reffn_abc"),
            "no footnote from fenced code: {}",
            html
        );
        assert!(
            html.contains("reffn_2"),
            "real footnote still works: {}",
            html
        );
    }
}

#[test]
fn test_footnote_in_table() {
    let md = r#"| Col1 | Col2 | Col3 |
|------|------|------|
| [A][^1] | data | end |

[A]: #link
[^1]: Footnote one
"#;
    let html = render_markdown(md);
    println!("HTML: {}", html);
    // Check that table cells are separate
    assert!(
        html.contains("<td>data</td>") || html.contains(">data<"),
        "data should be in its own cell: {}",
        html
    );
}

#[test]
fn test_reference_link_basic() {
    // Test basic reference link functionality
    let md = r#"[改定履歴][AL_RH]

[AL_RH]: #改訂履歴"#;
    let html = render_markdown(md);
    println!("Test 1 (basic with space): {}", html);
    assert!(
        html.contains("<a "),
        "Reference link should create anchor: {}",
        html
    );
}

#[test]
fn test_reference_link_no_space() {
    // Test reference link without space after colon (HonKit format)
    let md = r#"[改定履歴][AL_RH]

[AL_RH]:#改訂履歴"#;
    let html = render_markdown(md);
    println!("Test 2 (no space): {}", html);
    // This might fail - checking pulldown-cmark behavior
    assert!(
        html.contains("<a "),
        "Reference link without space should work: {}",
        html
    );
}

#[test]
fn test_reference_link_after_html_comment() {
    // Test reference link definition after HTML comment
    let md = r#"[改定履歴][AL_RH]

<!-- 目次 -->
[AL_RH]: #改訂履歴"#;
    let html = render_markdown(md);
    println!("Test 3 (after HTML comment): {}", html);
    assert!(
        html.contains("<a "),
        "Reference link after HTML comment should work: {}",
        html
    );
}

#[test]
fn test_reference_link_after_html_comment_with_blank_line() {
    // Test reference link definition after HTML comment with blank line
    let md = r#"[改定履歴][AL_RH]

<!-- 目次 -->

[AL_RH]: #改訂履歴"#;
    let html = render_markdown(md);
    println!("Test 4 (after HTML comment with blank line): {}", html);
    assert!(
        html.contains("<a "),
        "Reference link after HTML comment with blank line should work: {}",
        html
    );
}

#[test]
fn test_reference_link_with_bom() {
    // Test reference link with UTF-8 BOM at start of definitions
    // BOM is \xEF\xBB\xBF (357 273 277 in octal)
    let bom = "\u{FEFF}";
    let md = format!(
        r#"[改定履歴][AL_RH]

{}<!-- 目次 -->
[AL_RH]:#改訂履歴"#,
        bom
    );
    let html = render_markdown(&md);
    println!("Test 5 (with BOM): {}", html);
    assert!(
        html.contains("<a "),
        "Reference link with BOM should work: {}",
        html
    );
}

#[test]
fn test_footnote_with_list() {
    let content = "- データソース項目の値\n- 上記以外の場合";
    let html = render_footnote_continuation(content, false);
    println!("Footnote continuation HTML: {}", html);
    assert!(
        html.contains("<li>") && html.contains("<ul>"),
        "Should contain list: {}",
        html
    );
}

#[test]
fn test_full_reference_link_in_footnote() {
    // Test [text][ref] pattern in footnotes - the bug that was reported
    let md = r#"Text[^1].

[^1]: .paymentAvailableStatus=[未申込][決済方法申込状態]の場合: "銀行引落(登録)"

[決済方法申込状態]:#決済方法申込状態"#;
    let html = render_markdown(md);
    println!("Full reference link in footnote: {}", html);
    // The [未申込] should become a link with href="#決済方法申込状態"
    assert!(
        html.contains("<a href=\"#決済方法申込状態\">未申込</a>"),
        "Full reference link [text][ref] should be resolved: {}",
        html
    );
    // The text after should be preserved
    assert!(
        html.contains("の場合:"),
        "Text after reference link should be preserved: {}",
        html
    );
}

#[test]
fn test_resolve_reference_links_full_style() {
    // Direct test of resolve_reference_links function with [text][ref] pattern
    let mut refs = std::collections::HashMap::new();
    refs.insert(
        "決済方法申込状態".to_lowercase(),
        "#決済方法申込状態".to_string(),
    );

    let input = "[未申込][決済方法申込状態]の場合";
    let output = resolve_reference_links(input, &refs);
    println!("Resolved: {}", output);
    assert!(
        output.contains("<a href=\"#決済方法申込状態\">未申込</a>"),
        "Should resolve [text][ref]: {}",
        output
    );
    assert!(
        output.contains("の場合"),
        "Text after link should be preserved: {}",
        output
    );
}

#[test]
fn test_multilang_relative_links() {
    let md = "[Link](repositories/docs-path.md)";
    let current_path = "getting-started.md";
    let html = render_markdown_with_path(md, Some(current_path), false);
    println!("Result HTML: {}", html);

    // With the fix, it should NOT include "../" even if it contains a slash, because depth is 0
    assert!(
        !html.contains("../repositories/docs-path.html"),
        "Should not prepend ../ to relative links when depth is 0: {}",
        html
    );
    assert!(
        html.contains("href=\"repositories/docs-path.html\""),
        "Should preserve relative link: {}",
        html
    );
}