cvkg-core 0.1.5

Cyberpunk Viking Knowledge Graph (CVKG) - High-fidelity agentic UI framework
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
//! # CVKG Agentic Development Guidelines (v1.2)
//!
//! All AI agents contributing to this crate MUST follow ALL seven rules:
//!
//! ── Karpathy Guidelines (1–4) ────────────────────────────────────────────
//! 1. THINK FIRST     — State assumptions. Surface ambiguity. Push back on complexity.
//! 2. STAY SIMPLE     — Minimum code. No speculative features. No unasked-for abstractions.
//! 3. BE SURGICAL     — Touch only what's required. Own your orphans. Don't improve neighbors.
//! 4. VERIFY GOALS    — Turn tasks into checkable criteria. Loop until they pass. Never commit broken.
//!
//! ── CVKG Extended Protocols (5–7) ────────────────────────────────────────
//! 5. TRIPLE-PASS     — Read the target, its surrounding context, and its full call graph
//                      at least THREE TIMES before making any edit or revision.
//! 6. COMMENT ALL     — Every major pub fn, unsafe block, and non-trivial algorithm in
//                      every .rs/.ts/.h/.wgsl file MUST have a descriptive doc comment.
//                      Comments describe WHY and WHAT CONTRACT, not HOW mechanically.
//! 7. MONITOR LOOPS   — Check every tool call / command for progress every 30 seconds.
//                      After 3 consecutive identical failures, stop, write BLOCKED.md,
//                      and move to unblocked work. Never silently accept a broken state.
//!
//! Sources:
//   Karpathy: https://github.com/multica-ai/andrej-karpathy-skills
//   CVKG Extended: Section 2 of the CVKG Design Specification

//! The View trait is the fundamental building block of CVKG. Every UI element — from a plain text label
//! to a complex navigation controller — is a View. The trait is intentionally minimal; complexity emerges
//! through modifier composition.
//!
//! # Conformance rules:
//! 1. `body()` must be pure and side-effect free
//! 2. Primitive views use `Never` as `Body` and register a `PaintCommand` directly with the scene graph
//! 3. `View` types must implement `Send` but not necessarily `Sync`, enabling safe multi-threaded layout passes

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::str::FromStr;

/// Design token value that can adapt to light/dark mode
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TokenValue {
    /// Single value (same for light and dark)
    Single {
        value: String,
    },
    /// Different values for light and dark mode
    Adaptive {
        light: String,
        dark: String,
    },
}

/// YggdrasilTokens is the authoritative container for all design tokens in the CVKG ecosystem.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YggdrasilTokens {
    pub color: HashMap<String, TokenValue>,
    pub font: HashMap<String, TokenValue>,
    pub spacing: HashMap<String, TokenValue>,
    pub radius: HashMap<String, TokenValue>,
    pub shadow: HashMap<String, TokenValue>,
    pub border: HashMap<String, TokenValue>,
    pub anim: HashMap<String, TokenValue>,
    pub bifrost: HashMap<String, TokenValue>,
    pub gungnir: HashMap<String, TokenValue>,
    pub mjolnir: HashMap<String, TokenValue>,
    pub accessibility: HashMap<String, TokenValue>,
}

impl YggdrasilTokens {
    pub fn new() -> Self {
        Self {
            color: HashMap::new(),
            font: HashMap::new(),
            spacing: HashMap::new(),
            radius: HashMap::new(),
            shadow: HashMap::new(),
            border: HashMap::new(),
            anim: HashMap::new(),
            bifrost: HashMap::new(),
            gungnir: HashMap::new(),
            mjolnir: HashMap::new(),
            accessibility: HashMap::new(),
        }
    }

    /// Get a color token value for the current mode
    pub fn get_color(&self, key: &str, is_dark: bool) -> Option<String> {
        self.color.get(key).and_then(|token| {
            match token {
                TokenValue::Single { value } => Some(value.clone()),
                TokenValue::Adaptive { light, dark } => {
                    if is_dark { Some(dark.clone()) } else { Some(light.clone()) }
                }
            }
        })
    }

