standout-render 7.1.0

Styled terminal rendering with templates, themes, and adaptive color support
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
//! Theme struct for building style collections.
//!
//! Themes are named collections of styles that can adapt to the user's
//! display mode (light/dark). They support both programmatic construction
//! and YAML-based file loading.
//!
//! # Adaptive Styles
//!
//! Individual styles can define mode-specific variations. When resolving
//! styles for rendering, the theme selects the appropriate variant based
//! on the current color mode:
//!
//! - Base styles: Used when no mode override exists
//! - Light overrides: Applied in light mode
//! - Dark overrides: Applied in dark mode
//!
//! # Construction Methods
//!
//! ## Programmatic (Builder API)
//!
//! ```rust
//! use standout_render::Theme;
//! use console::Style;
//!
//! let theme = Theme::new()
//!     // Non-adaptive styles work in all modes
//!     .add("muted", Style::new().dim())
//!     .add("accent", Style::new().cyan().bold())
//!     // Aliases reference other styles
//!     .add("disabled", "muted");
//! ```
//!
//! ## From YAML
//!
//! ```rust
//! use standout_render::Theme;
//!
//! let theme = Theme::from_yaml(r#"
//! header:
//!   fg: cyan
//!   bold: true
//!
//! footer:
//!   fg: gray
//!   light:
//!     fg: black
//!   dark:
//!     fg: white
//!
//! muted:
//!   dim: true
//!
//! disabled: muted
//! "#).unwrap();
//! ```
//!
//! # Mode Resolution
//!
//! Use [`resolve_styles`](Theme::resolve_styles) to get a `Styles` collection
//! for a specific color mode. This is typically called during rendering.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use console::Style;

use super::super::style::{
    parse_stylesheet, StyleValidationError, StyleValue, Styles, StylesheetError, ThemeVariants,
};

use super::adaptive::ColorMode;
use super::icon_def::{IconDefinition, IconSet};
use super::icon_mode::IconMode;

/// A named collection of styles used when rendering templates.
///
/// Themes can be constructed programmatically or loaded from YAML files.
/// They support adaptive styles that vary based on the user's color mode.
///
/// # Example: Programmatic Construction
///
/// ```rust
/// use standout_render::Theme;
/// use console::Style;
///
/// let theme = Theme::new()
///     // Visual layer - concrete styles
///     .add("muted", Style::new().dim())
///     .add("accent", Style::new().cyan().bold())
///     // Presentation layer - aliases
///     .add("disabled", "muted")
///     .add("highlighted", "accent")
///     // Semantic layer - aliases to presentation
///     .add("timestamp", "disabled");
/// ```
///
/// # Example: From YAML
///
/// ```rust
/// use standout_render::Theme;
///
/// let theme = Theme::from_yaml(r#"
/// panel:
///   bg: gray
///   light:
///     bg: white
///   dark:
///     bg: black
/// header:
///   fg: cyan
///   bold: true
/// "#).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Theme {
    /// Theme name (optional, typically derived from filename).
    name: Option<String>,
    /// Source file path (for refresh support).
    source_path: Option<PathBuf>,
    /// Base styles (always populated).
    base: HashMap<String, Style>,
    /// Light mode style overrides.
    light: HashMap<String, Style>,
    /// Dark mode style overrides.
    dark: HashMap<String, Style>,
    /// Alias definitions (name → target).
    aliases: HashMap<String, String>,
    /// Icon definitions (classic + optional nerdfont variants).
    icons: IconSet,
}

impl Theme {
    /// Creates an empty, unnamed theme.
    pub fn new() -> Self {
        Self {
            name: None,
            source_path: None,
            base: HashMap::new(),
            light: HashMap::new(),
            dark: HashMap::new(),
            aliases: HashMap::new(),
            icons: IconSet::new(),
        }
    }

