vize_atelier_sfc 0.2.0

Atelier SFC - The Single File Component workshop for Vize
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
//! CSS compilation using LightningCSS.
//!
//! Provides high-performance CSS parsing, transformation, and minification.
//! When the `native` feature is disabled (e.g., for wasm builds), a simple
//! passthrough implementation is used.

#[cfg(feature = "native")]
use lightningcss::printer::PrinterOptions;
#[cfg(feature = "native")]
use lightningcss::stylesheet::{ParserFlags, ParserOptions, StyleSheet};
#[cfg(feature = "native")]
use lightningcss::targets::{Browsers, Targets};
use serde::{Deserialize, Serialize};
use vize_carton::{Bump, BumpVec};

use crate::types::SfcStyleBlock;

/// CSS compilation options
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CssCompileOptions {
    /// Scope ID for scoped CSS (e.g., "data-v-abc123")
    #[serde(default)]
    pub scope_id: Option<String>,

    /// Whether to apply scoped CSS transformation
    #[serde(default)]
    pub scoped: bool,

    /// Whether to minify the output
    #[serde(default)]
    pub minify: bool,

    /// Whether to generate source maps
    #[serde(default)]
    pub source_map: bool,

    /// Browser targets for autoprefixing
    #[serde(default)]
    pub targets: Option<CssTargets>,

    /// Filename for error reporting
    #[serde(default)]
    pub filename: Option<String>,

    /// Whether to enable custom media query resolution
    #[serde(default)]
    pub custom_media: bool,
}

/// Browser targets for CSS autoprefixing
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CssTargets {
    #[serde(default)]
    pub chrome: Option<u32>,
    #[serde(default)]
    pub firefox: Option<u32>,
    #[serde(default)]
    pub safari: Option<u32>,
    #[serde(default)]
    pub edge: Option<u32>,
    #[serde(default)]
    pub ios: Option<u32>,
    #[serde(default)]
    pub android: Option<u32>,
}

#[cfg(feature = "native")]
impl CssTargets {
    fn to_lightningcss_targets(&self) -> Targets {
        let mut browsers = Browsers::default();

        if let Some(v) = self.chrome {
            browsers.chrome = Some(version_to_u32(v));
        }
        if let Some(v) = self.firefox {
            browsers.firefox = Some(version_to_u32(v));
        }
        if let Some(v) = self.safari {
            browsers.safari = Some(version_to_u32(v));
        }
        if let Some(v) = self.edge {
            browsers.edge = Some(version_to_u32(v));
        }
        if let Some(v) = self.ios {
            browsers.ios_saf = Some(version_to_u32(v));
        }
        if let Some(v) = self.android {
            browsers.android = Some(version_to_u32(v));
        }

        Targets::from(browsers)
    }
}

/// Convert major version to LightningCSS format (major << 16)
#[cfg(feature = "native")]
fn version_to_u32(major: u32) -> u32 {
    major << 16
}

/// CSS compilation result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CssCompileResult {
    /// Compiled CSS code
    pub code: String,

    /// Source map (if requested)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub map: Option<String>,

    /// CSS variables found (from v-bind())
    #[serde(default)]
    pub css_vars: Vec<String>,

    /// Errors during compilation
    #[serde(default)]
    pub errors: Vec<String>,

    /// Warnings during compilation
    #[serde(default)]
    pub warnings: Vec<String>,
}

/// Compile CSS using LightningCSS (native feature enabled)
#[cfg(feature = "native")]
pub fn compile_css(css: &str, options: &CssCompileOptions) -> CssCompileResult {
    let bump = Bump::new();
    let filename = options.filename.as_deref().unwrap_or("style.css");

    // Extract v-bind() expressions before parsing
    let (processed_css, css_vars) = extract_and_transform_v_bind(&bump, css);

    // Apply scoped transformation if needed
    let scoped_css = if options.scoped {
        if let Some(ref scope_id) = options.scope_id {
            apply_scoped_css(&bump, processed_css, scope_id)
        } else {
            processed_css
        }
    } else {
        processed_css
    };

    // Apply targets for autoprefixing
    let targets = options
        .targets
        .as_ref()
        .map(|t| t.to_lightningcss_targets())
        .unwrap_or_default();

    // Parse and process CSS
    let (code, errors) = compile_css_internal(
        scoped_css,
        filename,
        options.minify,
        targets,
        options.custom_media,
    );

    CssCompileResult {
        code,
        map: None,
        css_vars,
        errors,
        warnings: vec![],
    }
}

