leptos-helios 0.8.1

High-performance Rust visualization library with Canvas2D, WebGPU, and WebAssembly 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
//! Advanced Theme Engine
//!
//! This module provides a comprehensive theming system for Helios visualizations,
//! including CSS-in-Rust styling, custom components, animations, and responsive design.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;

/// Theme engine errors
#[derive(Debug, Error)]
pub enum ThemeError {
    #[error("Theme not found: {id}")]
    ThemeNotFound { id: String },

    #[error("Invalid theme format: {message}")]
    InvalidThemeFormat { message: String },

    #[error("Style compilation failed: {message}")]
    StyleCompilationFailed { message: String },

    #[error("Component validation failed: {message}")]
    ComponentValidationFailed { message: String },

    #[error("Animation configuration error: {message}")]
    AnimationError { message: String },

    #[error("Responsive design error: {message}")]
    ResponsiveError { message: String },
}

/// Theme identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ThemeId(pub String);

/// Theme value types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ThemeValue {
    Color(String),
    Number(f64),
    String(String),
    Boolean(bool),
    Array(Vec<ThemeValue>),
    Object(HashMap<String, ThemeValue>),
}

/// Color palette for themes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColorPalette {
    pub primary: String,
    pub secondary: String,
    pub accent: String,
    pub background: String,
    pub surface: String,
    pub text: String,
    pub text_secondary: String,
    pub border: String,
    pub error: String,
    pub warning: String,
    pub success: String,
    pub info: String,
}

/// Typography configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypographySet {
    pub font_family: String,
    pub font_size_base: f64,
    pub font_size_small: f64,
    pub font_size_large: f64,
    pub font_weight_normal: u16,
    pub font_weight_bold: u16,
    pub line_height: f64,
    pub letter_spacing: f64,
}

/// Spacing configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpacingSet {
    pub xs: f64,
    pub sm: f64,
    pub md: f64,
    pub lg: f64,
    pub xl: f64,
    pub xxl: f64,
}

/// Shadow configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShadowSet {
    pub small: String,
    pub medium: String,
    pub large: String,
    pub xl: String,
}

/// Border configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorderSet {
    pub width: f64,
    pub radius: f64,
    pub style: String,
}

/// Theme variables
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeVariables {
    pub colors: ColorPalette,
    pub typography: TypographySet,
    pub spacing: SpacingSet,
    pub shadows: ShadowSet,
    pub borders: BorderSet,
}

/// Component type identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComponentType {
    Chart,
    Axis,
    Legend,
    Tooltip,
    Grid,
    DataPoint,
    Line,
    Bar,
    Area,
    Scatter,
    Pie,
    Custom(String),
}

/// Component style configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentStyle {
    pub component_type: ComponentType,
    pub styles: HashMap<String, ThemeValue>,
    pub variants: HashMap<String, HashMap<String, ThemeValue>>,
    pub states: HashMap<String, HashMap<String, ThemeValue>>,
}

/// Animation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Animation {
    pub name: String,
    pub duration: f64,
    pub easing: String,
    pub delay: f64,
    pub iteration_count: String,
    pub direction: String,
    pub fill_mode: String,
}

/// Animation set
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimationSet {
    pub animations: Vec<Animation>,
    pub transitions: HashMap<String, String>,
}

/// Breakpoint configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Breakpoint {
    pub name: String,
    pub min_width: Option<f64>,
    pub max_width: Option<f64>,
    pub styles: HashMap<String, ThemeValue>,
}

/// Breakpoint set
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreakpointSet {
    pub breakpoints: Vec<Breakpoint>,
    pub default: HashMap<String, ThemeValue>,
}

/// Complete theme definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Theme {
    pub id: ThemeId,
    pub name: String,
    pub description: Option<String>,
    pub version: String,
    pub variables: ThemeVariables,
    pub components: HashMap<ComponentType, ComponentStyle>,
    pub animations: AnimationSet,
    pub breakpoints: BreakpointSet,
    pub metadata: HashMap<String, ThemeValue>,
}

/// Compiled style information
#[derive(Debug, Clone)]
pub struct CompiledStyle {
    pub css: String,
    pub variables: HashMap<String, String>,
    pub media_queries: Vec<String>,
    pub animations: Vec<String>,
}

