css-variable-lsp 0.3.2

A fast, Rust-based Language Server Protocol implementation for CSS Variables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
use ls_types::{Range, Uri};
use tracing::warn;

use crate::color::normalized_color_key;
use crate::manager::CssVariableManager;
use crate::types::{
    offset_to_position, CssVariable, CssVariableUsage, DOMNodeInfo, LiteralColorOccurrence,
};

const UNKNOWN_SELECTOR: &str = "<unknown>";

/// Maximum input size to prevent memory exhaustion (10MB)
const MAX_INPUT_SIZE_BYTES: usize = 10 * 1024 * 1024;

/// At-rules that block variable extraction (descriptors, not CSS properties)
const BLOCK_LIST: &[&str] = &[
    "@font-face",
    "@property",
    "@keyframes",
    "@counter-style",
    "@font-feature-values",
    "@scroll-timeline",
];

/// Extract at-rule name, returns lowercase for case-insensitive matching.
/// Handles vendor prefixes and whitespace between @rule and {.
fn extract_at_rule_name(bytes: &[u8], start: usize) -> Option<String> {
    let remaining = &bytes[start + 1..]; // Skip '@'
    let mut end = 0;
    let mut found_ident = false;

    while end < remaining.len() {
        let b = remaining[end];
        if b.is_ascii_whitespace() {
            if found_ident {
                break; // Whitespace after ident = end of name
            }
            end += 1;
            continue;
        }
        if is_ident_char(b) || b == b'-' {
            found_ident = true;
            end += 1;
            continue;
        }
        break; // Non-ident char
    }

    if end > 0 {
        let name = std::str::from_utf8(&remaining[..end]).ok()?;
        Some(format!("@{}", name.to_ascii_lowercase()))
    } else {
        None
    }
}

/// Check if character is valid in CSS identifiers
#[inline]
fn is_ident_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
}

/// Returns true if this at-rule blocks custom property extraction.
/// Case-insensitive matching.
fn should_block_variables(at_rule: &str) -> bool {
    let at_rule_lower = at_rule.to_ascii_lowercase();

    // Check blocklist - handles @font-face, @property, @keyframes, etc.
    if BLOCK_LIST.iter().any(|name| *name == at_rule_lower) {
        return true;
    }

    // FIXED v3: Use contains("keyframes") instead of starts_with("@-")
    // because standard @keyframes doesn't start with "@-"
    if at_rule_lower.contains("keyframes") {
        return true;
    }

    false
}

/// Configuration for parsing CSS snippets
pub struct CssParseContext<'a> {
    pub css_text: &'a str,
    pub full_text: &'a str,
    pub uri: &'a Uri,
    pub manager: &'a CssVariableManager,
    pub base_offset: usize,
    pub inline: bool,
    pub usage_context_override: Option<&'a str>,
    pub dom_node: Option<DOMNodeInfo>,
}

/// Parse a CSS document and extract variable definitions and usages
pub async fn parse_css_document(
    text: &str,
    uri: &Uri,
    manager: &CssVariableManager,
) -> Result<(), String> {
    // Memory bounds check to prevent exhaustion attacks
    if text.len() > MAX_INPUT_SIZE_BYTES {
        return Err(format!(
            "CSS input too large ({} bytes), maximum allowed is {} bytes",
            text.len(),
            MAX_INPUT_SIZE_BYTES
        ));
    }

    let context = CssParseContext {
        css_text: text,
        full_text: text,
        uri,
        manager,
        base_offset: 0,
        inline: false,
        usage_context_override: None,
        dom_node: None,
    };
    parse_css_snippet(context).await
}

/// Parse a CSS snippet with a base offset into the full document.
pub async fn parse_css_snippet(context: CssParseContext<'_>) -> Result<(), String> {
    extract_definitions(
        context.css_text,
        context.full_text,
        context.uri,
        context.manager,
        context.base_offset,
        context.inline,
        context.usage_context_override,
    )
    .await;
    extract_usages(
        context.css_text,
        context.full_text,
        context.uri,
        context.manager,
        context.base_offset,
        context.usage_context_override,
        context.dom_node,
    )
    .await;
    extract_literal_colors(
        context.css_text,
        context.full_text,
        context.uri,
        context.manager,
        context.base_offset,
        context.usage_context_override,
    )
    .await;
    Ok(())
}

