umd 0.1.0

Universal Markdown - A post-Markdown superset with Bootstrap 5 integration and extensible syntax
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
//! Syntax conflict resolution for UMD and Markdown
//!
//! This module coordinates the pre-processing and post-processing stages
//! to resolve conflicts between UMD and Markdown syntax.

use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use std::collections::HashMap;

use super::plugin_markers;
use super::preprocessor;

thread_local! {
    static MATH_CONVERTER: std::cell::RefCell<Option<math_core::LatexToMathML>> =
        std::cell::RefCell::new(
            math_core::LatexToMathML::new(math_core::MathCoreConfig::default()).ok()
        );
}

/// Escape HTML special characters
///
/// # Arguments
///
/// * `input` - Text to escape
///
/// # Returns
///
/// HTML-escaped string
fn escape_html_text(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Parse comma-separated args into a vector
///
/// # Arguments
///
/// * `args` - Comma-separated argument string
///
/// # Returns
///
/// Vector of trimmed argument strings
fn parse_args(args: &str) -> Vec<String> {
    if args.trim().is_empty() {
        return vec![];
    }
    args.split(',').map(|s| s.trim().to_string()).collect()
}

/// Render args as <data> elements
///
/// # Arguments
///
/// * `args` - Comma-separated argument string
///
/// # Returns
///
/// HTML string with <data value="index">arg</data> elements
fn render_args_as_data(args: &str) -> String {
    parse_args(args)
        .iter()
        .enumerate()
        .map(|(i, arg)| format!("<data value=\"{}\">{}</data>", i, escape_html_text(arg)))
        .collect::<Vec<_>>()
        .join("")
}

fn map_table_plugin_option_to_class(option: &str) -> Option<&'static str> {
    match option {
        "striped" => Some("table-striped"),
        "hover" => Some("table-hover"),
        "dark" => Some("table-dark"),
        "bordered" => Some("table-bordered"),
        "borderless" => Some("table-borderless"),
        "sm" => Some("table-sm"),
        _ => None,
    }
}

