waterui-internal 0.3.0

Internal implementation crate for WaterUI
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
//! # Theme System
//!
//! The theme system provides a **type-safe bundle of colors and fonts** that can be
//! installed into an [`Environment`] to style all `WaterUI` components consistently.
//!
//! ## Design Principles
//!
//! - **System neutral**: `WaterUI` doesn't impose default colors. Native backends inject
//!   system colors, and the theme system just provides the wiring.
//! - **Reactive by design**: All theme values can be reactive (`Binding`, `Computed`)
//!   or static. When color scheme changes, all dependent colors update automatically.
//! - **Optional overrides**: Theme fields are optional. Only specified fields are
//!   installed; others retain their existing values or use native defaults.
//! - **Composable**: Theme is composed of smaller structs (`ColorSettings`, `FontSettings`)
//!   for easier maintenance and partial customization.
//!
//! ## For Users
//!
//! ### Quick Start
//!
//! ```rust
//! use waterui::color::Srgb;
//! use waterui::{Environment, theme::{Theme, ColorScheme, ColorSettings}};
//! use waterui_core::plugin::Plugin;
//! use nami::binding;
//!
//! let mut env = Environment::new();
//!
//! // Lock to dark mode (static)
//! Theme::new()
//!     .color_scheme(ColorScheme::Dark)
//!     .install(&mut env);
//!
//! // Or use a reactive binding that follows system preference
//! let system_scheme = binding::<ColorScheme>(ColorScheme::Light);
//! Theme::new()
//!     .color_scheme(system_scheme.clone())
//!     .install(&mut env);
//!
//! // Customize specific colors
//! Theme::new()
//!     .colors(ColorSettings::new().accent(Srgb::from_hex("#0066CC")))
//!     .install(&mut env);
//! ```
//!
//! ### Using Theme Tokens in Views
//!
//! Theme tokens are unit structs that implement `Resolvable`. Use them directly
//! with view modifiers:
//!
//! ```rust
//! use waterui::prelude::*;
//! use waterui::theme::color::{Background, Foreground};
//!
//! let themed = text!("Hello, World!")
//!     .foreground(Foreground)  // Uses theme's foreground color
//!     .background(Background); // Uses theme's background color
//! ```
//!
//! ### Available Tokens
//!
//! **Color Scheme** (`theme::ColorScheme`):
//! - `Light` - Light appearance
//! - `Dark` - Dark appearance
//!
//! **Colors** (`theme::color::*`):
//! - `Background` - Primary background
//! - `Surface` - Elevated surfaces (cards, sheets)
//! - `SurfaceVariant` - Alternate surface color
//! - `Border` - Borders and dividers
//! - `Foreground` - Primary text and icons
//! - `MutedForeground` - Secondary/dimmed text
//! - `Accent` - Interactive elements, links
//! - `AccentContainer` - Container backgrounds associated with the accent color
//! - `AccentForeground` - Text on accent backgrounds
//! - `Tertiary` - Contrasting accent for complementary emphasis
//! - `TertiaryContainer` - Container backgrounds associated with the tertiary color
//! - `SelectionContainer` - Fill painted behind a selected item
//! - `SelectionForeground` - Content drawn on the selection container
//!
//! **Fonts**: Use standard font tokens from `waterui::text::font`:
//! - `Body`, `Title`, `Headline`, `Subheadline`, `Caption`, `Footnote`
//!
//! ## For Maintainers
//!
//! ### How It Works
//!
//! 1. [`Theme`] composes [`ColorSettings`] and [`FontSettings`]
//! 2. Each settings struct holds optional `Computed<T>` signals
//! 3. Builder methods accept `impl IntoSignal<T>` - works with both
//!    static values and reactive bindings
//! 4. `Theme::install()` delegates to each settings struct's install method
//! 5. Only non-None fields are installed into the environment
//!
//! ### Native Backend Integration
//!
//! Native backends should:
//! 1. Create a `Binding<ColorScheme>` that tracks system appearance
//! 2. Create `Computed<ResolvedColor>` signals that react to color scheme changes
//! 3. Install via `Theme::new().color_scheme(binding).colors(ColorSettings::new()...)`

