ratatui-style 0.2.0

A CSS cascade engine for ratatui — selectors, specificity, inheritance, pseudo-states, and data-driven styling.
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
//! `@media` query support — conditional rules based on terminal size and color
//! capability.
//!
//! A [`MediaQuery`] is parsed from the text between `@media` and the block's
//! opening `{` (e.g. `(min-width: 80) and (max-height: 40)`). Each element rule
//! inside an `@media` block is tagged with the parsed query; the cascade skips a
//! tagged rule unless [`MediaQuery::matches`] the current [`MediaContext`].
//!
//! # Matching model
//!
//! A query is a comma-separated list (logical OR) of [`MediaAlternative`]s. Each
//! alternative is a conjunction (logical AND) of [`MediaTerm`]s, where each term
//! is a [`MediaCondition`] optionally prefixed by `not` (per-term negation,
//! following CSS4 feature negation). Precedence, tightest first:
//!
//! `not` (per-term) > `and` (terms within an alternative) > `,` (alternatives / OR)
//!
//! So `not (min-width: 80) and (color)` is ONE alternative with TWO terms:
//! `[¬(min-width: 80), (color)]` — it matches iff `cols < 80` AND color is on.
//! A leading `not` binds to the immediately following feature only, not to the
//! whole alternative.
//!
//! A query with **no alternatives** (e.g. a bare `@media {}` with no query text)
//! matches anything — a no-op gate — preserving the historically lenient behavior.
//!
//! Media types (`screen`, `all`, `print`, `only`) are accepted syntactically and
//! **ignored**: terminal apps are always "screen". A bare `@media print { }` is
//! treated like `@media all { }` (matches everything). Because types are ignored,
//! a `not <type>` (e.g. `not screen`) negates nothing meaningful and the `not`
//! is dropped along with the type.
//!
//! Default-context caution: [`MediaContext::default()`] is all-zero / all-false,
//! which means "no terminal info". A media-gated rule with any condition will
//! NOT match a default context (e.g. `min-width: 80` vs `cols = 0` is false).
//! This is by design: a host that never supplies media info should not have
//! media-gated rules silently apply.

use crate::error::{CssError, Result};

/// What the host knows about the current terminal, supplied per render.
///
/// Defaults (all zero/false) mean "no media info" — media-gated rules with any
/// condition will NOT match against a default context (e.g. `min-width: 80` vs
/// `cols = 0` is false).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MediaContext {
    /// Terminal width in cells.
    pub cols: u16,
    /// Terminal height in cells.
    pub rows: u16,
    /// Whether the terminal supports 24-bit color.
    pub truecolor: bool,
    /// Whether color is disabled (e.g. `$NO_COLOR` is set).
    pub no_color: bool,
}

/// One `@media` query: one or more [`MediaAlternative`]s joined by comma (OR).
///
/// The query matches if **any** alternative matches. An `alternatives` list with
/// zero entries (e.g. a bare `@media {}` with no query text) matches everything.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MediaQuery {
    /// Comma-separated alternatives; the query matches if ANY matches. An empty
    /// list matches everything (a no-op gate).
    pub alternatives: Vec<MediaAlternative>,
}

/// One condition in a media alternative, optionally negated (`not (feat)`).
///
/// Following CSS4 feature negation, `not` applies to the immediately following
/// feature only — it is per-term, not per-alternative. A term matches `ctx` iff
/// `cond.matches(ctx) != negated`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MediaTerm {
    /// A leading `not` negates this single condition.
    pub negated: bool,
    /// The underlying feature condition.
    pub cond: MediaCondition,
}

impl MediaTerm {
    /// True iff `cond` holds against `ctx`, XOR `negated`.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        self.cond.matches(ctx) != self.negated
    }
}

/// One `and`-conjunction of [`MediaTerm`]s (no whole-alternative negation).
///
/// `matches` is true iff **every** term holds (each term already accounts for its
/// own per-term `not`). Negation lives on individual terms, not on the
/// alternative, so `(¬a) ∧ b` is represented precisely as `[¬a, b]`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MediaAlternative {
    /// `and`-joined terms; ALL must hold (each term: condition XOR `negated`).
    pub terms: Vec<MediaTerm>,
}

/// A single media feature condition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MediaCondition {
    /// `(min-width: n)` — terminal width ≥ `n` cells.
    MinWidth(u16),
    /// `(max-width: n)` — terminal width ≤ `n` cells.
    MaxWidth(u16),
    /// `(width: n)` — terminal width exactly `n` cells.
    Width(u16),
    /// `(min-height: n)` — terminal height ≥ `n` cells.
    MinHeight(u16),
    /// `(max-height: n)` — terminal height ≤ `n` cells.
    MaxHeight(u16),
    /// `(height: n)` — terminal height exactly `n` cells.
    Height(u16),
    /// `(color)` — terminal has color (not `$NO_COLOR`).
    Color,
    /// `(monochrome)` — terminal has color disabled.
    Monochrome,
    /// `(truecolor)` — ratatui-style extension: terminal supports 24-bit color.
    Truecolor,
}