/// Compile CSS (wasm fallback - no LightningCSS)
#[cfg(not(feature = "native"))]
pub fn compile_css(css: &str, options: &CssCompileOptions) -> CssCompileResult {
    let bump = Bump::new();

    // Extract v-bind() expressions before parsing
    let (processed_css, css_vars) = extract_and_transform_v_bind(&bump, css);

    // Apply scoped transformation if needed
    let scoped_css = if options.scoped {
        if let Some(ref scope_id) = options.scope_id {
            apply_scoped_css(&bump, processed_css, scope_id)
        } else {
            processed_css
        }
    } else {
        processed_css
    };

    CssCompileResult {
        code: scoped_css.to_string(),
        map: None,
        css_vars,
        errors: vec![],
        warnings: vec![],
    }
}

/// Internal CSS compilation with owned strings to avoid borrow issues
#[cfg(feature = "native")]
fn compile_css_internal(
    css: &str,
    filename: &str,
    minify: bool,
    targets: Targets,
    custom_media: bool,
) -> (String, Vec<String>) {
    let mut flags = ParserFlags::NESTING | ParserFlags::DEEP_SELECTOR_COMBINATOR;
    if custom_media {
        flags |= ParserFlags::CUSTOM_MEDIA;
    }
    let parser_options = ParserOptions {
        filename: filename.to_string(),
        flags,
        ..Default::default()
    };

    let mut stylesheet = match StyleSheet::parse(css, parser_options) {
        Ok(ss) => ss,
        Err(e) => {
            let mut errors = Vec::with_capacity(1);
            let mut message = String::from("CSS parse error: ");
            message.push_str(&e.to_string());
            errors.push(message);
            return (css.to_string(), errors);
        }
    };

    // Minify if requested
    if minify {
        if let Err(e) = stylesheet.minify(lightningcss::stylesheet::MinifyOptions {
            targets,
            ..Default::default()
        }) {
            let mut errors = Vec::with_capacity(1);
            let mut message = String::from("CSS minify error: ");
            use std::fmt::Write as _;
            let _ = write!(&mut message, "{:?}", e);
            errors.push(message);
            return (css.to_string(), errors);
        }
    }

    // Print the CSS
    let printer_options = PrinterOptions {
        minify,
        targets,
        ..Default::default()
    };

    match stylesheet.to_css(printer_options) {
        Ok(result) => (result.code, vec![]),
        Err(e) => {
            let mut errors = Vec::with_capacity(1);
            let mut message = String::from("CSS print error: ");
            use std::fmt::Write as _;
            let _ = write!(&mut message, "{:?}", e);
            errors.push(message);
            (css.to_string(), errors)
        }
    }
}

/// Compile a style block
pub fn compile_style_block(style: &SfcStyleBlock, options: &CssCompileOptions) -> CssCompileResult {
    let mut opts = options.clone();
    opts.scoped = style.scoped || opts.scoped;
    compile_css(&style.content, &opts)
}

/// Extract v-bind() expressions and transform them to CSS variables
fn extract_and_transform_v_bind<'a>(bump: &'a Bump, css: &str) -> (&'a str, Vec<String>) {
    let css_bytes = css.as_bytes();
    let mut vars = Vec::new();
    let mut result = BumpVec::with_capacity_in(css_bytes.len() * 2, bump);
    let mut pos = 0;

    while pos < css_bytes.len() {
        if let Some(rel_pos) = find_bytes(&css_bytes[pos..], b"v-bind(") {
            let actual_pos = pos + rel_pos;
            let start = actual_pos + 7;

            if let Some(end) = find_byte(&css_bytes[start..], b')') {
                // Copy everything before v-bind(
                result.extend_from_slice(&css_bytes[pos..actual_pos]);

                // Extract expression
                let expr_bytes = &css_bytes[start..start + end];
                let expr_str = unsafe { std::str::from_utf8_unchecked(expr_bytes) }.trim();
                let expr_str = expr_str.trim_matches(|c| c == '"' || c == '\'');
                vars.push(expr_str.to_string());

                // Generate hash and write var(--hash-expr)
                result.extend_from_slice(b"var(--");
                write_v_bind_hash(&mut result, expr_str);
                result.push(b')');

                pos = start + end + 1;
            } else {
                result.extend_from_slice(&css_bytes[pos..]);
                break;
            }
        } else {
            result.extend_from_slice(&css_bytes[pos..]);
            break;
        }
    }

    // SAFETY: input is valid UTF-8, we only add ASCII bytes
    let result_str = unsafe { std::str::from_utf8_unchecked(bump.alloc_slice_copy(&result)) };
    (result_str, vars)
}