    /// Creates an empty theme with the given name.
    pub fn named(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            source_path: None,
            base: HashMap::new(),
            light: HashMap::new(),
            dark: HashMap::new(),
            aliases: HashMap::new(),
            icons: IconSet::new(),
        }
    }

    /// Sets the name on this theme, returning `self` for chaining.
    ///
    /// This is useful when loading themes from content where the name
    /// is known separately (e.g., from a filename).
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Loads a theme from a YAML file.
    ///
    /// The theme name is derived from the filename (without extension).
    /// The source path is stored for [`refresh`](Theme::refresh) support.
    ///
    /// # Errors
    ///
    /// Returns a [`StylesheetError`] if the file cannot be read or parsed.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use standout_render::Theme;
    ///
    /// let theme = Theme::from_file("./themes/darcula.yaml")?;
    /// assert_eq!(theme.name(), Some("darcula"));
    /// ```
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, StylesheetError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path).map_err(|e| StylesheetError::Load {
            message: format!("Failed to read {}: {}", path.display(), e),
        })?;

        let name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(|s| s.to_string());

        let icons = parse_icons_from_yaml_str(&content)?;
        let variants = parse_stylesheet(&content)?;
        Ok(Self {
            name,
            source_path: Some(path.to_path_buf()),
            base: variants.base().clone(),
            light: variants.light().clone(),
            dark: variants.dark().clone(),
            aliases: variants.aliases().clone(),
            icons,
        })
    }

    /// Creates a theme from YAML content.
    ///
    /// The YAML format supports:
    /// - Simple styles: `header: { fg: cyan, bold: true }`
    /// - Shorthand: `bold_text: bold` or `warning: "yellow italic"`
    /// - Aliases: `disabled: muted`
    /// - Adaptive styles with `light:` and `dark:` sections
    ///
    /// # Errors
    ///
    /// Returns a [`StylesheetError`] if parsing fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::Theme;
    ///
    /// let theme = Theme::from_yaml(r#"
    /// header:
    ///   fg: cyan
    ///   bold: true
    ///
    /// footer:
    ///   dim: true
    ///   light:
    ///     fg: black
    ///   dark:
    ///     fg: white
    /// "#).unwrap();
    /// ```
    pub fn from_yaml(yaml: &str) -> Result<Self, StylesheetError> {
        let icons = parse_icons_from_yaml_str(yaml)?;
        let variants = parse_stylesheet(yaml)?;
        Ok(Self {
            name: None,
            source_path: None,
            base: variants.base().clone(),
            light: variants.light().clone(),
            dark: variants.dark().clone(),
            aliases: variants.aliases().clone(),
            icons,
        })
    }

    /// Creates a theme from CSS content.
    ///
    /// The CSS format supports a subset of CSS Level 3 tailored for terminals.
    /// Class selectors map to style names (`.title { ... }` defines the `title` style).
    /// Adaptive styles use `@media (prefers-color-scheme: light|dark)` queries.
    ///
    /// # Errors
    ///
    /// Returns a [`StylesheetError`] if parsing fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::Theme;
    ///
    /// let theme = Theme::from_css(r#"
    /// .header { color: cyan; font-weight: bold; }
    /// .muted { opacity: 0.5; }
    /// "#).unwrap();
    /// ```
    pub fn from_css(css: &str) -> Result<Self, StylesheetError> {
        let variants = crate::parse_css(css)?;
        Ok(Self {
            name: None,
            source_path: None,
            base: variants.base().clone(),
            light: variants.light().clone(),
            dark: variants.dark().clone(),
            aliases: variants.aliases().clone(),
            icons: IconSet::new(),
        })
    }

    /// Loads a theme from a CSS file.
    ///
    /// The theme name is derived from the filename (without extension).
    /// The source path is stored for [`refresh`](Theme::refresh) support.
    ///
    /// # Errors
    ///
    /// Returns a [`StylesheetError`] if the file cannot be read or parsed.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use standout_render::Theme;
    ///
    /// let theme = Theme::from_css_file("./themes/default.css")?;
    /// assert_eq!(theme.name(), Some("default"));
    /// ```
    pub fn from_css_file<P: AsRef<Path>>(path: P) -> Result<Self, StylesheetError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path).map_err(|e| StylesheetError::Load {
            message: format!("Failed to read {}: {}", path.display(), e),
        })?;

        let name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(|s| s.to_string());

        let variants = crate::parse_css(&content)?;
        Ok(Self {
            name,
            source_path: Some(path.to_path_buf()),
            base: variants.base().clone(),
            light: variants.light().clone(),
            dark: variants.dark().clone(),
            aliases: variants.aliases().clone(),
            icons: IconSet::new(),
        })
    }

    /// Creates a theme from pre-parsed theme variants.
    pub fn from_variants(variants: ThemeVariants) -> Self {
        Self {
            name: None,
            source_path: None,
            base: variants.base().clone(),
            light: variants.light().clone(),
            dark: variants.dark().clone(),
            aliases: variants.aliases().clone(),
            icons: IconSet::new(),
        }
    }

    /// Returns the theme name, if set.
    ///
    /// The name is typically derived from the source filename when using
    /// [`from_file`](Theme::from_file), or set explicitly with [`named`](Theme::named).
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the source file path, if this theme was loaded from a file.
    pub fn source_path(&self) -> Option<&Path> {
        self.source_path.as_deref()
    }

    /// Reloads the theme from its source file.
    ///
    /// This is useful for hot-reloading during development. If the theme
    /// was not loaded from a file, this method returns an error.
    ///
    /// # Errors
    ///
    /// Returns a [`StylesheetError`] if:
    /// - The theme has no source file (wasn't loaded with [`from_file`](Theme::from_file))
    /// - The file cannot be read or parsed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut theme = Theme::from_file("./themes/darcula.yaml")?;
    ///
    /// // After editing the file...
    /// theme.refresh()?;
    /// ```
    pub fn refresh(&mut self) -> Result<(), StylesheetError> {
        let path = self
            .source_path
            .as_ref()
            .ok_or_else(|| StylesheetError::Load {
                message: "Cannot refresh: theme has no source file".to_string(),
            })?;

        let content = std::fs::read_to_string(path).map_err(|e| StylesheetError::Load {
            message: format!("Failed to read {}: {}", path.display(), e),
        })?;

        let icons = parse_icons_from_yaml_str(&content)?;
        let variants = parse_stylesheet(&content)?;
        self.base = variants.base().clone();
        self.light = variants.light().clone();
        self.dark = variants.dark().clone();
        self.aliases = variants.aliases().clone();
        self.icons = icons;

        Ok(())
    }

    /// Adds a named style, returning an updated theme for chaining.
    ///
    /// The value can be either a concrete `Style` or a `&str`/`String` alias
    /// to another style name, enabling layered styling.
    ///
    /// # Non-Adaptive
    ///
    /// Styles added via this method are non-adaptive (same in all modes).
    /// For adaptive styles, use [`add_adaptive`](Self::add_adaptive) or YAML.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::Theme;
    /// use console::Style;
    ///
    /// let theme = Theme::new()
    ///     // Visual layer - concrete styles
    ///     .add("muted", Style::new().dim())
    ///     .add("accent", Style::new().cyan().bold())
    ///     // Presentation layer - aliases
    ///     .add("disabled", "muted")
    ///     .add("highlighted", "accent")
    ///     // Semantic layer - aliases to presentation
    ///     .add("timestamp", "disabled");
    /// ```
    pub fn add<V: Into<StyleValue>>(mut self, name: &str, value: V) -> Self {
        match value.into() {
            StyleValue::Concrete(style) => {
                self.base.insert(name.to_string(), style);
            }
            StyleValue::Alias(target) => {
                self.aliases.insert(name.to_string(), target);
            }
        }
        self
    }

    /// Adds an adaptive style with separate light and dark variants.
    ///
    /// The base style is used when no mode override exists or when mode
    /// detection fails. Light and dark variants, if provided, override
    /// the base in their respective modes.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::Theme;
    /// use console::Style;
    ///
    /// let theme = Theme::new()
    ///     .add_adaptive(
    ///         "panel",
    ///         Style::new().dim(),                    // Base
    ///         Some(Style::new().fg(console::Color::Black)),  // Light mode
    ///         Some(Style::new().fg(console::Color::White)),  // Dark mode
    ///     );
    /// ```
    pub fn add_adaptive(
        mut self,
        name: &str,
        base: Style,
        light: Option<Style>,
        dark: Option<Style>,
    ) -> Self {
        self.base.insert(name.to_string(), base);
        if let Some(light_style) = light {
            self.light.insert(name.to_string(), light_style);
        }
        if let Some(dark_style) = dark {
            self.dark.insert(name.to_string(), dark_style);
        }
        self
    }

    /// Adds an icon definition to the theme, returning `self` for chaining.
    ///
    /// Icons are characters (not images) that adapt between classic Unicode
    /// and Nerd Font glyphs. Each icon has a classic variant and an optional
    /// Nerd Font variant.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::{Theme, IconDefinition};
    ///
    /// let theme = Theme::new()
    ///     .add_icon("pending", IconDefinition::new("⚪"))
    ///     .add_icon("done", IconDefinition::new("⚫").with_nerdfont("\u{f00c}"));
    /// ```
    pub fn add_icon(mut self, name: &str, def: IconDefinition) -> Self {
        self.icons.insert(name.to_string(), def);
        self
    }

    /// Resolves icons for the given icon mode.
    ///
    /// Returns a map of icon names to resolved strings for the given mode.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::{Theme, IconDefinition, IconMode};
    ///
    /// let theme = Theme::new()
    ///     .add_icon("done", IconDefinition::new("⚫").with_nerdfont("\u{f00c}"));
    ///
    /// let classic = theme.resolve_icons(IconMode::Classic);
    /// assert_eq!(classic.get("done").unwrap(), "⚫");
    ///
    /// let nerdfont = theme.resolve_icons(IconMode::NerdFont);
    /// assert_eq!(nerdfont.get("done").unwrap(), "\u{f00c}");
    /// ```
    pub fn resolve_icons(&self, mode: IconMode) -> HashMap<String, String> {
        self.icons.resolve(mode)
    }

    /// Returns a reference to the icon set.
    pub fn icons(&self) -> &IconSet {
        &self.icons
    }

    /// Resolves styles for the given color mode.
    ///
    /// Returns a [`Styles`] collection with the appropriate style for each
    /// defined style name:
    ///
    /// - For styles with a mode-specific override, uses the override
    /// - For styles without an override, uses the base style
    /// - Aliases are preserved for resolution during rendering
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::{Theme, ColorMode};
    /// use console::Style;
    ///
    /// let theme = Theme::new()
    ///     .add("header", Style::new().cyan())
    ///     .add_adaptive(
    ///         "panel",
    ///         Style::new(),
    ///         Some(Style::new().fg(console::Color::Black)),
    ///         Some(Style::new().fg(console::Color::White)),
    ///     );
    ///
    /// // Get styles for dark mode
    /// let dark_styles = theme.resolve_styles(Some(ColorMode::Dark));
    /// ```
    pub fn resolve_styles(&self, mode: Option<ColorMode>) -> Styles {
        let mut styles = Styles::new();

        // Select the mode-specific overrides map
        let mode_overrides = match mode {
            Some(ColorMode::Light) => &self.light,
            Some(ColorMode::Dark) => &self.dark,
            None => &HashMap::new(),
        };

        // Add concrete styles (base, with mode overrides applied)
        for (name, base_style) in &self.base {
            let style = mode_overrides.get(name).unwrap_or(base_style);
            styles = styles.add(name, style.clone());
        }

        // Add aliases
        for (name, target) in &self.aliases {
            styles = styles.add(name, target.clone());
        }

        styles
    }

    /// Validates that all style aliases in this theme resolve correctly.
    ///
    /// This is called automatically at render time, but can be called
    /// explicitly for early error detection.
    pub fn validate(&self) -> Result<(), StyleValidationError> {
        // Validate using a resolved Styles instance
        self.resolve_styles(None).validate()
    }

    /// Returns true if no styles are defined.
    pub fn is_empty(&self) -> bool {
        self.base.is_empty() && self.aliases.is_empty()
    }

    /// Returns the number of defined styles (base + aliases).
    pub fn len(&self) -> usize {
        self.base.len() + self.aliases.len()
    }

    /// Resolves a single style for the given mode.
    ///
    /// This is a convenience wrapper around [`resolve_styles`](Self::resolve_styles).
    pub fn get_style(&self, name: &str, mode: Option<ColorMode>) -> Option<Style> {
        let styles = self.resolve_styles(mode);
        // Styles::resolve is crate-private, so we have to use to_resolved_map or check internal.
        // Wait, Styles::resolve is pub(crate). We are in rendering/theme/theme.rs,
        // Styles is in rendering/style/registry.rs. Same crate.
        // But Theme is in `rendering::theme`, Styles in `rendering::style`.
        // They are different modules. `pub(crate)` is visible.
        styles.resolve(name).cloned()
    }

    /// Returns the number of light mode overrides.
    pub fn light_override_count(&self) -> usize {
        self.light.len()
    }

    /// Returns the number of dark mode overrides.
    pub fn dark_override_count(&self) -> usize {
        self.dark.len()
    }

    /// Merges another theme into this one.
    ///
    /// Styles from `other` take precedence over styles in `self`.
    /// This allows layering themes, e.g., loading a base theme and applying user overrides.
    ///
    /// # Example
    ///
    /// ```rust
    /// use standout_render::Theme;
    /// use console::Style;
    ///
    /// let base = Theme::new().add("text", Style::new().dim());
    /// let user = Theme::new().add("text", Style::new().bold());
    ///
    /// let merged = base.merge(user);
    /// // "text" is now bold (from user)
    /// ```
    pub fn merge(mut self, other: Theme) -> Self {
        self.base.extend(other.base);
        self.light.extend(other.light);
        self.dark.extend(other.dark);
        self.aliases.extend(other.aliases);
        self.icons = self.icons.merge(other.icons);
        self
    }
}