fn merge_class_attr(existing_attrs: &str, add_classes: &[String]) -> String {
    if add_classes.is_empty() {
        return existing_attrs.to_string();
    }

    let class_pattern = Regex::new(r#"class=\"([^\"]*)\""#).unwrap();

    if let Some(class_caps) = class_pattern.captures(existing_attrs) {
        let existing_classes = class_caps.get(1).map_or("", |m| m.as_str());
        let mut class_list: Vec<String> = existing_classes
            .split_whitespace()
            .map(|s| s.to_string())
            .collect();

        for class_name in add_classes {
            if !class_list.iter().any(|c| c == class_name) {
                class_list.push(class_name.clone());
            }
        }

        let merged = format!(r#"class=\"{}\""#, class_list.join(" "));
        class_pattern.replace(existing_attrs, merged).to_string()
    } else {
        let mut attrs = existing_attrs.to_string();
        attrs.push_str(&format!(r#" class=\"{}\""#, add_classes.join(" ")));
        attrs
    }
}

fn process_table_plugin(function_args: &str, content: &str) -> String {
    let rendered_content = crate::parse(content);

    let parsed_args = parse_args(function_args);
    let is_responsive = parsed_args.iter().any(|arg| arg == "responsive");
    let mut table_classes: Vec<String> = Vec::new();

    for arg in &parsed_args {
        if let Some(mapped_class) = map_table_plugin_option_to_class(arg) {
            if !table_classes.iter().any(|c| c == mapped_class) {
                table_classes.push(mapped_class.to_string());
            }
        }
    }

    let table_pattern = Regex::new(r"(?s)<table[^>]*>.*?</table>").unwrap();
    let open_table_pattern = Regex::new(r"<table([^>]*)>").unwrap();

    if let Some(table_match) = table_pattern.find(&rendered_content) {
        let table_html = table_match.as_str();

        let table_with_classes = open_table_pattern
            .replace(table_html, |caps: &Captures| {
                let existing_attrs = caps.get(1).map_or("", |m| m.as_str());
                let merged_attrs = merge_class_attr(existing_attrs, &table_classes);
                format!("<table{}>", merged_attrs)
            })
            .to_string();

        let processed_table = if is_responsive {
            format!(
                "<div class=\"table-responsive\">{}</div>",
                table_with_classes
            )
        } else {
            table_with_classes
        };

        format!(
            "{}{}{}",
            &rendered_content[..table_match.start()],
            processed_table,
            &rendered_content[table_match.end()..]
        )
    } else {
        eprintln!(
            "[UMD warning] @table plugin requires a table inside its content: {}",
            content.replace('\n', "\\n")
        );
        rendered_content
    }
}

/// Map font size value to Bootstrap class or inline style
fn map_font_size_value(value: &str) -> (bool, String) {
    // Check if value has unit (rem, em, px, etc.)
    if value.contains("rem") || value.contains("em") || value.contains("px") {
        return (false, value.to_string()); // Return as inline style
    }

    // Map to Bootstrap fs-* classes (unitless values)
    let class = match value {
        "2.5" => "fs-1",
        "2" | "2.0" => "fs-2",
        "1.75" => "fs-3",
        "1.5" => "fs-4",
        "1.25" => "fs-5",
        "0.875" => "fs-6",
        _ => return (false, format!("{}rem", value)), // Custom value as inline style
    };

    (true, class.to_string())
}

/// Map color value to Bootstrap class or inline style
fn map_color_value(value: &str, is_background: bool) -> Option<(bool, String)> {
    let trimmed = value.trim();

    // Bootstrap theme colors (14) + custom colors (10)
    let bootstrap_colors = [
        // Theme colors
        "primary",
        "secondary",
        "success",
        "danger",
        "warning",
        "info",
        "light",
        "dark",
        "body",
        "body-secondary",
        "body-tertiary",
        "body-emphasis",
        // Custom colors
        "blue",
        "indigo",
        "purple",
        "pink",
        "red",
        "orange",
        "yellow",
        "green",
        "teal",
        "cyan",
    ];

    let prefix = if is_background { "bg" } else { "text" };

    // Check if it's a Bootstrap color or variant
    for color in &bootstrap_colors {
        if trimmed == *color || trimmed.starts_with(&format!("{}-", color)) {
            return Some((true, format!("{}-{}", prefix, trimmed)));
        }
    }

    // Validate HEX color format (#RGB or #RRGGBB)
    // TODO: Future support for rgb() and hsl() formats
    if trimmed.starts_with('#') && (trimmed.len() == 4 || trimmed.len() == 7) {
        // Validate all characters after # are hex digits
        if trimmed[1..].chars().all(|c| c.is_ascii_hexdigit()) {
            return Some((false, trimmed.to_string()));
        }
    }

    // Invalid color - reject
    None
}

// Patterns that need special handling

/// Regex to detect UMD blockquote: > ... <
static UMD_BLOCKQUOTE: Lazy<Regex> = Lazy::new(|| {
    // Match single line > content < pattern
    Regex::new(r"(?m)^>\s*(.+?)\s*<\s*$").unwrap()
});

/// Regex to detect Markdown-style emphasis that might conflict with UMD
/// Detects ***text*** which could be confused with '''text'''
static TRIPLE_STAR_EMPHASIS: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\*\*\*([^*]+)\*\*\*").unwrap());

/// Regex to detect custom header ID syntax: # Header {#custom-id}
static CUSTOM_HEADER_ID: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?m)^(#{1,6})\s+(.+?)\s+\{#([a-zA-Z0-9_-]+)\}\s*$").unwrap());

/// Store custom header IDs and UMD tables during preprocessing
#[derive(Debug, Clone)]
pub struct HeaderIdMap {
    /// Maps heading number (1-based) to custom ID
    pub ids: HashMap<usize, String>,
    /// Maps table markers to HTML content
    pub tables: Vec<(String, String)>,
}

impl HeaderIdMap {
    pub fn new() -> Self {
        Self {
            ids: HashMap::new(),
            tables: Vec::new(),
        }
    }
}

/// Pre-process input to resolve conflicts before Markdown parsing
///
/// This function escapes or transforms syntax that would otherwise create
/// ambiguous parsing situations. It also extracts custom header IDs.
///
/// # Arguments
///
/// * `input` - The raw wiki markup input
///
/// # Returns
///
/// A tuple of (pre-processed markup, header ID map)
///
/// # Examples
///
/// ```
/// use umd::extensions::conflict_resolver::preprocess_conflicts;
///
/// let input = "> quote <";
/// let (output, _) = preprocess_conflicts(input);
/// // UMD blockquote is preserved
/// ```
pub fn preprocess_conflicts(input: &str) -> (String, HeaderIdMap) {
    // Step 1: Remove comments before any other processing
    let mut result = preprocessor::remove_comments(input);

    let mut header_map = HeaderIdMap::new();
    let mut heading_counter = 0;

    // Extract custom header IDs: # Header {#custom-id}
    result = CUSTOM_HEADER_ID
        .replace_all(&result, |caps: &Captures| {
            heading_counter += 1;
            let hashes = &caps[1];
            let title = &caps[2];
            let custom_id = &caps[3];

            // Store the custom ID for this heading
            header_map
                .ids
                .insert(heading_counter, custom_id.to_string());

            // Return the heading without the {#id} part
            format!("{} {}", hashes, title)
        })
        .to_string();

    // Handle UMD blockquotes: > ... <
    // Use a safe marker that won't be affected by HTML escaping
    result = UMD_BLOCKQUOTE
        .replace_all(&result, |caps: &Captures| {
            let content = &caps[1];
            format!("{{{{UMD_BLOCKQUOTE:{}:UMD_BLOCKQUOTE}}}}", content)
        })
        .to_string();

    // Protect UMD block decorations (COLOR, SIZE, TRUNCATE, alignment, vertical alignment)
    // These will be applied in post-processing.
    let block_decoration_prefix = Regex::new(
        r"(?m)^((?:(?:SIZE\([^)]+\)|COLOR\([^)]*\)|TRUNCATE|TOP|MIDDLE|BOTTOM|BASELINE|JUSTIFY|RIGHT|CENTER|LEFT):[ \t]*)+.*)$",
    )
    .unwrap();
    result = block_decoration_prefix
        .replace_all(&result, |caps: &Captures| {
            use base64::{Engine as _, engine::general_purpose};
            let encoded = general_purpose::STANDARD.encode(caps[1].as_bytes());
            format!(
                "{{{{BLOCK_DECORATION_B64:{}:BLOCK_DECORATION_B64}}}}",
                encoded
            )
        })
        .to_string();

    // Protect inline and block plugin syntax
    result = plugin_markers::protect_inline_plugins(&result);
    result = plugin_markers::protect_block_plugins(&result);

    // Extract and protect UMD tables (before definition lists)
    let (result, table_map) = crate::extensions::table::umd::extract_umd_tables(&result);
    header_map.tables = table_map;

    // Process definition lists: :term|definition
    let result = preprocessor::process_definition_lists(&result);

    (result, header_map)
}

/// Convert inline decoration function to HTML
/// Returns None if not a decoration function
fn convert_inline_decoration_to_html(function: &str, args: &str, content: &str) -> Option<String> {
    match function {
        // Simple wrapper tags without content
        "dfn" => Some(format!("<dfn>{}</dfn>", content)),
        "kbd" => Some(format!("<kbd>{}</kbd>", content)),
        "samp" => Some(format!("<samp>{}</samp>", content)),
        "var" => Some(format!("<var>{}</var>", content)),
        "cite" => Some(format!("<cite>{}</cite>", content)),
        "q" => Some(format!("<q>{}</q>", content)),
        "small" => Some(format!("<small>{}</small>", content)),
        "u" => Some(format!("<u>{}</u>", content)),
        "bdi" => Some(format!("<bdi>{}</bdi>", content)),

        // Tags with attributes
        "ruby" => {
            // &ruby(reading){text}; → <ruby>text<rp>(</rp><rt>reading</rt><rp>)</rp></ruby>
            Some(format!(
                "<ruby>{}<rp>(</rp><rt>{}</rt><rp>)</rp></ruby>",
                content, args
            ))
        }
        "time" => {
            // &time(datetime){text}; → <time datetime="datetime">text</time>
            Some(format!("<time datetime=\"{}\">{}</time>", args, content))
        }
        "data" => {
            // &data(value){text}; → <data value="value">text</data>
            Some(format!("<data value=\"{}\">{}</data>", args, content))
        }
        "bdo" => {
            // &bdo(dir){text}; → <bdo dir="dir">text</bdo>
            Some(format!("<bdo dir=\"{}\">{}</bdo>", args, content))
        }
        "lang" => {
            // &lang(locale){text}; → <span lang="locale">text</span>
            Some(format!("<span lang=\"{}\">{}</span>", args, content))
        }
        "abbr" => {
            // &abbr(text){description}; → <abbr title="description">text</abbr>
            Some(format!("<abbr title=\"{}\">{}</abbr>", content, args))
        }
        "sup" => {
            // &sup(text); → <sup>text</sup>
            Some(format!("<sup>{}</sup>", args))
        }
        "sub" => {
            // &sub(text); → <sub>text</sub>
            Some(format!("<sub>{}</sub>", args))
        }
        "badge" => {
            // &badge(type){content}; → <span class="badge bg-type">content</span>
            // Support for badge-pill variants and links
            let badge_class = if args.ends_with("-pill") {
                let color = args.trim_end_matches("-pill");
                format!("badge rounded-pill bg-{}", color)
            } else {
                format!("badge bg-{}", args)
            };

            // Check if content contains a Markdown link: [text](url)
            let link_regex = Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap();
            if let Some(link_caps) = link_regex.captures(content) {
                let text = link_caps.get(1).map_or("", |m| m.as_str());
                let url = link_caps.get(2).map_or("", |m| m.as_str());
                Some(format!(
                    "<a href=\"{}\" class=\"{}\">{}</a>",
                    url, badge_class, text
                ))
            } else {
                Some(format!(
                    "<span class=\"{}\">{}</span>",
                    badge_class, content
                ))
            }
        }
        "color" => {
            // &color(fg,bg){text}; with Bootstrap support
            let parts: Vec<&str> = args.split(',').collect();
            let fg = parts.get(0).map_or("", |m| m.trim());
            let bg = parts.get(1).map_or("", |m| m.trim());

            let mut classes = Vec::new();
            let mut styles = Vec::new();

            if !fg.is_empty() && fg != "inherit" {
                if let Some((is_class, value)) = map_color_value(fg, false) {
                    if is_class {
                        classes.push(value);
                    } else {
                        styles.push(format!("color: {}", value));
                    }
                }
            }

            if !bg.is_empty() && bg != "inherit" {
                if let Some((is_class, value)) = map_color_value(bg, true) {
                    if is_class {
                        classes.push(value);
                    } else {
                        styles.push(format!("background-color: {}", value));
                    }
                }
            }

            if classes.is_empty() && styles.is_empty() {
                Some(content.to_string())
            } else {
                let mut attrs = Vec::new();
                if !classes.is_empty() {
                    attrs.push(format!("class=\"{}\"", classes.join(" ")));
                }
                if !styles.is_empty() {
                    attrs.push(format!("style=\"{}\"", styles.join("; ")));
                }
                Some(format!("<span {}>{}</span>", attrs.join(" "), content))
            }
        }
        "size" => {
            // &size(value){text}; with Bootstrap support
            let (is_class, value) = map_font_size_value(args);
            if is_class {
                Some(format!("<span class=\"{}\">{}</span>", value, content))
            } else {
                Some(format!(
                    "<span style=\"font-size: {}\">{}</span>",
                    value, content
                ))
            }
        }
        _ => None,
    }
}

/// Convert args-only inline decoration function to HTML
fn convert_inline_decoration_argsonly_to_html(function: &str, args: &str) -> Option<String> {
    match function {
        "sup" => Some(format!("<sup>{}</sup>", args)),
        "sub" => Some(format!("<sub>{}</sub>", args)),
        "math" => render_math_html(args, false),
        _ => None,
    }
}

/// Convert no-args inline decoration function to HTML
fn convert_inline_decoration_noargs_to_html(function: &str) -> Option<String> {
    match function {
        "wbr" => Some("<wbr />".to_string()),
        "br" => Some("<br />".to_string()),
        _ => None,
    }
}

fn render_math_html(formula: &str, block_display: bool) -> Option<String> {
    let formula = formula.trim();
    if formula.is_empty() {
        return None;
    }

    let display = if block_display {
        math_core::MathDisplay::Block
    } else {
        math_core::MathDisplay::Inline
    };

    let converted = MATH_CONVERTER.with(|converter_cell| {
        let mut converter = converter_cell.borrow_mut();
        converter
            .as_mut()
            .and_then(|converter| converter.convert_with_local_counter(formula, display).ok())
    });

    match converted {
        Some(mathml) => Some(mathml),
        None => Some(format!(
            "<span class=\"umd-math-error\" data-math-source=\"{}\">{}</span>",
            escape_html_text(formula),
            escape_html_text(formula)
        )),
    }
}

fn render_popover_html(trigger_text: &str, raw_content: &str) -> String {
    let popover_id = format!("umd-popover-{}", uuid::Uuid::new_v4().simple());
    let content_html = crate::parse(raw_content);
    format!(
        "<button command=\"show-popover\" commandfor=\"{}\">{}</button><div id=\"{}\" popover>{}</div>",
        popover_id,
        escape_html_text(trigger_text.trim()),
        popover_id,
        content_html
    )
}

fn is_valid_link_attr_token(token: &str) -> bool {
    !token.is_empty()
        && token
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
}

fn parse_link_attribute_spec(spec: &str) -> (Option<String>, Vec<String>) {
    let mut id = None;
    let mut classes = Vec::new();

    for raw_token in spec.split_whitespace() {
        let token = raw_token.trim();
        if token.is_empty() {
            continue;
        }

        if let Some(stripped) = token.strip_prefix('#') {
            if is_valid_link_attr_token(stripped) {
                id = Some(stripped.to_string());
            }
            continue;
        }

        if let Some(stripped) = token.strip_prefix('.') {
            if is_valid_link_attr_token(stripped) {
                classes.push(stripped.to_string());
            }
            continue;
        }

        if id.is_none() {
            if is_valid_link_attr_token(token) {
                id = Some(token.to_string());
            }
        } else if is_valid_link_attr_token(token) {
            classes.push(token.to_string());
        }
    }

    (id, classes)
}

fn apply_custom_link_attributes(html: &str) -> String {
    let link_pattern =
        Regex::new(r#"(?s)<a\s+([^>]*\bhref=\"[^\"]+\"[^>]*)>(.*?)</a>\s*\{([^}]+)\}"#).unwrap();
    let class_pattern = Regex::new(r#"class=\"([^\"]*)\""#).unwrap();
    let id_pattern = Regex::new(r#"\bid=\"[^\"]*\""#).unwrap();

    link_pattern
        .replace_all(html, |caps: &Captures| {
            let mut attrs = caps[1].to_string();
            let content = &caps[2];
            let spec = &caps[3];

            let (id, classes) = parse_link_attribute_spec(spec);

            if let Some(id_value) = id {
                if !id_pattern.is_match(&attrs) {
                    attrs.push_str(&format!(" id=\"{}\"", id_value));
                }
            }

            if !classes.is_empty() {
                if let Some(class_caps) = class_pattern.captures(&attrs) {
                    let existing = class_caps.get(1).map_or("", |m| m.as_str());
                    let mut class_list: Vec<String> =
                        existing.split_whitespace().map(|s| s.to_string()).collect();
                    for class_name in classes {
                        if !class_list.iter().any(|c| c == &class_name) {
                            class_list.push(class_name);
                        }
                    }
                    let merged = class_list.join(" ");
                    attrs = class_pattern
                        .replace(&attrs, format!("class=\"{}\"", merged))
                        .to_string();
                } else {
                    attrs.push_str(&format!(" class=\"{}\"", classes.join(" ")));
                }
            }

            format!("<a {}>{}</a>", attrs, content)
        })
        .to_string()
}

pub fn postprocess_conflicts(html: &str, header_map: &HeaderIdMap) -> String {
    use crate::extensions::block_decorations;

    // First, unescape quotes within markers to allow proper JSON parsing
    // comrak escapes quotes in JSON within markers, so we need to restore them
    // but ONLY within marker boundaries to avoid XSS
    let result = html.to_string();

    // Helper function to unescape quotes only within markers
    let unescape_marker_quotes = |input: &str| -> String {
        let marker_patterns = vec![
            (
                r"\{\{DEFINITION_LIST:([^\}]+):DEFINITION_LIST\}\}",
                "{{DEFINITION_LIST:",
            ),
            (
                r"\{\{INLINE_PLUGIN:([^\}]+):INLINE_PLUGIN\}\}",
                "{{INLINE_PLUGIN:",
            ),
            (
                r"\{\{BLOCK_PLUGIN:([^\}]+):BLOCK_PLUGIN\}\}",
                "{{BLOCK_PLUGIN:",
            ),
            (
                r"\{\{BLOCK_PLUGIN_ARGSONLY:([^\}]+):BLOCK_PLUGIN_ARGSONLY\}\}",
                "{{BLOCK_PLUGIN_ARGSONLY:",
            ),
            (
                r"\{\{INLINE_PLUGIN_ARGSONLY:([^\}]+):INLINE_PLUGIN_ARGSONLY\}\}",
                "{{INLINE_PLUGIN_ARGSONLY:",
            ),
            (
                r"\{\{INLINE_PLUGIN_NOARGS:([^\}]+):INLINE_PLUGIN_NOARGS\}\}",
                "{{INLINE_PLUGIN_NOARGS:",
            ),
        ];

        let mut result = input.to_string();
        for (pattern, _marker_start) in marker_patterns {
            let re = Regex::new(pattern).unwrap();
            result = re
                .replace_all(&result, |caps: &Captures| {
                    let content = &caps[0];
                    content.replace("&quot;", "\"")
                })
                .to_string();
        }
        result
    };

    let mut result = unescape_marker_quotes(&result);

    // Add header IDs: <h1>Title</h1> -> <h1><a href="#id" id="id"></a>Title</h1>
    let mut heading_counter = 0;
    let header_regex = Regex::new(r"<h([1-6])>([^<]+)</h([1-6])>").unwrap();
    result = header_regex
        .replace_all(&result, |caps: &Captures| {
            heading_counter += 1;
            let level = &caps[1];
            let title = &caps[2];
            let close_level = &caps[3];

            let id = if let Some(custom_id) = header_map.ids.get(&heading_counter) {
                // Add 'h-' prefix to custom IDs to avoid conflicts with system IDs
                format!("h-{}", custom_id)
            } else {
                // Auto-numbered IDs also use 'h-' prefix for consistency
                format!("h-{}", heading_counter)
            };

            format!(
                "<h{}><a href=\"#{}\" aria-hidden=\"true\" class=\"anchor\" id=\"{}\"></a>{}</h{}>",
                level, id, id, title, close_level
            )
        })
        .to_string();

    // Restore UMD blockquotes
    let umd_blockquote_marker = Regex::new(r"\{\{UMD_BLOCKQUOTE:(.+?):UMD_BLOCKQUOTE\}\}").unwrap();

    result = umd_blockquote_marker
        .replace_all(&result, |caps: &Captures| {
            let content = &caps[1];
            format!(
                "<blockquote class=\"umd-blockquote\">{}</blockquote>",
                content
            )
        })
        .to_string();

    // Restore and apply block decorations
    let block_decoration_marker =
        Regex::new(r"\{\{BLOCK_DECORATION_B64:([A-Za-z0-9+/=]+):BLOCK_DECORATION_B64\}\}").unwrap();

    result = block_decoration_marker
        .replace_all(&result, |caps: &Captures| {
            use base64::{Engine as _, engine::general_purpose};
            let encoded = &caps[1];
            let decoration = general_purpose::STANDARD
                .decode(encoded.as_bytes())
                .ok()
                .and_then(|bytes| String::from_utf8(bytes).ok())
                .unwrap_or_else(|| encoded.to_string());
            // Multiline decorations (e.g., RIGHT:\n<media>) and standalone block placement
            // prefixes are handled later by apply_block_placement.
            let placement_only = Regex::new(r"^(LEFT|CENTER|RIGHT|JUSTIFY):\s*$")
                .unwrap()
                .is_match(decoration.trim());

            if decoration.contains('\n') || placement_only {
                decoration
            } else {
                block_decorations::apply_block_decorations(&decoration)
            }
        })
        .to_string();

    // Restore inline plugins
    let inline_plugin_marker =
        Regex::new(r"\{\{INLINE_PLUGIN:(\w+):([\s\S]*?):([\s\S]*?):INLINE_PLUGIN\}\}").unwrap();
    result = inline_plugin_marker
        .replace_all(&result, |caps: &Captures| {
            use base64::{Engine as _, engine::general_purpose};
            let function = &caps[1];
            let args = &caps[2];
            let encoded_content = &caps[3];

            // Decode base64 to get original content
            let content = general_purpose::STANDARD
                .decode(encoded_content.as_bytes())
                .ok()
                .and_then(|bytes| String::from_utf8(bytes).ok())
                .unwrap_or_else(|| encoded_content.to_string());

            if function == "math" {
                let formula = if content.trim().is_empty() {
                    args
                } else {
                    &content
                };
                if let Some(mathml) = render_math_html(formula, false) {
                    return mathml;
                }
            }

            if function == "popover" {
                return render_popover_html(args, &content);
            }

            // Try to convert as inline decoration function
            if let Some(html) = convert_inline_decoration_to_html(function, args, &content) {
                return html;
            }

            // Otherwise, convert to plugin <template>
            let args_html = render_args_as_data(args);
            let escaped_content = escape_html_text(&content);

            if escaped_content.is_empty() {
                format!(
                    "<template class=\"umd-plugin umd-plugin-{}\">{}</template>",
                    function, args_html
                )
            } else {
                format!(
                    "<template class=\"umd-plugin umd-plugin-{}\">{}{}</template>",
                    function, args_html, escaped_content
                )
            }
        })
        .to_string();

    // Restore inline plugins (args only)
    let inline_plugin_argsonly_marker =
        Regex::new(r"\{\{INLINE_PLUGIN_ARGSONLY:(\w+):([\s\S]*?):INLINE_PLUGIN_ARGSONLY\}\}")
            .unwrap();
    result = inline_plugin_argsonly_marker
        .replace_all(&result, |caps: &Captures| {
            let function = &caps[1];
            let args = &caps[2];

            // Try to convert as inline decoration function
            if let Some(html) = convert_inline_decoration_argsonly_to_html(function, args) {
                return html;
            }

            // Otherwise, convert to plugin <template>
            let args_html = render_args_as_data(args);
            format!(
                "<template class=\"umd-plugin umd-plugin-{}\">{}</template>",
                function, args_html
            )
        })
        .to_string();

    // Restore inline plugins (no args)
    let inline_plugin_noargs_marker =
        Regex::new(r"\{\{INLINE_PLUGIN_NOARGS:(\w+):INLINE_PLUGIN_NOARGS\}\}").unwrap();
    result = inline_plugin_noargs_marker
        .replace_all(&result, |caps: &Captures| {
            let function = &caps[1];

            // Try to convert as inline decoration function
            if let Some(html) = convert_inline_decoration_noargs_to_html(function) {
                return html;
            }

            // Otherwise, convert to plugin <template>
            format!(
                "<template class=\"umd-plugin umd-plugin-{}\"></template>",
                function
            )
        })
        .to_string();

    // Restore block plugins
    let block_plugin_marker =
        Regex::new(r"\{\{BLOCK_PLUGIN:(\w+):([\s\S]*?):([\s\S]*?):BLOCK_PLUGIN\}\}").unwrap();
    result = block_plugin_marker
        .replace_all(&result, |caps: &Captures| {
            use base64::{Engine as _, engine::general_purpose};
            let function = &caps[1];
            let args = &caps[2];
            let encoded_content = &caps[3];

            // Decode base64 to get original content
            let content = general_purpose::STANDARD
                .decode(encoded_content.as_bytes())
                .ok()
                .and_then(|bytes| String::from_utf8(bytes).ok())
                .unwrap_or_else(|| encoded_content.to_string());

            if function == "table" {
                return process_table_plugin(args, &content);
            }

            if function == "math" {
                let formula = if content.trim().is_empty() {
                    args
                } else {
                    &content
                };
                if let Some(mathml) = render_math_html(formula, true) {
                    return mathml;
                }
            }

            if function == "popover" {
                return render_popover_html(args, &content);
            }

            let args_html = render_args_as_data(args);
            let escaped_content = escape_html_text(&content);

            if escaped_content.is_empty() {
                format!(
                    "<template class=\"umd-plugin umd-plugin-{}\">{}</template>",
                    function, args_html
                )
            } else {
                format!(
                    "<template class=\"umd-plugin umd-plugin-{}\">{}{}</template>",
                    function, args_html, escaped_content
                )
            }
        })
        .to_string();

    // Restore block plugins (args only, no content)
    let block_plugin_argsonly_marker =
        Regex::new(r"\{\{BLOCK_PLUGIN_ARGSONLY:(\w+):([\s\S]*?):BLOCK_PLUGIN_ARGSONLY\}\}")
            .unwrap();
    result = block_plugin_argsonly_marker
        .replace_all(&result, |caps: &Captures| {
            use base64::{Engine as _, engine::general_purpose};
            let function = &caps[1];
            let encoded_args = &caps[2];

            // Decode base64 to get original args
            let args = general_purpose::STANDARD
                .decode(encoded_args.as_bytes())
                .ok()
                .and_then(|bytes| String::from_utf8(bytes).ok())
                .unwrap_or_else(|| encoded_args.to_string());

            if function == "clear" && args.trim().is_empty() {
                return "<div class=\"clearfix\"></div>".to_string();
            }

            if function == "math" {
                if let Some(mathml) = render_math_html(&args, true) {
                    return mathml;
                }
            }

            let args_html = render_args_as_data(&args);
            format!(
                "<template class=\"umd-plugin umd-plugin-{}\">{}</template>",
                function, args_html
            )
        })
        .to_string();

    // Remove wrapping <p> tags around template plugins
    let wrapped_plugin =
        Regex::new(r#"<p>\s*(<template class="umd-plugin[^"]*"[^>]*>.*?</template>)\s*</p>"#)
            .unwrap();
    result = wrapped_plugin.replace_all(&result, "$1").to_string();

    // Remove wrapping <p> tags around clearfix blocks
    let wrapped_clearfix = Regex::new(r#"<p>\s*(<div class="clearfix"></div>)\s*</p>"#).unwrap();
    result = wrapped_clearfix.replace_all(&result, "$1").to_string();

    // Restore definition lists
    let definition_list_marker =
        Regex::new(r"\{\{DEFINITION_LIST:([\s\S]*?):DEFINITION_LIST\}\}").unwrap();
    result = definition_list_marker
        .replace_all(&result, |caps: &Captures| {
            let items_json = &caps[1];

            // Parse JSON to get items
            let items: Vec<(String, String)> = serde_json::from_str(items_json).unwrap_or_default();

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

            let mut dl_html = String::from("<dl>");
            for (term, definition) in items {
                dl_html.push_str(&format!("<dt>{}</dt><dd>{}</dd>", term, definition));
            }
            dl_html.push_str("</dl>");
            dl_html
        })
        .to_string();

    // Remove wrapping <p> tags around definition lists
    let wrapped_dl = Regex::new(r"<p>\s*(<dl>.*?</dl>)\s*</p>").unwrap();
    result = wrapped_dl.replace_all(&result, "$1").to_string();

    // Apply custom link attributes: [text](url){id class}
    result = apply_custom_link_attributes(&result);

    // Apply indeterminate task list markers before other HTML transforms
    result = apply_tasklist_indeterminate(&result);

    // Apply Bootstrap default classes, GFM alerts, and table cell alignment
    result = apply_bootstrap_enhancements(&result, &header_map);

    result
}

/// Apply indeterminate task list state to rendered checkboxes.
fn apply_tasklist_indeterminate(html: &str) -> String {
    let pattern =
        Regex::new(r#"<input([^>]*\btype=\"checkbox\"[^>]*)/?>\s*\{\{TASK_INDETERMINATE\}\}"#)
            .unwrap();

    pattern
        .replace_all(html, |caps: &Captures| {
            let mut attrs = caps[1].to_string();
            if !attrs.contains("data-task=") {
                attrs.push_str(" data-task=\"indeterminate\"");
            }
            if !attrs.contains("aria-checked=") {
                attrs.push_str(" aria-checked=\"mixed\"");
            }
            format!("<input{} />", attrs)
        })
        .to_string()
}

/// Apply Bootstrap 5 enhancements to HTML
///
/// - Add default `table` class to all <table> elements
/// - Add default `blockquote` class to all <blockquote> elements (except UMD-style)
/// - Convert GFM alerts ([!NOTE], etc.) to Bootstrap alert components
/// - Add JUSTIFY support for tables (w-100 class)
fn apply_bootstrap_enhancements(html: &str, header_map: &HeaderIdMap) -> String {
    let mut result = html.to_string();

    // Add default class to tables
    let table_pattern = Regex::new(r"<table>").unwrap();
    result = table_pattern
        .replace_all(&result, "<table class=\"table\">")
        .to_string();

    // Add default class to blockquotes (check if it doesn't already have class="umd-blockquote")
    let blockquote_pattern = Regex::new(r#"<blockquote>"#).unwrap();
    result = blockquote_pattern
        .replace_all(&result, "<blockquote class=\"blockquote\">")
        .to_string();

    // UMD blockquotes already have class="umd-blockquote", so they remain unchanged

    // Handle GFM alerts: > [!NOTE] etc.
    // These are rendered as <blockquote class="blockquote"><p>[!NOTE] ...</p></blockquote>
    let gfm_alert_pattern = Regex::new(
        r#"<blockquote class="blockquote">\s*<p>\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*?)</p>\s*</blockquote>"#
    ).unwrap();

    result = gfm_alert_pattern
        .replace_all(&result, |caps: &Captures| {
            let alert_type = &caps[1];
            let content = &caps[2];

            let (alert_class, icon_text) = match alert_type {
                "NOTE" => ("alert-info", "Note"),
                "TIP" => ("alert-success", "Tip"),
                "IMPORTANT" => ("alert-primary", "Important"),
                "WARNING" => ("alert-warning", "Warning"),
                "CAUTION" => ("alert-danger", "Caution"),
                _ => ("alert-info", "Note"),
            };

            format!(
                "<div class=\"alert {}\" role=\"alert\"><strong>{}:</strong> {}</div>",
                alert_class, icon_text, content
            )
        })
        .to_string();

    // Restore UMD tables
    // comrak wraps markers in <p> tags and strips newlines
    for (marker, html) in &header_map.tables {
        let marker_text = marker.trim();
        let comrak_marker = format!("<p>{}</p>", marker_text);
        result = result.replace(&comrak_marker, html);
    }

    // Process table cell vertical alignment prefixes (for GFM tables only)
    result = process_table_cell_alignment(&result);

    result
}

/// Process table cell alignment prefixes (TOP:, MIDDLE:, BOTTOM:, BASELINE:)
///
/// Detects alignment prefixes in table cells and adds Bootstrap alignment classes.
/// Note: GFM tables are handled by comrak without extensions.
/// UMD tables have their own cell spanning and decoration support.
fn process_table_cell_alignment(html: &str) -> String {
    let mut result = html.to_string();

    // Process <td> tags
    let td_pattern = Regex::new(r"<td([^>]*)>(.*?)</td>").unwrap();
    result = td_pattern
        .replace_all(&result, |caps: &Captures| {
            let existing_attrs = &caps[1];
            let content = &caps[2];
            process_cell_content("td", existing_attrs, content)
        })
        .to_string();

    // Process <th> tags
    let th_pattern = Regex::new(r"<th([^>]*)>(.*?)</th>").unwrap();
    result = th_pattern
        .replace_all(&result, |caps: &Captures| {
            let existing_attrs = &caps[1];
            let content = &caps[2];
            process_cell_content("th", existing_attrs, content)
        })
        .to_string();

    result
}

/// Process individual cell content for alignment
fn process_cell_content(tag: &str, existing_attrs: &str, content: &str) -> String {
    // Check for vertical alignment prefixes
    let (align_class, remaining_content) =
        if let Some(stripped) = content.trim_start().strip_prefix("TOP:") {
            ("align-top", stripped.trim_start())
        } else if let Some(stripped) = content.trim_start().strip_prefix("MIDDLE:") {
            ("align-middle", stripped.trim_start())
        } else if let Some(stripped) = content.trim_start().strip_prefix("BOTTOM:") {
            ("align-bottom", stripped.trim_start())
        } else if let Some(stripped) = content.trim_start().strip_prefix("BASELINE:") {
            ("align-baseline", stripped.trim_start())
        } else {
            ("", content)
        };

    if align_class.is_empty() {
        // No alignment prefix, return original
        format!("<{}{}>{}</{}>", tag, existing_attrs, content, tag)
    } else {
        // Add alignment class
        if existing_attrs.contains("class=") {
            // Append to existing class attribute
            let new_attrs =
                existing_attrs.replace("class=\"", &format!("class=\"{} ", align_class));
            format!("<{}{}>{}</{}>", tag, new_attrs, remaining_content, tag)
        } else {
            // Add new class attribute
            format!(
                "<{} class=\"{}\"{}>{}</{}>",
                tag, align_class, existing_attrs, remaining_content, tag
            )
        }
    }
}

/// Check if input contains potentially ambiguous syntax
///
/// Used for diagnostics and warnings. Returns descriptions of
/// detected conflicts.
///
/// # Arguments
///
/// * `input` - The raw wiki markup input
///
/// # Returns
///
/// Vector of warning messages for ambiguous patterns
pub fn detect_ambiguous_syntax(input: &str) -> Vec<String> {
    let mut warnings = Vec::new();

    // Check for ***text*** which could be confused with '''text'''
    if TRIPLE_STAR_EMPHASIS.is_match(input) && input.contains("'''") {
        warnings.push(
            "Detected both ***text*** (Markdown) and '''text''' (UMD). \
             Consider using **text** for Markdown bold-italic."
                .to_string(),
        );
    }

    // Check for potential COLOR(): vs Markdown definition list conflict
    if input.contains("COLOR(") && input.contains("\n:") {
        warnings.push(
            "Detected COLOR() syntax near Markdown definition list. \
             Ensure proper spacing to avoid ambiguity."
                .to_string(),
        );
    }

    warnings
}

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

    #[test]
    fn test_umd_blockquote_preprocessing() {
        let input = "> This is a UMD quote <";
        let (output, _) = preprocess_conflicts(input);
        assert!(output.contains("{{UMD_BLOCKQUOTE:"));
        assert!(!output.starts_with(">"));
    }

    #[test]
    fn test_umd_blockquote_postprocessing() {
        let header_map = HeaderIdMap::new();
        let input = "{{UMD_BLOCKQUOTE:Test content:UMD_BLOCKQUOTE}}";
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains("<blockquote class=\"umd-blockquote\">Test content</blockquote>"));
    }

    #[test]
    fn test_markdown_blockquote_unchanged() {
        let input = "> Standard Markdown quote\n> Second line";
        let (output, _) = preprocess_conflicts(input);
        // Should NOT be converted (no closing <)
        assert_eq!(output, input);
    }

    #[test]
    fn test_roundtrip_blockquote() {
        let header_map = HeaderIdMap::new();
        let input = "> UMD style <";
        let (preprocessed, _) = preprocess_conflicts(input);
        let postprocessed = postprocess_conflicts(&preprocessed, &header_map);
        assert!(postprocessed.contains("<blockquote class=\"umd-blockquote\">"));
    }

    #[test]
    fn test_custom_header_id() {
        let input = "# My Header {#custom-id}\n\nContent";
        let (output, header_map) = preprocess_conflicts(input);
        // Should extract the custom ID
        assert_eq!(header_map.ids.get(&1), Some(&"custom-id".to_string()));
        // Should remove {#custom-id} from the text
        assert!(!output.contains("{#custom-id}"));
        assert!(output.contains("# My Header"));
    }

    #[test]
    fn test_multiple_custom_header_ids() {
        let input = "# First {#first}\n\n## Second {#second}\n\n### Third";
        let (_output, header_map) = preprocess_conflicts(input);
        assert_eq!(header_map.ids.get(&1), Some(&"first".to_string()));
        assert_eq!(header_map.ids.get(&2), Some(&"second".to_string()));
        assert_eq!(header_map.ids.get(&3), None); // No custom ID for third
    }

    #[test]
    fn test_apply_custom_header_ids() {
        let mut header_map = HeaderIdMap::new();
        header_map.ids.insert(1, "my-custom-id".to_string());

        let html = "<h1>Header</h1>";
        let output = postprocess_conflicts(html, &header_map);

        assert!(output.contains("id=\"h-my-custom-id\""));
        assert!(output.contains("href=\"#h-my-custom-id\""));
        assert!(!output.contains("heading-1"));
    }

    #[test]
    fn test_sequential_header_ids() {
        let header_map = HeaderIdMap::new();
        let html = "<h1>First</h1><h2>Second</h2>";
        let output = postprocess_conflicts(html, &header_map);

        assert!(output.contains("id=\"h-1\""));
        assert!(output.contains("id=\"h-2\""));
    }

    #[test]
    fn test_detect_triple_emphasis_conflict() {
        let input = "***Markdown*** and '''UMD'''";
        let warnings = detect_ambiguous_syntax(input);
        assert!(!warnings.is_empty());
        assert!(warnings[0].contains("***text***"));
    }

    #[test]
    fn test_detect_color_definition_conflict() {
        let input = "COLOR(red): text\n: definition";
        let warnings = detect_ambiguous_syntax(input);
        assert!(!warnings.is_empty());
        assert!(warnings[0].contains("COLOR()"));
    }

    #[test]
    fn test_no_warnings_for_clean_syntax() {
        let input = "# Heading\n\n**Bold** and ''UMD bold''";
        let warnings = detect_ambiguous_syntax(input);
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_bootstrap_table_class() {
        let header_map = HeaderIdMap::new();
        let input = "<table><tr><td>Cell</td></tr></table>";
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"<table class="table">"#));
    }

    #[test]
    fn test_bootstrap_blockquote_class() {
        let header_map = HeaderIdMap::new();
        let input = "<blockquote><p>Quote</p></blockquote>";
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"<blockquote class="blockquote">"#));
    }

    #[test]
    fn test_gfm_alert_note() {
        let header_map = HeaderIdMap::new();
        let input = r#"<blockquote class="blockquote"><p>[!NOTE] This is a note</p></blockquote>"#;
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"<div class="alert alert-info" role="alert">"#));
        assert!(output.contains("<strong>Note:</strong>"));
        assert!(output.contains("This is a note"));
    }

    #[test]
    fn test_gfm_alert_warning() {
        let header_map = HeaderIdMap::new();
        let input = r#"<blockquote class="blockquote"><p>[!WARNING] Be careful</p></blockquote>"#;
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"<div class="alert alert-warning" role="alert">"#));
        assert!(output.contains("<strong>Warning:</strong>"));
    }

    #[test]
    fn test_umd_blockquote_no_bootstrap_class() {
        let header_map = HeaderIdMap::new();
        let input = "{{UMD_BLOCKQUOTE:Test content:UMD_BLOCKQUOTE}}";
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"<blockquote class="umd-blockquote">"#));
        assert!(!output.contains(r#"class="blockquote""#));
    }

    #[test]
    fn test_definition_list() {
        let input = ":Term 1|Definition 1\n:Term 2|Definition 2";
        let (preprocessed, _) = preprocess_conflicts(input);
        assert!(preprocessed.contains("{{DEFINITION_LIST:"));
    }

    #[test]
    fn test_definition_list_html_output() {
        let header_map = HeaderIdMap::new();
        let input = ":HTML|HyperText Markup Language\n:CSS|Cascading Style Sheets";
        let (preprocessed, _) = preprocess_conflicts(input);
        let output = postprocess_conflicts(&preprocessed, &header_map);
        assert!(output.contains("<dl>"));
        assert!(output.contains("<dt>HTML</dt>"));
        assert!(output.contains("<dd>HyperText Markup Language</dd>"));
        assert!(output.contains("<dt>CSS</dt>"));
        assert!(output.contains("<dd>Cascading Style Sheets</dd>"));
        assert!(output.contains("</dl>"));
    }

    #[test]
    fn test_table_cell_vertical_alignment() {
        let header_map = HeaderIdMap::new();
        let input =
            r#"<table class="table"><tr><td>TOP: Cell1</td><td>MIDDLE: Cell2</td></tr></table>"#;
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"class="align-top""#));
        assert!(output.contains("Cell1"));
        assert!(output.contains(r#"class="align-middle""#));
        assert!(output.contains("Cell2"));
    }

    #[test]
    fn test_table_cell_multiple_alignments() {
        let header_map = HeaderIdMap::new();
        let input = r#"<table><tr><th>BASELINE: Header</th><td>BOTTOM: Data</td></tr></table>"#;
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"class="align-baseline""#));
        assert!(output.contains(r#"class="align-bottom""#));
    }

    #[test]
    fn test_tasklist_indeterminate_marker() {
        let header_map = HeaderIdMap::new();
        let input = r#"<li><input type="checkbox" disabled="" /> {{TASK_INDETERMINATE}}Item</li>"#;
        let output = postprocess_conflicts(input, &header_map);
        assert!(output.contains(r#"data-task="indeterminate""#));
        assert!(output.contains(r#"aria-checked="mixed""#));
        assert!(!output.contains("{{TASK_INDETERMINATE}}"));
    }

    #[test]
    fn test_custom_link_attributes_id_and_class() {
        let header_map = HeaderIdMap::new();
        let input = r#"<p><a href="/docs">Docs</a>{docs-link btn btn-primary}</p>"#;
        let output = postprocess_conflicts(input, &header_map);

        assert!(
            output.contains(r#"<a href="/docs" id="docs-link" class="btn btn-primary">Docs</a>"#)
        );
        assert!(!output.contains("{docs-link btn btn-primary}"));
    }

    #[test]
    fn test_custom_link_attributes_merge_class() {
        let header_map = HeaderIdMap::new();
        let input = r#"<a href="/home" class="existing">Home</a>{home-link new}"#;
        let output = postprocess_conflicts(input, &header_map);

        assert!(output.contains(r#"id="home-link""#));
        assert!(output.contains(r#"class="existing new""#));
    }
}

/// Apply base URL to absolute paths in links and media
///
/// Resolves absolute paths (starting with "/") by prefixing them with the base_url.
/// Relative URLs (http://, https://, //, etc.) are left unchanged.
///
/// # Arguments
///
/// * `html` - The HTML to process
/// * `base_url` - The base URL to prepend (e.g., "/app", "https://example.com/app")
///
/// # Returns
///
/// HTML with absolute paths resolved to base_url + path
///
/// # Examples
///
/// ```
/// use umd::extensions::conflict_resolver::apply_base_url_to_links;
///
/// let html = r#"<a href="/docs">Docs</a><img src="/image.png" />"#;
/// let result = apply_base_url_to_links(html, "/app");
/// assert!(result.contains(r#"href="/app/docs""#));
/// assert!(result.contains(r#"src="/app/image.png""#));
/// ```
pub fn apply_base_url_to_links(html: &str, base_url: &str) -> String {
    // Normalize base_url: remove trailing slash
    let normalized_base = if base_url.ends_with('/') && base_url.len() > 1 {
        &base_url[..base_url.len() - 1]
    } else {
        base_url
    };

    let mut result = html.to_string();

    // Replace href="/path" with href="/base_url/path"
    let href_double = Regex::new(r#"((?:href|src|srcset)\s*=\s*)"(/[^"]*)""#).unwrap();
    result = href_double
        .replace_all(&result, |caps: &Captures| {
            let attr = &caps[1];
            let path = &caps[2];
            let new_url = format!("{}{}", normalized_base, path);
            format!("{}\"{}\"", attr, new_url)
        })
        .to_string();

    // Replace href='/path' with href='/base_url/path' (single quotes)
    let href_single = Regex::new(r"((?:href|src|srcset)\s*=\s*)'(/[^']*)'").unwrap();
    result = href_single
        .replace_all(&result, |caps: &Captures| {
            let attr = &caps[1];
            let path = &caps[2];
            let new_url = format!("{}{}", normalized_base, path);
            format!("{}'{}'", attr, new_url)
        })
        .to_string();

    result
}