/// Write v-bind variable hash to output
fn write_v_bind_hash(out: &mut BumpVec<u8>, expr: &str) {
    let hash: u32 = expr
        .bytes()
        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));

    // Write hash as hex
    write_hex_u32(out, hash);
    out.push(b'-');

    // Write sanitized expression
    for b in expr.bytes() {
        match b {
            b'.' | b'[' | b']' | b'(' | b')' => out.push(b'_'),
            _ => out.push(b),
        }
    }
}

/// Write u32 as 8-digit hex
fn write_hex_u32(out: &mut BumpVec<u8>, val: u32) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push(HEX[((val >> 28) & 0xF) as usize]);
    out.push(HEX[((val >> 24) & 0xF) as usize]);
    out.push(HEX[((val >> 20) & 0xF) as usize]);
    out.push(HEX[((val >> 16) & 0xF) as usize]);
    out.push(HEX[((val >> 12) & 0xF) as usize]);
    out.push(HEX[((val >> 8) & 0xF) as usize]);
    out.push(HEX[((val >> 4) & 0xF) as usize]);
    out.push(HEX[(val & 0xF) as usize]);
}

/// Apply scoped CSS transformation
fn apply_scoped_css<'a>(bump: &'a Bump, css: &str, scope_id: &str) -> &'a str {
    let css_bytes = css.as_bytes();

    // Build attr_selector: [scope_id]
    let mut attr_selector = BumpVec::with_capacity_in(scope_id.len() + 2, bump);
    attr_selector.push(b'[');
    attr_selector.extend_from_slice(scope_id.as_bytes());
    attr_selector.push(b']');
    let attr_selector = bump.alloc_slice_copy(&attr_selector);

    let mut output = BumpVec::with_capacity_in(css_bytes.len() * 2, bump);
    let mut chars = css.char_indices().peekable();
    let mut in_selector = true;
    let mut in_string = false;
    let mut string_char = b'"';
    let mut in_comment = false;
    let mut brace_depth = 0u32;
    let mut last_selector_end = 0usize;
    let mut in_at_rule = false;
    let mut at_rule_depth = 0u32;
    let mut pending_keyframes = false;
    let mut keyframes_brace_depth: Option<u32> = None;
    let mut saved_at_rule_depth: Option<u32> = None;

    while let Some((i, c)) = chars.next() {
        if in_comment {
            if c == '*' {
                if let Some(&(_, '/')) = chars.peek() {
                    chars.next();
                    in_comment = false;
                }
            }
            continue;
        }

        if in_string {
            if c as u8 == string_char {
                // Check for escape
                let prev_byte = if i > 0 { css_bytes[i - 1] } else { 0 };
                if prev_byte != b'\\' {
                    in_string = false;
                }
            }
            if !in_selector && !in_at_rule {
                output.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
            }
            continue;
        }

        match c {
            '"' | '\'' => {
                in_string = true;
                string_char = c as u8;
                if !in_selector && !in_at_rule {
                    output.push(c as u8);
                }
            }
            '/' => {
                if let Some(&(_, '*')) = chars.peek() {
                    chars.next();
                    in_comment = true;
                } else if !in_selector && !in_at_rule {
                    output.push(b'/');
                }
            }
            '@' if in_selector => {
                in_at_rule = true;
                in_selector = false;
                // Look ahead to detect @keyframes (including vendor prefixes)
                let remaining = &css[i + 1..];
                pending_keyframes = remaining.starts_with("keyframes")
                    || remaining.starts_with("-webkit-keyframes")
                    || remaining.starts_with("-moz-keyframes")
                    || remaining.starts_with("-o-keyframes");
                // Don't output '@' — the entire at-rule header will be flushed
                // from the buffer when we encounter '{' or ';'
            }
            '@' => {
                // @ in non-selector context (e.g., CSS nesting @media inside a rule)
                output.push(b'@');
            }
            ';' if in_at_rule => {
                // Statement at-rule (e.g., @import, @charset, @namespace)
                // Flush the entire at-rule including the semicolon
                let stmt = &css_bytes[last_selector_end..=i];
                let stmt_str = unsafe { std::str::from_utf8_unchecked(stmt) }.trim();
                output.extend_from_slice(stmt_str.as_bytes());
                output.push(b'\n');
                in_at_rule = false;
                in_selector = true;
                pending_keyframes = false;
                last_selector_end = i + 1;
            }
            '{' => {
                brace_depth += 1;
                if in_at_rule {
                    in_at_rule = false;
                    // Flush the buffered at-rule header (e.g., "@media (--mobile)")
                    let at_rule_header = &css_bytes[last_selector_end..i];
                    let at_rule_str =
                        unsafe { std::str::from_utf8_unchecked(at_rule_header) }.trim();
                    output.extend_from_slice(at_rule_str.as_bytes());
                    output.push(b'{');
                    if pending_keyframes {
                        saved_at_rule_depth = Some(at_rule_depth);
                        keyframes_brace_depth = Some(brace_depth);
                        pending_keyframes = false;
                    }
                    at_rule_depth = brace_depth;
                    in_selector = true;
                    last_selector_end = i + 1;
                } else if keyframes_brace_depth.is_some_and(|d| brace_depth > d) {
                    // Inside @keyframes: output the stop name (from/to/0%/100%)
                    let kf_part = &css_bytes[last_selector_end..i];
                    let kf_str = unsafe { std::str::from_utf8_unchecked(kf_part) }.trim();
                    output.extend_from_slice(kf_str.as_bytes());
                    output.push(b'{');
                    in_selector = false;
                    last_selector_end = i + 1;
                } else if in_selector
                    && (brace_depth == 1 || (at_rule_depth > 0 && brace_depth > at_rule_depth))
                {
                    // End of selector, apply scope
                    let selector_bytes = &css_bytes[last_selector_end..i];
                    let selector_str =
                        unsafe { std::str::from_utf8_unchecked(selector_bytes) }.trim();
                    scope_selector(&mut output, selector_str, attr_selector);
                    output.push(b'{');
                    in_selector = false;
                    last_selector_end = i + 1;
                } else {
                    output.push(b'{');
                }
            }
            '}' => {
                brace_depth = brace_depth.saturating_sub(1);
                output.push(b'}');
                // Check @keyframes block end — restore parent at_rule_depth
                if keyframes_brace_depth.is_some_and(|d| brace_depth < d) {
                    keyframes_brace_depth = None;
                    if let Some(saved) = saved_at_rule_depth.take() {
                        at_rule_depth = saved;
                    }
                }
                if brace_depth == 0 {
                    in_selector = true;
                    last_selector_end = i + 1;
                    at_rule_depth = 0;
                } else if at_rule_depth > 0 && brace_depth >= at_rule_depth {
                    // Inside at-rule, back to selector mode for next rule
                    in_selector = true;
                    last_selector_end = i + 1;
                }
            }
            _ if in_selector || in_at_rule => {
                // Still building selector or at-rule header, don't output yet
            }
            _ => {
                output.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
            }
        }
    }

    // Handle any remaining content
    if in_selector && last_selector_end < css_bytes.len() {
        output.extend_from_slice(&css_bytes[last_selector_end..]);
    }

    // SAFETY: input is valid UTF-8, we only add ASCII bytes
    unsafe { std::str::from_utf8_unchecked(bump.alloc_slice_copy(&output)) }
}