use core::{any::TypeId, marker::PhantomData};

use nami::{Computed, SignalExt, impl_constant, signal::IntoSignal};
use waterui_core::{Environment, env::Store, plugin::Plugin};

use crate::{
    color::ResolvedColor,
    text::font::{Body, Caption, Footnote, Headline, ResolvedFont, Subheadline, Title},
};

// ============================================================================
// ColorScheme - Light/Dark appearance preference
// ============================================================================

/// The color scheme preference for the UI.
///
/// This is used to switch between light and dark appearances. Native backends
/// typically bind this to the system appearance setting.
///
/// # Example
///
/// ```rust
/// use waterui::theme::{Theme, ColorScheme};
/// use nami::binding;
///
/// // Static: always dark
/// Theme::new().color_scheme(ColorScheme::Dark);
///
/// // Reactive: follows system
/// let system_scheme = binding(ColorScheme::Light);
/// Theme::new().color_scheme(system_scheme);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ColorScheme {
    /// Light appearance (light backgrounds, dark text).
    #[default]
    Light,
    /// Dark appearance (dark backgrounds, light text).
    Dark,
}

impl_constant!(ColorScheme);

// ============================================================================
// ColorSettings - All color overrides
// ============================================================================

/// Color settings for a theme.
///
/// All fields are optional. Only specified colors will be installed.
/// Use the builder pattern to set individual colors.
///
/// # Example
///
/// ```rust
/// use waterui::color::Srgb;
/// use waterui::theme::ColorSettings;
///
/// let colors = ColorSettings::new()
///     .accent(Srgb::from_hex("#0066CC"))
///     .foreground(Srgb::from_hex("#111111"));
/// ```
#[derive(Default, Debug)]
pub struct ColorSettings {
    background: Option<Computed<ResolvedColor>>,
    surface: Option<Computed<ResolvedColor>>,
    surface_variant: Option<Computed<ResolvedColor>>,
    border: Option<Computed<ResolvedColor>>,
    foreground: Option<Computed<ResolvedColor>>,
    muted_foreground: Option<Computed<ResolvedColor>>,
    accent: Option<Computed<ResolvedColor>>,
    accent_container: Option<Computed<ResolvedColor>>,
    accent_foreground: Option<Computed<ResolvedColor>>,
    tertiary: Option<Computed<ResolvedColor>>,
    tertiary_container: Option<Computed<ResolvedColor>>,
    selection_container: Option<Computed<ResolvedColor>>,
    selection_foreground: Option<Computed<ResolvedColor>>,
}

impl ColorSettings {
    /// Creates empty color settings with no overrides.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the background color.
    #[must_use]
    pub fn background(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.background = Some(color.into_signal().computed());
        self
    }

    /// Sets the surface color (cards, sheets).
    #[must_use]
    pub fn surface(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.surface = Some(color.into_signal().computed());
        self
    }

    /// Sets the surface variant color.
    #[must_use]
    pub fn surface_variant(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.surface_variant = Some(color.into_signal().computed());
        self
    }

    /// Sets the border color.
    #[must_use]
    pub fn border(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.border = Some(color.into_signal().computed());
        self
    }

    /// Sets the foreground color (text, icons).
    #[must_use]
    pub fn foreground(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.foreground = Some(color.into_signal().computed());
        self
    }

    /// Sets the muted foreground color (secondary text).
    #[must_use]
    pub fn muted_foreground(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.muted_foreground = Some(color.into_signal().computed());
        self
    }

    /// Sets the accent color (interactive elements).
    #[must_use]
    pub fn accent(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.accent = Some(color.into_signal().computed());
        self
    }

    /// Sets the accent container color.
    #[must_use]
    pub fn accent_container(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.accent_container = Some(color.into_signal().computed());
        self
    }

    /// Sets the accent foreground color (text on accent).
    #[must_use]
    pub fn accent_foreground(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.accent_foreground = Some(color.into_signal().computed());
        self
    }

    /// Sets the tertiary accent color.
    #[must_use]
    pub fn tertiary(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.tertiary = Some(color.into_signal().computed());
        self
    }