    /// Get a token value of any type and parse it into the target type
    pub fn get<T: FromStr>(&self, category: &str, key: &str, is_dark: bool) -> Option<T> {
        let map = match category {
            "color" => &self.color,
            "font" => &self.font,
            "spacing" => &self.spacing,
            "radius" => &self.radius,
            "shadow" => &self.shadow,
            "border" => &self.border,
            "anim" => &self.anim,
            "bifrost" => &self.bifrost,
            "gungnir" => &self.gungnir,
            "mjolnir" => &self.mjolnir,
            "accessibility" => &self.accessibility,
            _ => return None,
        };

        map.get(key).and_then(|token| {
            match token {
                TokenValue::Single { value } => value.parse().ok(),
                TokenValue::Adaptive { light, dark } => {
                    let value = if is_dark { dark } else { light };
                    value.parse().ok()
                }
            }
        })
    }
}

pub trait View: Sized + Send {
    /// The concrete type produced after applying modifiers.
    /// For primitive views this is Self.
    type Body: View;

    fn body(self) -> Self::Body;

    /// Render this view into the provided renderer at the specified bounds.
    /// Primitive views override this to perform drawing operations.
    fn render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}

    /// Provided modifier entry point
    fn modifier<M: ViewModifier>(self, m: M) -> ModifiedView<Self, M> {
        ModifiedView::new(self, m)
    }

    /// Apply a Bifrost (Frosted Glass) effect to the view
    fn bifrost(self, blur: f32, saturation: f32, opacity: f32) -> ModifiedView<Self, BifrostModifier> {
        self.modifier(BifrostModifier { blur, saturation, opacity })
    }

    /// Apply a Gungnir (Neon Glow) effect to the view
    fn gungnir(self, color: impl Into<String>, radius: f32, intensity: f32) -> ModifiedView<Self, GungnirModifier> {
        self.modifier(GungnirModifier { color: color.into(), radius, intensity })
    }

    /// Apply a Mjolnir Slice (Geometric cut) to the view
    fn mjolnir_slice(self, angle: f32, offset: f32) -> ModifiedView<Self, MjolnirSliceModifier> {
        self.modifier(MjolnirSliceModifier { angle, offset })
    }

    /// Apply a Mjolnir Shatter (Fragmented transition) to the view
    fn mjolnir_shatter(self, pieces: u32, force: f32) -> ModifiedView<Self, MjolnirShatterModifier> {
        self.modifier(MjolnirShatterModifier { pieces, force })
    }

    /// Mark this view as a Bifrost Bridge (Shared Element) for cross-view persistence
    fn bifrost_bridge(self, id: impl Into<String>) -> ModifiedView<Self, BifrostBridgeModifier> {
        self.modifier(BifrostBridgeModifier { id: id.into() })
    }

    /// Add a background color to this view
    fn background(self, color: [f32; 4]) -> ModifiedView<Self, BackgroundModifier> {
        self.modifier(BackgroundModifier { color })
    }

    /// Add padding to this view
    fn padding(self, amount: f32) -> ModifiedView<Self, PaddingModifier> {
        self.modifier(PaddingModifier { amount })
    }

    /// Set the opacity (alpha) of this view in the range [0.0, 1.0].
    fn opacity(self, opacity: f32) -> ModifiedView<Self, OpacityModifier> {
        self.modifier(OpacityModifier { opacity: opacity.clamp(0.0, 1.0) })
    }

    /// Override the foreground (text / icon) color of this view.
    fn foreground_color(self, color: [f32; 4]) -> ModifiedView<Self, ForegroundColorModifier> {
        self.modifier(ForegroundColorModifier { color })
    }

    /// Constrain this view to an explicit width and/or height.
    fn frame(self, width: Option<f32>, height: Option<f32>) -> ModifiedView<Self, FrameModifier> {
        self.modifier(FrameModifier { width, height })
    }

    /// Clip all child drawing to this view's bounds.
    fn clip_to_bounds(self) -> ModifiedView<Self, ClipModifier> {
        self.modifier(ClipModifier)
    }

    /// Draw a colored border around this view.
    fn border(self, color: [f32; 4], width: f32) -> ModifiedView<Self, BorderModifier> {
        self.modifier(BorderModifier { color, width })
    }

    /// Trigger an action when the view appears
    fn on_appear<F: Fn() + Send + Sync + 'static>(self, action: F) -> ModifiedView<Self, LifecycleModifier> {
        self.modifier(LifecycleModifier {
            on_appear: Some(Arc::new(action)),
            on_disappear: None,
        })
    }

    /// Trigger an action when the view disappears
    fn on_disappear<F: Fn() + Send + Sync + 'static>(self, action: F) -> ModifiedView<Self, LifecycleModifier> {
        self.modifier(LifecycleModifier {
            on_appear: None,
            on_disappear: Some(Arc::new(action)),
        })
    }

    /// Type-erase this view into AnyView
    fn erase(self) -> AnyView where Self: 'static {
        AnyView::new(self)
    }
}