async fn extract_definitions(
    css_text: &str,
    full_text: &str,
    uri: &Uri,
    manager: &CssVariableManager,
    base_offset: usize,
    inline: bool,
    selector_override: Option<&str>,
) {
    for_each_declaration(
        css_text,
        selector_override,
        |property_name,
         property_name_start,
         property_name_end,
         value_start,
         value_end,
         selector| {
            if !property_name.starts_with("--") {
                return None;
            }

            let value = css_text[value_start..value_end].trim().to_string();
            let abs_name_start = base_offset + property_name_start;
            let abs_name_end = base_offset + property_name_end;
            let abs_value_start = base_offset + value_start;
            let abs_value_end = base_offset + value_end;

            Some(CssVariable {
                name: property_name.to_string(),
                value: value.clone(),
                uri: uri.clone(),
                range: Range::new(
                    offset_to_position(full_text, abs_name_start),
                    offset_to_position(full_text, abs_value_end),
                ),
                name_range: Some(Range::new(
                    offset_to_position(full_text, abs_name_start),
                    offset_to_position(full_text, abs_name_end),
                )),
                value_range: Some(Range::new(
                    offset_to_position(full_text, abs_value_start),
                    offset_to_position(full_text, abs_value_end),
                )),
                selector,
                important: value.to_lowercase().contains("!important"),
                inline,
                source_position: abs_name_start,
            })
        },
        |variable| async move {
            if let Err(e) = manager.add_variable(variable).await {
                warn!("Failed to add CSS variable: {}", e);
            }
        },
    )
    .await;
}

async fn extract_literal_colors(
    css_text: &str,
    full_text: &str,
    uri: &Uri,
    manager: &CssVariableManager,
    base_offset: usize,
    selector_override: Option<&str>,
) {
    for_each_declaration(
        css_text,
        selector_override,
        |_, _, _, value_start, value_end, selector| {
            let value = &css_text[value_start..value_end];
            let colors = extract_literal_colors_from_value(value)
                .into_iter()
                .map(
                    |(relative_start, relative_end, normalized_color)| LiteralColorOccurrence {
                        text: value[relative_start..relative_end].to_string(),
                        uri: uri.clone(),
                        range: Range::new(
                            offset_to_position(
                                full_text,
                                base_offset + value_start + relative_start,
                            ),
                            offset_to_position(full_text, base_offset + value_start + relative_end),
                        ),
                        usage_context: selector.clone(),
                        normalized_color,
                    },
                )
                .collect::<Vec<_>>();
            Some(colors)
        },
        |occurrences| async move {
            for occurrence in occurrences {
                manager.add_literal_color(occurrence).await;
            }
        },
    )
    .await;
}

