umd 0.1.1

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
//! Media file auto-detection and HTML generation
//!
//! This module provides functionality to detect media files by extension
//! and generate appropriate HTML5 media tags (video, audio, picture).

use std::path::Path;

/// Media type detected from file extension
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MediaType {
    Video,
    Audio,
    Image,
    Downloadable,
}

fn media_type_from_extension(ext: &str) -> Option<MediaType> {
    match ext {
        // Video extensions
        "mp4" | "webm" | "ogv" | "mov" | "avi" | "mkv" | "m4v" => Some(MediaType::Video),
        // Audio extensions
        "mp3" | "wav" | "ogg" | "oga" | "m4a" | "aac" | "flac" | "opus" | "weba" => {
            Some(MediaType::Audio)
        }
        // Image extensions
        "jpg" | "jpeg" | "png" | "gif" | "svg" | "webp" | "avif" | "bmp" | "ico" | "jxl"
        | "tif" | "tiff" => Some(MediaType::Image),
        // Downloadable file extensions
        // Archive formats
        "zip" | "tar" | "gz" | "7z" | "rar" | "bz2" | "xz" => Some(MediaType::Downloadable),
        // Document formats
        "pdf" | "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx" | "odt" | "ods" | "odp" => {
            Some(MediaType::Downloadable)
        }
        // Text formats
        "txt" | "md" | "csv" | "json" | "xml" | "yaml" | "yml" | "toml" => {
            Some(MediaType::Downloadable)
        }
        // Executable formats
        "exe" | "dmg" | "deb" | "rpm" | "app" | "apk" | "msi" => Some(MediaType::Downloadable),
        _ => None,
    }
}

fn resolve_extension(url: &str, allow_fragment_extension_hint: bool) -> Option<String> {
    // 1) Prefer path extension from the actual URL path.
    let path = url.split('?').next()?.split('#').next()?;
    if let Some(ext) = Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_lowercase())
    {
        return Some(ext);
    }

    // 2) Optionally allow fragment hint extension (e.g. `#.png`) for extension-less URLs.
    if !allow_fragment_extension_hint {
        return None;
    }

    let fragment = url.split('#').nth(1)?;
    let hinted = fragment.strip_prefix('.')?;
    if hinted.is_empty() || !hinted.chars().all(|c| c.is_ascii_alphanumeric()) {
        return None;
    }

    Some(hinted.to_lowercase())
}

/// Detect media type from URL
///
/// # Arguments
///
/// * `url` - The URL to analyze (may include query parameters)
///
/// # Returns
///
/// `Some(MediaType)` if a known extension is found, `None` otherwise
///
/// # Examples
///
/// ```
/// use umd::extensions::media::detect_media_type;
/// use umd::extensions::media::MediaType;
///
/// assert_eq!(detect_media_type("video.mp4"), Some(MediaType::Video));
/// assert_eq!(detect_media_type("audio.mp3"), Some(MediaType::Audio));
/// assert_eq!(detect_media_type("image.png"), Some(MediaType::Image));
/// assert_eq!(detect_media_type("file.unknown"), None);
/// ```
pub fn detect_media_type(url: &str) -> Option<MediaType> {
    detect_media_type_with_hint(url, false)
}

/// Detect media type from URL with optional fragment extension hint support.
pub fn detect_media_type_with_hint(
    url: &str,
    allow_fragment_extension_hint: bool,
) -> Option<MediaType> {
    let ext = resolve_extension(url, allow_fragment_extension_hint)?;
    media_type_from_extension(ext.as_str())
}

/// Get MIME type for a file extension
///
/// # Arguments
///
/// * `url` - The URL to analyze
/// * `media_type` - The detected media type
///
/// # Returns
///
/// MIME type string
fn get_mime_type_with_hint(
    url: &str,
    media_type: &MediaType,
    allow_fragment_extension_hint: bool,
) -> String {
    let ext = resolve_extension(url, allow_fragment_extension_hint).unwrap_or_default();

    match media_type {
        MediaType::Video => match ext.as_str() {
            "mp4" => "video/mp4",
            "webm" => "video/webm",
            "ogv" | "ogg" => "video/ogg",
            "mov" => "video/quicktime",
            "avi" => "video/x-msvideo",
            "mkv" => "video/x-matroska",
            "m4v" => "video/x-m4v",
            _ => "video/mp4",
        },
        MediaType::Audio => match ext.as_str() {
            "mp3" => "audio/mpeg",
            "wav" => "audio/wav",
            "ogg" | "oga" => "audio/ogg",
            "m4a" => "audio/mp4",
            "aac" => "audio/aac",
            "flac" => "audio/flac",
            "opus" => "audio/opus",
            "weba" => "audio/webm",
            _ => "audio/mpeg",
        },
        MediaType::Image => match ext.as_str() {
            "jpg" | "jpeg" => "image/jpeg",
            "png" => "image/png",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "webp" => "image/webp",
            "avif" => "image/avif",
            "bmp" => "image/bmp",
            "ico" => "image/x-icon",
            "jxl" => "image/jxl",
            _ => "image/png",
        },
        MediaType::Downloadable => match ext.as_str() {
            "pdf" => "application/pdf",
            "zip" => "application/zip",
            "tar" => "application/x-tar",
            "gz" => "application/gzip",
            "json" => "application/json",
            "xml" => "application/xml",
            _ => "application/octet-stream",
        },
    }
    .to_string()
}