/// An object-safe version of the View trait for type erasure.
pub trait ErasedView: Send {
    fn render_erased(&self, renderer: &mut dyn Renderer, rect: Rect);
}

impl<V: View + 'static> ErasedView for V {
    fn render_erased(&self, renderer: &mut dyn Renderer, rect: Rect) {
        self.render(renderer, rect);
    }
}

/// A type-erased View wrapper.
pub struct AnyView {
    inner: Box<dyn ErasedView>,
}

impl AnyView {
    pub fn new<V: View + 'static>(view: V) -> Self {
        Self { inner: Box::new(view) }
    }
}

impl View for AnyView {
    type Body = Never;
    fn body(self) -> Self::Body { unreachable!() }
    
    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        self.inner.render_erased(renderer, rect);
    }
}

/// BifrostBridgeModifier enables shared-element transitions.
/// When two views share the same Bifrost Bridge ID, the Sleipnir solver will
/// interpolate their geometry and effects (blur, glow) during the transition.
#[derive(Debug, Clone, PartialEq)]
pub struct BifrostBridgeModifier {
    pub id: String,
}

impl ViewModifier for BifrostBridgeModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// MjolnirSliceModifier implements the "Geometric Slice" aesthetic.
/// It uses a signed distance field (SDF) to clip the view along a sharp angled line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MjolnirSliceModifier {
    pub angle: f32,
    pub offset: f32,
}

impl ViewModifier for MjolnirSliceModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// MjolnirShatterModifier implements the "Shattering" effect.
/// It breaks the view into discrete geometric fragments that can be animated.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MjolnirShatterModifier {
    pub pieces: u32,
    pub force: f32,
}

impl ViewModifier for MjolnirShatterModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// BifrostModifier implements the Cyberpunk "Frosted Glass" aesthetic.
/// It triggers backdrop blurring and light scattering in the render pipeline.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BifrostModifier {
    pub blur: f32,
    pub saturation: f32,
    pub opacity: f32,
}

impl ViewModifier for BifrostModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        // Frosted glass placeholder
        renderer.fill_rect(rect, [1.0, 1.0, 1.0, 0.1]);
    }
}

/// A modifier that adds a background color to a view.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BackgroundModifier {
    pub color: [f32; 4],
}

impl ViewModifier for BackgroundModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        renderer.fill_rect(rect, self.color);
    }
}

/// A modifier that adds padding to a view.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PaddingModifier {
    pub amount: f32,
}

impl ViewModifier for PaddingModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn transform_rect(&self, rect: Rect) -> Rect {
        Rect {
            x: rect.x + self.amount,
            y: rect.y + self.amount,
            width: (rect.width - 2.0 * self.amount).max(0.0),
            height: (rect.height - 2.0 * self.amount).max(0.0),
        }
    }
}

/// GungnirModifier implements the "Neon Glow" aesthetic.
/// It uses additive blending and multi-pass blurring to simulate glowing light.
#[derive(Debug, Clone, PartialEq)]
pub struct GungnirModifier {
    pub color: String,
    pub radius: f32,
    pub intensity: f32,
}

impl ViewModifier for GungnirModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        // Neon Glow placeholder
        renderer.stroke_rect(rect, [0.0, 1.0, 1.0, self.intensity], self.radius / 10.0);
    }
}