async fn for_each_declaration<T, F, Fut>(
    css_text: &str,
    selector_override: Option<&str>,
    mut build: F,
    mut on_item: impl FnMut(T) -> Fut,
) where
    F: FnMut(&str, usize, usize, usize, usize, String) -> Option<T>,
    Fut: std::future::Future<Output = ()>,
{
    let bytes = css_text.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut in_comment = false;
    let mut in_string: Option<u8> = None;
    let mut brace_depth = 0;
    let mut current_at_rule: Option<String> = None;
    let mut blocking_at_rule: Option<String> = None;
    let mut declaration_start = 0usize;
    let mut selector_stack: Vec<String> = Vec::with_capacity(16);
    let allow_without_braces = selector_override.is_some();

    while i < len {
        if in_comment {
            if i + 1 < len && bytes[i] == b'*' && bytes[i + 1] == b'/' {
                in_comment = false;
                i += 2;
                continue;
            }
            i += 1;
            continue;
        }

        if let Some(quote) = in_string {
            if bytes[i] == b'\\' {
                i += 2;
                continue;
            }
            if bytes[i] == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
            in_comment = true;
            i += 2;
            continue;
        }

        if bytes[i] == b'"' || bytes[i] == b'\'' {
            in_string = Some(bytes[i]);
            i += 1;
            continue;
        }

        if bytes[i] == b'@' && !in_comment && in_string.is_none() {
            // Extract at-rule name for case-insensitive matching
            current_at_rule = extract_at_rule_name(bytes, i);
        }

        if bytes[i] == b'{' {
            brace_depth += 1;

            // Check if this at-rule blocks variable extraction
            if let Some(ref at_rule) = current_at_rule {
                if should_block_variables(at_rule) {
                    blocking_at_rule = Some(at_rule.clone());
                }
            }

            // Skip selector push for blocking at-rules (@font-face, @keyframes, etc.)
            if blocking_at_rule.is_none() {
                selector_stack.push(resolve_block_selector(
                    css_text,
                    i,
                    current_at_rule.is_some(),
                    selector_stack.last(),
                ));
            }

            // Reset at-rule tracking after entering block
            current_at_rule = None;
            declaration_start = i + 1;
            i += 1;
            continue;
        }

        if bytes[i] == b'}' {
            brace_depth -= 1;
            if brace_depth < 0 {
                brace_depth = 0;
            }
            // SECURE: Guard against empty stack on malformed CSS
            if !selector_stack.is_empty() {
                selector_stack.pop();
            }
            // Clear blocking state when exiting a blocking at-rule's block
            if blocking_at_rule.is_some() && brace_depth == 0 {
                blocking_at_rule = None;
            }
            declaration_start = i + 1;
            i += 1;
            continue;
        }

        if bytes[i] == b';' {
            if current_at_rule.is_some() {
                // At-rule ended without braces (e.g., @import "file.css";)
                current_at_rule = None;
            }
            declaration_start = i + 1;
            i += 1;
            continue;
        }

        if bytes[i] != b':' || (brace_depth == 0 && !allow_without_braces) {
            i += 1;
            continue;
        }

        let mut name_end = i;
        while name_end > declaration_start && bytes[name_end - 1].is_ascii_whitespace() {
            name_end -= 1;
        }

        let mut name_start = name_end;
        while name_start > declaration_start && is_ident_char(bytes[name_start - 1]) {
            name_start -= 1;
        }

        if name_end <= name_start {
            i += 1;
            continue;
        }

        if has_non_whitespace_outside_comments(&css_text[declaration_start..name_start]) {
            i += 1;
            continue;
        }

        let property_name = &css_text[name_start..name_end];
        let mut value_start = i + 1;
        while value_start < len && bytes[value_start].is_ascii_whitespace() {
            value_start += 1;
        }

        let mut value_end = value_start;
        let mut depth = 0i32;
        let mut val_in_comment = false;
        let mut val_in_string: Option<u8> = None;
        while value_end < len {
            let b = bytes[value_end];
            if val_in_comment {
                if value_end + 1 < len && b == b'*' && bytes[value_end + 1] == b'/' {
                    val_in_comment = false;
                    value_end += 2;
                    continue;
                }
                value_end += 1;
                continue;
            }
            if let Some(q) = val_in_string {
                if b == b'\\' {
                    value_end += 2;
                    continue;
                }
                if b == q {
                    val_in_string = None;
                }
                value_end += 1;
                continue;
            }
            if value_end + 1 < len && b == b'/' && bytes[value_end + 1] == b'*' {
                val_in_comment = true;
                value_end += 2;
                continue;
            }
            if b == b'"' || b == b'\'' {
                val_in_string = Some(b);
                value_end += 1;
                continue;
            }
            if b == b'(' {
                depth += 1;
                value_end += 1;
                continue;
            }
            if b == b')' && depth > 0 {
                depth -= 1;
                value_end += 1;
                continue;
            }
            if depth == 0 && (b == b';' || b == b'}') {
                break;
            }
            value_end += 1;
        }

        let mut value_end_trim = value_end;
        while value_end_trim > value_start && bytes[value_end_trim - 1].is_ascii_whitespace() {
            value_end_trim -= 1;
        }

        let selector = selector_override
            .map(|s| s.to_string())
            .or_else(|| selector_stack.last().cloned())
            .or_else(|| find_selector_before(css_text, name_start, current_at_rule.is_some()))
            .unwrap_or_else(|| UNKNOWN_SELECTOR.to_string());

        if let Some(item) = build(
            property_name,
            name_start,
            name_end,
            value_start,
            value_end_trim,
            selector,
        ) {
            on_item(item).await;
        }

        i = value_end;
    }
}