    /// Sets the tertiary container color.
    #[must_use]
    pub fn tertiary_container(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.tertiary_container = Some(color.into_signal().computed());
        self
    }

    /// Sets the fill painted behind a selected item.
    #[must_use]
    pub fn selection_container(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.selection_container = Some(color.into_signal().computed());
        self
    }

    /// Sets the foreground drawn on the selection container.
    #[must_use]
    pub fn selection_foreground(mut self, color: impl IntoSignal<ResolvedColor>) -> Self {
        self.selection_foreground = Some(color.into_signal().computed());
        self
    }

    /// Installs the color settings into the environment.
    /// Only non-None fields are installed.
    fn install(self, env: &mut Environment) {
        if let Some(signal) = self.background {
            install_color_signal::<color::Background>(env, signal);
        }
        if let Some(signal) = self.surface {
            install_color_signal::<color::Surface>(env, signal);
        }
        if let Some(signal) = self.surface_variant {
            install_color_signal::<color::SurfaceVariant>(env, signal);
        }
        if let Some(signal) = self.border {
            install_color_signal::<color::Border>(env, signal);
        }
        if let Some(signal) = self.foreground {
            install_color_signal::<color::Foreground>(env, signal);
        }
        if let Some(signal) = self.muted_foreground {
            install_color_signal::<color::MutedForeground>(env, signal);
        }
        if let Some(signal) = self.accent {
            install_color_signal::<color::Accent>(env, signal);
        }
        if let Some(signal) = self.accent_container {
            install_color_signal::<color::AccentContainer>(env, signal);
        }
        if let Some(signal) = self.accent_foreground {
            install_color_signal::<color::AccentForeground>(env, signal);
        }
        if let Some(signal) = self.tertiary {
            install_color_signal::<color::Tertiary>(env, signal);
        }
        if let Some(signal) = self.tertiary_container {
            install_color_signal::<color::TertiaryContainer>(env, signal);
        }
        if let Some(signal) = self.selection_container {
            install_color_signal::<color::SelectionContainer>(env, signal);
        }
        if let Some(signal) = self.selection_foreground {
            install_color_signal::<color::SelectionForeground>(env, signal);
        }
    }
}

// ============================================================================
// FontSettings - All font overrides
// ============================================================================

/// Font settings for a theme.
///
/// All fields are optional. Only specified fonts will be installed.
/// Use the builder pattern to set individual fonts.
///
/// # Example
///
/// ```rust
/// use waterui::text::font::{FontWeight, ResolvedFont};
/// use waterui::theme::FontSettings;
///
/// let fonts = FontSettings::new()
///     .body(ResolvedFont::new(16.0, FontWeight::Normal))
///     .title(ResolvedFont::new(28.0, FontWeight::Bold));
/// ```
#[derive(Default, Debug)]
pub struct FontSettings {
    body: Option<Computed<ResolvedFont>>,
    title: Option<Computed<ResolvedFont>>,
    headline: Option<Computed<ResolvedFont>>,
    subheadline: Option<Computed<ResolvedFont>>,
    caption: Option<Computed<ResolvedFont>>,
    footnote: Option<Computed<ResolvedFont>>,
}

impl FontSettings {
    /// Creates empty font settings with no overrides.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the body font.
    #[must_use]
    pub fn body(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.body = Some(font.into_signal().computed());
        self
    }

    /// Sets the title font.
    #[must_use]
    pub fn title(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.title = Some(font.into_signal().computed());
        self
    }

    /// Sets the headline font.
    #[must_use]
    pub fn headline(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.headline = Some(font.into_signal().computed());
        self
    }

    /// Sets the subheadline font.
    #[must_use]
    pub fn subheadline(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.subheadline = Some(font.into_signal().computed());
        self
    }

    /// Sets the caption font.
    #[must_use]
    pub fn caption(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.caption = Some(font.into_signal().computed());
        self
    }

    /// Sets the footnote font.
    #[must_use]
    pub fn footnote(mut self, font: impl IntoSignal<ResolvedFont>) -> Self {
        self.footnote = Some(font.into_signal().computed());
        self
    }