impl Default for Theme {
    fn default() -> Self {
        Self::new()
    }
}

/// Parses icon definitions from a YAML string.
///
/// Extracts the `icons:` section from the YAML root mapping and
/// parses each entry into an [`IconDefinition`].
///
/// # YAML Format
///
/// ```yaml
/// icons:
///   # String shorthand (classic only)
///   pending: "⚪"
///
///   # Mapping with both variants
///   done:
///     classic: "⚫"
///     nerdfont: "\uf00c"
/// ```
fn parse_icons_from_yaml_str(yaml: &str) -> Result<IconSet, StylesheetError> {
    let root: serde_yaml::Value =
        serde_yaml::from_str(yaml).map_err(|e| StylesheetError::Parse {
            path: None,
            message: e.to_string(),
        })?;

    parse_icons_from_yaml(&root)
}

/// Parses icon definitions from a parsed YAML value.
fn parse_icons_from_yaml(root: &serde_yaml::Value) -> Result<IconSet, StylesheetError> {
    let mut icon_set = IconSet::new();

    let mapping = match root.as_mapping() {
        Some(m) => m,
        None => return Ok(icon_set),
    };

    let icons_value = match mapping.get(serde_yaml::Value::String("icons".into())) {
        Some(v) => v,
        None => return Ok(icon_set),
    };

    let icons_map = icons_value
        .as_mapping()
        .ok_or_else(|| StylesheetError::Parse {
            path: None,
            message: "'icons' must be a mapping".to_string(),
        })?;

    for (key, value) in icons_map {
        let name = key.as_str().ok_or_else(|| StylesheetError::Parse {
            path: None,
            message: format!("Icon name must be a string, got {:?}", key),
        })?;

        let def = match value {
            serde_yaml::Value::String(s) => {
                // Shorthand: classic-only
                IconDefinition::new(s.clone())
            }
            serde_yaml::Value::Mapping(map) => {
                let classic = map
                    .get(serde_yaml::Value::String("classic".into()))
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| StylesheetError::InvalidDefinition {
                        style: name.to_string(),
                        message: "Icon mapping must have a 'classic' key".to_string(),
                        path: None,
                    })?;
                let nerdfont = map
                    .get(serde_yaml::Value::String("nerdfont".into()))
                    .and_then(|v| v.as_str());
                let mut def = IconDefinition::new(classic);
                if let Some(nf) = nerdfont {
                    def = def.with_nerdfont(nf);
                }
                def
            }
            _ => {
                return Err(StylesheetError::InvalidDefinition {
                    style: name.to_string(),
                    message: "Icon must be a string or mapping with 'classic' key".to_string(),
                    path: None,
                });
            }
        };

        icon_set.insert(name.to_string(), def);
    }

    Ok(icon_set)
}

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

    #[test]
    fn test_theme_new_is_empty() {
        let theme = Theme::new();
        assert!(theme.is_empty());
        assert_eq!(theme.len(), 0);
    }

    #[test]
    fn test_theme_add_concrete() {
        let theme = Theme::new().add("bold", Style::new().bold());
        assert!(!theme.is_empty());
        assert_eq!(theme.len(), 1);
    }

    #[test]
    fn test_theme_add_alias_str() {
        let theme = Theme::new()
            .add("base", Style::new().dim())
            .add("alias", "base");

        assert_eq!(theme.len(), 2);

        let styles = theme.resolve_styles(None);
        assert!(styles.has("base"));
        assert!(styles.has("alias"));
    }

    #[test]
    fn test_theme_add_alias_string() {
        let target = String::from("base");
        let theme = Theme::new()
            .add("base", Style::new().dim())
            .add("alias", target);

        let styles = theme.resolve_styles(None);
        assert!(styles.has("alias"));
    }

    #[test]
    fn test_theme_validate_valid() {
        let theme = Theme::new()
            .add("visual", Style::new().cyan())
            .add("semantic", "visual");

        assert!(theme.validate().is_ok());
    }

    #[test]
    fn test_theme_validate_invalid() {
        let theme = Theme::new().add("orphan", "missing");
        assert!(theme.validate().is_err());
    }

    #[test]
    fn test_theme_default() {
        let theme = Theme::default();
        assert!(theme.is_empty());
    }

    // =========================================================================
    // Adaptive style tests
    // =========================================================================

    #[test]
    fn test_theme_add_adaptive() {
        let theme = Theme::new().add_adaptive(
            "panel",
            Style::new().dim(),
            Some(Style::new().bold()),
            Some(Style::new().italic()),
        );

        assert_eq!(theme.len(), 1);
        assert_eq!(theme.light_override_count(), 1);
        assert_eq!(theme.dark_override_count(), 1);
    }

    #[test]
    fn test_theme_add_adaptive_light_only() {
        let theme =
            Theme::new().add_adaptive("panel", Style::new().dim(), Some(Style::new().bold()), None);

        assert_eq!(theme.light_override_count(), 1);
        assert_eq!(theme.dark_override_count(), 0);
    }

    #[test]
    fn test_theme_add_adaptive_dark_only() {
        let theme =
            Theme::new().add_adaptive("panel", Style::new().dim(), None, Some(Style::new().bold()));

        assert_eq!(theme.light_override_count(), 0);
        assert_eq!(theme.dark_override_count(), 1);
    }

    #[test]
    fn test_theme_resolve_styles_no_mode() {
        let theme = Theme::new()
            .add("header", Style::new().cyan())
            .add_adaptive(
                "panel",
                Style::new().dim(),
                Some(Style::new().bold()),
                Some(Style::new().italic()),
            );

        let styles = theme.resolve_styles(None);
        assert!(styles.has("header"));
        assert!(styles.has("panel"));
    }

    #[test]
    fn test_theme_resolve_styles_light_mode() {
        let theme = Theme::new().add_adaptive(
            "panel",
            Style::new().dim(),
            Some(Style::new().bold()),
            Some(Style::new().italic()),
        );

        let styles = theme.resolve_styles(Some(ColorMode::Light));
        assert!(styles.has("panel"));
        // The style should be the light override, not base
        // We can't easily check the actual style, but we verify resolution works
    }

    #[test]
    fn test_theme_resolve_styles_dark_mode() {
        let theme = Theme::new().add_adaptive(
            "panel",
            Style::new().dim(),
            Some(Style::new().bold()),
            Some(Style::new().italic()),
        );

        let styles = theme.resolve_styles(Some(ColorMode::Dark));
        assert!(styles.has("panel"));
    }

    #[test]
    fn test_theme_resolve_styles_preserves_aliases() {
        let theme = Theme::new()
            .add("base", Style::new().dim())
            .add("alias", "base");

        let styles = theme.resolve_styles(Some(ColorMode::Light));
        assert!(styles.has("base"));
        assert!(styles.has("alias"));

        // Validate that alias resolution still works
        assert!(styles.validate().is_ok());
    }

    // =========================================================================
    // YAML parsing tests
    // =========================================================================

    #[test]
    fn test_theme_from_yaml_simple() {
        let theme = Theme::from_yaml(
            r#"
            header:
                fg: cyan
                bold: true
            "#,
        )
        .unwrap();

        assert_eq!(theme.len(), 1);
        let styles = theme.resolve_styles(None);
        assert!(styles.has("header"));
    }

    #[test]
    fn test_theme_from_yaml_shorthand() {
        let theme = Theme::from_yaml(
            r#"
            bold_text: bold
            accent: cyan
            warning: "yellow italic"
            "#,
        )
        .unwrap();

        assert_eq!(theme.len(), 3);
    }

    #[test]
    fn test_theme_from_yaml_alias() {
        let theme = Theme::from_yaml(
            r#"
            muted:
                dim: true
            disabled: muted
            "#,
        )
        .unwrap();

        assert_eq!(theme.len(), 2);
        assert!(theme.validate().is_ok());
    }

    #[test]
    fn test_theme_from_yaml_adaptive() {
        let theme = Theme::from_yaml(
            r#"
            panel:
                fg: gray
                light:
                    fg: black
                dark:
                    fg: white
            "#,
        )
        .unwrap();

        assert_eq!(theme.len(), 1);
        assert_eq!(theme.light_override_count(), 1);
        assert_eq!(theme.dark_override_count(), 1);
    }

    #[test]
    fn test_theme_from_yaml_invalid() {
        let result = Theme::from_yaml("not valid yaml: [");
        assert!(result.is_err());
    }

    #[test]
    fn test_theme_from_yaml_complete() {
        let theme = Theme::from_yaml(
            r##"
            # Visual layer
            muted:
                dim: true

            accent:
                fg: cyan
                bold: true

            # Adaptive
            background:
                light:
                    bg: "#f8f8f8"
                dark:
                    bg: "#1e1e1e"

            # Aliases
            header: accent
            footer: muted
            "##,
        )
        .unwrap();

        // 3 concrete styles + 2 aliases = 5 total
        assert_eq!(theme.len(), 5);
        assert!(theme.validate().is_ok());

        // background is adaptive
        assert_eq!(theme.light_override_count(), 1);
        assert_eq!(theme.dark_override_count(), 1);
    }

    // =========================================================================
    // Name and source path tests
    // =========================================================================

    #[test]
    fn test_theme_named() {
        let theme = Theme::named("darcula");
        assert_eq!(theme.name(), Some("darcula"));
        assert!(theme.is_empty());
    }

    #[test]
    fn test_theme_new_has_no_name() {
        let theme = Theme::new();
        assert_eq!(theme.name(), None);
        assert_eq!(theme.source_path(), None);
    }

    #[test]
    fn test_theme_from_file() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let theme_path = temp_dir.path().join("darcula.yaml");
        fs::write(
            &theme_path,
            r#"
            header:
                fg: cyan
                bold: true
            muted:
                dim: true
            "#,
        )
        .unwrap();

        let theme = Theme::from_file(&theme_path).unwrap();
        assert_eq!(theme.name(), Some("darcula"));
        assert_eq!(theme.source_path(), Some(theme_path.as_path()));
        assert_eq!(theme.len(), 2);
    }

    #[test]
    fn test_theme_from_file_not_found() {
        let result = Theme::from_file("/nonexistent/path/theme.yaml");
        assert!(result.is_err());
    }

    #[test]
    fn test_theme_refresh() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let theme_path = temp_dir.path().join("dynamic.yaml");
        fs::write(
            &theme_path,
            r#"
            header:
                fg: red
            "#,
        )
        .unwrap();

        let mut theme = Theme::from_file(&theme_path).unwrap();
        assert_eq!(theme.len(), 1);

        // Update the file
        fs::write(
            &theme_path,
            r#"
            header:
                fg: blue
            footer:
                dim: true
            "#,
        )
        .unwrap();

        // Refresh
        theme.refresh().unwrap();
        assert_eq!(theme.len(), 2);
    }

    #[test]
    fn test_theme_refresh_without_source() {
        let mut theme = Theme::new();
        let result = theme.refresh();
        assert!(result.is_err());
    }

    #[test]
    fn test_theme_merge() {
        let base = Theme::new()
            .add("keep", Style::new().dim())
            .add("overwrite", Style::new().red());

        let extension = Theme::new()
            .add("overwrite", Style::new().blue())
            .add("new", Style::new().bold());

        let merged = base.merge(extension);

        let styles = merged.resolve_styles(None);

        // "keep" should be from base
        assert!(styles.has("keep"));

        // "overwrite" should be from extension (blue, not red)
        assert!(styles.has("overwrite"));

        // "new" should be from extension
        assert!(styles.has("new"));

        assert_eq!(merged.len(), 3);
    }

    // =========================================================================
    // Icon tests
    // =========================================================================

    #[test]
    fn test_theme_add_icon() {
        let theme = Theme::new()
            .add_icon("pending", IconDefinition::new(""))
            .add_icon("done", IconDefinition::new("").with_nerdfont("\u{f00c}"));

        assert_eq!(theme.icons().len(), 2);
        assert!(!theme.icons().is_empty());
    }

    #[test]
    fn test_theme_resolve_icons_classic() {
        let theme = Theme::new()
            .add_icon("pending", IconDefinition::new(""))
            .add_icon("done", IconDefinition::new("").with_nerdfont("\u{f00c}"));

        let resolved = theme.resolve_icons(IconMode::Classic);
        assert_eq!(resolved.get("pending").unwrap(), "");
        assert_eq!(resolved.get("done").unwrap(), "");
    }

    #[test]
    fn test_theme_resolve_icons_nerdfont() {
        let theme = Theme::new()
            .add_icon("pending", IconDefinition::new(""))
            .add_icon("done", IconDefinition::new("").with_nerdfont("\u{f00c}"));

        let resolved = theme.resolve_icons(IconMode::NerdFont);
        assert_eq!(resolved.get("pending").unwrap(), ""); // No nerdfont, falls back
        assert_eq!(resolved.get("done").unwrap(), "\u{f00c}");
    }

    #[test]
    fn test_theme_icons_empty_by_default() {
        let theme = Theme::new();
        assert!(theme.icons().is_empty());
    }

    #[test]
    fn test_theme_merge_with_icons() {
        let base = Theme::new()
            .add_icon("keep", IconDefinition::new("K"))
            .add_icon("override", IconDefinition::new("OLD"));

        let ext = Theme::new()
            .add_icon("override", IconDefinition::new("NEW"))
            .add_icon("added", IconDefinition::new("A"));

        let merged = base.merge(ext);
        assert_eq!(merged.icons().len(), 3);

        let resolved = merged.resolve_icons(IconMode::Classic);
        assert_eq!(resolved.get("keep").unwrap(), "K");
        assert_eq!(resolved.get("override").unwrap(), "NEW");
        assert_eq!(resolved.get("added").unwrap(), "A");
    }

    #[test]
    fn test_theme_from_yaml_with_icons() {
        let theme = Theme::from_yaml(
            r#"
            header:
                fg: cyan
                bold: true
            icons:
                pending: "⚪"
                done:
                    classic: "⚫"
                    nerdfont: "nf_done"
            "#,
        )
        .unwrap();

        // Styles
        assert_eq!(theme.len(), 1);
        let styles = theme.resolve_styles(None);
        assert!(styles.has("header"));

        // Icons
        assert_eq!(theme.icons().len(), 2);
        let resolved = theme.resolve_icons(IconMode::Classic);
        assert_eq!(resolved.get("pending").unwrap(), "");
        assert_eq!(resolved.get("done").unwrap(), "");

        let resolved = theme.resolve_icons(IconMode::NerdFont);
        assert_eq!(resolved.get("done").unwrap(), "nf_done");
    }

    #[test]
    fn test_theme_from_yaml_no_icons() {
        let theme = Theme::from_yaml(
            r#"
            header:
                fg: cyan
            "#,
        )
        .unwrap();

        assert!(theme.icons().is_empty());
    }

    #[test]
    fn test_theme_from_yaml_icons_only() {
        let theme = Theme::from_yaml(
            r#"
            icons:
                check: "✓"
            "#,
        )
        .unwrap();

        assert_eq!(theme.icons().len(), 1);
        assert_eq!(theme.len(), 0); // No styles
    }

    #[test]
    fn test_theme_from_yaml_icons_invalid_type() {
        let result = Theme::from_yaml(
            r#"
            icons:
                bad: 42
            "#,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_theme_from_yaml_icons_mapping_without_classic() {
        let result = Theme::from_yaml(
            r#"
            icons:
                bad:
                    nerdfont: "nf"
            "#,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_theme_from_file_with_icons() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let theme_path = temp_dir.path().join("iconic.yaml");
        fs::write(
            &theme_path,
            r#"
            header:
                fg: cyan
            icons:
                check:
                    classic: "[ok]"
                    nerdfont: "nf_check"
            "#,
        )
        .unwrap();

        let theme = Theme::from_file(&theme_path).unwrap();
        assert_eq!(theme.icons().len(), 1);
        let resolved = theme.resolve_icons(IconMode::NerdFont);
        assert_eq!(resolved.get("check").unwrap(), "nf_check");
    }

    #[test]
    fn test_theme_refresh_with_icons() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let theme_path = temp_dir.path().join("refresh.yaml");
        fs::write(
            &theme_path,
            r#"
            icons:
                v1: "one"
            "#,
        )
        .unwrap();

        let mut theme = Theme::from_file(&theme_path).unwrap();
        assert_eq!(theme.icons().len(), 1);

        fs::write(
            &theme_path,
            r#"
            icons:
                v1: "one"
                v2: "two"
            "#,
        )
        .unwrap();

        theme.refresh().unwrap();
        assert_eq!(theme.icons().len(), 2);
    }
}