async fn extract_usages(
    css_text: &str,
    full_text: &str,
    uri: &Uri,
    manager: &CssVariableManager,
    base_offset: usize,
    usage_context_override: Option<&str>,
    dom_node: Option<DOMNodeInfo>,
) {
    let bytes = css_text.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut in_comment = false;
    let mut in_string: Option<u8> = None;
    let mut brace_depth = 0;
    let mut current_at_rule: Option<String> = None;
    let mut blocking_at_rule: Option<String> = None;
    let mut selector_stack: Vec<String> = Vec::with_capacity(16);

    while i < len {
        if in_comment {
            if i + 1 < len && bytes[i] == b'*' && bytes[i + 1] == b'/' {
                in_comment = false;
                i += 2;
                continue;
            }
            i += 1;
            continue;
        }

        if let Some(quote) = in_string {
            if bytes[i] == b'\\' {
                i += 2;
                continue;
            }
            if bytes[i] == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
            in_comment = true;
            i += 2;
            continue;
        }

        if bytes[i] == b'"' || bytes[i] == b'\'' {
            in_string = Some(bytes[i]);
            i += 1;
            continue;
        }

        // Track braces for scope
        if bytes[i] == b'{' {
            // Check if this at-rule blocks variable extraction
            if let Some(ref at_rule) = current_at_rule {
                if should_block_variables(at_rule) {
                    blocking_at_rule = Some(at_rule.clone());
                }
            }

            // Skip selector push for blocking at-rules
            if blocking_at_rule.is_none() {
                selector_stack.push(resolve_block_selector(
                    css_text,
                    i,
                    current_at_rule.is_some(),
                    selector_stack.last(),
                ));
            }

            // Reset at-rule tracking after entering block
            current_at_rule = None;
            brace_depth += 1;
        } else if bytes[i] == b'}' {
            brace_depth -= 1;
            if brace_depth < 0 {
                brace_depth = 0;
            }
            // SECURE: Guard against empty stack on malformed CSS
            if !selector_stack.is_empty() {
                selector_stack.pop();
            }
            // Clear blocking state when exiting a blocking at-rule's block
            if blocking_at_rule.is_some() && brace_depth == 0 {
                blocking_at_rule = None;
            }
        }

        // Track @-rules
        if bytes[i] == b'@' && !in_comment && in_string.is_none() {
            current_at_rule = extract_at_rule_name(bytes, i);
        }

        if is_var_function(bytes, i) {
            let var_start = i;
            let mut j = i + 3;
            while j < len && bytes[j].is_ascii_whitespace() {
                j += 1;
            }
            if j >= len || bytes[j] != b'(' {
                i += 1;
                continue;
            }
            let args_start = j + 1;
            let mut name_start = None;
            let mut name_end = None;
            let mut k = args_start;
            while k < len && bytes[k].is_ascii_whitespace() {
                k += 1;
            }
            if k + 1 < len && bytes[k] == b'-' && bytes[k + 1] == b'-' {
                name_start = Some(k);
                k += 2;
                while k < len && is_ident_char(bytes[k]) {
                    k += 1;
                }
                name_end = Some(k);
            }

            let mut depth = 1i32;
            let mut p = args_start;
            let mut var_in_comment = false;
            let mut var_in_string: Option<u8> = None;
            while p < len && depth > 0 {
                let b = bytes[p];
                if var_in_comment {
                    if p + 1 < len && b == b'*' && bytes[p + 1] == b'/' {
                        var_in_comment = false;
                        p += 2;
                        continue;
                    }
                    p += 1;
                    continue;
                }
                if let Some(q) = var_in_string {
                    if b == b'\\' {
                        p += 2;
                        continue;
                    }
                    if b == q {
                        var_in_string = None;
                    }
                    p += 1;
                    continue;
                }
                if p + 1 < len && b == b'/' && bytes[p + 1] == b'*' {
                    var_in_comment = true;
                    p += 2;
                    continue;
                }
                if b == b'"' || b == b'\'' {
                    var_in_string = Some(b);
                    p += 1;
                    continue;
                }
                if b == b'(' {
                    depth += 1;
                    p += 1;
                    continue;
                }
                if b == b')' {
                    depth -= 1;
                    p += 1;
                    continue;
                }
                p += 1;
            }

            let var_end = p.min(len);
            if let (Some(ns), Some(ne)) = (name_start, name_end) {
                let name = css_text[ns..ne].to_string();
                let usage_context = usage_context_override
                    .map(|s| s.to_string())
                    .or_else(|| selector_stack.last().cloned())
                    .or_else(|| {
                        find_selector_before(css_text, var_start, current_at_rule.is_some())
                    })
                    .unwrap_or_else(|| UNKNOWN_SELECTOR.to_string());
                let abs_start = base_offset + var_start;
                let abs_end = base_offset + var_end;
                let abs_name_start = base_offset + ns;
                let abs_name_end = base_offset + ne;

                let usage = CssVariableUsage {
                    name,
                    uri: uri.clone(),
                    range: Range::new(
                        offset_to_position(full_text, abs_start),
                        offset_to_position(full_text, abs_end),
                    ),
                    name_range: Some(Range::new(
                        offset_to_position(full_text, abs_name_start),
                        offset_to_position(full_text, abs_name_end),
                    )),
                    usage_context,
                    dom_node: dom_node.clone(),
                };
                manager.add_usage(usage).await;
            }

            i = var_end;
            continue;
        }

        i += 1;
    }
}

fn is_var_function(bytes: &[u8], idx: usize) -> bool {
    if idx + 2 >= bytes.len() {
        return false;
    }
    if !bytes[idx].eq_ignore_ascii_case(&b'v')
        || !bytes[idx + 1].eq_ignore_ascii_case(&b'a')
        || !bytes[idx + 2].eq_ignore_ascii_case(&b'r')
    {
        return false;
    }
    if idx > 0 && is_ident_char(bytes[idx - 1]) {
        return false;
    }
    true
}

fn has_non_whitespace_outside_comments(segment: &str) -> bool {
    let bytes = segment.as_bytes();
    let mut i = 0usize;
    let mut in_comment = false;
    let mut in_string: Option<u8> = None;

    while i < bytes.len() {
        if in_comment {
            if i + 1 < bytes.len() && bytes[i] == b'*' && bytes[i + 1] == b'/' {
                in_comment = false;
                i += 2;
                continue;
            }
            i += 1;
            continue;
        }

        if let Some(quote) = in_string {
            if bytes[i] == b'\\' {
                i = i.saturating_add(2);
                continue;
            }
            if bytes[i] == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' {
            in_comment = true;
            i += 2;
            continue;
        }

        if bytes[i] == b'"' || bytes[i] == b'\'' {
            in_string = Some(bytes[i]);
            i += 1;
            continue;
        }

        if !bytes[i].is_ascii_whitespace() {
            return true;
        }

        i += 1;
    }

    false
}