/// Style cache entry
#[derive(Debug, Clone)]
pub struct StyleCacheEntry {
    pub style: CompiledStyle,
    pub timestamp: u64,
    pub size: usize,
}

/// Theme registry
#[derive(Debug)]
pub struct ThemeRegistry {
    themes: HashMap<ThemeId, Theme>,
    active_theme: Option<ThemeId>,
    default_theme: ThemeId,
}

impl ThemeRegistry {
    /// Create a new theme registry
    pub fn new() -> Self {
        Self {
            themes: HashMap::new(),
            active_theme: None,
            default_theme: ThemeId("default".to_string()),
        }
    }

    /// Register a theme
    pub fn register_theme(&mut self, theme: Theme) -> Result<(), ThemeError> {
        self.validate_theme(&theme)?;
        self.themes.insert(theme.id.clone(), theme);
        Ok(())
    }

    /// Get a theme by ID
    pub fn get_theme(&self, id: &ThemeId) -> Result<&Theme, ThemeError> {
        self.themes
            .get(id)
            .ok_or_else(|| ThemeError::ThemeNotFound { id: id.0.clone() })
    }

    /// Set the active theme
    pub fn set_active_theme(&mut self, id: &ThemeId) -> Result<(), ThemeError> {
        if self.themes.contains_key(id) {
            self.active_theme = Some(id.clone());
            Ok(())
        } else {
            Err(ThemeError::ThemeNotFound { id: id.0.clone() })
        }
    }

    /// Get the active theme
    pub fn get_active_theme(&self) -> Result<&Theme, ThemeError> {
        if let Some(ref id) = self.active_theme {
            self.get_theme(id)
        } else {
            self.get_theme(&self.default_theme)
        }
    }

    /// List all registered themes
    pub fn list_themes(&self) -> Vec<&Theme> {
        self.themes.values().collect()
    }