impl MediaQuery {
    /// True iff **any** alternative matches `ctx`. A query with no alternatives
    /// matches anything (a no-op gate).
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        if self.alternatives.is_empty() {
            return true;
        }
        self.alternatives.iter().any(|a| a.matches(ctx))
    }

    /// Combine two queries with logical AND: the result matches iff **both**
    /// `self` and `other` match.
    ///
    /// This is used to resolve nested `@media` blocks (`@media (a) { @media (b)
    /// { … } }` is equivalent to a single `@media (a) and (b) { … }`).
    ///
    /// # Semantics
    ///
    /// A query is an OR of [`MediaAlternative`]s, and each alternative is an AND
    /// of [`MediaTerm`]s. To form `self ∧ other` we take the **cross product**
    /// of the two alternatives lists: for each `a1` in `self` and each `a2` in
    /// `other`, the combined alternative has `terms = a1.terms ++ a2.terms`. So
    /// `(a),(b)` AND-ed with `(c)` yields two alternatives `(a,c)` and `(b,c)` —
    /// each must be fully satisfied for the OR to match, which is exactly
    /// AND-of-OR semantics.
    ///
    /// Match-all short-circuits: if either side has **zero alternatives** (the
    /// match-all gate) the other side is returned unchanged (cloned). If both
    /// are empty the result is empty (still match-all).
    ///
    /// # Negation (exact)
    ///
    /// Because negation is per-term (CSS4 feature negation), there is no
    /// approximation: a `(¬a) ∧ b` combination is represented precisely as a
    /// single alternative `[¬a, b]`. The cross product simply concatenates the
    /// term lists, preserving each term's `negated` flag.
    pub fn and(&self, other: &MediaQuery) -> MediaQuery {
        // Match-all short-circuits: an empty alternatives list means "matches
        // everything", so X AND all == X.
        if self.alternatives.is_empty() {
            return other.clone();
        }
        if other.alternatives.is_empty() {
            return self.clone();
        }

        let mut combined = Vec::with_capacity(self.alternatives.len() * other.alternatives.len());
        for a1 in &self.alternatives {
            for a2 in &other.alternatives {
                // Concatenate terms; each term carries its own negation flag, so
                // the combined alternative is exact (no approximation).
                let mut terms = Vec::with_capacity(a1.terms.len() + a2.terms.len());
                terms.extend(a1.terms.iter().cloned());
                terms.extend(a2.terms.iter().cloned());
                combined.push(MediaAlternative { terms });
            }
        }
        MediaQuery { alternatives: combined }
    }

    /// The specificity of `self` against `media`: the maximum term-count among
    /// the alternatives that **match** under `media`. Returns `None` if the
    /// query does not match `media` at all.
    ///
    /// A match-all query (zero alternatives) has specificity `0`. Used by the
    /// media-token resolution scan to rank competing overrides: the override
    /// backed by the most-term matching query wins (ties broken by source order).
    pub(crate) fn matching_specificity(&self, media: &MediaContext) -> Option<usize> {
        if self.alternatives.is_empty() {
            // Matches everything (specificity 0).
            return Some(0);
        }
        let mut best: Option<usize> = None;
        for a in &self.alternatives {
            if a.matches(media) {
                let n = a.terms.len();
                best = Some(match best {
                    Some(b) if b >= n => b,
                    _ => n,
                });
            }
        }
        best
    }

    /// Parse the text BETWEEN `@media` and the block's opening `{`.
    ///
    /// Grammar (case-insensitive), precedence tightest first:
    ///
    /// `not` (per-term) > `and` (terms within an alternative) > `,` (alternatives / OR)
    ///
    /// - The text is split on top-level commas into one [`MediaAlternative`]
    ///   per part (OR).
    /// - Each part may begin with an optional media-type keyword sequence
    ///   (`only`, `screen`, `all`, `print`, possibly `only screen`) which is
    ///   accepted and **ignored** — terminal apps are always "screen". If a media
    ///   type is present it may be followed by `and`, which is also consumed. A
    ///   leading `not` immediately before a media type (e.g. `not screen`)
    ///   negates nothing meaningful (types are ignored) and is dropped along
    ///   with the type.
    /// - The remainder is zero or more terms joined by `and`. Each term is an
    ///   optional leading `not` (per-term negation, CSS4 feature negation)
    ///   followed by a `(condition)` clause. So `not (a) and (b)` → two terms
    ///   `[¬a, b]`.
    ///
    /// Unknown / malformed features surface as a [`CssError`] so strict stays
    /// honest; the stylesheet parser propagates it.
    pub fn parse(s: &str) -> Result<MediaQuery> {
        // Lowercase once; tokens are case-insensitive.
        let lower = s.to_ascii_lowercase();

        // A wholly empty/whitespace query → zero alternatives (match-all gate).
        // This is distinct from a stray comma, which yields an empty PART among
        // non-empty ones and is a structural error.
        if lower.trim().is_empty() {
            return Ok(MediaQuery { alternatives: Vec::new() });
        }

        // Split on top-level commas (respecting paren depth — commas inside
        // parens don't occur in this grammar, but guard against future
        // extensions like `(prefers-color-scheme: dark, light)`).
        let mut alternatives = Vec::new();
        for part in split_top_level_commas(&lower) {
            let trimmed = part.trim();
            // An empty part between/around commas (e.g. trailing `, `) is a
            // structural error rather than a silent match-all alternative.
            if trimmed.is_empty() {
                return Err(CssError::invalid_selector(
                    "media query: empty alternative (stray comma?)",
                ));
            }
            alternatives.push(parse_alternative(trimmed)?);
        }

        Ok(MediaQuery { alternatives })
    }
}

impl MediaAlternative {
    /// True iff **every** term holds against `ctx`. Each term already accounts
    /// for its own per-term `not`, so there is no alternative-level negation.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        self.terms.iter().all(|t| t.matches(ctx))
    }
}