/// Add scope attribute to a selector
fn scope_selector(out: &mut BumpVec<u8>, selector: &str, attr_selector: &[u8]) {
    if selector.is_empty() {
        return;
    }

    // Handle at-rules that don't have selectors
    if selector.starts_with('@') {
        out.extend_from_slice(selector.as_bytes());
        return;
    }

    // Handle multiple selectors separated by comma
    let mut first = true;
    for part in selector.split(',') {
        if !first {
            out.extend_from_slice(b", ");
        }
        first = false;
        scope_single_selector(out, part.trim(), attr_selector);
    }
}

/// Add scope attribute to a single selector
fn scope_single_selector(out: &mut BumpVec<u8>, selector: &str, attr_selector: &[u8]) {
    if selector.is_empty() {
        return;
    }

    // Handle :deep(), :slotted(), :global()
    if let Some(pos) = selector.find(":deep(") {
        transform_deep(out, selector, pos, attr_selector);
        return;
    }

    if let Some(pos) = selector.find(":slotted(") {
        transform_slotted(out, selector, pos, attr_selector);
        return;
    }

    if let Some(pos) = selector.find(":global(") {
        transform_global(out, selector, pos);
        return;
    }

    // Find the last simple selector to append the attribute
    let parts: Vec<&str> = selector.split_whitespace().collect();
    if parts.is_empty() {
        out.extend_from_slice(selector.as_bytes());
        return;
    }

    // Add scope to the last part
    for (i, part) in parts.iter().enumerate() {
        if i > 0 {
            out.push(b' ');
        }

        if i == parts.len() - 1 {
            // Last part - add scope
            add_scope_to_element(out, part, attr_selector);
        } else {
            out.extend_from_slice(part.as_bytes());
        }
    }
}

