fontcull 2.0.1

Pure Rust font subsetting library
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
//! Static HTML/CSS analysis for font usage detection
//!
//! Parses HTML and CSS to determine which characters are used with which fonts,
//! without requiring a browser.

use scraper::{Html, Selector};
use std::collections::{HashMap, HashSet};

/// CSS custom properties (variables) map
type CssVariables = HashMap<String, String>;

/// A parsed @font-face rule
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // weight and style reserved for font-weight matching
pub struct FontFace {
    /// The font-family name declared in @font-face
    pub family: String,
    /// The URL to the font file (from src)
    pub src: String,
    /// Font weight (e.g., "400", "bold")
    pub weight: Option<String>,
    /// Font style (e.g., "normal", "italic")
    pub style: Option<String>,
}

/// Result of analyzing CSS for font information
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FontAnalysis {
    /// Map of font-family name -> characters used
    pub chars_per_font: HashMap<String, HashSet<char>>,
    /// Parsed @font-face rules
    pub font_faces: Vec<FontFace>,
}

/// Analyze HTML and CSS to collect font usage information
pub fn analyze_fonts(html: &str, css: &str) -> FontAnalysis {
    let chars_per_font = collect_chars_per_font(html, css);
    let font_faces = parse_font_face_rules(css);

    FontAnalysis {
        chars_per_font,
        font_faces,
    }
}

/// Extracts all text content and maps it to font-families based on CSS rules.
///
/// Returns a map of font-family name -> set of characters used with that font.
pub fn collect_chars_per_font(html: &str, css: &str) -> HashMap<String, HashSet<char>> {
    let document = Html::parse_document(html);

    // First, parse CSS custom properties (variables)
    let css_vars = parse_css_custom_properties(css);

    // Parse font-family rules with variable resolution
    let font_rules = parse_font_family_rules_with_vars(css, &css_vars);

    let mut result: HashMap<String, HashSet<char>> = HashMap::new();

    // For each element with text, determine which font-family applies
    // by checking CSS rules in order of specificity (simplified: last match wins)
    let all_elements = Selector::parse("*").unwrap();

    for element in document.select(&all_elements) {
        // Get direct text content (not from children)
        let text: String = element
            .text()
            .next()
            .map(|s| s.to_string())
            .unwrap_or_default();

        if text.trim().is_empty() {
            continue;
        }

        // Find which font-family applies to this element
        let font_family = find_font_family_for_element(&element, &font_rules)
            .unwrap_or_else(|| "sans-serif".to_string());

        // Add characters to that font's set
        let chars = result.entry(font_family).or_default();
        for c in text.chars() {
            chars.insert(c);
        }
    }

    result
}

/// A CSS rule that sets font-family
#[derive(Debug)]
struct FontFamilyRule {
    selector: String,
    font_family: String,
}

/// Parse CSS and extract rules that set font-family, with CSS variable resolution
fn parse_font_family_rules_with_vars(css: &str, css_vars: &CssVariables) -> Vec<FontFamilyRule> {
    let mut rules = Vec::new();

    // Simple CSS parser - find rule blocks and extract font-family
    // This is a simplified parser that handles basic cases
    let chars = css.chars().peekable();
    let mut current_selector = String::new();
    let mut in_block = false;
    let mut block_content = String::new();

    for c in chars {
        if c == '{' {
            in_block = true;
            block_content.clear();
        } else if c == '}' {
            in_block = false;

            // Parse the block content for font-family
            if let Some(font_family) = extract_font_family_with_vars(&block_content, css_vars) {
                let selector = current_selector.trim().to_string();
                if !selector.is_empty() && !selector.starts_with('@') {
                    rules.push(FontFamilyRule {
                        selector,
                        font_family,
                    });
                }
            }

            current_selector.clear();
        } else if in_block {
            block_content.push(c);
        } else {
            current_selector.push(c);
        }
    }

    rules
}

/// Extract font-family value from a CSS declaration block, with CSS variable resolution
fn extract_font_family_with_vars(block: &str, css_vars: &CssVariables) -> Option<String> {
    // Look for font-family: value; or font: ... value;
    for declaration in block.split(';') {
        let declaration = declaration.trim();

        if let Some(value) = declaration.strip_prefix("font-family:") {
            return Some(parse_font_family_value_with_vars(value, css_vars));
        }

        // Handle shorthand 'font' property (simplified - just look for font-family at end)
        if declaration.starts_with("font:") {
            // The font shorthand is complex; for now just skip it
            // TODO: properly parse font shorthand
        }
    }

    None
}