/// SleipnirModifier handles physics-based animations via the Sleipnir RK4 solver.
#[derive(Debug, Clone, PartialEq)]
pub struct SleipnirModifier<T> {
    pub target: T,
    pub stiffness: f32,
    pub damping: f32,
}

impl<T: Send + Sync + 'static + Clone> ViewModifier for SleipnirModifier<T> {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// LifecycleModifier handles on_appear and on_disappear hooks.
#[derive(Clone)]
pub struct LifecycleModifier {
    pub on_appear: Option<Arc<dyn Fn() + Send + Sync>>,
    pub on_disappear: Option<Arc<dyn Fn() + Send + Sync>>,
}

impl ViewModifier for LifecycleModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// OpacityModifier fades this view and all its descendants to the given alpha.
/// The renderer is expected to honour `push_opacity`/`pop_opacity` on the Renderer trait.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OpacityModifier {
    pub opacity: f32,
}

impl ViewModifier for OpacityModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        renderer.push_opacity(self.opacity);
    }
}

/// ForegroundColorModifier overrides the foreground (text / icon) color inherited
/// by all descendants until another ForegroundColorModifier is encountered.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ForegroundColorModifier {
    pub color: [f32; 4],
}

impl ViewModifier for ForegroundColorModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// ClipModifier restricts all child drawing to the view's layout rectangle.
/// The renderer must support `push_clip_rect`/`pop_clip_rect`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClipModifier;

impl ViewModifier for ClipModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        renderer.push_clip_rect(rect);
    }
}

/// BorderModifier draws a solid-color border around the view bounds.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BorderModifier {
    pub color: [f32; 4],
    pub width: f32,
}

impl ViewModifier for BorderModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        renderer.stroke_rect(rect, self.color, self.width);
    }
}

// Primitive (leaf) views implement Never as body
#[doc(hidden)]
pub enum Never {}

impl View for Never {
    type Body = Never;
    fn body(self) -> Never {
        unreachable!()
    }
}

/// A view that has been transformed by a modifier.
///
/// Section 4.3: "Each modifier implements ViewModifier and produces a ModifiedView<Inner, Self>."
pub struct ModifiedView<V, M> {
    view: V,
    modifier: M,
}

    impl<V: View, M: ViewModifier> ModifiedView<V, M> {
        #[doc(hidden)]
        pub fn new(view: V, modifier: M) -> Self {
            Self { view, modifier }
        }
    }

    impl<V: View, M: ViewModifier> View for ModifiedView<V, M> {
        type Body = ModifiedView<V::Body, M>;

        fn body(self) -> Self::Body {
            ModifiedView {
                view: self.view.body(),
                modifier: self.modifier.clone(),
            }
        }

        fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
            self.modifier.render(renderer, rect);
            let child_rect = self.modifier.transform_rect(rect);
            self.view.render(renderer, child_rect);
        }
    }


    pub trait ViewModifier: Send + Clone {
        fn modify<V: View>(self, content: V) -> impl View;
        fn render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}
        fn transform_rect(&self, rect: Rect) -> Rect { rect }
    }

    /// The Renderer trait defines the atomic drawing operations for all CVKG backends.
    /// This trait is object-safe and used by the View::render system.
    ///
    /// # Implementation Requirements
    /// 1. Coordinate system is origin-top-left (0,0) with Y increasing downwards.
    /// 2. Colors are [R, G, B, A] in the [0.0, 1.0] range.
    /// 3. All operations must be batchable by the underlying backend.
    pub trait Renderer: Send {
        // ── Filled shapes ────────────────────────────────────────────────────
        fn fill_rect(&mut self, rect: Rect, color: [f32; 4]);
        fn fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: [f32; 4]);
        /// Fill an ellipse/circle that fits inside `rect`.
        fn fill_ellipse(&mut self, rect: Rect, color: [f32; 4]);

        // ── Stroked shapes ───────────────────────────────────────────────────
        fn stroke_rect(&mut self, rect: Rect, color: [f32; 4], stroke_width: f32);
        fn stroke_rounded_rect(&mut self, rect: Rect, radius: f32, color: [f32; 4], stroke_width: f32);
        /// Stroke an ellipse/circle that fits inside `rect`.
        fn stroke_ellipse(&mut self, rect: Rect, color: [f32; 4], stroke_width: f32);
        /// Draw a straight line from (x1,y1) to (x2,y2).
        fn draw_line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, color: [f32; 4], stroke_width: f32);

        // ── Text ─────────────────────────────────────────────────────────────
        fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: [f32; 4]);

        // ── Images & textures ────────────────────────────────────────────────
        /// Draw a texture (GPU-side) at the specified rect.
        fn draw_texture(&mut self, texture_id: u32, rect: Rect);
        /// Draw an image asset by name or path.
        fn draw_image(&mut self, image_name: &str, rect: Rect);

        // ── Clipping ─────────────────────────────────────────────────────────
        /// Push a clip rectangle.  All subsequent drawing is clipped to `rect`.
        /// Implementations that do not support clipping may ignore this call.
        fn push_clip_rect(&mut self, rect: Rect);
        /// Pop the most recently pushed clip rectangle.
        fn pop_clip_rect(&mut self);

        // ── Global opacity ───────────────────────────────────────────────────
        /// Set a global opacity multiplier applied to all subsequent draw calls
        /// until `pop_opacity` is called.  `opacity` is in [0.0, 1.0].
        fn push_opacity(&mut self, opacity: f32);
        /// Restore the previous opacity level.
        fn pop_opacity(&mut self);
    }

    /// FrameRenderer extends Renderer with frame lifecycle management.
    /// It is typically implemented by the host windowing/rendering environment.
    pub trait FrameRenderer<E = ()>: Renderer {
        fn begin_frame(&mut self) -> E;
        fn end_frame(&mut self, encoder: E);
    }