    /// Installs the font settings into the environment.
    /// Only non-None fields are installed.
    fn install(self, env: &mut Environment) {
        if let Some(signal) = self.body {
            install_font_signal::<Body>(env, signal);
        }
        if let Some(signal) = self.title {
            install_font_signal::<Title>(env, signal);
        }
        if let Some(signal) = self.headline {
            install_font_signal::<Headline>(env, signal);
        }
        if let Some(signal) = self.subheadline {
            install_font_signal::<Subheadline>(env, signal);
        }
        if let Some(signal) = self.caption {
            install_font_signal::<Caption>(env, signal);
        }
        if let Some(signal) = self.footnote {
            install_font_signal::<Footnote>(env, signal);
        }
    }
}

// ============================================================================
// Theme - Composes all settings
// ============================================================================

/// A theme configuration composed of color scheme, colors, and fonts.
///
/// Use the builder pattern to configure what to override. Only specified
/// values are installed; others retain existing values.
///
/// # Example
///
/// ```rust
/// use nami::binding;
/// use waterui::Environment;
/// use waterui::color::Srgb;
/// use waterui::text::font::{FontWeight, ResolvedFont};
/// use waterui::theme::{ColorScheme, ColorSettings, FontSettings, Theme};
/// use waterui_core::plugin::Plugin;
///
/// let mut env = Environment::new();
///
/// // Create a theme with reactive color scheme
/// let scheme = binding::<ColorScheme>(ColorScheme::Light);
/// Theme::new()
///     .color_scheme(scheme)
///     .colors(ColorSettings::new().accent(Srgb::from_hex("#0066CC")))
///     .fonts(FontSettings::new().body(ResolvedFont::new(16.0, FontWeight::Normal)))
///     .install(&mut env);
/// ```
#[derive(Default, Debug)]
pub struct Theme {
    color_scheme: Option<Computed<ColorScheme>>,
    colors: Option<ColorSettings>,
    fonts: Option<FontSettings>,
}

impl Theme {
    /// Creates a new empty theme with no overrides.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the color scheme (light/dark).
    ///
    /// Accepts any value that implements `IntoSignal<ColorScheme>`:
    /// - Static: `ColorScheme::Dark`
    /// - Reactive: `binding(ColorScheme::Light)`
    #[must_use]
    pub fn color_scheme(mut self, scheme: impl IntoSignal<ColorScheme>) -> Self {
        self.color_scheme = Some(scheme.into_signal().computed());
        self
    }

    /// Sets the color settings.
    #[must_use]
    pub fn colors(mut self, colors: ColorSettings) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Sets the font settings.
    #[must_use]
    pub fn fonts(mut self, fonts: FontSettings) -> Self {
        self.fonts = Some(fonts);
        self
    }
}

impl Plugin for Theme {
    /// Installs this theme into the environment.
    ///
    /// Only non-None fields are installed. Existing values for unspecified
    /// fields remain unchanged.
    fn install(self, env: &mut Environment) {
        // Install color scheme if specified
        if let Some(scheme) = self.color_scheme {
            env.insert(ColorSchemeSignal(scheme));
        }

        // Install color settings if specified
        if let Some(colors) = self.colors {
            colors.install(env);
        }

        // Install font settings if specified
        if let Some(fonts) = self.fonts {
            fonts.install(env);
        }
    }
}

// ============================================================================
// Color Tokens - Resolvable types for each color slot
// ============================================================================

/// Color token definitions.
///
/// These unit structs implement `Resolvable<Resolved = ResolvedColor>`, so they
/// can be used directly with view modifiers like `.foreground(Foreground)`.
pub mod color {
    use super::{Environment, ResolvedColor};
    use nami::{Signal, impl_constant};
    use waterui_core::resolve::Resolvable;

    macro_rules! define_color_token {
        ($name:ident, $doc:literal) => {
            #[doc = $doc]
            #[derive(Debug, Clone, Copy, Default)]
            pub struct $name;

            impl Resolvable for $name {
                type Resolved = ResolvedColor;

                fn resolve(&self, env: &Environment) -> impl Signal<Output = Self::Resolved> {
                    super::resolve_color_slot::<Self>(env)
                }
            }

            impl_constant!($name);

            impl crate::View for $name {
                fn body(self, _env: &Environment) -> impl crate::View {
                    crate::color::Color::new(self)
                }
            }
        };
    }