/// Add scope attribute to an element selector
fn add_scope_to_element(out: &mut BumpVec<u8>, selector: &str, attr_selector: &[u8]) {
    let bytes = selector.as_bytes();

    // Handle pseudo-elements (::before, ::after, etc.)
    if let Some(pseudo_pos) = find_bytes(bytes, b"::") {
        out.extend_from_slice(&bytes[..pseudo_pos]);
        out.extend_from_slice(attr_selector);
        out.extend_from_slice(&bytes[pseudo_pos..]);
        return;
    }

    // Handle pseudo-classes (:hover, :focus, etc.)
    if let Some(pseudo_pos) = rfind_byte(bytes, b':') {
        if pseudo_pos > 0 && bytes[pseudo_pos - 1] != b'\\' {
            out.extend_from_slice(&bytes[..pseudo_pos]);
            out.extend_from_slice(attr_selector);
            out.extend_from_slice(&bytes[pseudo_pos..]);
            return;
        }
    }

    out.extend_from_slice(bytes);
    out.extend_from_slice(attr_selector);
}

/// Transform :deep() to descendant selector
fn transform_deep(out: &mut BumpVec<u8>, selector: &str, start: usize, attr_selector: &[u8]) {
    let before = &selector[..start];
    let after = &selector[start + 6..];

    if let Some(end) = find_matching_paren(after) {
        let inner = &after[..end];
        let rest = &after[end + 1..];

        if before.is_empty() {
            out.extend_from_slice(attr_selector);
        } else {
            out.extend_from_slice(before.trim().as_bytes());
            out.extend_from_slice(attr_selector);
        }
        out.push(b' ');
        out.extend_from_slice(inner.as_bytes());
        out.extend_from_slice(rest.as_bytes());
    } else {
        out.extend_from_slice(selector.as_bytes());
    }
}

/// Transform :slotted() for slot content
fn transform_slotted(out: &mut BumpVec<u8>, selector: &str, start: usize, attr_selector: &[u8]) {
    let after = &selector[start + 9..];

    if let Some(end) = find_matching_paren(after) {
        let inner = &after.as_bytes()[..end];
        let rest = &after.as_bytes()[end + 1..];

        out.extend_from_slice(inner);
        // Convert [data-v-xxx] to [data-v-xxx-s] for slotted styles
        if attr_selector.last() == Some(&b']') {
            out.extend_from_slice(&attr_selector[..attr_selector.len() - 1]);
            out.extend_from_slice(b"-s]");
        } else {
            out.extend_from_slice(attr_selector);
            out.extend_from_slice(b"-s");
        }
        out.extend_from_slice(rest);
    } else {
        out.extend_from_slice(selector.as_bytes());
    }
}

/// Transform :global() to unscoped
fn transform_global(out: &mut BumpVec<u8>, selector: &str, start: usize) {
    let before = &selector[..start];
    let after = &selector[start + 8..];

    if let Some(end) = find_matching_paren(after) {
        let inner = &after[..end];
        let rest = &after[end + 1..];

        out.extend_from_slice(before.as_bytes());
        out.extend_from_slice(inner.as_bytes());
        out.extend_from_slice(rest.as_bytes());
    } else {
        out.extend_from_slice(selector.as_bytes());
    }
}