fn extract_literal_colors_from_value(
    value: &str,
) -> Vec<(usize, usize, crate::color::NormalizedColorKey)> {
    let bytes = value.as_bytes();
    let ignored_ranges = find_ignored_var_ranges(value);
    let mut colors = Vec::new();
    let mut i = 0usize;
    let mut ignored_idx = 0usize;
    let mut in_string: Option<u8> = None;

    while i < bytes.len() {
        while ignored_idx < ignored_ranges.len() && i >= ignored_ranges[ignored_idx].1 {
            ignored_idx += 1;
        }
        if ignored_idx < ignored_ranges.len() && i >= ignored_ranges[ignored_idx].0 {
            i = ignored_ranges[ignored_idx].1;
            continue;
        }

        if let Some(quote) = in_string {
            if bytes[i] == b'\\' {
                i = i.saturating_add(2);
                continue;
            }
            if bytes[i] == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if bytes[i] == b'"' || bytes[i] == b'\'' {
            in_string = Some(bytes[i]);
            i += 1;
            continue;
        }

        if bytes[i] == b'#' {
            let mut end = i + 1;
            while end < bytes.len() && bytes[end].is_ascii_hexdigit() {
                end += 1;
            }
            let len = end - i;
            if matches!(len, 3..=9) {
                if let Some(color) = normalized_color_key(&value[i..end]) {
                    colors.push((i, end, color));
                }
            }
            i = end;
            continue;
        }

        if bytes[i].is_ascii_alphabetic() {
            let start = i;
            let mut end = i + 1;
            while end < bytes.len() && is_ident_char(bytes[end]) {
                end += 1;
            }

            let mut j = end;
            while j < bytes.len() && bytes[j].is_ascii_whitespace() {
                j += 1;
            }

            if j < bytes.len() && bytes[j] == b'(' {
                let ident = value[start..end].to_ascii_lowercase();
                if matches!(ident.as_str(), "rgb" | "rgba" | "hsl" | "hsla") {
                    if let Some(func_end) = find_balanced_call_end(value, j) {
                        if let Some(color) = normalized_color_key(&value[start..func_end]) {
                            colors.push((start, func_end, color));
                        }
                        i = func_end;
                        continue;
                    }
                }
            } else if let Some(color) = normalized_color_key(&value[start..end]) {
                colors.push((start, end, color));
            }

            i = end;
            continue;
        }

        i += 1;
    }

    colors
}

fn find_ignored_var_ranges(value: &str) -> Vec<(usize, usize)> {
    let bytes = value.as_bytes();
    let mut ranges = Vec::new();
    let mut i = 0usize;
    let mut in_string: Option<u8> = None;

    while i < bytes.len() {
        if let Some(quote) = in_string {
            if bytes[i] == b'\\' {
                i = i.saturating_add(2);
                continue;
            }
            if bytes[i] == quote {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if bytes[i] == b'"' || bytes[i] == b'\'' {
            in_string = Some(bytes[i]);
            i += 1;
            continue;
        }

        if is_var_function(bytes, i) {
            let mut j = i + 3;
            while j < bytes.len() && bytes[j].is_ascii_whitespace() {
                j += 1;
            }
            if j < bytes.len() && bytes[j] == b'(' {
                if let Some(end) = find_balanced_call_end(value, j) {
                    ranges.push((i, end));
                    i = end;
                    continue;
                }
            }
        }

        i += 1;
    }

    ranges
}

fn find_balanced_call_end(value: &str, open_paren_idx: usize) -> Option<usize> {
    let bytes = value.as_bytes();
    let mut depth = 0i32;
    let mut i = open_paren_idx;
    let mut in_string: Option<u8> = None;

    while i < bytes.len() {
        let b = bytes[i];
        if let Some(q) = in_string {
            if b == b'\\' {
                i = i.saturating_add(2);
                continue;
            }
            if b == q {
                in_string = None;
            }
            i += 1;
            continue;
        }

        if b == b'"' || b == b'\'' {
            in_string = Some(b);
            i += 1;
            continue;
        }

        if b == b'(' {
            depth += 1;
        } else if b == b')' {
            depth -= 1;
            if depth == 0 {
                return Some(i + 1);
            }
        }
        i += 1;
    }

    None
}

fn resolve_block_selector(
    text: &str,
    brace_pos: usize,
    in_at_rule: bool,
    parent_selector: Option<&String>,
) -> String {
    if in_at_rule {
        return parent_selector
            .cloned()
            .or_else(|| find_selector_before(text, brace_pos, true))
            .unwrap_or_else(|| UNKNOWN_SELECTOR.to_string());
    }

    let before = &text[..brace_pos];
    let start = before
        .rfind(['{', '}', ';'])
        .map(|pos| pos + 1)
        .unwrap_or(0);
    extract_last_selector(before[start..].trim()).unwrap_or_else(|| UNKNOWN_SELECTOR.to_string())
}

fn find_selector_before(text: &str, offset: usize, in_at_rule: bool) -> Option<String> {
    let before = &text[..offset];

    if in_at_rule {
        // For variables defined in @-rules, find the @-rule context
        if let Some(at_pos) = before.rfind('@') {
            let at_rule_end = before[at_pos..]
                .find('{')
                .map(|pos| pos + at_pos)
                .unwrap_or(before.len());
            let at_rule = before[at_pos..at_rule_end].trim();
            return Some(format!("@{}", at_rule));
        }
        return None;
    }

    if let Some(brace_pos) = before.rfind('{') {
        let start = before[..brace_pos].rfind('}').map(|p| p + 1).unwrap_or(0);
        let selector_block = before[start..brace_pos].trim();

        // If the selector block contains a nested `{` (from an @-rule), the actual
        // selector lives between the innermost `{` and the outer `{`.
        // e.g. "@media (min-width: 768px) { .responsive" → ".responsive"
        let inner_brace = before[start..brace_pos].rfind('{');
        let effective_block = if let Some(pos) = inner_brace {
            before[start + pos + 1..brace_pos].trim()
        } else {
            selector_block
        };

        // Handle complex selectors that might span multiple lines or have nested braces
        extract_last_selector(effective_block)
    } else {
        None
    }
}

/// Extract the last selector from a selector block, handling complex cases
fn extract_last_selector(selector_block: &str) -> Option<String> {
    // Find the last complete selector by tracking balanced parentheses and commas
    let bytes = selector_block.as_bytes();
    let len = bytes.len();
    let mut paren_depth: usize = 0;
    let mut last_selector_start = 0;
    let last_selector_end = len;

    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'(' => {
                paren_depth += 1;
            }
            b')' => {
                paren_depth = paren_depth.saturating_sub(1);
            }
            b',' if paren_depth == 0 => {
                // This is a selector list separator
                // The next character (if any) starts a new selector
                last_selector_start = i + 1;
            }
            _ => {}
        }
    }

    // Extract the last selector
    let last_selector = selector_block[last_selector_start..last_selector_end].trim();

    // Clean up the selector - remove any trailing braces or CSS at-rules
    let cleaned = last_selector
        .split('{')
        .next()
        .unwrap_or(last_selector)
        .trim();

    // Handle CSS at-rules by finding the actual selector part
    let selector = if cleaned.starts_with('@') {
        // This is an at-rule like @media, find the selector inside
        if let Some(open_brace) = cleaned.find('{') {
            cleaned[..open_brace].trim().to_string()
        } else {
            cleaned.to_string()
        }
    } else {
        cleaned.to_string()
    };

    if selector.is_empty() {
        None
    } else {
        Some(selector)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::manager::CssVariableManager;
    use crate::types::Config;
    use std::collections::HashSet;
    use std::str::FromStr;

    #[tokio::test]
    async fn parse_css_document_extracts_definitions_and_usages() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();
        let text = ":root { --primary: #fff; color: var(--primary); } \
                    .button { --secondary: var(--primary, #000); }";

        parse_css_document(text, &uri, &manager).await.unwrap();

        let primary_defs = manager.get_variables("--primary").await;
        assert_eq!(primary_defs.len(), 1);
        assert_eq!(primary_defs[0].value, "#fff");

        let secondary_defs = manager.get_variables("--secondary").await;
        assert_eq!(secondary_defs.len(), 1);
        assert_eq!(secondary_defs[0].value, "var(--primary, #000)");

        let usages = manager.get_usages("--primary").await;
        assert_eq!(usages.len(), 2);

        let contexts: HashSet<String> = usages.into_iter().map(|u| u.usage_context).collect();
        assert!(contexts.contains(":root"));
        assert!(contexts.contains(".button"));
    }

    #[tokio::test]
    async fn parse_css_document_skips_nested_var_fallback_usages() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();
        let text = ".button { color: var(--primary, var(--fallback)); }";

        parse_css_document(text, &uri, &manager).await.unwrap();

        let primary_usages = manager.get_usages("--primary").await;
        assert_eq!(primary_usages.len(), 1);

        let fallback_usages = manager.get_usages("--fallback").await;
        assert_eq!(fallback_usages.len(), 0);
    }

    #[tokio::test]
    async fn parse_css_document_extracts_literal_colors_in_compound_values() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();
        let text = r#"
            .button {
                color: #fff;
                background: linear-gradient(red, rgb(255 255 255));
                box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
            }
        "#;

        parse_css_document(text, &uri, &manager).await.unwrap();

        let occurrences = manager.get_document_literal_colors(&uri).await;
        let literals: HashSet<String> = occurrences.into_iter().map(|occ| occ.text).collect();
        assert!(literals.contains("#fff"));
        assert!(literals.contains("red"));
        assert!(literals.contains("rgb(255 255 255)"));
        assert!(literals.contains("rgba(0, 0, 0, 0.5)"));
    }

    #[tokio::test]
    async fn parse_css_document_ignores_literal_colors_inside_var_calls() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();
        let text = r#"
            .button {
                color: var(--primary, #fff);
                background: linear-gradient(var(--from, red), blue);
            }
        "#;

        parse_css_document(text, &uri, &manager).await.unwrap();

        let occurrences = manager.get_document_literal_colors(&uri).await;
        let literals: HashSet<String> = occurrences.into_iter().map(|occ| occ.text).collect();
        assert!(!literals.contains("#fff"));
        assert!(!literals.contains("red"));
        assert!(literals.contains("blue"));
    }
}