    /// Validate a theme
    fn validate_theme(&self, theme: &Theme) -> Result<(), ThemeError> {
        // Validate theme ID
        if theme.id.0.is_empty() {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Theme ID cannot be empty".to_string(),
            });
        }

        // Validate theme name
        if theme.name.is_empty() {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Theme name cannot be empty".to_string(),
            });
        }

        // Validate version
        if theme.version.is_empty() {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Theme version cannot be empty".to_string(),
            });
        }

        // Validate color palette
        self.validate_color_palette(&theme.variables.colors)?;

        // Validate typography
        self.validate_typography(&theme.variables.typography)?;

        // Validate spacing
        self.validate_spacing(&theme.variables.spacing)?;

        // Validate animations
        self.validate_animations(&theme.animations)?;

        // Validate breakpoints
        self.validate_breakpoints(&theme.breakpoints)?;

        Ok(())
    }

    /// Validate color palette
    fn validate_color_palette(&self, palette: &ColorPalette) -> Result<(), ThemeError> {
        let colors = vec![
            &palette.primary,
            &palette.secondary,
            &palette.accent,
            &palette.background,
            &palette.surface,
            &palette.text,
            &palette.text_secondary,
            &palette.border,
            &palette.error,
            &palette.warning,
            &palette.success,
            &palette.info,
        ];

        for color in colors {
            if !self.is_valid_color(color) {
                return Err(ThemeError::InvalidThemeFormat {
                    message: format!("Invalid color format: {}", color),
                });
            }
        }

        Ok(())
    }

    /// Validate typography
    fn validate_typography(&self, typography: &TypographySet) -> Result<(), ThemeError> {
        if typography.font_family.is_empty() {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Font family cannot be empty".to_string(),
            });
        }

        if typography.font_size_base <= 0.0 {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Font size base must be positive".to_string(),
            });
        }

        if typography.line_height <= 0.0 {
            return Err(ThemeError::InvalidThemeFormat {
                message: "Line height must be positive".to_string(),
            });
        }

        Ok(())
    }

    /// Validate spacing
    fn validate_spacing(&self, spacing: &SpacingSet) -> Result<(), ThemeError> {
        let spacing_values = vec![
            spacing.xs,
            spacing.sm,
            spacing.md,
            spacing.lg,
            spacing.xl,
            spacing.xxl,
        ];

        for value in spacing_values {
            if value < 0.0 {
                return Err(ThemeError::InvalidThemeFormat {
                    message: "Spacing values cannot be negative".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Validate animations
    fn validate_animations(&self, animations: &AnimationSet) -> Result<(), ThemeError> {
        for animation in &animations.animations {
            if animation.name.is_empty() {
                return Err(ThemeError::AnimationError {
                    message: "Animation name cannot be empty".to_string(),
                });
            }

            if animation.duration < 0.0 {
                return Err(ThemeError::AnimationError {
                    message: "Animation duration cannot be negative".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Validate breakpoints
    fn validate_breakpoints(&self, breakpoints: &BreakpointSet) -> Result<(), ThemeError> {
        for breakpoint in &breakpoints.breakpoints {
            if breakpoint.name.is_empty() {
                return Err(ThemeError::ResponsiveError {
                    message: "Breakpoint name cannot be empty".to_string(),
                });
            }

            if let (Some(min), Some(max)) = (breakpoint.min_width, breakpoint.max_width) {
                if min >= max {
                    return Err(ThemeError::ResponsiveError {
                        message: "Breakpoint min_width must be less than max_width".to_string(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Check if a color string is valid
    fn is_valid_color(&self, color: &str) -> bool {
        // Basic color validation - can be enhanced
        color.starts_with('#') && color.len() == 7
            || color.starts_with("rgb(")
            || color.starts_with("rgba(")
            || color.starts_with("hsl(")
            || color.starts_with("hsla(")
            || ["red", "blue", "green", "black", "white", "transparent"].contains(&color)
    }
}

/// Style compiler for CSS-in-Rust
#[derive(Debug)]
pub struct StyleCompiler {
    cache: HashMap<String, CompiledStyle>,
    optimization_level: OptimizationLevel,
}

#[derive(Debug, Clone, Copy)]
pub enum OptimizationLevel {
    None,
    Basic,
    Aggressive,
}

impl StyleCompiler {
    /// Create a new style compiler
    pub fn new() -> Self {
        Self {
            cache: HashMap::new(),
            optimization_level: OptimizationLevel::Basic,
        }
    }

    /// Compile a theme to CSS
    pub fn compile_theme(&mut self, theme: &Theme) -> Result<CompiledStyle, ThemeError> {
        let cache_key = format!("theme_{}", theme.id.0);

        if let Some(cached) = self.cache.get(&cache_key) {
            return Ok(cached.clone());
        }

        let compiled = self.compile_theme_internal(theme)?;
        self.cache.insert(cache_key, compiled.clone());

        Ok(compiled)
    }

    /// Internal theme compilation
    fn compile_theme_internal(&self, theme: &Theme) -> Result<CompiledStyle, ThemeError> {
        let mut css = String::new();
        let mut variables = HashMap::new();
        let mut media_queries = Vec::new();
        let mut animations = Vec::new();

        // Generate CSS variables
        self.generate_css_variables(&theme.variables, &mut variables);

        // Generate component styles
        self.generate_component_styles(&theme.components, &mut css);

        // Generate animations
        self.generate_animations(&theme.animations, &mut animations);

        // Generate responsive styles
        self.generate_responsive_styles(&theme.breakpoints, &mut media_queries);

        // Combine all CSS
        let mut full_css = String::new();

        // Add CSS variables
        full_css.push_str(":root {\n");
        for (name, value) in &variables {
            full_css.push_str(&format!("  --{}: {};\n", name, value));
        }
        full_css.push_str("}\n\n");

        // Add component styles
        full_css.push_str(&css);
        full_css.push('\n');

        // Add animations
        for animation in &animations {
            full_css.push_str(animation);
            full_css.push('\n');
        }

        // Add media queries
        for media_query in &media_queries {
            full_css.push_str(media_query);
            full_css.push('\n');
        }

        Ok(CompiledStyle {
            css: full_css,
            variables,
            media_queries,
            animations,
        })
    }

    /// Generate CSS variables from theme variables
    fn generate_css_variables(
        &self,
        variables: &ThemeVariables,
        output: &mut HashMap<String, String>,
    ) {
        // Color variables
        output.insert(
            "color-primary".to_string(),
            variables.colors.primary.clone(),
        );
        output.insert(
            "color-secondary".to_string(),
            variables.colors.secondary.clone(),
        );
        output.insert("color-accent".to_string(), variables.colors.accent.clone());
        output.insert(
            "color-background".to_string(),
            variables.colors.background.clone(),
        );
        output.insert(
            "color-surface".to_string(),
            variables.colors.surface.clone(),
        );
        output.insert("color-text".to_string(), variables.colors.text.clone());
        output.insert(
            "color-text-secondary".to_string(),
            variables.colors.text_secondary.clone(),
        );
        output.insert("color-border".to_string(), variables.colors.border.clone());
        output.insert("color-error".to_string(), variables.colors.error.clone());
        output.insert(
            "color-warning".to_string(),
            variables.colors.warning.clone(),
        );
        output.insert(
            "color-success".to_string(),
            variables.colors.success.clone(),
        );
        output.insert("color-info".to_string(), variables.colors.info.clone());

        // Typography variables
        output.insert(
            "font-family".to_string(),
            variables.typography.font_family.clone(),
        );
        output.insert(
            "font-size-base".to_string(),
            format!("{}px", variables.typography.font_size_base),
        );
        output.insert(
            "font-size-small".to_string(),
            format!("{}px", variables.typography.font_size_small),
        );
        output.insert(
            "font-size-large".to_string(),
            format!("{}px", variables.typography.font_size_large),
        );
        output.insert(
            "font-weight-normal".to_string(),
            variables.typography.font_weight_normal.to_string(),
        );
        output.insert(
            "font-weight-bold".to_string(),
            variables.typography.font_weight_bold.to_string(),
        );
        output.insert(
            "line-height".to_string(),
            variables.typography.line_height.to_string(),
        );
        output.insert(
            "letter-spacing".to_string(),
            format!("{}px", variables.typography.letter_spacing),
        );

        // Spacing variables
        output.insert(
            "spacing-xs".to_string(),
            format!("{}px", variables.spacing.xs),
        );
        output.insert(
            "spacing-sm".to_string(),
            format!("{}px", variables.spacing.sm),
        );
        output.insert(
            "spacing-md".to_string(),
            format!("{}px", variables.spacing.md),
        );
        output.insert(
            "spacing-lg".to_string(),
            format!("{}px", variables.spacing.lg),
        );
        output.insert(
            "spacing-xl".to_string(),
            format!("{}px", variables.spacing.xl),
        );
        output.insert(
            "spacing-xxl".to_string(),
            format!("{}px", variables.spacing.xxl),
        );

        // Shadow variables
        output.insert("shadow-small".to_string(), variables.shadows.small.clone());
        output.insert(
            "shadow-medium".to_string(),
            variables.shadows.medium.clone(),
        );
        output.insert("shadow-large".to_string(), variables.shadows.large.clone());
        output.insert("shadow-xl".to_string(), variables.shadows.xl.clone());

        // Border variables
        output.insert(
            "border-width".to_string(),
            format!("{}px", variables.borders.width),
        );
        output.insert(
            "border-radius".to_string(),
            format!("{}px", variables.borders.radius),
        );
        output.insert("border-style".to_string(), variables.borders.style.clone());
    }

    /// Generate component styles
    fn generate_component_styles(
        &self,
        components: &HashMap<ComponentType, ComponentStyle>,
        output: &mut String,
    ) {
        for (component_type, style) in components {
            let selector = self.get_component_selector(component_type);
            output.push_str(&format!(".{} {{\n", selector));

            for (property, value) in &style.styles {
                if let Some(css_value) = self.theme_value_to_css(value) {
                    output.push_str(&format!("  {}: {};\n", property, css_value));
                }
            }

            output.push_str("}\n\n");

            // Generate variants
            for (variant_name, variant_styles) in &style.variants {
                output.push_str(&format!(".{}-{} {{\n", selector, variant_name));
                for (property, value) in variant_styles {
                    if let Some(css_value) = self.theme_value_to_css(value) {
                        output.push_str(&format!("  {}: {};\n", property, css_value));
                    }
                }
                output.push_str("}\n\n");
            }

            // Generate states
            for (state_name, state_styles) in &style.states {
                output.push_str(&format!(".{}:{} {{\n", selector, state_name));
                for (property, value) in state_styles {
                    if let Some(css_value) = self.theme_value_to_css(value) {
                        output.push_str(&format!("  {}: {};\n", property, css_value));
                    }
                }
                output.push_str("}\n\n");
            }
        }
    }

    /// Generate animations
    fn generate_animations(&self, animations: &AnimationSet, output: &mut Vec<String>) {
        for animation in &animations.animations {
            let keyframes = format!(
                "@keyframes {} {{\n  from {{ opacity: 0; }}\n  to {{ opacity: 1; }}\n}}",
                animation.name
            );
            output.push(keyframes);
        }

        for (property, transition) in &animations.transitions {
            let transition_css = format!(
                ".transition-{} {{\n  transition: {};\n}}",
                property, transition
            );
            output.push(transition_css);
        }
    }

    /// Generate responsive styles
    fn generate_responsive_styles(&self, breakpoints: &BreakpointSet, output: &mut Vec<String>) {
        for breakpoint in &breakpoints.breakpoints {
            let mut media_query = String::new();

            if let Some(min_width) = breakpoint.min_width {
                media_query.push_str(&format!("(min-width: {}px)", min_width));
            }

            if let Some(max_width) = breakpoint.max_width {
                if !media_query.is_empty() {
                    media_query.push_str(" and ");
                }
                media_query.push_str(&format!("(max-width: {}px)", max_width));
            }

            let mut styles = String::new();
            for (property, value) in &breakpoint.styles {
                if let Some(css_value) = self.theme_value_to_css(value) {
                    styles.push_str(&format!("  {}: {};\n", property, css_value));
                }
            }

            if !styles.is_empty() {
                output.push(format!("@media {} {{\n{}}}\n", media_query, styles));
            }
        }
    }

    /// Get component selector
    fn get_component_selector(&self, component_type: &ComponentType) -> String {
        match component_type {
            ComponentType::Chart => "helios-chart",
            ComponentType::Axis => "helios-axis",
            ComponentType::Legend => "helios-legend",
            ComponentType::Tooltip => "helios-tooltip",
            ComponentType::Grid => "helios-grid",
            ComponentType::DataPoint => "helios-data-point",
            ComponentType::Line => "helios-line",
            ComponentType::Bar => "helios-bar",
            ComponentType::Area => "helios-area",
            ComponentType::Scatter => "helios-scatter",
            ComponentType::Pie => "helios-pie",
            ComponentType::Custom(name) => &format!("helios-{}", name),
        }
        .to_string()
    }

    /// Convert theme value to CSS value
    fn theme_value_to_css(&self, value: &ThemeValue) -> Option<String> {
        match value {
            ThemeValue::Color(color) => Some(color.clone()),
            ThemeValue::Number(num) => Some(format!("{}px", num)),
            ThemeValue::String(s) => Some(s.clone()),
            ThemeValue::Boolean(b) => Some(b.to_string()),
            ThemeValue::Array(arr) => {
                let values: Vec<String> = arr
                    .iter()
                    .filter_map(|v| self.theme_value_to_css(v))
                    .collect();
                Some(values.join(" "))
            }
            ThemeValue::Object(_) => None, // Objects not supported in CSS
        }
    }
}

/// Main theme engine
#[derive(Debug)]
pub struct ThemeEngine {
    registry: ThemeRegistry,
    compiler: StyleCompiler,
    cache: HashMap<String, StyleCacheEntry>,
    cache_size_limit: usize,
}

impl ThemeEngine {
    /// Create a new theme engine
    pub fn new() -> Self {
        Self {
            registry: ThemeRegistry::new(),
            compiler: StyleCompiler::new(),
            cache: HashMap::new(),
            cache_size_limit: 100 * 1024 * 1024, // 100MB
        }
    }

    /// Register a theme
    pub fn register_theme(&mut self, theme: Theme) -> Result<(), ThemeError> {
        self.registry.register_theme(theme)
    }

    /// Set the active theme
    pub fn set_active_theme(&mut self, id: &ThemeId) -> Result<(), ThemeError> {
        self.registry.set_active_theme(id)
    }

    /// Get the active theme
    pub fn get_active_theme(&self) -> Result<&Theme, ThemeError> {
        self.registry.get_active_theme()
    }

    /// Compile the active theme
    pub fn compile_active_theme(&mut self) -> Result<CompiledStyle, ThemeError> {
        let theme = self.registry.get_active_theme()?;
        self.compiler.compile_theme(theme)
    }

    /// Get compiled style from cache
    pub fn get_cached_style(&self, theme_id: &ThemeId) -> Option<&CompiledStyle> {
        self.cache.get(&theme_id.0).map(|entry| &entry.style)
    }

    /// Clear the style cache
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.compiler.cache.clear();
    }

    /// Get cache statistics
    pub fn get_cache_stats(&self) -> CacheStats {
        let total_size: usize = self.cache.values().map(|entry| entry.size).sum();
        let entry_count = self.cache.len();

        CacheStats {
            entry_count,
            total_size,
            size_limit: self.cache_size_limit,
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub entry_count: usize,
    pub total_size: usize,
    pub size_limit: usize,
}

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

/// Create a default theme
pub fn create_default_theme() -> Theme {
    Theme {
        id: ThemeId("default".to_string()),
        name: "Default Theme".to_string(),
        description: Some("Default Helios theme with clean, modern styling".to_string()),
        version: "1.0.0".to_string(),
        variables: ThemeVariables {
            colors: ColorPalette {
                primary: "#3b82f6".to_string(),
                secondary: "#64748b".to_string(),
                accent: "#f59e0b".to_string(),
                background: "#ffffff".to_string(),
                surface: "#f8fafc".to_string(),
                text: "#1e293b".to_string(),
                text_secondary: "#64748b".to_string(),
                border: "#e2e8f0".to_string(),
                error: "#ef4444".to_string(),
                warning: "#f59e0b".to_string(),
                success: "#10b981".to_string(),
                info: "#3b82f6".to_string(),
            },
            typography: TypographySet {
                font_family: "Inter, system-ui, sans-serif".to_string(),
                font_size_base: 14.0,
                font_size_small: 12.0,
                font_size_large: 16.0,
                font_weight_normal: 400,
                font_weight_bold: 600,
                line_height: 1.5,
                letter_spacing: 0.0,
            },
            spacing: SpacingSet {
                xs: 4.0,
                sm: 8.0,
                md: 16.0,
                lg: 24.0,
                xl: 32.0,
                xxl: 48.0,
            },
            shadows: ShadowSet {
                small: "0 1px 2px 0 rgb(0 0 0 / 0.05)".to_string(),
                medium: "0 4px 6px -1px rgb(0 0 0 / 0.1)".to_string(),
                large: "0 10px 15px -3px rgb(0 0 0 / 0.1)".to_string(),
                xl: "0 20px 25px -5px rgb(0 0 0 / 0.1)".to_string(),
            },
            borders: BorderSet {
                width: 1.0,
                radius: 6.0,
                style: "solid".to_string(),
            },
        },
        components: HashMap::new(),
        animations: AnimationSet {
            animations: vec![Animation {
                name: "fadeIn".to_string(),
                duration: 0.3,
                easing: "ease-in-out".to_string(),
                delay: 0.0,
                iteration_count: "1".to_string(),
                direction: "normal".to_string(),
                fill_mode: "forwards".to_string(),
            }],
            transitions: HashMap::new(),
        },
        breakpoints: BreakpointSet {
            breakpoints: vec![
                Breakpoint {
                    name: "mobile".to_string(),
                    min_width: None,
                    max_width: Some(768.0),
                    styles: HashMap::new(),
                },
                Breakpoint {
                    name: "tablet".to_string(),
                    min_width: Some(768.0),
                    max_width: Some(1024.0),
                    styles: HashMap::new(),
                },
                Breakpoint {
                    name: "desktop".to_string(),
                    min_width: Some(1024.0),
                    max_width: None,
                    styles: HashMap::new(),
                },
            ],
            default: HashMap::new(),
        },
        metadata: HashMap::new(),
    }
}