/// Find the matching closing parenthesis
fn find_matching_paren(s: &str) -> Option<usize> {
    let mut depth = 1u32;
    for (i, c) in s.char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Find byte sequence in slice
#[inline]
fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Find single byte in slice
#[inline]
fn find_byte(haystack: &[u8], needle: u8) -> Option<usize> {
    haystack.iter().position(|&b| b == needle)
}

/// Reverse find single byte in slice
#[inline]
fn rfind_byte(haystack: &[u8], needle: u8) -> Option<usize> {
    haystack.iter().rposition(|&b| b == needle)
}

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

    #[test]
    fn test_compile_simple_css() {
        let css = ".foo { color: red; }";
        let result = compile_css(css, &CssCompileOptions::default());
        assert!(result.errors.is_empty());
        assert!(result.code.contains(".foo"));
        assert!(result.code.contains("color"));
    }

    #[test]
    fn test_compile_scoped_css() {
        let css = ".foo { color: red; }";
        let result = compile_css(
            css,
            &CssCompileOptions {
                scoped: true,
                scope_id: Some("data-v-123".to_string()),
                ..Default::default()
            },
        );
        assert!(result.errors.is_empty());
        assert!(result.code.contains("[data-v-123]"));
    }

    #[test]
    #[cfg(feature = "native")]
    fn test_compile_minified_css() {
        let css = ".foo {\n  color: red;\n  background: blue;\n}";
        let result = compile_css(
            css,
            &CssCompileOptions {
                minify: true,
                ..Default::default()
            },
        );
        assert!(result.errors.is_empty());
        // Minified should have no newlines in simple case
        assert!(!result.code.contains('\n') || result.code.lines().count() == 1);
    }

    #[test]
    fn test_v_bind_extraction() {
        let bump = Bump::new();
        let css = ".foo { color: v-bind(color); background: v-bind('bgColor'); }";
        let (transformed, vars) = extract_and_transform_v_bind(&bump, css);
        assert_eq!(vars.len(), 2);
        assert!(vars.contains(&"color".to_string()));
        assert!(vars.contains(&"bgColor".to_string()));
        assert!(transformed.contains("var(--"));
    }

    #[test]
    fn test_scope_deep() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        transform_deep(&mut out, ":deep(.child)", 0, b"[data-v-123]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, "[data-v-123] .child");
    }

    #[test]
    fn test_scope_global() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        transform_global(&mut out, ":global(.foo)", 0);
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, ".foo");
    }

    #[test]
    fn test_scope_slotted() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        transform_slotted(&mut out, ":slotted(.child)", 0, b"[data-v-123]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, ".child[data-v-123-s]");
    }

    #[test]
    fn test_scope_slotted_with_pseudo() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        transform_slotted(&mut out, ":slotted(.child):hover", 0, b"[data-v-abc]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, ".child[data-v-abc-s]:hover");
    }

    #[test]
    fn test_scope_slotted_complex() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        transform_slotted(&mut out, ":slotted(div.foo)", 0, b"[data-v-12345678]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, "div.foo[data-v-12345678-s]");
    }

    #[test]
    fn test_scope_with_pseudo_element() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        add_scope_to_element(&mut out, ".foo::before", b"[data-v-123]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, ".foo[data-v-123]::before");
    }

    #[test]
    fn test_scope_with_pseudo_class() {
        let bump = Bump::new();
        let mut out = BumpVec::new_in(&bump);
        add_scope_to_element(&mut out, ".foo:hover", b"[data-v-123]");
        let result = unsafe { std::str::from_utf8_unchecked(&out) };
        assert_eq!(result, ".foo[data-v-123]:hover");
    }

    #[test]
    #[cfg(feature = "native")]
    fn test_compile_with_targets() {
        let css = ".foo { display: flex; }";
        let result = compile_css(
            css,
            &CssCompileOptions {
                targets: Some(CssTargets {
                    chrome: Some(80),
                    ..Default::default()
                }),
                ..Default::default()
            },
        );
        assert!(result.errors.is_empty());
        assert!(result.code.contains("flex"));
    }

    #[test]
    fn test_scoped_css_with_quoted_font_family() {
        let css = ".foo { font-family: 'JetBrains Mono', monospace; }";
        let result = compile_css(
            css,
            &CssCompileOptions {
                scoped: true,
                scope_id: Some("data-v-123".to_string()),
                ..Default::default()
            },
        );
        println!("Result: {}", result.code);
        assert!(result.errors.is_empty());
        // Note: LightningCSS may remove quotes from font names
        assert!(
            result.code.contains("JetBrains Mono"),
            "Expected font name in: {}",
            result.code
        );
        assert!(result.code.contains("monospace"));
    }

    #[test]
    fn test_apply_scoped_css_at_media() {
        let bump = Bump::new();
        // Root-level @media with selectors inside
        let css = ".foo { color: red; }\n@media (max-width: 768px) { .foo { color: blue; } }";
        let result = apply_scoped_css(&bump, css, "data-v-123");
        println!("@media result: {}", result);
        assert!(
            result.contains("@media (max-width: 768px)"),
            "Expected @media query preserved in: {}",
            result
        );
        // Both .foo selectors should be scoped
        assert_eq!(
            result.matches("[data-v-123]").count(),
            2,
            "Expected 2 scope attributes in: {}",
            result
        );
    }

    #[test]
    fn test_apply_scoped_css_at_media_custom_media() {
        let bump = Bump::new();
        // @media with custom media queries (like --mobile)
        let css = ".a { color: red; }\n@media (--mobile) { .a { font-size: 12px; } }";
        let result = apply_scoped_css(&bump, css, "data-v-abc");
        println!("Custom media result: {}", result);
        assert!(
            result.contains("@media (--mobile)"),
            "Expected @media (--mobile) preserved in: {}",
            result
        );
        assert_eq!(
            result.matches("[data-v-abc]").count(),
            2,
            "Expected 2 scope attributes in: {}",
            result
        );
    }

    #[test]
    fn test_apply_scoped_css_multiple_selectors_in_media() {
        let bump = Bump::new();
        // Multiple selectors inside @media
        let css = "@media (--mobile) { .a { color: red; } .b { color: blue; } }";
        let result = apply_scoped_css(&bump, css, "data-v-xyz");
        println!("Multi selector result: {}", result);
        assert!(result.contains("@media (--mobile)"));
        assert_eq!(
            result.matches("[data-v-xyz]").count(),
            2,
            "Expected 2 scope attributes in: {}",
            result
        );
    }

    #[test]
    fn test_apply_scoped_css_with_quoted_string() {
        let bump = Bump::new();
        // Test the raw scoping function without LightningCSS
        let css = ".foo { font-family: 'JetBrains Mono', monospace; }";
        let result = apply_scoped_css(&bump, css, "data-v-123");
        println!("Scoped result: {}", result);
        assert!(
            result.contains("'JetBrains Mono'"),
            "Expected quoted font name in: {}",
            result
        );
        assert!(result.contains("monospace"));
    }

    #[test]
    fn test_apply_scoped_css_at_import() {
        let bump = Bump::new();
        // @import should be preserved and not treated as a block at-rule
        let css = "@import \"~/assets/styles/custom-media-query.css\";\n\nfooter { width: 100%; }";
        let result = apply_scoped_css(&bump, css, "data-v-123");
        println!("@import result: {}", result);
        assert!(
            result.contains("@import \"~/assets/styles/custom-media-query.css\";"),
            "Expected @import preserved in: {}",
            result
        );
        assert!(
            result.contains("footer[data-v-123]"),
            "Expected footer scoped in: {}",
            result
        );
    }

    #[test]
    fn test_apply_scoped_css_at_import_with_nested_css() {
        let bump = Bump::new();
        // @import followed by CSS nesting with @media
        let css = "@import \"custom.css\";\n\nfooter {\n  width: 100%;\n  @media (--mobile) {\n    padding: 1rem;\n  }\n}";
        let result = apply_scoped_css(&bump, css, "data-v-abc");
        println!("@import + nesting result: {}", result);
        assert!(
            result.contains("@import \"custom.css\";"),
            "Expected @import preserved in: {}",
            result
        );
        assert!(
            result.contains("footer[data-v-abc]"),
            "Expected footer scoped in: {}",
            result
        );
        // Nested @media should be inside the scoped footer block
        assert!(
            result.contains("@media (--mobile)"),
            "Expected nested @media preserved in: {}",
            result
        );
    }
}