/// Generate HTML for media element
///
/// # Arguments
///
/// * `url` - The media URL
/// * `alt` - Alt text (used for track label in video, ignored in audio)
/// * `title` - Optional title attribute
/// * `media_type` - The type of media
///
/// # Returns
///
/// HTML string for the media element
///
/// # Examples
///
/// ```
/// use umd::extensions::media::{generate_media_html, MediaType};
/// use umd::parser::Icons;
///
/// let html = generate_media_html("video.mp4", "Demo", Some("Product demo"), &MediaType::Video, &Icons::default());
/// assert!(html.contains("<video"));
/// assert!(html.contains("controls"));
/// ```
pub fn generate_media_html(
    url: &str,
    alt: &str,
    title: Option<&str>,
    media_type: &MediaType,
    icons: &crate::parser::Icons,
) -> String {
    generate_media_html_with_hint(url, alt, title, media_type, icons, false)
}

fn generate_media_html_with_hint(
    url: &str,
    alt: &str,
    title: Option<&str>,
    media_type: &MediaType,
    icons: &crate::parser::Icons,
    allow_fragment_extension_hint: bool,
) -> String {
    let mime_type = get_mime_type_with_hint(url, media_type, allow_fragment_extension_hint);
    let title_attr = title
        .map(|t| format!(" title=\"{}\"", escape_html(t)))
        .unwrap_or_default();

    match media_type {
        MediaType::Video => {
            let track_label = escape_html(alt);
            let display_text = if alt.is_empty() { url } else { alt };
            format!(
                "<video controls{}>\n  <source src=\"{}\" type=\"{}\" />\n  <track kind=\"captions\" label=\"{}\" />\n  <a href=\"{}\" download class=\"download-link video-fallback\">{} {}</a>\n</video>",
                title_attr,
                escape_html(url),
                mime_type,
                track_label,
                escape_html(url),
                icons.video,
                escape_html(display_text)
            )
        }
        MediaType::Audio => {
            let display_text = if alt.is_empty() { url } else { alt };
            format!(
                "<audio controls{}>\n  <source src=\"{}\" type=\"{}\" />\n  <a href=\"{}\" download class=\"download-link audio-fallback\">{} {}</a>\n</audio>",
                title_attr,
                escape_html(url),
                mime_type,
                escape_html(url),
                icons.audio,
                escape_html(display_text)
            )
        }
        MediaType::Image => {
            let img_title = title
                .map(|t| format!(" title=\"{}\"", escape_html(t)))
                .unwrap_or_default();
            format!(
                "<picture{}>\n  <source srcset=\"{}\" type=\"{}\" />\n  <img src=\"{}\" alt=\"{}\" loading=\"lazy\" class=\"img-fluid\"{} />\n</picture>",
                title_attr,
                escape_html(url),
                mime_type,
                escape_html(url),
                escape_html(alt),
                img_title
            )
        }
        MediaType::Downloadable => {
            let display_text = if alt.is_empty() { url } else { alt };
            format!(
                "<a href=\"{}\" download class=\"download-link\"{}>\n  {} {}\n</a>",
                escape_html(url),
                title_attr,
                icons.download,
                escape_html(display_text)
            )
        }
    }
}