    define_color_token!(Background, "Primary background color.");
    define_color_token!(Surface, "Elevated surface color (cards, sheets).");
    define_color_token!(SurfaceVariant, "Alternate surface color.");
    define_color_token!(Border, "Border and divider color.");
    define_color_token!(Foreground, "Primary text and icon color.");
    define_color_token!(MutedForeground, "Secondary/dimmed text color.");
    define_color_token!(Accent, "Accent color for interactive elements.");
    define_color_token!(
        AccentContainer,
        "Container color associated with the accent."
    );
    define_color_token!(AccentForeground, "Foreground on accent backgrounds.");
    define_color_token!(
        Tertiary,
        "Contrasting accent color for complementary emphasis."
    );
    define_color_token!(
        TertiaryContainer,
        "Container color associated with the tertiary accent."
    );
    define_color_token!(
        SelectionContainer,
        "The fill a platform paints behind a selected item."
    );
    define_color_token!(
        SelectionForeground,
        "Foreground drawn on the selection container."
    );
}

// ============================================================================
// Internal: Storage and Resolution
// ============================================================================

/// Storage for the color scheme signal.
#[derive(Clone)]
struct ColorSchemeSignal(Computed<ColorScheme>);

/// Internal storage for a color signal in the environment.
#[derive(Clone)]
struct ColorSlotValue<T> {
    signal: Computed<ResolvedColor>,
    _marker: PhantomData<T>,
}

impl<T> ColorSlotValue<T> {
    const fn new(signal: Computed<ResolvedColor>) -> Self {
        Self {
            signal,
            _marker: PhantomData,
        }
    }
}

/// Resolves a color slot by looking up the signal installed by the backend or theme.
fn resolve_color_slot<T: 'static>(env: &Environment) -> Computed<ResolvedColor> {
    env.get::<ColorSlotValue<T>>()
        .unwrap_or_else(|| {
            panic!(
                "WaterUI color token `{}` is not installed in the environment",
                core::any::type_name::<T>()
            )
        })
        .signal
        .clone()
}

// ============================================================================
// Public API for Native Backends (FFI)
// ============================================================================

/// Returns the current color scheme signal from the environment.
///
/// # Panics
///
/// Panics when the active backend or theme has not installed a color scheme.
#[must_use]
pub fn current_color_scheme(env: &Environment) -> Computed<ColorScheme> {
    installed_color_scheme(env).expect("WaterUI color scheme is not installed in the environment")
}

/// Returns the color-scheme signal installed by the active backend or theme.
#[must_use]
pub fn installed_color_scheme(env: &Environment) -> Option<Computed<ColorScheme>> {
    env.get::<ColorSchemeSignal>()
        .map(|signal| signal.0.clone())
}

/// Installs an explicit color signal for a specific slot.
///
/// This is primarily used by native backends (via FFI) to inject platform-specific
/// color signals that can update reactively (e.g., when dark mode toggles).
///
/// # Example
///
/// ```rust
/// use nami::Computed;
/// use waterui::Environment;
/// use waterui::color::ResolvedColor;
/// use waterui::theme::{color, install_color_signal};
///
/// let mut env = Environment::new();
///
/// // A backend supplies a reactive colour for the slot.
/// let dark_mode_color: Computed<ResolvedColor> =
///     Computed::constant(ResolvedColor::default());
///
/// // Install it for the Foreground slot
/// install_color_signal::<color::Foreground>(&mut env, dark_mode_color);
/// ```
pub fn install_color_signal<T: 'static>(env: &mut Environment, signal: Computed<ResolvedColor>) {
    env.insert(ColorSlotValue::<T>::new(signal.clone()));

    macro_rules! mirror_graphics_color {
        ($theme_slot:ty, $graphics_slot:ty) => {
            if TypeId::of::<T>() == TypeId::of::<$theme_slot>() {
                env.insert(Store::<$graphics_slot, Computed<ResolvedColor>>::new(
                    signal,
                ));
                return;
            }
        };
    }

    mirror_graphics_color!(color::Background, waterui_graphics::color::BackgroundColor);
    mirror_graphics_color!(color::Surface, waterui_graphics::color::SurfaceColor);
    mirror_graphics_color!(
        color::SurfaceVariant,
        waterui_graphics::color::SurfaceVariantColor
    );
    mirror_graphics_color!(color::Border, waterui_graphics::color::BorderColor);
    mirror_graphics_color!(color::Foreground, waterui_graphics::color::ForegroundColor);
    mirror_graphics_color!(
        color::MutedForeground,
        waterui_graphics::color::MutedForegroundColor
    );
    mirror_graphics_color!(color::Accent, waterui_graphics::color::AccentColor);
    mirror_graphics_color!(
        color::AccentContainer,
        waterui_graphics::color::AccentContainerColor
    );
    mirror_graphics_color!(
        color::AccentForeground,
        waterui_graphics::color::AccentForegroundColor
    );
    mirror_graphics_color!(color::Tertiary, waterui_graphics::color::TertiaryColor);
    mirror_graphics_color!(
        color::TertiaryContainer,
        waterui_graphics::color::TertiaryContainerColor
    );
    mirror_graphics_color!(
        color::SelectionContainer,
        waterui_graphics::color::SelectionContainerColor
    );
    mirror_graphics_color!(
        color::SelectionForeground,
        waterui_graphics::color::SelectionForegroundColor
    );
}