use std::sync::Arc;

/// State wrapper that owns a value and notifies subscribers when changed
#[derive(Clone)]
pub struct State<T: Clone + Send + Sync + 'static> {
    value: Arc<std::sync::RwLock<T>>,
    subscribers: Arc<std::sync::RwLock<Vec<Box<dyn FnMut(&T) + Send + Sync>>>>,
}

impl<T: Clone + Send + Sync + 'static> State<T> {
    /// Create a new State with initial value
    pub fn new(value: T) -> Self {
        Self {
            value: Arc::new(std::sync::RwLock::new(value)),
            subscribers: Arc::new(std::sync::RwLock::new(Vec::new())),
        }
    }
    
    /// Get the current value
    pub fn get(&self) -> T {
        self.value.read().unwrap().clone()
    }
    
    /// Set a new value, notifying all subscribers
    pub fn set(&self, value: T) {
        *self.value.write().unwrap() = value;
        // Notify subscribers
        let mut subscribers = self.subscribers.write().unwrap();
        for subscriber in subscribers.iter_mut() {
            subscriber(&self.get());
        }
    }
    
    /// Subscribe to state changes
    pub fn subscribe<F: FnMut(&T) + Send + Sync + 'static>(&self, callback: F) {
        self.subscribers.write().unwrap().push(Box::new(callback));
    }
}

/// Read/write reference to state owned by another view
#[derive(Clone)]
pub struct Binding<T: Clone + Send + Sync + 'static> {
    state: Arc<std::sync::RwLock<T>>,
}

impl<T: Clone + Send + Sync + 'static> Binding<T> {
    /// Create a binding from a State
    pub fn from_state(state: &State<T>) -> Self {
        Self {
            state: state.value.clone(),
        }
    }
    
    /// Get the current value
    pub fn get(&self) -> T {
        self.state.read().unwrap().clone()
    }
    
    /// Set a new value
    pub fn set(&self, value: T) {
        *self.state.write().unwrap() = value;
    }
}

use std::any::TypeId;
use std::sync::{Mutex, OnceLock};

/// Global environment storage using TypeId as keys.
pub(crate) static ENVIRONMENT: OnceLock<Mutex<HashMap<TypeId, Box<dyn std::any::Any + Send + Sync>>>> = OnceLock::new();

/// Environment key type for accessing ambient values
///
/// Implement this trait to define a new environment key.
pub trait EnvKey: 'static + Send + Sync {
    /// The type of value stored in the environment
    type Value: Clone + Send + Sync + 'static;
    
    /// Get a default value for this key
    fn default_value() -> Self::Value;
}