/// Parse @font-face rules from CSS
fn parse_font_face_rules(css: &str) -> Vec<FontFace> {
    let mut faces = Vec::new();

    // Find all @font-face blocks
    let mut remaining = css;
    while let Some(start) = remaining.find("@font-face") {
        remaining = &remaining[start + "@font-face".len()..];

        // Find the opening brace
        let Some(brace_start) = remaining.find('{') else {
            break;
        };
        remaining = &remaining[brace_start + 1..];

        // Find matching closing brace (handle nested braces)
        let mut depth = 1;
        let mut block_end = 0;
        for (i, c) in remaining.char_indices() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        block_end = i;
                        break;
                    }
                }
                _ => {}
            }
        }

        if block_end == 0 {
            break;
        }

        let block = &remaining[..block_end];
        remaining = &remaining[block_end + 1..];

        // Parse the @font-face block
        if let Some(face) = parse_font_face_block(block) {
            faces.push(face);
        }
    }

    faces
}

/// Parse a single @font-face block content
fn parse_font_face_block(block: &str) -> Option<FontFace> {
    let mut family = None;
    let mut src = None;
    let mut weight = None;
    let mut style = None;

    for declaration in block.split(';') {
        let declaration = declaration.trim();

        if let Some(value) = declaration.strip_prefix("font-family:") {
            family = Some(parse_font_family_value(value));
        } else if let Some(value) = declaration.strip_prefix("src:") {
            src = parse_font_src(value);
        } else if let Some(value) = declaration.strip_prefix("font-weight:") {
            weight = Some(value.trim().to_string());
        } else if let Some(value) = declaration.strip_prefix("font-style:") {
            style = Some(value.trim().to_string());
        }
    }

    Some(FontFace {
        family: family?,
        src: src?,
        weight,
        style,
    })
}

/// Parse the src property of @font-face
/// Handles: url("/path/to/font.woff2"), url('/path'), url(path)
fn parse_font_src(value: &str) -> Option<String> {
    let value = value.trim();

    // Find url(...) - take the first one if there are multiple (fallbacks)
    let url_start = value.find("url(")?;
    let after_url = &value[url_start + 4..];

    // Find the closing paren
    let url_end = after_url.find(')')?;
    let url_content = &after_url[..url_end];

    // Remove quotes if present
    let url = url_content
        .trim()
        .trim_matches('"')
        .trim_matches('\'')
        .to_string();

    Some(url)
}

/// Parse a font-family value, returning the first (primary) font
/// If css_vars is provided, resolves var() references
fn parse_font_family_value(value: &str) -> String {
    parse_font_family_value_with_vars(value, &HashMap::new())
}

/// Parse a font-family value with CSS variable resolution
fn parse_font_family_value_with_vars(value: &str, css_vars: &CssVariables) -> String {
    let value = value.trim();

    // Resolve var() references first
    let resolved = resolve_css_var(value, css_vars);

    // font-family can be: "Font Name", 'Font Name', Font-Name, or a list
    // We take the first one
    let first = resolved.split(',').next().unwrap_or(&resolved).trim();

    // Remove quotes if present
    let first = first.trim_matches('"').trim_matches('\'');

    first.to_string()
}