/// Escape HTML special characters
fn escape_html(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

/// Transform image tags to media tags based on file extension
///
/// This function processes HTML and converts `<img>` tags to appropriate
/// media tags (`<video>`, `<audio>`, or `<picture>`) based on the file extension.
///
/// # Arguments
///
/// * `html` - The HTML string to transform
///
/// # Returns
///
/// Transformed HTML with media tags
///
/// # Examples
///
/// ```
/// use umd::extensions::media::transform_images_to_media;
/// use umd::parser::Icons;
///
/// let html = r#"<img src="video.mp4" alt="Demo" />"#;
/// let result = transform_images_to_media(html, &Icons::default(), false);
/// assert!(result.contains("<video"));
/// ```
pub fn transform_images_to_media(
    html: &str,
    icons: &crate::parser::Icons,
    allow_fragment_extension_hint: bool,
) -> String {
    use regex::Regex;

    // Pattern to match <img> tags with src and alt attributes
    let img_re =
        Regex::new(r#"<img\s+src="([^"]+)"(?:\s+alt="([^"]*)")?(?:\s+title="([^"]*)")?\s*/>"#)
            .unwrap();

    let transformed = img_re
        .replace_all(html, |caps: &regex::Captures| {
            let url = caps.get(1).map_or("", |m| m.as_str());
            let alt = caps.get(2).map_or("", |m| m.as_str());
            let title = caps.get(3).map(|m| m.as_str());

            // Detect media type and generate appropriate HTML
            if let Some(media_type) =
                detect_media_type_with_hint(url, allow_fragment_extension_hint)
            {
                generate_media_html_with_hint(
                    url,
                    alt,
                    title,
                    &media_type,
                    icons,
                    allow_fragment_extension_hint,
                )
            } else {
                // Not a recognized media file, wrap in <picture> tag anyway
                let title_attr = title
                    .map(|t| format!(" title=\"{}\"", t))
                    .unwrap_or_default();
                let img_title = title
                    .map(|t| format!(" title=\"{}\"", t))
                    .unwrap_or_default();
                format!(
                    "<picture{}>\n  <img src=\"{}\" alt=\"{}\" loading=\"lazy\" class=\"img-fluid\"{} />\n</picture>",
                    title_attr, url, alt, img_title
                )
            }
        })
        .to_string();

    // Block media: if a paragraph consists only of a media element,
    // treat it as block-level output and wrap with <figure>.
    // Inline media inside text remains unchanged.
    let media_only_paragraph = Regex::new(
        r#"(?s)<p>\s*(<picture[\s\S]*?</picture>|<video[\s\S]*?</video>|<audio[\s\S]*?</audio>|<a href="[^"]+" download class="download-link[^"]*"[^>]*>[\s\S]*?</a>)\s*</p>"#,
    )
    .unwrap();

    media_only_paragraph
        .replace_all(&transformed, |caps: &regex::Captures| {
            format!("<figure class=\"w-100\">\n{}\n</figure>", &caps[1])
        })
        .to_string()
}

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

    #[test]
    fn test_detect_video() {
        assert_eq!(detect_media_type("video.mp4"), Some(MediaType::Video));
        assert_eq!(detect_media_type("video.webm"), Some(MediaType::Video));
        assert_eq!(detect_media_type("video.ogv"), Some(MediaType::Video));
        assert_eq!(detect_media_type("video.mov"), Some(MediaType::Video));
        assert_eq!(detect_media_type("VIDEO.MP4"), Some(MediaType::Video)); // Case insensitive
    }

    #[test]
    fn test_detect_audio() {
        assert_eq!(detect_media_type("audio.mp3"), Some(MediaType::Audio));
        assert_eq!(detect_media_type("audio.wav"), Some(MediaType::Audio));
        assert_eq!(detect_media_type("audio.ogg"), Some(MediaType::Audio));
        assert_eq!(detect_media_type("AUDIO.MP3"), Some(MediaType::Audio)); // Case insensitive
    }

    #[test]
    fn test_detect_image() {
        assert_eq!(detect_media_type("image.png"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.jpg"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.jpeg"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.gif"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.webp"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.avif"), Some(MediaType::Image));
        assert_eq!(detect_media_type("image.jxl"), Some(MediaType::Image)); // JPEG XL
    }

    #[test]
    fn test_detect_with_query_params() {
        assert_eq!(detect_media_type("video.mp4?v=123"), Some(MediaType::Video));
        assert_eq!(
            detect_media_type("image.png?size=large#anchor"),
            Some(MediaType::Image)
        );
    }

    #[test]
    fn test_detect_fragment_extension_hint_opt_in() {
        assert_eq!(
            detect_media_type_with_hint("/assets/image#.png", false),
            None
        );
        assert_eq!(
            detect_media_type_with_hint("/assets/image#.png", true),
            Some(MediaType::Image)
        );
    }

    #[test]
    fn test_detect_fragment_extension_hint_reject_non_extension() {
        assert_eq!(
            detect_media_type_with_hint("/assets/media#t=10", true),
            None
        );
        assert_eq!(
            detect_media_type_with_hint("/assets/image#section", true),
            None
        );
    }

    #[test]
    fn test_detect_fragment_extension_hint_tiff() {
        assert_eq!(
            detect_media_type_with_hint("/assets/photo#.tiff", true),
            Some(MediaType::Image)
        );
        assert_eq!(
            detect_media_type_with_hint("/assets/photo#.tif", true),
            Some(MediaType::Image)
        );
    }

    #[test]
    fn test_detect_downloadable_archives() {
        assert_eq!(detect_media_type("file.zip"), Some(MediaType::Downloadable));
        assert_eq!(detect_media_type("file.tar"), Some(MediaType::Downloadable));
        assert_eq!(detect_media_type("file.gz"), Some(MediaType::Downloadable));
        assert_eq!(detect_media_type("file.7z"), Some(MediaType::Downloadable));
        assert_eq!(detect_media_type("file.rar"), Some(MediaType::Downloadable));
    }

    #[test]
    fn test_detect_downloadable_documents() {
        assert_eq!(
            detect_media_type("document.pdf"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("document.doc"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("document.docx"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("spreadsheet.xls"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("spreadsheet.xlsx"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("presentation.ppt"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("presentation.pptx"),
            Some(MediaType::Downloadable)
        );
    }

    #[test]
    fn test_detect_downloadable_text() {
        assert_eq!(detect_media_type("file.txt"), Some(MediaType::Downloadable));
        assert_eq!(detect_media_type("data.csv"), Some(MediaType::Downloadable));
        assert_eq!(
            detect_media_type("config.json"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(detect_media_type("data.xml"), Some(MediaType::Downloadable));
        assert_eq!(
            detect_media_type("config.yaml"),
            Some(MediaType::Downloadable)
        );
    }

    #[test]
    fn test_detect_downloadable_executables() {
        assert_eq!(
            detect_media_type("installer.exe"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("installer.dmg"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("package.deb"),
            Some(MediaType::Downloadable)
        );
        assert_eq!(
            detect_media_type("package.rpm"),
            Some(MediaType::Downloadable)
        );
    }

    #[test]
    fn test_detect_unknown() {
        assert_eq!(detect_media_type("file.unknown"), None);
        assert_eq!(detect_media_type("noextension"), None);
    }

    #[test]
    fn test_generate_video_html() {
        let html = generate_media_html(
            "video.mp4",
            "Demo video",
            Some("Product demo"),
            &MediaType::Video,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("<video controls"));
        assert!(html.contains("title=\"Product demo\""));
        assert!(html.contains("src=\"video.mp4\""));
        assert!(html.contains("type=\"video/mp4\""));
        assert!(html.contains("<track kind=\"captions\" label=\"Demo video\""));
        // Check for download fallback
        assert!(
            html.contains("<a href=\"video.mp4\" download class=\"download-link video-fallback\">")
        );
        assert!(html.contains(
            r#"<span class="bi bi-camera-video-fill" aria-hidden="true"></span> Demo video"#
        ));
    }

    #[test]
    fn test_generate_audio_html() {
        let html = generate_media_html(
            "audio.mp3",
            "Background music",
            Some("Theme song"),
            &MediaType::Audio,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("<audio controls"));
        assert!(html.contains("title=\"Theme song\""));
        assert!(html.contains("src=\"audio.mp3\""));
        assert!(html.contains("type=\"audio/mpeg\""));
        // Check for download fallback
        assert!(
            html.contains("<a href=\"audio.mp3\" download class=\"download-link audio-fallback\">")
        );
        assert!(html.contains(
            r#"<span class="bi bi-music-note-beamed" aria-hidden="true"></span> Background music"#
        ));
    }

    #[test]
    fn test_generate_image_html() {
        let html = generate_media_html(
            "image.png",
            "Logo",
            Some("Company logo"),
            &MediaType::Image,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("<picture"));
        assert!(html.contains("title=\"Company logo\""));
        assert!(html.contains("srcset=\"image.png\""));
        assert!(html.contains("type=\"image/png\""));
        assert!(html.contains("alt=\"Logo\""));
        assert!(html.contains("loading=\"lazy\""));
    }

    #[test]
    fn test_generate_without_title() {
        let html = generate_media_html(
            "video.mp4",
            "Video",
            None,
            &MediaType::Video,
            &crate::parser::Icons::default(),
        );
        assert!(!html.contains("title="));
        assert!(html.contains("<video controls>"));
    }

    #[test]
    fn test_html_escape() {
        let html = generate_media_html(
            "video.mp4?foo=bar&baz=qux",
            "Test <script>",
            Some("Title with \"quotes\""),
            &MediaType::Video,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("&amp;"));
        assert!(html.contains("&lt;"));
        assert!(html.contains("&quot;"));
    }

    #[test]
    fn test_generate_downloadable_html() {
        let html = generate_media_html(
            "document.pdf",
            "Research Report",
            Some("Annual Research"),
            &MediaType::Downloadable,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("<a href=\"document.pdf\" download class=\"download-link\""));
        assert!(html.contains("title=\"Annual Research\""));
        assert!(html.contains(
            r#"<span class="bi bi-file-earmark-arrow-down-fill" aria-hidden="true"></span> Research Report"#
        ));
    }

    #[test]
    fn test_downloadable_empty_alt() {
        let html = generate_media_html(
            "archive.zip",
            "",
            None,
            &MediaType::Downloadable,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("<a href=\"archive.zip\" download"));
        assert!(html.contains(
            r#"<span class="bi bi-file-earmark-arrow-down-fill" aria-hidden="true"></span> archive.zip"#
        )); // URL as fallback
    }

    #[test]
    fn test_video_empty_alt_fallback() {
        let html = generate_media_html(
            "video.mp4",
            "",
            None,
            &MediaType::Video,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains(
            r#"<span class="bi bi-camera-video-fill" aria-hidden="true"></span> video.mp4"#
        )); // URL as fallback in download link
    }

    #[test]
    fn test_audio_empty_alt_fallback() {
        let html = generate_media_html(
            "audio.mp3",
            "",
            None,
            &MediaType::Audio,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains(
            r#"<span class="bi bi-music-note-beamed" aria-hidden="true"></span> audio.mp3"#
        )); // URL as fallback in download link
    }

    #[test]
    fn test_downloadable_with_query_params() {
        let html = generate_media_html(
            "document.pdf?version=2",
            "User Guide",
            None,
            &MediaType::Downloadable,
            &crate::parser::Icons::default(),
        );
        assert!(html.contains("href=\"document.pdf?version=2\""));
        assert!(html.contains(
            r#"<span class="bi bi-file-earmark-arrow-down-fill" aria-hidden="true"></span> User Guide"#
        ));
    }

    #[test]
    fn test_custom_icons() {
        let icons = crate::parser::Icons {
            video: r#"<i class="bi bi-camera-video"></i>"#.to_string(),
            audio: r#"<i class="bi bi-music-note"></i>"#.to_string(),
            download: r#"<i class="bi bi-file-earmark-arrow-down"></i>"#.to_string(),
            ..crate::parser::Icons::default()
        };
        let html = generate_media_html("video.mp4", "Demo", None, &MediaType::Video, &icons);
        assert!(html.contains(r#"<i class="bi bi-camera-video"></i>"#));
        assert!(!html.contains("bi-camera-video-fill"));

        let html = generate_media_html("doc.pdf", "Doc", None, &MediaType::Downloadable, &icons);
        assert!(html.contains(r#"<i class="bi bi-file-earmark-arrow-down"></i>"#));
        assert!(!html.contains("bi-file-earmark-arrow-down-fill"));
    }

    #[test]
    fn test_transform_media_paragraph_to_figure() {
        let html = r#"<p><img src="image.png" alt="alt" title="Title" /></p>"#;
        let transformed = transform_images_to_media(html, &crate::parser::Icons::default(), false);
        assert!(transformed.contains(r#"<figure class="w-100">"#));
        assert!(transformed.contains("<picture"));
        assert!(transformed.contains("src=\"image.png\""));
    }

    #[test]
    fn test_transform_inline_media_remains_inline() {
        let html = r#"<p>before <img src="image.png" alt="alt" /> after</p>"#;
        let transformed = transform_images_to_media(html, &crate::parser::Icons::default(), false);
        assert!(!transformed.contains("<figure>"));
        assert!(transformed.contains("before"));
        assert!(transformed.contains("after"));
        assert!(transformed.contains("<picture"));
    }

    #[test]
    fn test_transform_fragment_extension_hint_opt_in() {
        let html = r#"<p><img src="/assets/image#.png" alt="alt" /></p>"#;
        let transformed = transform_images_to_media(html, &crate::parser::Icons::default(), true);
        assert!(transformed.contains("<picture"));
        assert!(transformed.contains("type=\"image/png\""));
    }
}