#[cfg(test)]
mod edge_case_tests {
    use super::*;
    use crate::types::Config;
    use ls_types::Uri;
    use std::str::FromStr;

    #[tokio::test]
    async fn test_parse_empty_css() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///empty.css").unwrap();

        let result = parse_css_document("", &uri, &manager).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_parse_css_with_comments() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            /* Comment before */
            :root {
                /* Inline comment */
                --primary: blue; /* End comment */
                --secondary: red;
            }
            /* Comment after */
        "#;

        let result = parse_css_document(css, &uri, &manager).await;
        assert!(result.is_ok());

        let vars = manager.get_all_variables().await;
        assert_eq!(vars.len(), 2);
    }

    #[tokio::test]
    async fn test_parse_css_with_important() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root {
                --color: red !important;
                --spacing: 1rem;
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_variables("--color").await;
        assert_eq!(vars.len(), 1);
        assert!(vars[0].important);

        let spacing = manager.get_variables("--spacing").await;
        assert!(!spacing[0].important);
    }

    #[tokio::test]
    async fn test_parse_css_var_with_fallback() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            .button {
                color: var(--primary, blue);
                background: var(--bg, var(--fallback, #fff));
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let primary_usages = manager.get_usages("--primary").await;
        assert_eq!(primary_usages.len(), 1);
        // Fallback values are parsed but not stored in the usage struct

        let bg_usages = manager.get_usages("--bg").await;
        assert_eq!(bg_usages.len(), 1);
    }

    #[tokio::test]
    async fn test_parse_css_complex_selectors() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            #id .class > div[data-attr="value"]:hover::before {
                --complex: value;
            }
            
            @media (min-width: 768px) {
                .responsive {
                    --media: query;
                }
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_all_variables().await;
        assert!(vars.len() >= 2);
    }

    #[tokio::test]
    async fn test_parse_css_multiline_values() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root {
                --gradient: linear-gradient(
                    to bottom,
                    red,
                    blue
                );
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_variables("--gradient").await;
        assert_eq!(vars.len(), 1);
        assert!(vars[0].value.contains("linear-gradient"));
    }

    #[tokio::test]
    async fn test_parse_css_variable_names_with_dashes() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root {
                --primary-color: blue;
                --bg-color-dark: #333;
                --font-size-xl: 2rem;
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_all_variables().await;
        assert_eq!(vars.len(), 3);
        assert!(vars.iter().any(|v| v.name == "--primary-color"));
        assert!(vars.iter().any(|v| v.name == "--bg-color-dark"));
        assert!(vars.iter().any(|v| v.name == "--font-size-xl"));
    }

    #[tokio::test]
    async fn test_parse_css_special_characters_in_values() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root {
                --shadow: 0 2px 4px rgba(0,0,0,0.1);
                --calc: calc(100% - 20px);
                --url: url("https://example.com/image.jpg");
                --content: "Hello, World!";
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_all_variables().await;
        assert_eq!(vars.len(), 4);
    }

    #[tokio::test]
    async fn test_parse_css_nested_var_calls() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            .element {
                color: var(--primary);
                background: var(--bg);
                border: 1px solid var(--border-color);
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        assert_eq!(manager.get_usages("--primary").await.len(), 1);
        assert_eq!(manager.get_usages("--bg").await.len(), 1);
        assert_eq!(manager.get_usages("--border-color").await.len(), 1);
    }

    #[tokio::test]
    async fn test_parse_css_whitespace_variations() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root{--no-space:value;}
            :root { --normal-space: value; }
            :root  {  --extra-space  :  value  ;  }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let vars = manager.get_all_variables().await;
        assert_eq!(vars.len(), 3);
    }

    #[tokio::test]
    async fn test_parse_css_variables_after_nested_media_inside_root() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let css = r#"
            :root {
                --before: blue;

                @media (prefers-color-scheme: dark) {
                    --during: red;
                }

                --after: green;
            }
        "#;

        parse_css_document(css, &uri, &manager).await.unwrap();

        let before = manager.get_variables("--before").await;
        let during = manager.get_variables("--during").await;
        let after = manager.get_variables("--after").await;

        assert_eq!(before.len(), 1);
        assert_eq!(during.len(), 1);
        assert_eq!(after.len(), 1);
        assert_eq!(before[0].selector, ":root");
        assert_eq!(during[0].selector, ":root");
        assert_eq!(after[0].selector, ":root");
    }

    #[tokio::test]
    async fn test_parse_css_malformed_but_parseable() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        // Missing closing brace, but should still parse what it can
        let css = r#"
            :root {
                --valid: blue;
        "#;

        let result = parse_css_document(css, &uri, &manager).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_find_selector_in_at_rule_block() {
        // Bug: @-rule prelude is returned instead of the actual selector
        let css = "@media (min-width: 768px) { .responsive { color: var(--x); } }";
        let var_pos = css.find("var").unwrap();
        let result = find_selector_before(css, var_pos, false);
        assert_eq!(
            result,
            Some(".responsive".to_string()),
            "Expected selector '.responsive' inside @media block, got: '{}'",
            result.as_deref().unwrap_or("<none>")
        );
    }

    #[test]
    fn test_find_selector_deeply_nested_at_rule() {
        let css = "@media (min-width: 768px) { @supports (display: grid) { .grid-item { color: var(--x); } } }";
        let var_pos = css.find("var").unwrap();
        let result = find_selector_before(css, var_pos, false);
        assert_eq!(
            result,
            Some(".grid-item".to_string()),
            "Expected selector '.grid-item' inside nested @-rules, got: '{}'",
            result.as_deref().unwrap_or("<none>")
        );
    }

    #[test]
    fn test_find_selector_definition_in_at_rule() {
        let css = "@media (min-width: 768px) { .responsive { --responsive: value; } }";
        let decl_pos = css.find("--responsive").unwrap();
        let result = find_selector_before(css, decl_pos, false);
        assert_eq!(
            result,
            Some(".responsive".to_string()),
            "Expected selector '.responsive' for definition inside @media, got: '{}'",
            result.as_deref().unwrap_or("<none>")
        );
    }

    /// Bug demonstration: Complex pseudo-selectors are not parsed correctly
    ///
    /// ISSUE: The extract_last_selector function may have issues with:
    /// - Complex pseudo-selectors like :nth-child(2n+1)
    /// - Attribute selectors with complex values
    /// - Nested parentheses
    ///
    /// EXPECTED TO FAIL: This test proves edge cases are not handled.
    /// After fix: Complex selectors should be extracted correctly.
    #[test]
    fn test_extract_last_selector_complex_pseudo() {
        use crate::specificity::calculate_specificity;

        let test_cases = vec![
            // (input, expected selector that should be present)
            (":root", "root"),
            (":host", "host"),
            (".class", "class"),
            ("#id", "id"),
            ("div.class", "div.class"),
            ("div::before", "div::before"),
            // Complex pseudo-selectors that may fail
            (":nth-child(2n)", "nth-child"),
            (":nth-child(2n+1)", "nth-child"),
            (":nth-child(odd)", "nth-child"),
            (":nth-child(3n-1)", "nth-child"),
            (":nth-of-type(2n)", "nth-of-type"),
            (":not(.hidden)", "not"),
            (":is(div, span)", "is"),
            (":where(.theme)", "where"),
            (":has(+ div)", "has"),
            (":first-letter", "first-letter"),
            (":first-line", "first-line"),
            (":placeholder-shown", "placeholder-shown"),
            (":focus-visible", "focus-visible"),
            (":focus-within", "focus-within"),
            // Complex attribute selectors
            ("[data-value^=\"test\"]", "data-value"),
            ("[class~=\"token\"]", "class"),
            ("[lang|=\"en\"]", "lang"),
        ];

        for (input, expected_contains) in test_cases {
            // Find selector before a position (simulating cursor at end)
            let css = format!("{} {{ color: red; }}", input);
            let position = css.len() - 1; // Position after selector

            let result = find_selector_before(&css, position, false);
            let result = result.expect("selector should be present");

            assert!(
                result.contains(expected_contains),
                "Selector '{}' should contain '{}' (from input: {})",
                result,
                expected_contains,
                input
            );

            // Also verify specificity calculation doesn't panic
            let specificity = calculate_specificity(&result);

            // For complex selectors, specificity should still be calculable
            let _ = specificity; // verify calculate_specificity doesn't panic
        }

        // Additional edge case: selector with nested pseudo-classes
        let nested = ".container:not(:has(.hidden)):nth-child(2n+1)";
        let result = find_selector_before(
            &format!("{} {{ color: red; }}", nested),
            nested.len() + 5,
            false,
        )
        .expect("selector should be present");

        // BUG: Currently this assertion may FAIL because nested selectors are not handled
        // After fix: Should extract the full compound selector
        assert!(
            result.contains("container") && result.contains("not") && result.contains("nth-child"),
            "Nested selector '{}' should contain all parts, got: {}",
            nested,
            result
        );
    }

    #[test]
    fn test_find_selector_before_returns_none_without_selector_context() {
        assert_eq!(find_selector_before("--x: red;", 4, false), None);
    }
}