/// Resolve CSS var() references in a value
/// Handles: var(--property-name) and var(--property-name, fallback)
fn resolve_css_var(value: &str, css_vars: &CssVariables) -> String {
    let mut result = value.to_string();

    // Keep resolving var() references until none remain (handles nested vars)
    let mut iterations = 0;
    const MAX_ITERATIONS: usize = 10; // Prevent infinite loops from circular references

    while let Some(var_start) = result.find("var(") {
        if iterations >= MAX_ITERATIONS {
            break;
        }
        iterations += 1;

        // Find matching closing paren (handle nested parens)
        let after_var = &result[var_start + 4..];
        let mut depth = 1;
        let mut var_end = None;
        for (i, c) in after_var.char_indices() {
            match c {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        var_end = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }

        let Some(end_offset) = var_end else {
            break; // Malformed var()
        };

        let var_content = &after_var[..end_offset];
        let full_var_end = var_start + 4 + end_offset + 1; // Include closing paren

        // Parse var content: --property-name or --property-name, fallback
        let (var_name, fallback) = if let Some(comma_pos) = var_content.find(',') {
            let name = var_content[..comma_pos].trim();
            let fallback = var_content[comma_pos + 1..].trim();
            (name, Some(fallback))
        } else {
            (var_content.trim(), None)
        };

        // Look up the variable value
        let replacement = css_vars
            .get(var_name)
            .map(|s| s.as_str())
            .or(fallback)
            .unwrap_or("");

        // Replace the var() with its resolved value
        result = format!(
            "{}{}{}",
            &result[..var_start],
            replacement,
            &result[full_var_end..]
        );
    }

    result
}

/// Parse CSS custom property declarations from CSS
/// Returns a map of --property-name -> value
fn parse_css_custom_properties(css: &str) -> CssVariables {
    let mut vars = HashMap::new();

    // Parse through CSS looking for custom property declarations
    let mut remaining = css;

    while let Some(brace_start) = remaining.find('{') {
        let after_brace = &remaining[brace_start + 1..];

        // Find matching closing brace
        let mut depth = 1;
        let mut block_end = None;
        for (i, c) in after_brace.char_indices() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        block_end = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }

        let Some(end) = block_end else {
            break;
        };

        let block = &after_brace[..end];

        // Parse declarations in this block
        for declaration in block.split(';') {
            let declaration = declaration.trim();

            // Look for custom property declarations (--name: value)
            if declaration.starts_with("--")
                && let Some(colon_pos) = declaration.find(':')
            {
                let name = declaration[..colon_pos].trim();
                let value = declaration[colon_pos + 1..].trim();
                vars.insert(name.to_string(), value.to_string());
            }
        }

        remaining = &after_brace[end + 1..];
    }

    vars
}

/// Find which font-family applies to an element based on CSS rules
fn find_font_family_for_element(
    element: &scraper::ElementRef,
    rules: &[FontFamilyRule],
) -> Option<String> {
    let mut matched_font: Option<String> = None;

    // Check each rule (later rules override earlier ones - simplified specificity)
    for rule in rules {
        if let Ok(selector) = Selector::parse(&rule.selector) {
            // Check if this element matches the selector
            if selector.matches(element) {
                matched_font = Some(rule.font_family.clone());
            }
        }
    }

    // If no direct match, check ancestors (font-family is inherited)
    if matched_font.is_none() {
        for ancestor in element.ancestors() {
            if let Some(ancestor_el) = scraper::ElementRef::wrap(ancestor) {
                for rule in rules {
                    if let Ok(selector) = Selector::parse(&rule.selector)
                        && selector.matches(&ancestor_el)
                    {
                        matched_font = Some(rule.font_family.clone());
                        // Don't break - later rules still override
                    }
                }
            }
            if matched_font.is_some() {
                break;
            }
        }
    }

    matched_font
}