/// Parse one comma-separated alternative (already trimmed, lowercased).
///
/// Handles the optional media-type keyword sequence, then parses the remainder
/// as `and`-joined terms — each term being an optional leading `not` (per-term
/// negation) followed by a `(condition)`.
fn parse_alternative(part: &str) -> Result<MediaAlternative> {
    let bytes = part.as_bytes();
    let mut i = 0usize;

    // Skip leading whitespace.
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }

    // A leading `not` before a media TYPE (e.g. `not screen`) negates the type.
    // Since types are ignored, that `not` applies to nothing — drop it along
    // with the type. We only treat `not` as a per-term prefix when it is
    // immediately followed by a `(` (a feature). So: if `not` appears here and
    // the next non-space token is a media-type keyword, consume both and drop
    // them; if the next token is `(`, leave the `not` for the per-term loop.
    if let Some(consumed) = consume_keyword(bytes, i, "not") {
        // Peek: skip whitespace, check whether a media type follows.
        let mut j = consumed;
        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
            j += 1;
        }
        let mut is_type = false;
        for kw in ["only", "screen", "all", "print"] {
            if consume_keyword(bytes, j, kw).is_some() {
                is_type = true;
                break;
            }
        }
        if is_type {
            // Drop the leading `not <type>`: consume the `not` and fall through
            // to the media-type consumption loop below.
            i = consumed;
            while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                i += 1;
            }
        }
        // Otherwise (next is `(` or end): leave `i` untouched so the per-term
        // loop sees the `not` and binds it to the following feature.
    }

    // Consume an optional media-type keyword sequence: `only`, `screen`, `all`,
    // `print`, possibly `only screen`. These are IGNORED (terminal apps are
    // always "screen"). Also consume a trailing `and` if present so the
    // remainder is the term list.
    loop {
        let prev_i = i;
        for kw in ["only", "screen", "all", "print"] {
            if let Some(consumed) = consume_keyword(bytes, i, kw) {
                i = consumed;
                while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                    i += 1;
                }
                break;
            }
        }
        if i == prev_i {
            break;
        }
    }
    // After consuming media types, consume a single following `and` if present
    // (e.g. `screen and (...)`). This `and` separates the media type from the
    // feature terms, not terms from each other.
    if let Some(consumed) = consume_keyword(bytes, i, "and") {
        i = consumed;
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
    }

    // The remainder is the term list: zero or more `[not] (cond)` joined by
    // `and`. If nothing remains (e.g. bare `screen` or `not screen`), the
    // alternative has zero terms → matches everything.
    let mut terms = Vec::new();
    loop {
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= bytes.len() {
            break;
        }

        // Per-term `not` (CSS4 feature negation): a `not` immediately before a
        // `(feature)` negates that single feature. It is NOT whole-alternative.
        let mut negated = false;
        if let Some(consumed) = consume_keyword(bytes, i, "not") {
            negated = true;
            i = consumed;
            while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                i += 1;
            }
        }

        if i >= bytes.len() {
            return Err(CssError::invalid_selector(
                "media query: `not` at end of alternative (nothing to negate)",
            ));
        }
        if bytes[i] != b'(' {
            return Err(CssError::invalid_selector(format!(
                "media query: expected `(` near `{}`",
                &part[i.min(part.len())..]
            )));
        }
        // Find the matching `)`.
        let close = match part[i..].find(')') {
            Some(rel) => i + rel,
            None => {
                return Err(CssError::invalid_selector(
                    "media query: unbalanced parens (missing `)`)",
                ));
            }
        };
        let inner = &part[i + 1..close];
        let cond = parse_condition(inner)?;
        terms.push(MediaTerm { negated, cond });
        i = close + 1;

        // After a term, expect either end-of-string or ` and `.
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= bytes.len() {
            break;
        }
        if let Some(consumed) = consume_keyword(bytes, i, "and") {
            i = consumed;
            continue;
        }
        return Err(CssError::invalid_selector(format!(
            "media query: expected `and` between terms near `{}`",
            &part[i..]
        )));
    }

    Ok(MediaAlternative { terms })
}

/// If `bytes[i..]` begins with `kw` as a whole word (followed by whitespace, a
/// `(`, a `,`, or end-of-input), return the index just past the keyword; else
/// `None`. Whole-word match prevents `notable` from matching `not`.
fn consume_keyword(bytes: &[u8], i: usize, kw: &str) -> Option<usize> {
    let kw_bytes = kw.as_bytes();
    if i + kw_bytes.len() > bytes.len() {
        return None;
    }
    if &bytes[i..i + kw_bytes.len()] != kw_bytes {
        return None;
    }
    let after = i + kw_bytes.len();
    // Whole-word boundary: next char must be whitespace, `(`, `,`, or end.
    if after < bytes.len()
        && !bytes[after].is_ascii_whitespace()
        && bytes[after] != b'('
        && bytes[after] != b','
    {
        return None;
    }
    Some(after)
}

/// Split `s` on top-level commas (those at paren depth 0), returning owned
/// slices of the original. Whitespace is NOT trimmed here — callers trim.
fn split_top_level_commas(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0i32;
    let mut start = 0usize;
    for (idx, ch) in s.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => {
                if depth > 0 {
                    depth -= 1;
                }
            }
            ',' if depth == 0 => {
                parts.push(&s[start..idx]);
                start = idx + 1;
            }
            _ => {}
        }
    }
    parts.push(&s[start..]);
    parts
}

/// Parse the inner content of one `(feature)` or `(feature: value)` condition
/// (already lowercased, no surrounding parens).
fn parse_condition(inner: &str) -> Result<MediaCondition> {
    let trimmed = inner.trim();
    if trimmed.is_empty() {
        return Err(CssError::invalid_selector(
            "media query: empty condition `()`",
        ));
    }
    // Split on `:` if present.
    if let Some(colon) = trimmed.find(':') {
        let feature = trimmed[..colon].trim();
        let value = trimmed[colon + 1..].trim();
        parse_feature_value(feature, value)
    } else {
        parse_feature_bare(trimmed)
    }
}

/// Parse a bare `(feature)` condition (no value).
fn parse_feature_bare(feature: &str) -> Result<MediaCondition> {
    match feature {
        "min-width" | "max-width" | "width" | "min-height" | "max-height" | "height" => {
            Err(CssError::invalid_selector(format!(
                "media query: `({feature})` requires a value, e.g. `({feature}: 80)`"
            )))
        }
        "color" => Ok(MediaCondition::Color),
        "monochrome" => Ok(MediaCondition::Monochrome),
        "truecolor" => Ok(MediaCondition::Truecolor),
        other => Err(CssError::invalid_selector(format!(
            "media query: unknown feature `{other}`"
        ))),
    }
}