/// Key for accessing the Yggdrasil design token tree
pub struct YggdrasilKey;

impl EnvKey for YggdrasilKey {
    type Value = YggdrasilTokens;
    fn default_value() -> Self::Value {
        default_tokens()
    }
}

/// System appearance (Light/Dark mode)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Appearance {
    Light,
    Dark,
}

/// Orientation for layouts
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Orientation {
    Horizontal,
    Vertical,
}

/// A color represented by RGBA components in the [0.0, 1.0] range.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const BLACK: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
    pub const WHITE: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
    pub const TRANSPARENT: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 };
    pub const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
    pub const GREEN: Color = Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 };
    pub const BLUE: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };

    /// Create a new color from RGBA components.
    pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    /// Convert the color to a [r, g, b, a] array.
    pub fn as_array(&self) -> [f32; 4] {
        [self.r, self.g, self.b, self.a]
    }
}

impl View for Color {
    type Body = Never;
    fn body(self) -> Self::Body { unreachable!() }
    
    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        renderer.fill_rect(rect, self.as_array());
    }
}

/// Key for accessing the current system appearance
pub struct AppearanceKey;

impl EnvKey for AppearanceKey {
    type Value = Appearance;
    fn default_value() -> Self::Value {
        Appearance::Dark // Default to Dark (Ginnungagap) for Berserker aesthetic
    }
}

/// StyleResolver provides high-level access to themed values from the environment.
pub struct StyleResolver;

impl StyleResolver {
    /// Resolve a color from the current environment
    pub fn color(key: &str) -> String {
        let tokens = Environment::<YggdrasilKey>::new().get();
        let appearance = Environment::<AppearanceKey>::new().get();
        let is_dark = appearance == Appearance::Dark;
        
        tokens.get_color(key, is_dark).unwrap_or_else(|| "#FF00FF".to_string()) // Default to MuspelMagenta on failure
    }

    /// Resolve a generic token value
    pub fn get<T: FromStr>(category: &str, key: &str) -> Option<T> {
        let tokens = Environment::<YggdrasilKey>::new().get();
        let appearance = Environment::<AppearanceKey>::new().get();
        let is_dark = appearance == Appearance::Dark;
        
        tokens.get(category, key, is_dark)
    }
}

/// The authoritative Cyberpunk Viking default tokens
pub fn default_tokens() -> YggdrasilTokens {
    let mut tokens = YggdrasilTokens::new();
    
    // Core Norse Colorways
    tokens.color.insert("background".to_string(), TokenValue::Single {
        value: "#000000".to_string(), // Ginnungagap (The Void)
    });
    
    tokens.color.insert("primary".to_string(), TokenValue::Single {
        value: "#00FFFF".to_string(), // NiflCyan (Aesir Primary)
    });
    
    tokens.color.insert("secondary".to_string(), TokenValue::Single {
        value: "#FF00FF".to_string(), // MuspelMagenta (Berserker Secondary)
    });

    tokens.color.insert("surface".to_string(), TokenValue::Adaptive {
        light: "#FFFFFF".to_string(),
        dark: "#121212".to_string(),
    });

    tokens.color.insert("text".to_string(), TokenValue::Adaptive {
        light: "#000000".to_string(),
        dark: "#FFFFFF".to_string(),
    });
    
    // Bifrost (Glassmorphism) - Frosted Style
    tokens.bifrost.insert("blur".to_string(), TokenValue::Single {
        value: "25.0".to_string(),
    });
    tokens.bifrost.insert("saturation".to_string(), TokenValue::Single {
        value: "1.2".to_string(),
    });
    tokens.bifrost.insert("opacity".to_string(), TokenValue::Single {
        value: "0.65".to_string(),
    });
    
    // Gungnir (Neon Glow)
    tokens.gungnir.insert("intensity".to_string(), TokenValue::Single {
        value: "1.0".to_string(),
    });
    tokens.gungnir.insert("radius".to_string(), TokenValue::Single {
        value: "15.0".to_string(),
    });

    // Mjolnir (Sharp Geometry)
    tokens.mjolnir.insert("clip_angle".to_string(), TokenValue::Single {
        value: "12.0".to_string(),
    });
    tokens.mjolnir.insert("border_width".to_string(), TokenValue::Single {
        value: "2.0".to_string(),
    });
    
    // Sleipnir (Spring Animation)
    tokens.anim.insert("stiffness".to_string(), TokenValue::Single {
        value: "170.0".to_string(),
    });
    tokens.anim.insert("damping".to_string(), TokenValue::Single {
        value: "26.0".to_string(),
    });
    tokens.anim.insert("mass".to_string(), TokenValue::Single {
        value: "1.0".to_string(),
    });

    // Accessibility
    tokens.accessibility.insert("reduce_motion".to_string(), TokenValue::Single {
        value: "false".to_string(),
    });
    
    tokens
}