/// Returns an installed color signal for the requested slot when one exists.
#[must_use]
pub fn installed_color_signal<T: 'static>(env: &Environment) -> Option<Computed<ResolvedColor>> {
    env.get::<ColorSlotValue<T>>()
        .map(|value| value.signal.clone())
}

/// Installs an explicit font signal for a specific slot.
///
/// This is primarily used by native backends (via FFI) to inject platform-specific
/// font signals. Uses `Store<T, Computed<ResolvedFont>>` to be compatible with
/// the existing font resolution system.
pub fn install_font_signal<T: 'static>(env: &mut Environment, signal: Computed<ResolvedFont>) {
    env.insert(Store::<T, Computed<ResolvedFont>>::new(signal));
}

/// Installs a color scheme signal.
///
/// This is used by native backends to inject a reactive color scheme that
/// tracks the system appearance setting.
pub fn install_color_scheme(env: &mut Environment, signal: Computed<ColorScheme>) {
    env.insert(ColorSchemeSignal(signal));
}

// ============================================================================
// ForegroundOverride - Plugin for .foreground() view modifier
// ============================================================================

use waterui_graphics::color::Color;

/// A plugin that overrides the foreground color for a view subtree.
///
/// This is used by the `.foreground()` view modifier to inject a custom
/// foreground color into the environment.
#[derive(Debug)]
pub struct ForegroundOverride {
    color: Color,
}

impl ForegroundOverride {
    /// Creates a new foreground override with the specified color.
    pub fn new(color: impl Into<Color>) -> Self {
        Self {
            color: color.into(),
        }
    }
}

impl Plugin for ForegroundOverride {
    fn install(self, env: &mut Environment) {
        let resolved = self.color.resolve(env);
        install_color_signal::<color::Foreground>(env, resolved);
    }
}

#[cfg(test)]
mod tests {
    use alloc::rc::Rc;
    use core::cell::Cell;
    use nami::{Binding, Signal, SignalExt};
    use waterui_graphics::color::{AccentColor, Color};

    use super::*;

    #[test]
    fn graphics_accent_color_tracks_installed_theme_signal() {
        let accent = Binding::container(ResolvedColor::default());
        let mut env = Environment::new();
        install_color_signal::<color::Accent>(&mut env, accent.computed());
        let resolved = Color::new(AccentColor).resolve(&env);
        let observed_red = Rc::new(Cell::new(0.0));
        let captured_red = Rc::clone(&observed_red);
        let _guard = resolved.watch(move |context| {
            captured_red.set(context.into_value().red);
        });

        accent.set(ResolvedColor {
            red: 1.0,
            ..ResolvedColor::default()
        });

        assert!((observed_red.get() - 1.0).abs() < f32::EPSILON);
        assert!((resolved.get().red - 1.0).abs() < f32::EPSILON);
    }
}