/// Parse a `(feature: value)` condition.
fn parse_feature_value(feature: &str, value: &str) -> Result<MediaCondition> {
    match feature {
        "min-width" => Ok(MediaCondition::MinWidth(parse_u16(value, "min-width")?)),
        "max-width" => Ok(MediaCondition::MaxWidth(parse_u16(value, "max-width")?)),
        "width" => Ok(MediaCondition::Width(parse_u16(value, "width")?)),
        "min-height" => Ok(MediaCondition::MinHeight(parse_u16(value, "min-height")?)),
        "max-height" => Ok(MediaCondition::MaxHeight(parse_u16(value, "max-height")?)),
        "height" => Ok(MediaCondition::Height(parse_u16(value, "height")?)),
        "color" => {
            // `(color: 0)` → Monochrome; `(color: N)` with N>=1 → Color.
            match value {
                "0" => Ok(MediaCondition::Monochrome),
                _ => {
                    // Validate it's a non-negative number for the error path,
                    // then treat any nonzero as Color.
                    let n = parse_u16(value, "color")?;
                    if n == 0 {
                        Ok(MediaCondition::Monochrome)
                    } else {
                        Ok(MediaCondition::Color)
                    }
                }
            }
        }
        "monochrome" => {
            // `(monochrome: 0)` → Color; otherwise Monochrome.
            match value {
                "0" => Ok(MediaCondition::Color),
                _ => {
                    let n = parse_u16(value, "monochrome")?;
                    if n == 0 {
                        Ok(MediaCondition::Color)
                    } else {
                        Ok(MediaCondition::Monochrome)
                    }
                }
            }
        }
        "truecolor" => {
            // `(truecolor: 1)` → Truecolor; `(truecolor: 0)` → treat as
            // negation? For v1, keep simple: only `1` (or bare) means truecolor.
            let n = parse_u16(value, "truecolor")?;
            if n >= 1 {
                Ok(MediaCondition::Truecolor)
            } else {
                // A `(truecolor: 0)` query is nonsensical in the AND model
                // (it would need a NOT). Surface as an error for v1.
                Err(CssError::invalid_selector(
                    "media query: `(truecolor: 0)` is not supported — use a separate context",
                ))
            }
        }
        other => Err(CssError::invalid_selector(format!(
            "media query: unknown feature `{other}`"
        ))),
    }
}

/// Parse a `u16` value, rejecting negatives and non-numeric text.
fn parse_u16(value: &str, feature: &str) -> Result<u16> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(CssError::invalid_selector(format!(
            "media query: `({feature}:)` has no value"
        )));
    }
    // Reject a leading `-` explicitly (u16 parse would reject it anyway, but
    // give a clearer message).
    if trimmed.starts_with('-') {
        return Err(CssError::invalid_selector(format!(
            "media query: `({feature}: {trimmed})` value must be non-negative"
        )));
    }
    trimmed.parse::<u16>().map_err(|_| {
        CssError::invalid_selector(format!(
            "media query: `({feature}: {trimmed})` value is not a number"
        ))
    })
}

impl MediaCondition {
    /// True iff this single condition holds against `ctx`.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        match *self {
            MediaCondition::MinWidth(n) => ctx.cols >= n,
            MediaCondition::MaxWidth(n) => ctx.cols <= n,
            MediaCondition::Width(n) => ctx.cols == n,
            MediaCondition::MinHeight(n) => ctx.rows >= n,
            MediaCondition::MaxHeight(n) => ctx.rows <= n,
            MediaCondition::Height(n) => ctx.rows == n,
            MediaCondition::Color => !ctx.no_color,
            MediaCondition::Monochrome => ctx.no_color,
            MediaCondition::Truecolor => ctx.truecolor,
        }
    }
}

impl std::fmt::Display for MediaQuery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.alternatives.is_empty() {
            return write!(f, "all");
        }
        for (i, a) in self.alternatives.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            std::fmt::Display::fmt(a, f)?;
        }
        Ok(())
    }
}

impl std::fmt::Display for MediaAlternative {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, t) in self.terms.iter().enumerate() {
            if i > 0 {
                write!(f, " and ")?;
            }
            std::fmt::Display::fmt(t, f)?;
        }
        Ok(())
    }
}

impl std::fmt::Display for MediaTerm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.negated {
            write!(f, "not ")?;
        }
        std::fmt::Display::fmt(&self.cond, f)
    }
}