/// Environment wrapper for accessing ambient values
pub struct Environment<K: EnvKey> {
    _marker: std::marker::PhantomData<K>,
}

impl<K: EnvKey> Environment<K> {
    /// Create a new Environment
    pub fn new() -> Self {
        Self {
            _marker: std::marker::PhantomData,
        }
    }
    
    /// Get the current value from the environment
    pub fn get(&self) -> K::Value {
        if let Some(env_store) = ENVIRONMENT.get() {
            let env_lock = env_store.lock().unwrap();
            if let Some(val) = env_lock.get(&std::any::TypeId::of::<K>()) {
                if let Some(typed_val) = val.downcast_ref::<K::Value>() {
                    return typed_val.clone();
                }
            }
        }
        K::default_value()
    }
}
mod env {
    
    
    
    
    /// Insert a value into the environment
    #[allow(dead_code)]
    pub fn insert<K: super::EnvKey>(value: K::Value) {
        if let Some(store) = super::ENVIRONMENT.get() {
            let mut env_map = store.lock().unwrap();
            env_map.insert(std::any::TypeId::of::<K>(), Box::new(value));
        }
    }
    
    /// Remove a value from the environment.
    #[allow(dead_code)]
    pub fn remove<K: super::EnvKey>() {
        if let Some(store) = super::ENVIRONMENT.get() {
            let mut env_map = store.lock().unwrap();
            env_map.remove(&std::any::TypeId::of::<K>());
        }
    }
}



/// Geometry modifiers

/// Size of the view in logical pixels
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Size {
    pub width: f32,
    pub height: f32,
}

/// Insets for padding
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EdgeInsets {
    pub top: f32,
    pub leading: f32,
    pub bottom: f32,
    pub trailing: f32,
}

impl EdgeInsets {
    /// Equal insets on all edges
    pub fn all(value: f32) -> Self {
        Self {
            top: value,
            leading: value,
            bottom: value,
            trailing: value,
        }
    }
    
    /// Vertical insets (top and bottom)
    pub fn vertical(value: f32) -> Self {
        Self {
            top: value,
            leading: 0.0,
            bottom: value,
            trailing: 0.0,
        }
    }
    
    /// Horizontal insets (leading and trailing)
    pub fn horizontal(value: f32) -> Self {
        Self {
            top: 0.0,
            leading: value,
            bottom: 0.0,
            trailing: value,
        }
    }
}

/// Modifier to set the size of a view
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrameModifier {
    pub width: Option<f32>,
    pub height: Option<f32>,
}

impl FrameModifier {
    pub fn new() -> Self {
        Self {
            width: None,
            height: None,
        }
    }
    
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }
    
    pub fn height(mut self, height: f32) -> Self {
        self.height = Some(height);
        self
    }
    
    pub fn size(mut self, width: f32, height: f32) -> Self {
        self.width = Some(width);
        self.height = Some(height);
        self
    }
}

impl ViewModifier for FrameModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}


/// Modifier to offset a view
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OffsetModifier {
    pub x: f32,
    pub y: f32,
}