/// Extract CSS from HTML document (from `<style>` tags and inline styles)
pub fn extract_css_from_html(html: &str) -> String {
    let document = Html::parse_document(html);
    let style_selector = Selector::parse("style").unwrap();

    let mut css = String::new();

    for style in document.select(&style_selector) {
        css.push_str(&style.inner_html());
        css.push('\n');
    }

    css
}

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

    #[test]
    fn test_parse_font_family_rules() {
        let css = r#"
            body { font-family: "Inter", sans-serif; }
            h1 { font-family: 'Playfair Display'; }
            .code { font-family: monospace; }
        "#;

        let rules = parse_font_family_rules_with_vars(css, &HashMap::new());
        assert_eq!(rules.len(), 3);
        assert_eq!(rules[0].selector, "body");
        assert_eq!(rules[0].font_family, "Inter");
        assert_eq!(rules[1].font_family, "Playfair Display");
        assert_eq!(rules[2].font_family, "monospace");
    }

    #[test]
    fn test_collect_chars_basic() {
        let html = r#"
            <html>
            <head>
                <style>
                    body { font-family: "TestFont"; }
                </style>
            </head>
            <body>
                <p>Hello</p>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let chars = collect_chars_per_font(html, &css);

        assert!(chars.contains_key("TestFont"));
        let test_font_chars = &chars["TestFont"];
        assert!(test_font_chars.contains(&'H'));
        assert!(test_font_chars.contains(&'e'));
        assert!(test_font_chars.contains(&'l'));
        assert!(test_font_chars.contains(&'o'));
    }

    #[test]
    fn test_different_fonts_for_elements() {
        let html = r#"
            <html>
            <head>
                <style>
                    body { font-family: "BodyFont"; }
                    h1 { font-family: "HeadingFont"; }
                </style>
            </head>
            <body>
                <h1>Title</h1>
                <p>Body text</p>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let chars = collect_chars_per_font(html, &css);

        // h1 should use HeadingFont
        assert!(chars.contains_key("HeadingFont"));
        assert!(chars["HeadingFont"].contains(&'T'));

        // p should inherit from body -> BodyFont
        assert!(chars.contains_key("BodyFont"));
        assert!(chars["BodyFont"].contains(&'B'));
    }

    #[test]
    fn test_parse_font_face_rules() {
        let css = r#"
            @font-face {
                font-family: "Inter";
                src: url("/fonts/Inter-Regular.woff2") format("woff2");
                font-weight: 400;
                font-style: normal;
            }

            @font-face {
                font-family: "Inter";
                src: url('/fonts/Inter-Bold.woff2');
                font-weight: 700;
            }

            @font-face {
                font-family: 'Playfair Display';
                src: url(fonts/Playfair.ttf);
            }

            body { font-family: "Inter", sans-serif; }
        "#;

        let faces = parse_font_face_rules(css);
        assert_eq!(faces.len(), 3);

        assert_eq!(faces[0].family, "Inter");
        assert_eq!(faces[0].src, "/fonts/Inter-Regular.woff2");
        assert_eq!(faces[0].weight, Some("400".to_string()));
        assert_eq!(faces[0].style, Some("normal".to_string()));

        assert_eq!(faces[1].family, "Inter");
        assert_eq!(faces[1].src, "/fonts/Inter-Bold.woff2");
        assert_eq!(faces[1].weight, Some("700".to_string()));
        assert_eq!(faces[1].style, None);

        assert_eq!(faces[2].family, "Playfair Display");
        assert_eq!(faces[2].src, "fonts/Playfair.ttf");
    }

    #[test]
    fn test_analyze_fonts_full() {
        let html = r#"
            <html>
            <head>
                <style>
                    @font-face {
                        font-family: "MyFont";
                        src: url("/fonts/MyFont.woff2");
                    }
                    body { font-family: "MyFont"; }
                </style>
            </head>
            <body>
                <p>Hello World</p>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let analysis = analyze_fonts(html, &css);

        // Should have the font-face
        assert_eq!(analysis.font_faces.len(), 1);
        assert_eq!(analysis.font_faces[0].family, "MyFont");
        assert_eq!(analysis.font_faces[0].src, "/fonts/MyFont.woff2");

        // Should have collected chars for MyFont
        assert!(analysis.chars_per_font.contains_key("MyFont"));
        let chars = &analysis.chars_per_font["MyFont"];
        assert!(chars.contains(&'H'));
        assert!(chars.contains(&'W'));
    }

    #[test]
    fn test_parse_css_custom_properties() {
        let css = r#"
            :root {
                --font-mono: 'Iosevka', monospace;
                --font-body: "Inter", sans-serif;
                --spacing: 1rem;
            }
            body { color: black; }
        "#;

        let vars = parse_css_custom_properties(css);
        assert_eq!(
            vars.get("--font-mono"),
            Some(&"'Iosevka', monospace".to_string())
        );
        assert_eq!(
            vars.get("--font-body"),
            Some(&"\"Inter\", sans-serif".to_string())
        );
        assert_eq!(vars.get("--spacing"), Some(&"1rem".to_string()));
    }

    #[test]
    fn test_resolve_css_var_simple() {
        let mut vars = HashMap::new();
        vars.insert(
            "--font-mono".to_string(),
            "'Iosevka', monospace".to_string(),
        );

        let result = resolve_css_var("var(--font-mono)", &vars);
        assert_eq!(result, "'Iosevka', monospace");
    }

    #[test]
    fn test_resolve_css_var_with_fallback() {
        let vars: CssVariables = HashMap::new();

        // When variable doesn't exist, should use fallback
        let result = resolve_css_var("var(--undefined, Arial)", &vars);
        assert_eq!(result, "Arial");
    }

    #[test]
    fn test_resolve_css_var_nested() {
        let mut vars = HashMap::new();
        vars.insert("--base-font".to_string(), "'Inter'".to_string());
        vars.insert(
            "--font-stack".to_string(),
            "var(--base-font), sans-serif".to_string(),
        );

        let result = resolve_css_var("var(--font-stack)", &vars);
        assert_eq!(result, "'Inter', sans-serif");
    }

    #[test]
    fn test_font_family_with_css_var() {
        // This is the exact reproduction case from the issue
        let html = r#"
            <html>
            <head>
                <style>
                    @font-face {
                        font-family: 'Iosevka';
                        src: url('/fonts/Iosevka-Regular.woff2') format('woff2');
                    }

                    :root {
                        --font-mono: 'Iosevka', monospace;
                    }

                    code {
                        font-family: var(--font-mono);
                    }
                </style>
            </head>
            <body>
                <code>fn main() { println!("hello"); }</code>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let analysis = analyze_fonts(html, &css);

        // Should have the font-face for Iosevka
        assert_eq!(analysis.font_faces.len(), 1);
        assert_eq!(analysis.font_faces[0].family, "Iosevka");

        // Should have collected chars for Iosevka (not None/empty!)
        assert!(
            analysis.chars_per_font.contains_key("Iosevka"),
            "chars_per_font should contain Iosevka, but got: {:?}",
            analysis.chars_per_font.keys().collect::<Vec<_>>()
        );

        let iosevka_chars = &analysis.chars_per_font["Iosevka"];
        // Check for characters from: fn main() { println!("hello"); }
        assert!(iosevka_chars.contains(&'f'));
        assert!(iosevka_chars.contains(&'n'));
        assert!(iosevka_chars.contains(&'m'));
        assert!(iosevka_chars.contains(&'('));
        assert!(iosevka_chars.contains(&'{'));
        assert!(iosevka_chars.contains(&'h'));
        assert!(iosevka_chars.contains(&'e'));
        assert!(iosevka_chars.contains(&'l'));
        assert!(iosevka_chars.contains(&'o'));
    }

    #[test]
    fn test_css_var_in_multiple_rules() {
        let css = r#"
            :root {
                --heading-font: 'Playfair Display';
                --body-font: 'Inter';
            }

            h1 { font-family: var(--heading-font); }
            h2 { font-family: var(--heading-font); }
            p { font-family: var(--body-font); }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);

        // Should have 3 rules (h1, h2, p)
        assert_eq!(rules.len(), 3);
        assert_eq!(rules[0].font_family, "Playfair Display");
        assert_eq!(rules[1].font_family, "Playfair Display");
        assert_eq!(rules[2].font_family, "Inter");
    }
}

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

    #[test]
    fn test_css_var_with_unicode_variable_name() {
        let css = r#"
            :root {
                --日本語: 'Noto Sans JP';
            }
            body {
                font-family: var(--日本語);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        assert_eq!(vars.get("--日本語"), Some(&"'Noto Sans JP'".to_string()));

        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].font_family, "Noto Sans JP");
    }

    #[test]
    fn test_css_var_with_unicode_in_value() {
        let css = r#"
            :root {
                --font: '日本語フォント', sans-serif;
            }
            body {
                font-family: var(--font);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "日本語フォント");
    }

    #[test]
    fn test_css_var_unicode_before_var() {
        // Unicode content before var() in the same property value
        let css = r#"
            :root {
                --font: 'Test';
            }
            body {
                font-family: var(--font);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "Test");
    }

    #[test]
    fn test_css_var_with_emoji() {
        let css = r#"
            :root {
                --emoji-font: '🎉 Party Font';
            }
            body {
                font-family: var(--emoji-font);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "🎉 Party Font");
    }

    #[test]
    fn test_css_var_fallback_with_unicode() {
        let css = r#"
            body {
                font-family: var(--undefined, '日本語フォント');
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "日本語フォント");
    }

    #[test]
    fn test_css_var_nested_with_unicode() {
        let css = r#"
            :root {
                --base: '日本語';
                --full: var(--base), sans-serif;
            }
            body {
                font-family: var(--full);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "日本語");
    }

    #[test]
    fn test_unicode_selector() {
        let css = r#"
            .日本語-class {
                font-family: 'Test Font';
            }
        "#;

        let rules = parse_font_family_rules_with_vars(css, &HashMap::new());
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].selector, ".日本語-class");
        assert_eq!(rules[0].font_family, "Test Font");
    }

    #[test]
    fn test_unicode_in_font_face() {
        let css = r#"
            @font-face {
                font-family: '日本語フォント';
                src: url('/fonts/japanese.woff2');
            }
        "#;

        let faces = parse_font_face_rules(css);
        assert_eq!(faces.len(), 1);
        assert_eq!(faces[0].family, "日本語フォント");
    }

    #[test]
    fn test_mixed_unicode_and_ascii_complex() {
        let css = r#"
            :root {
                --primary: 'Helvetica';
                --日本語: 'Noto Sans JP';
                --combined: var(--primary), var(--日本語), sans-serif;
            }
            .my-class {
                font-family: var(--combined);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        assert_eq!(vars.get("--primary"), Some(&"'Helvetica'".to_string()));
        assert_eq!(vars.get("--日本語"), Some(&"'Noto Sans JP'".to_string()));

        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "Helvetica");
    }

    #[test]
    fn test_collect_chars_with_unicode_content() {
        let html = r#"
            <html>
            <head>
                <style>
                    :root { --font: 'TestFont'; }
                    body { font-family: var(--font); }
                </style>
            </head>
            <body>
                <p>日本語テキスト</p>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let chars = collect_chars_per_font(html, &css);

        assert!(chars.contains_key("TestFont"));
        let font_chars = &chars["TestFont"];
        assert!(font_chars.contains(&''));
        assert!(font_chars.contains(&''));
        assert!(font_chars.contains(&''));
    }

    #[test]
    fn test_analyze_fonts_unicode_everywhere() {
        let html = r#"
            <html>
            <head>
                <style>
                    @font-face {
                        font-family: '日本語フォント';
                        src: url('/fonts/jp.woff2');
                    }
                    :root {
                        --jp-font: '日本語フォント', sans-serif;
                    }
                    body {
                        font-family: var(--jp-font);
                    }
                </style>
            </head>
            <body>
                <p>こんにちは世界</p>
            </body>
            </html>
        "#;

        let css = extract_css_from_html(html);
        let analysis = analyze_fonts(html, &css);

        // Font face should be parsed
        assert_eq!(analysis.font_faces.len(), 1);
        assert_eq!(analysis.font_faces[0].family, "日本語フォント");

        // Characters should be collected
        assert!(analysis.chars_per_font.contains_key("日本語フォント"));
        let chars = &analysis.chars_per_font["日本語フォント"];
        assert!(chars.contains(&''));
        assert!(chars.contains(&''));
        assert!(chars.contains(&''));
    }

    #[test]
    fn test_var_immediately_after_unicode() {
        // Edge case: var() immediately after multi-byte chars
        let value = "日本語var(--test)";
        let mut vars = HashMap::new();
        vars.insert("--test".to_string(), "'Result'".to_string());

        let resolved = resolve_css_var(value, &vars);
        assert_eq!(resolved, "日本語'Result'");
    }

    #[test]
    fn test_var_between_unicode() {
        let value = "前var(--mid)後";
        let mut vars = HashMap::new();
        vars.insert("--mid".to_string(), "".to_string());

        let resolved = resolve_css_var(value, &vars);
        assert_eq!(resolved, "前中後");
    }

    #[test]
    fn test_multiple_vars_with_unicode() {
        let value = "var(--a)日本語var(--b)";
        let mut vars = HashMap::new();
        vars.insert("--a".to_string(), "".to_string());
        vars.insert("--b".to_string(), "".to_string());

        let resolved = resolve_css_var(value, &vars);
        assert_eq!(resolved, "前日本語後");
    }

    #[test]
    fn test_four_byte_unicode() {
        // Test with 4-byte UTF-8 characters (emoji, etc.)
        let css = r#"
            :root {
                --emoji: '😀🎉🚀';
            }
            body {
                font-family: var(--emoji);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        assert_eq!(vars.get("--emoji"), Some(&"'😀🎉🚀'".to_string()));

        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "😀🎉🚀");
    }

    #[test]
    fn test_zalgo_text() {
        // Test with combining characters (Zalgo-style text)
        let css = r#"
            :root {
                --zalgo: 'H̷e̶l̵l̴o̷';
            }
            body {
                font-family: var(--zalgo);
            }
        "#;

        let vars = parse_css_custom_properties(css);
        let rules = parse_font_family_rules_with_vars(css, &vars);
        assert_eq!(rules[0].font_family, "H̷e̶l̵l̴o̷");
    }
}