impl std::fmt::Display for MediaCondition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            MediaCondition::MinWidth(n) => write!(f, "(min-width: {n})"),
            MediaCondition::MaxWidth(n) => write!(f, "(max-width: {n})"),
            MediaCondition::Width(n) => write!(f, "(width: {n})"),
            MediaCondition::MinHeight(n) => write!(f, "(min-height: {n})"),
            MediaCondition::MaxHeight(n) => write!(f, "(max-height: {n})"),
            MediaCondition::Height(n) => write!(f, "(height: {n})"),
            MediaCondition::Color => write!(f, "(color)"),
            MediaCondition::Monochrome => write!(f, "(monochrome)"),
            MediaCondition::Truecolor => write!(f, "(truecolor)"),
        }
    }
}

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

    fn ctx(cols: u16, rows: u16) -> MediaContext {
        MediaContext {
            cols,
            rows,
            truecolor: false,
            no_color: false,
        }
    }

    /// Build a `MediaAlternative` from a list of conditions (none negated).
    fn alt<I: IntoIterator<Item = MediaCondition>>(conds: I) -> MediaAlternative {
        MediaAlternative {
            terms: conds
                .into_iter()
                .map(|c| MediaTerm { negated: false, cond: c })
                .collect(),
        }
    }

    /// Build a single negated `MediaTerm` for a condition.
    fn not_term(c: MediaCondition) -> MediaTerm {
        MediaTerm { negated: true, cond: c }
    }

    /// Build a single (non-negated) `MediaTerm` for a condition.
    fn term(c: MediaCondition) -> MediaTerm {
        MediaTerm { negated: false, cond: c }
    }

    /// Build a `MediaAlternative` from a single negated term.
    fn alt_neg(c: MediaCondition) -> MediaAlternative {
        MediaAlternative { terms: vec![not_term(c)] }
    }

    /// Build a `MediaAlternative` from a list of `MediaTerm`s (for mixed
    /// negation within one alternative).
    fn alt_terms<I: IntoIterator<Item = MediaTerm>>(terms: I) -> MediaAlternative {
        MediaAlternative { terms: terms.into_iter().collect() }
    }

    fn no_color_ctx() -> MediaContext {
        MediaContext { no_color: true, ..Default::default() }
    }

    // --- parse ---------------------------------------------------------------

    #[test]
    fn parse_min_width() {
        let q = MediaQuery::parse("(min-width: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::MinWidth(80)])]);
    }

    #[test]
    fn parse_max_width_and_min_height() {
        let q = MediaQuery::parse("(max-width: 120) and (min-height: 24)").unwrap();
        assert_eq!(
            q.alternatives,
            vec![alt([MediaCondition::MaxWidth(120), MediaCondition::MinHeight(24)])]
        );
    }

    #[test]
    fn parse_width_exact() {
        let q = MediaQuery::parse("(width: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::Width(80)])]);
    }

    #[test]
    fn parse_color_bare() {
        let q = MediaQuery::parse("(color)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::Color])]);
    }

    #[test]
    fn parse_monochrome_bare() {
        let q = MediaQuery::parse("(monochrome)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::Monochrome])]);
    }

    #[test]
    fn parse_truecolor_bare() {
        let q = MediaQuery::parse("(truecolor)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::Truecolor])]);
    }

    #[test]
    fn parse_leading_media_type_ignored() {
        let q = MediaQuery::parse("screen and (min-width: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::MinWidth(80)])]);

        let q2 = MediaQuery::parse("all and (max-height: 40)").unwrap();
        assert_eq!(q2.alternatives, vec![alt([MediaCondition::MaxHeight(40)])]);
    }

    #[test]
    fn parse_empty_query_matches_all() {
        let q = MediaQuery::parse("").unwrap();
        assert!(q.alternatives.is_empty());
        assert!(q.matches(&MediaContext::default()));
    }

    #[test]
    fn parse_uppercase_features() {
        // Case-insensitive: features get lowercased internally.
        let q = MediaQuery::parse("(MIN-WIDTH: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::MinWidth(80)])]);
    }

    // --- parse: not / comma / and --------------------------------------------

    #[test]
    fn parse_comma_or_two_alternatives() {
        let q = MediaQuery::parse("(min-width: 80), (max-width: 120)").unwrap();
        assert_eq!(
            q.alternatives,
            vec![
                alt([MediaCondition::MinWidth(80)]),
                alt([MediaCondition::MaxWidth(120)]),
            ]
        );
    }

    #[test]
    fn parse_not_prefix_single() {
        // Per-term negation: `not (min-width: 80)` → one alternative with one
        // negated term.
        let q = MediaQuery::parse("not (min-width: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt_neg(MediaCondition::MinWidth(80))]);
    }

    #[test]
    fn parse_comma_three_alternatives() {
        let q = MediaQuery::parse("(min-width: 80), (max-width: 120), (color)").unwrap();
        assert_eq!(
            q.alternatives,
            vec![
                alt([MediaCondition::MinWidth(80)]),
                alt([MediaCondition::MaxWidth(120)]),
                alt([MediaCondition::Color]),
            ]
        );
    }

    #[test]
    fn parse_not_screen_media_type_ignored() {
        // `not screen` negates the media TYPE, which is ignored → the `not` is
        // dropped along with the type. The remaining `(min-width: 80)` is a
        // single non-negated term.
        let q = MediaQuery::parse("not screen and (min-width: 80)").unwrap();
        assert_eq!(q.alternatives, vec![alt([MediaCondition::MinWidth(80)])]);
    }

    #[test]
    fn parse_comma_with_not_second_alt() {
        let q = MediaQuery::parse("(min-width: 80), not (color)").unwrap();
        assert_eq!(
            q.alternatives,
            vec![
                alt([MediaCondition::MinWidth(80)]),
                alt_neg(MediaCondition::Color),
            ]
        );
    }

    #[test]
    fn parse_and_chain_one_alternative_regression() {
        // Existing AND behavior: one alternative, two conditions.
        let q = MediaQuery::parse("(min-width: 80) and (max-height: 40)").unwrap();
        assert_eq!(
            q.alternatives,
            vec![alt([MediaCondition::MinWidth(80), MediaCondition::MaxHeight(40)])]
        );
    }

    #[test]
    fn parse_not_is_whole_word() {
        // `notable` must NOT be parsed as `not`.
        assert!(MediaQuery::parse("notable").is_err());
    }

    #[test]
    fn parse_bare_media_type_matches_all() {
        // Bare media type, no terms → one alternative with zero terms (matches
        // everything).
        let q = MediaQuery::parse("screen").unwrap();
        assert_eq!(q.alternatives, vec![MediaAlternative { terms: vec![] }]);
        assert!(q.matches(&MediaContext::default()));
    }

    #[test]
    fn parse_empty_alternative_errors() {
        // Stray trailing comma → empty alternative is a structural error.
        assert!(MediaQuery::parse("(min-width: 80),").is_err());
        assert!(MediaQuery::parse(", (min-width: 80)").is_err());
    }

    // --- parse errors --------------------------------------------------------

    #[test]
    fn parse_unknown_feature_errors() {
        assert!(MediaQuery::parse("(foo: 1)").is_err());
    }

    #[test]
    fn parse_non_numeric_width_errors() {
        assert!(MediaQuery::parse("(min-width: wide)").is_err());
    }

    #[test]
    fn parse_unbalanced_parens_error() {
        assert!(MediaQuery::parse("(min-width: 80").is_err());
    }

    #[test]
    fn parse_missing_value_errors() {
        assert!(MediaQuery::parse("(min-width)").is_err());
    }

    #[test]
    fn parse_negative_value_errors() {
        assert!(MediaQuery::parse("(min-width: -5)").is_err());
    }

    // --- matches -------------------------------------------------------------

    #[test]
    fn min_width_matches() {
        let q = MediaQuery::parse("(min-width: 80)").unwrap();
        assert!(q.matches(&ctx(100, 24)));
        assert!(q.matches(&ctx(80, 24)));
        assert!(!q.matches(&ctx(60, 24)));
    }

    #[test]
    fn max_width_and_min_height_matches() {
        let q = MediaQuery::parse("(max-width: 120) and (min-height: 24)").unwrap();
        // Both hold.
        assert!(q.matches(&ctx(100, 24)));
        assert!(q.matches(&ctx(120, 30)));
        // One fails.
        assert!(!q.matches(&ctx(200, 24))); // width too big
        assert!(!q.matches(&ctx(100, 10))); // height too small
        assert!(!q.matches(&ctx(200, 10))); // both fail
    }

    #[test]
    fn truecolor_only_when_flag_set() {
        let q = MediaQuery::parse("(truecolor)").unwrap();
        assert!(!q.matches(&MediaContext { truecolor: false, ..Default::default() }));
        assert!(q.matches(&MediaContext { truecolor: true, ..Default::default() }));
    }

    #[test]
    fn monochrome_only_when_no_color() {
        let q = MediaQuery::parse("(monochrome)").unwrap();
        assert!(!q.matches(&MediaContext { no_color: false, ..Default::default() }));
        assert!(q.matches(&MediaContext { no_color: true, ..Default::default() }));
    }

    #[test]
    fn color_inverts_monochrome() {
        let color_q = MediaQuery::parse("(color)").unwrap();
        assert!(color_q.matches(&MediaContext { no_color: false, ..Default::default() }));
        assert!(!color_q.matches(&MediaContext { no_color: true, ..Default::default() }));
    }

    #[test]
    fn default_context_does_not_match_gated_query() {
        // A default (all-zero) context must NOT satisfy min-width: 80.
        let q = MediaQuery::parse("(min-width: 80)").unwrap();
        assert!(!q.matches(&MediaContext::default()));
    }

    // --- matches: not / comma / and -----------------------------------------

    #[test]
    fn comma_or_matches_either_alternative() {
        // (min-width: 100), (max-width: 50)
        let q = MediaQuery::parse("(min-width: 100), (max-width: 50)").unwrap();
        // First alt: cols >= 100.
        assert!(q.matches(&ctx(100, 24)));
        assert!(q.matches(&ctx(150, 24)));
        // Second alt: cols <= 50.
        assert!(q.matches(&ctx(40, 24)));
        assert!(q.matches(&ctx(50, 24)));
        // Neither: cols = 70.
        assert!(!q.matches(&ctx(70, 24)));
    }

    #[test]
    fn not_prefix_inverts_single_condition() {
        // not (min-width: 80): matches when cols < 80.
        let q = MediaQuery::parse("not (min-width: 80)").unwrap();
        assert!(q.matches(&ctx(60, 24))); // condition false → negated true
        assert!(q.matches(&ctx(79, 24)));
        assert!(!q.matches(&ctx(100, 24))); // condition true → negated false
        assert!(!q.matches(&ctx(80, 24)));
    }

    #[test]
    fn and_chain_matches_only_when_all_hold() {
        // (min-width: 80) and (max-width: 120)
        let q = MediaQuery::parse("(min-width: 80) and (max-width: 120)").unwrap();
        assert!(q.matches(&ctx(100, 24)));
        assert!(q.matches(&ctx(80, 24)));
        assert!(q.matches(&ctx(120, 24)));
        assert!(!q.matches(&ctx(60, 24))); // below min
        assert!(!q.matches(&ctx(200, 24))); // above max
    }

    #[test]
    fn comma_with_not_second_alt() {
        // (min-width: 200), not (color) against a no_color ctx → second alt.
        let q = MediaQuery::parse("(min-width: 200), not (color)").unwrap();
        // no_color ctx: (color) is false, so `not (color)` is true → matches.
        assert!(q.matches(&no_color_ctx()));
        // A color ctx with cols < 200: (min-width: 200) false, (color) true so
        // `not (color)` false → neither alt matches.
        assert!(!q.matches(&ctx(100, 24)));
        // Color ctx with cols >= 200: first alt matches.
        assert!(q.matches(&ctx(200, 24)));
    }

    #[test]
    fn not_all_conditions_in_one_alternative() {
        // Per-term negation: `not (min-width: 80) and (color)` is ONE alternative
        // with TWO terms `[¬(min-width:80), (color)]`. It matches iff
        // (cols < 80) AND (color on). This is DIFFERENT from whole-alternative
        // negation `not ((min-width:80) and (color))`.
        let q = MediaQuery::parse("not (min-width: 80) and (color)").unwrap();
        // Structure: one alternative, two terms — first negated, second not.
        assert_eq!(
            q.alternatives,
            vec![alt_terms([
                not_term(MediaCondition::MinWidth(80)),
                term(MediaCondition::Color),
            ])]
        );
        // cols=60 + color → ¬min-width true (60<80) AND color true → matches.
        assert!(q.matches(&ctx(60, 24)));
        // cols=100 + color → ¬min-width false (100>=80) → no match (per-term).
        assert!(!q.matches(&ctx(100, 24)));
        // cols=60 + no_color → ¬min-width true BUT color false → no match.
        let small_mono = MediaContext { cols: 60, no_color: true, ..Default::default() };
        assert!(!q.matches(&small_mono));
        // cols=100 + no_color → both fail → no match.
        let large_mono = MediaContext { cols: 100, no_color: true, ..Default::default() };
        assert!(!q.matches(&large_mono));
    }

    // --- Display -------------------------------------------------------------

    #[test]
    fn display_roundtrip() {
        let q = MediaQuery::parse("(min-width: 80) and (color)").unwrap();
        assert_eq!(q.to_string(), "(min-width: 80) and (color)");
    }

    #[test]
    fn display_roundtrip_comma_and_not() {
        let q = MediaQuery::parse("(min-width: 80), not (color)").unwrap();
        assert_eq!(q.to_string(), "(min-width: 80), not (color)");
    }

    // --- and (nested @media combinator) -------------------------------------

    #[test]
    fn media_query_and_concatenates_conditions() {
        // (min-width: 80).and((color)) → one alternative with BOTH conditions;
        // matches only when both hold.
        let q1 = MediaQuery::parse("(min-width: 80)").unwrap();
        let q2 = MediaQuery::parse("(color)").unwrap();
        let combined = q1.and(&q2);
        assert_eq!(
            combined.alternatives,
            vec![alt([MediaCondition::MinWidth(80), MediaCondition::Color])],
            "AND of two single-condition queries concatenates conditions"
        );
        // Matches only when both hold.
        let both = MediaContext { cols: 100, no_color: false, ..Default::default() };
        let width_only = MediaContext { cols: 100, no_color: true, ..Default::default() };
        let color_only = MediaContext { cols: 60, no_color: false, ..Default::default() };
        let neither = MediaContext { cols: 60, no_color: true, ..Default::default() };
        assert!(combined.matches(&both), "both hold → matches");
        assert!(!combined.matches(&width_only), "color missing → no match");
        assert!(!combined.matches(&color_only), "width missing → no match");
        assert!(!combined.matches(&neither), "neither → no match");
    }

    #[test]
    fn media_query_and_cross_product() {
        // (a),(b) AND (c) → two alternatives (a,c),(b,c).
        let q1 = MediaQuery::parse("(min-width: 80), (max-width: 40)").unwrap();
        let q2 = MediaQuery::parse("(color)").unwrap();
        let combined = q1.and(&q2);
        assert_eq!(
            combined.alternatives,
            vec![
                alt([MediaCondition::MinWidth(80), MediaCondition::Color]),
                alt([MediaCondition::MaxWidth(40), MediaCondition::Color]),
            ],
            "OR cross-product with AND concatenates per-alternative"
        );
        // cols:100, color → first alt matches.
        let large_color = MediaContext { cols: 100, no_color: false, ..Default::default() };
        assert!(combined.matches(&large_color));
        // cols:30, color → second alt matches.
        let small_color = MediaContext { cols: 30, no_color: false, ..Default::default() };
        assert!(combined.matches(&small_color));
        // cols:50, color → neither alt (50 is between 40 and 80).
        let mid_color = MediaContext { cols: 50, no_color: false, ..Default::default() };
        assert!(!combined.matches(&mid_color));
        // cols:100, no color → first alt's color condition fails; second alt's
        // width fails too.
        let large_mono = MediaContext { cols: 100, no_color: true, ..Default::default() };
        assert!(!combined.matches(&large_mono));
    }

    #[test]
    fn media_query_and_empty_short_circuit() {
        // empty AND other == other; other AND empty == other.
        let empty = MediaQuery::default();
        let other = MediaQuery::parse("(min-width: 80)").unwrap();
        assert_eq!(empty.and(&other), other, "match-all AND other == other");
        assert_eq!(other.and(&empty), other, "other AND match-all == other");
        // Both empty → empty.
        assert_eq!(empty.and(&MediaQuery::default()), MediaQuery::default());
    }

    #[test]
    fn media_query_and_is_now_exact_with_negation() {
        // (not (min-width: 80)).and((color)): with per-term negation the AND is
        // EXACT. The combined alternative is `[¬(min-width:80), (color)]` — one
        // alternative, two terms (first negated). It matches iff
        // (cols < 80) AND (color on). This replaces the old
        // `media_query_and_negation_is_approximate` test, which pinned the
        // whole-alternative-negation approximation.
        let not_q = MediaQuery::parse("not (min-width: 80)").unwrap();
        let color_q = MediaQuery::parse("(color)").unwrap();
        let combined = not_q.and(&color_q);
        // One alternative, two terms — first negated, second not.
        assert_eq!(
            combined.alternatives,
            vec![alt_terms([
                not_term(MediaCondition::MinWidth(80)),
                term(MediaCondition::Color),
            ])],
            "AND is exact: per-term negation preserved, no whole-alt negation"
        );
        // cols:60, color → ¬min-width true AND color true → matches.
        let small_color = MediaContext { cols: 60, no_color: false, ..Default::default() };
        assert!(combined.matches(&small_color), "exact: ¬width AND color → matches");
        // cols:100, color → ¬min-width false (100>=80) → no match.
        let large_color = MediaContext { cols: 100, no_color: false, ..Default::default() };
        assert!(!combined.matches(&large_color), "exact: width holds so ¬width false → no match");
        // cols:60, no_color → ¬min-width true BUT color false → no match.
        let small_mono = MediaContext { cols: 60, no_color: true, ..Default::default() };
        assert!(!combined.matches(&small_mono), "exact: color missing → no match");
    }

    #[test]
    fn matching_specificity_returns_max_condition_count() {
        // A 2-condition matching alternative is more specific than a 1-condition
        // one in the same query (under OR).
        let q = MediaQuery::parse("(min-width: 80) and (color), (max-width: 40)").unwrap();
        // cols:100, color → first alt (2 conds) matches → specificity 2.
        let large_color = MediaContext { cols: 100, no_color: false, ..Default::default() };
        assert_eq!(q.matching_specificity(&large_color), Some(2));
        // cols:30, color → only second alt (1 cond) matches → specificity 1.
        let small_color = MediaContext { cols: 30, no_color: false, ..Default::default() };
        assert_eq!(q.matching_specificity(&small_color), Some(1));
    }

    #[test]
    fn matching_specificity_none_when_no_match() {
        let q = MediaQuery::parse("(min-width: 80)").unwrap();
        // cols:60 → no match → None.
        let small = MediaContext { cols: 60, ..Default::default() };
        assert_eq!(q.matching_specificity(&small), None);
    }

    #[test]
    fn matching_specificity_zero_for_match_all() {
        let empty = MediaQuery::default();
        assert_eq!(empty.matching_specificity(&MediaContext::default()), Some(0));
    }

    #[test]
    fn matching_specificity_counts_terms() {
        // Specificity is now the term count of the matching alternative. A
        // 2-term alternative has specificity 2.
        let q = MediaQuery::parse("(min-width: 80) and (color)").unwrap();
        let large_color = MediaContext { cols: 100, no_color: false, ..Default::default() };
        assert_eq!(q.matching_specificity(&large_color), Some(2));
    }

    #[test]
    fn matching_specificity_counts_negated_terms() {
        // Negated terms count toward specificity too. `not (min-width: 80)` is
        // one term (negated) → specificity 1 when it matches.
        let q = MediaQuery::parse("not (min-width: 80)").unwrap();
        let small = MediaContext { cols: 60, ..Default::default() };
        assert_eq!(q.matching_specificity(&small), Some(1));
        // And a 2-term negated alternative `not (min-width:80) and (color)`.
        let q2 = MediaQuery::parse("not (min-width: 80) and (color)").unwrap();
        // cols:60, no_color:true → ¬min-width true BUT (color) false → no match.
        let small_mono = MediaContext { cols: 60, no_color: true, ..Default::default() };
        assert_eq!(q2.matching_specificity(&small_mono), None, "color missing → no match");
        // cols:60, color on → both terms satisfied → 2-term specificity.
        let small_color = MediaContext { cols: 60, no_color: false, ..Default::default() };
        assert_eq!(
            q2.matching_specificity(&small_color),
            Some(2),
            "both terms satisfied → 2-term specificity"
        );
    }

    // --- per-term negation (P6-2) -------------------------------------------

    #[test]
    fn not_is_per_term() {
        // `not (min-width:80) and (color)` parses to ONE alternative with TWO
        // terms `[¬min-width:80, color]` — NOT two alternatives, NOT whole-alt
        // negation.
        let q = MediaQuery::parse("not (min-width: 80) and (color)").unwrap();
        assert_eq!(q.alternatives.len(), 1, "one alternative, not two");
        let alt0 = &q.alternatives[0];
        assert_eq!(alt0.terms.len(), 2, "two terms in the alternative");
        assert_eq!(alt0.terms[0], not_term(MediaCondition::MinWidth(80)));
        assert_eq!(alt0.terms[1], term(MediaCondition::Color));
    }

    #[test]
    fn per_term_negation_matches() {
        // `not (min-width:80)` matches ctx{cols:60} (¬true=true), not {cols:100}.
        let q = MediaQuery::parse("not (min-width: 80)").unwrap();
        assert!(q.matches(&ctx(60, 24)));
        assert!(!q.matches(&ctx(100, 24)));

        // `not (min-width:80) and (color)` matches {cols:60,color}, not
        // {cols:60,no_color}, not {cols:100,color}.
        let q2 = MediaQuery::parse("not (min-width: 80) and (color)").unwrap();
        let small_color = MediaContext { cols: 60, no_color: false, ..Default::default() };
        let small_mono = MediaContext { cols: 60, no_color: true, ..Default::default() };
        let large_color = MediaContext { cols: 100, no_color: false, ..Default::default() };
        assert!(q2.matches(&small_color), "cols<80 AND color → matches");
        assert!(!q2.matches(&small_mono), "cols<80 but no color → no match");
        assert!(!q2.matches(&large_color), "cols>=80 → ¬min-width false → no match");
    }

    #[test]
    fn comma_with_not_terms() {
        // `(min-width:200), not (color)` → two alternatives; matches no_color ctx
        // via the second (negated-term) alternative.
        let q = MediaQuery::parse("(min-width: 200), not (color)").unwrap();
        assert_eq!(q.alternatives.len(), 2);
        // Structure: second alt is one negated term.
        assert_eq!(q.alternatives[1], alt_neg(MediaCondition::Color));
        // no_color ctx → (color) false → ¬(color) true → matches via second alt.
        assert!(q.matches(&no_color_ctx()));
        // color ctx, cols<200 → first alt fails, second alt (¬color) false → no match.
        assert!(!q.matches(&ctx(100, 24)));
        // color ctx, cols>=200 → first alt matches.
        assert!(q.matches(&ctx(200, 24)));
    }

    #[test]
    fn display_roundtrip_negated_term() {
        // A negated term round-trips through Display.
        let q = MediaQuery::parse("not (min-width: 80) and (color)").unwrap();
        assert_eq!(q.to_string(), "not (min-width: 80) and (color)");
        // Re-parse and confirm structural equality (round-trip stable).
        let q2 = MediaQuery::parse(&q.to_string()).unwrap();
        assert_eq!(q, q2);
    }

    #[test]
    fn not_at_end_of_alternative_errors() {
        // A trailing `not` with nothing to negate is a structural error.
        assert!(MediaQuery::parse("(min-width: 80) and not").is_err());
    }
}