impl OffsetModifier {
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

impl ViewModifier for OffsetModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// Modifier to set the z-index of a view
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZIndexModifier {
    pub z_index: i32,
}

impl ZIndexModifier {
    pub fn new(z_index: i32) -> Self {
        Self { z_index }
    }
}

impl ViewModifier for ZIndexModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// Layout constraints for views
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayoutConstraints {
    pub min_width: Option<f32>,
    pub max_width: Option<f32>,
    pub min_height: Option<f32>,
    pub max_height: Option<f32>,
}

impl Default for LayoutConstraints {
    fn default() -> Self {
        Self {
            min_width: None,
            max_width: None,
            min_height: None,
            max_height: None,
        }
    }
}

/// Modifier to set layout constraints
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayoutModifier {
    pub constraints: LayoutConstraints,
}

impl LayoutModifier {
    pub fn new(constraints: LayoutConstraints) -> Self {
        Self { constraints }
    }
}

impl ViewModifier for LayoutModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

/// Modifier to make a view flexible in layout
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FlexModifier {
    pub flex: f32,
}

impl FlexModifier {
    pub fn new(flex: f32) -> Self {
        Self { flex }
    }
}

impl ViewModifier for FlexModifier {
    fn modify<V: View>(self, content: V) -> impl View {
        ModifiedView::new(content, self)
    }
}

// Layout subsystem
pub mod layout {
    use super::*;

    // Layout pass scratch space
    pub struct LayoutCache;

    impl LayoutCache {
        pub fn new() -> Self {
            Self
        }

        pub fn clear(&mut self) {
            // In a real implementation, this would clear cached layout data
        }
    }
    
    /// Proposed size from parent view
    #[derive(Debug, Clone, Copy, PartialEq)]
    pub struct SizeProposal {
        pub width: Option<f32>,
        pub height: Option<f32>,
    }
    
    impl SizeProposal {
        pub fn unspecified() -> Self {
            Self {
                width: None,
                height: None,
            }
        }
        
        pub fn width(width: f32) -> Self {
            Self {
                width: Some(width),
                height: None,
            }
        }
        
        pub fn height(height: f32) -> Self {
            Self {
                width: None,
                height: Some(height),
            }
        }
        
        pub fn tight(width: f32, height: f32) -> Self {
            Self {
                width: Some(width),
                height: Some(height),
            }
        }
    }
    
    /// A view that can participate in layout
    pub trait LayoutView: Send {
        /// Propose a size for this view given the available space
        fn size_that_fits(&self, proposal: SizeProposal, subviews: &[&dyn LayoutView], cache: &mut LayoutCache) -> Size;
        
        /// Place subviews within the given bounds
        fn place_subviews(&self, bounds: Rect, subviews: &mut [&mut dyn LayoutView], cache: &mut LayoutCache);
    }
    
    /// Rectangle in logical pixels
    #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
    pub struct Rect {
        pub x: f32,
        pub y: f32,
        pub width: f32,
        pub height: f32,
    }
    
    impl Rect {
        pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
            Self { x, y, width, height }
        }
        
        pub fn zero() -> Self {
            Self { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }
        }
        
        pub fn size(&self) -> Size {
            Size { width: self.width, height: self.height }
        }

        /// Split the rect horizontally into N equal pieces
        pub fn split_horizontal(&self, n: usize) -> Vec<Rect> {
            if n == 0 { return vec![]; }
            let item_width = self.width / n as f32;
            (0..n).map(|i| Rect {
                x: self.x + i as f32 * item_width,
                y: self.y,
                width: item_width,
                height: self.height,
            }).collect()
        }

        /// Split the rect vertically into N equal pieces
        pub fn split_vertical(&self, n: usize) -> Vec<Rect> {
            if n == 0 { return vec![]; }
            let item_height = self.height / n as f32;
            (0..n).map(|i| Rect {
                x: self.x,
                y: self.y + i as f32 * item_height,
                width: self.width,
                height: item_height,
            }).collect()
        }
    }
}

// Re-export layout items for convenience
pub use layout::{LayoutView, SizeProposal, Rect, LayoutCache};
// Size and FrameRenderer are pub items in this module; no re-export alias needed.

pub mod runtime;
pub mod scene_graph;

pub use scene_graph::{NodeId, bifrost_registry};

#[cfg(test)]
mod phase1_test;