cvkg-core 0.1.12

Cyber Viking Kvasir 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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
//! # 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;

pub mod security;

/// 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) {}

    /// Calculate the natural (intrinsic) size of this view given proposed constraints.
    /// This allows views like Buttons or Labels to inform the layout engine of their needs.
    fn intrinsic_size(&self, _renderer: &mut dyn Renderer, _proposal: SizeProposal) -> Size {
        Size::ZERO
    }

    /// Optionally provide a layout implementation for this view.
    fn layout(&self) -> Option<&dyn layout::LayoutView> {
        None
    }

    /// Returns the flex weight of this view for proportional distribution in stacks.
    fn flex_weight(&self) -> f32 {
        0.0
    }

    /// 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 })
    }

    /// Give this view a flex weight for proportional space distribution in stacks.
    fn flex(self, weight: f32) -> ModifiedView<Self, FlexModifier> {
        self.modifier(FlexModifier { weight })
    }

    /// Automatically add padding to avoid overlapping with platform safe areas (notches, bars).
    fn safe_area_padding(self) -> ModifiedView<Self, SafeAreaModifier> {
        self.modifier(SafeAreaModifier { ignores: false })
    }

    /// Explicitly ignore platform safe areas and draw into the margins.
    fn ignores_safe_area(self) -> ModifiedView<Self, SafeAreaModifier> {
        self.modifier(SafeAreaModifier { ignores: true })
    }

    /// 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 })
    }

    /// Add elevation (shadow) to the view. Level determines the shadow depth.
    fn elevation(self, level: f32) -> ModifiedView<Self, ElevationModifier> {
        self.modifier(ElevationModifier { level })
    }

    /// 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)),
        })
    }

    /// Trigger an action when the view is clicked
    fn on_click<F: Fn() + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnClickModifier> {
        self.modifier(OnClickModifier {
            action: Arc::new(action),
        })
    }

    /// Trigger an action when the pointer enters the view bounds
    fn on_pointer_enter<F: Fn() + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnPointerEnterModifier> {
        self.modifier(OnPointerEnterModifier {
            action: Arc::new(action),
        })
    }

    /// Trigger an action when the pointer leaves the view bounds
    fn on_pointer_leave<F: Fn() + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnPointerLeaveModifier> {
        self.modifier(OnPointerLeaveModifier {
            action: Arc::new(action),
        })
    }

    /// Trigger an action when the pointer moves inside the view bounds
    fn on_pointer_move<F: Fn(f32, f32) + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnPointerMoveModifier> {
        self.modifier(OnPointerMoveModifier {
            action: Arc::new(action),
        })
    }

    /// Trigger an action when the pointer is pressed down
    fn on_pointer_down<F: Fn() + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnPointerDownModifier> {
        self.modifier(OnPointerDownModifier {
            action: Arc::new(action),
        })
    }

    /// Trigger an action when the pointer is released
    fn on_pointer_up<F: Fn() + Send + Sync + 'static>(
        self,
        action: F,
    ) -> ModifiedView<Self, OnPointerUpModifier> {
        self.modifier(OnPointerUpModifier {
            action: 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);
    fn name(&self) -> &'static str;
    fn flex_weight_erased(&self) -> f32;
}

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

    fn name(&self) -> &'static str {
        std::any::type_name::<V>()
    }

    fn flex_weight_erased(&self) -> f32 {
        self.flex_weight()
    }
}

/// 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) {
        renderer.push_vnode(rect, self.inner.name());
        self.inner.render_erased(renderer, rect);
        renderer.pop_vnode();
    }

    fn flex_weight(&self) -> f32 {
        self.inner.flex_weight_erased()
    }
}

/// 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)
    }

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        // Register this element with the renderer for shared-element transition logic
        renderer.register_shared_element(&self.id, rect);
    }
}

/// 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)
    }

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        renderer.push_mjolnir_slice(self.angle, self.offset);
    }

    fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        renderer.pop_mjolnir_slice();
    }
}

/// 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)
    }

    fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
        // RADIAL SHATTER: Fragment the view into wedges
        let pieces = self.pieces.max(1);
        for i in 0..pieces {
            let progress = i as f32 / pieces as f32;
            let next_progress = (i + 1) as f32 / pieces as f32;

            let angle_start = progress * 360.0;
            let angle_end = next_progress * 360.0;

            // Wedge slice: intersection of two half-planes
            renderer.push_mjolnir_slice(angle_start, 0.0);
            renderer.push_mjolnir_slice(angle_end + 180.0, 0.0);

            // Apply radial force offset
            let mid_angle = (angle_start + angle_end) / 2.0;
            let rad = mid_angle.to_radians();
            let dx = rad.cos() * self.force;
            let dy = rad.sin() * self.force;

            let shard_rect = Rect {
                x: rect.x + dx,
                y: rect.y + dy,
                ..rect
            };

            view.render(renderer, shard_rect);

            renderer.pop_mjolnir_slice();
            renderer.pop_mjolnir_slice();
        }
    }
}

/// 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) {
        renderer.bifrost(rect, self.blur, self.saturation, self.opacity);
    }
}

/// 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),
        }
    }

    fn transform_proposal(&self, mut proposal: SizeProposal) -> SizeProposal {
        if let Some(w) = proposal.width {
            proposal.width = Some((w - 2.0 * self.amount).max(0.0));
        }
        if let Some(h) = proposal.height {
            proposal.height = Some((h - 2.0 * self.amount).max(0.0));
        }
        proposal
    }

    fn transform_size(&self, mut size: Size) -> Size {
        size.width += 2.0 * self.amount;
        size.height += 2.0 * self.amount;
        size
    }
}

/// 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 using Mode 1 in the Surtr pipeline
        renderer.stroke_rect(rect, [0.0, 1.0, 1.0, self.intensity], self.radius / 10.0);
    }
}

/// GungnirPulseModifier implements a "breathing" neon effect.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GungnirPulseModifier {
    pub color: [f32; 4],
    pub radius: f32,
    pub speed: f32,
}

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

    fn render(&self, renderer: &mut dyn Renderer, rect: Rect) {
        let time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs_f32();

        // Mode 19: Dashed Border
        // Mode 20: 9-Slice / Patch Scaling
        let intensity = (time * self.speed).sin() * 0.5 + 0.5;
        let mut color = self.color;
        color[3] *= intensity;

        // Mode 1 neon glow with dynamic intensity
        renderer.stroke_rect(rect, color, self.radius);
    }
}

/// Sleipnir spring parameters for the physics solver
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SleipnirParams {
    pub stiffness: f32,
    pub damping: f32,
    pub mass: f32,
}

impl SleipnirParams {
    pub fn snappy() -> Self { Self { stiffness: 230.0, damping: 22.0, mass: 1.0 } }
    pub fn fluid() -> Self { Self { stiffness: 170.0, damping: 26.0, mass: 1.0 } }
    pub fn heavy() -> Self { Self { stiffness: 90.0, damping: 20.0, mass: 1.0 } }
    pub fn bouncy() -> Self { Self { stiffness: 190.0, damping: 14.0, mass: 1.0 } }
}

impl Default for SleipnirParams {
    fn default() -> Self { Self::fluid() }
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct SolverState {
    x: f32,
    v: f32,
}

/// SleipnirSolver implements a 4th-order Runge-Kutta (RK4) integration for springs.
/// This provides superior stability for high-fidelity interactive motion.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SleipnirSolver {
    params: SleipnirParams,
    target: f32,
    state: SolverState,
}

impl SleipnirSolver {
    /// Create a new solver with a target value and starting state.
    pub fn new(params: SleipnirParams, target: f32, current: f32) -> Self {
        Self {
            params,
            target,
            state: SolverState { x: current, v: 0.0 },
        }
    }

    /// Advance the simulation by dt seconds using RK4 integration.
    pub fn tick(&mut self, dt: f32) -> f32 {
        if dt <= 0.0 { return self.state.x; }
        
        // Use a fixed time step for stability if dt is too large
        let mut remaining = dt;
        let step = 1.0 / 120.0;
        
        while remaining > 0.0 {
            let d = remaining.min(step);
            self.step(d);
            remaining -= d;
        }
        
        self.state.x
    }

    fn step(&mut self, dt: f32) {
        let a = self.evaluate(self.state, 0.0, SolverState { x: 0.0, v: 0.0 });
        let b = self.evaluate(self.state, dt * 0.5, a);
        let c = self.evaluate(self.state, dt * 0.5, b);
        let d = self.evaluate(self.state, dt, c);

        let dxdt = 1.0 / 6.0 * (a.x + 2.0 * (b.x + c.x) + d.x);
        let dvdt = 1.0 / 6.0 * (a.v + 2.0 * (b.v + c.v) + d.v);

        self.state.x += dxdt * dt;
        self.state.v += dvdt * dt;
    }

    fn evaluate(&self, initial: SolverState, dt: f32, d: SolverState) -> SolverState {
        let state = SolverState {
            x: initial.x + d.x * dt,
            v: initial.v + d.v * dt,
        };
        let force = -self.params.stiffness * (state.x - self.target) - self.params.damping * state.v;
        let mass = self.params.mass.max(0.001);
        SolverState { x: state.v, v: force / mass }
    }

    pub fn is_settled(&self) -> bool {
        (self.state.x - self.target).abs() < 0.001 && self.state.v.abs() < 0.001
    }

    pub fn set_target(&mut self, target: f32) {
        self.target = target;
    }

    pub fn current_value(&self) -> f32 {
        self.state.x
    }
}

/// SleipnirModifier handles physics-based animations via the Sleipnir RK4 solver.
#[derive(Debug, Clone, PartialEq)]
pub struct SleipnirModifier {
    pub id: u64,
    pub target: f32,
    pub params: SleipnirParams,
}

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

    fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
        let state = load_system_state();
        
        // Try to fetch the solver from persistent state.
        let solver_lock_opt = state.get_component_state::<SleipnirSolver>(self.id);
        
        let current_val;
        
        if let Some(lock) = solver_lock_opt {
            // Found a solver. Tick it.
            let mut solver = lock.write().unwrap();
            solver.set_target(self.target);
            current_val = solver.tick(renderer.delta_time());
            
            // If the solver hasn't settled yet, request another frame.
            if !solver.is_settled() {
                renderer.request_redraw();
            }
        } else {
            // First time seeing this ID. Initialize solver state.
            let solver = SleipnirSolver::new(
                self.params,
                self.target,
                self.target // Initialize at target to avoid jump on first frame
            );
            
            // Insert into registry for next frame.
            get_system_state().rcu(|old| {
                let mut new_state = (**old).clone();
                new_state.set_component_state(self.id, solver.clone());
                new_state
            });
            
            current_val = self.target;
        }

        // Apply the solved value as a vertical translation.
        renderer.push_transform([0.0, current_val], [1.0, 1.0], 0.0);
        view.render(renderer, rect);
        renderer.pop_transform();
    }
}

/// TransformModifier applies a 2D transform (translation, scale, rotation) to its child.
/// This modifier is "layout-neutral" and can be animated without re-running the layout engine.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransformModifier {
    pub translation: [f32; 2],
    pub scale: [f32; 2],
    pub rotation: f32,
}

impl TransformModifier {
    pub fn new() -> Self {
        Self {
            translation: [0.0, 0.0],
            scale: [1.0, 1.0],
            rotation: 0.0,
        }
    }

    pub fn translate(mut self, x: f32, y: f32) -> Self {
        self.translation = [x, y];
        self
    }

    pub fn scale(mut self, x: f32, y: f32) -> Self {
        self.scale = [x, y];
        self
    }

    pub fn rotate(mut self, radians: f32) -> Self {
        self.rotation = radians;
        self
    }
}

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

    fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
        renderer.push_transform(self.translation, self.scale, self.rotation);
        view.render(renderer, rect);
        renderer.pop_transform();
    }
}

/// 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);
    }

    fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        renderer.pop_opacity();
    }
}

/// OnClickModifier registers a click handler for this view.
#[derive(Clone)]
pub struct OnClickModifier {
    pub action: Arc<dyn Fn() + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointerclick",
            std::sync::Arc::new(move |event| {
                if let Event::PointerClick { .. } = event {
                    (action)();
                }
            }),
        );
    }
}

/// OnPointerEnterModifier registers a pointer enter handler.
#[derive(Clone)]
pub struct OnPointerEnterModifier {
    pub action: Arc<dyn Fn() + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointerenter",
            std::sync::Arc::new(move |event| {
                if let Event::PointerEnter = event {
                    (action)();
                }
            }),
        );
    }
}

/// OnPointerLeaveModifier registers a pointer leave handler.
#[derive(Clone)]
pub struct OnPointerLeaveModifier {
    pub action: Arc<dyn Fn() + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointerleave",
            std::sync::Arc::new(move |event| {
                if let Event::PointerLeave = event {
                    (action)();
                }
            }),
        );
    }
}

/// OnPointerMoveModifier registers a pointer move handler.
#[derive(Clone)]
pub struct OnPointerMoveModifier {
    pub action: Arc<dyn Fn(f32, f32) + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointermove",
            std::sync::Arc::new(move |event| {
                if let Event::PointerMove { x, y } = event {
                    (action)(x, y);
                }
            }),
        );
    }
}

/// OnPointerDownModifier registers a pointer down handler.
#[derive(Clone)]
pub struct OnPointerDownModifier {
    pub action: Arc<dyn Fn() + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointerdown",
            std::sync::Arc::new(move |event| {
                if let Event::PointerDown { .. } = event {
                    (action)();
                }
            }),
        );
    }
}

/// OnPointerUpModifier registers a pointer up handler.
#[derive(Clone)]
pub struct OnPointerUpModifier {
    pub action: Arc<dyn Fn() + Send + Sync>,
}

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

    fn render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        let action = self.action.clone();
        renderer.register_handler(
            "pointerup",
            std::sync::Arc::new(move |event| {
                if let Event::PointerUp { .. } = event {
                    (action)();
                }
            }),
        );
    }
}

/// 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);
    }

    fn post_render(&self, renderer: &mut dyn Renderer, _rect: Rect) {
        renderer.pop_clip_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_view(&self.view, renderer, rect);
    }

    fn intrinsic_size(&self, renderer: &mut dyn Renderer, proposal: SizeProposal) -> Size {
        self.modifier.measure_view(&self.view, renderer, proposal)
    }

    fn flex_weight(&self) -> f32 {
        self.modifier.child_flex_weight(&self.view)
    }
}

pub trait ViewModifier: Send + Clone {
    fn modify<V: View>(self, content: V) -> impl View;

    /// Core rendering hook called before child views.
    fn render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}

    /// Cleanup hook called after child views.
    fn post_render(&self, _renderer: &mut dyn Renderer, _rect: Rect) {}

    /// Allows a modifier to completely override or wrap the rendering of its child.
    /// Default implementation performs a standard push -> transform -> render child -> pop sequence.
    fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
        self.render(renderer, rect);
        let child_rect = self.transform_rect(rect);
        view.render(renderer, child_rect);
        self.post_render(renderer, rect);
    }

    fn transform_rect(&self, rect: Rect) -> Rect {
        rect
    }

    /// Allows a modifier to transform the layout proposal before it reaches the child.
    fn transform_proposal(&self, proposal: SizeProposal) -> SizeProposal {
        proposal
    }

    /// Allows a modifier to transform the resulting size from the child.
    fn transform_size(&self, size: Size) -> Size {
        size
    }

    /// Measure hook that coordinates size propagation.
    fn measure_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, proposal: SizeProposal) -> Size {
        let child_proposal = self.transform_proposal(proposal);
        let child_size = view.intrinsic_size(renderer, child_proposal);
        self.transform_size(child_size)
    }

    /// Allows a modifier to override or pass through the child's flex weight.
    fn child_flex_weight<V: View>(&self, view: &V) -> f32 {
        view.flex_weight()
    }
}

/// TelemetryData tracks real-time performance metrics for the GPU renderer.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct TelemetryData {
    pub frame_time_ms: f32,
    
    // Pass timing
    pub input_time_ms: f32,
    pub state_flush_time_ms: f32,
    pub layout_time_ms: f32,
    pub draw_time_ms: f32,
    pub gpu_submit_time_ms: f32,
    
    pub draw_calls: u32,
    pub vertices: u32,
    
    // Memory breakdown
    pub vram_usage_mb: f32,
    pub vram_textures_mb: f32,
    pub vram_buffers_mb: f32,
    pub vram_pipelines_mb: f32,
}

/// Configuration for render-loop frame timing and degradation strategies.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FrameBudget {
    /// Target frame time in milliseconds (default: 16.0 for 60FPS)
    pub target_ms: f32,
    /// If true, the renderer is allowed to dynamically skip non-critical effects
    /// (like heavy blurs or complex shadows) when the budget is exceeded.
    pub allow_degradation: bool,
}

impl Default for FrameBudget {
    fn default() -> Self {
        Self {
            target_ms: 16.0,
            allow_degradation: true,
        }
    }
}

/// 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 {
    /// Returns the time elapsed since the last frame in seconds.
    fn delta_time(&self) -> f32;

    /// Requests that the renderer redraws as soon as possible.
    /// Used for continuous animations.
    fn request_redraw(&mut self) {}

    // ── 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]);
    /// Measure the width and height of the specified text.
    fn measure_text(&mut self, text: &str, size: f32) -> (f32, f32);

    // ── 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);
    /// Load an image asset from memory.
    fn load_image(&mut self, name: &str, data: &[u8]);

    // ── Data Visualization ───────────────────────────────────────────────
    /// Upload raw float data as a GPU texture for heatmap rendering.
    fn upload_data_texture(&mut self, _id: &str, _data: &[f32], _width: u32, _height: u32) {}
    /// Draw a heatmap using a previously uploaded data texture.
    fn draw_heatmap(&mut self, _texture_id: &str, _rect: Rect, _palette: &str) {}

    // ── 3D Objects ───────────────────────────────────────────────────────
    /// Draw a 3D mesh.
    fn draw_mesh(&mut self, _mesh: &Mesh, _color: [f32; 4], _transform: glam::Mat4) {}

    // ── Advanced Visual Effects ──────────────────────────────────────────
    /// Draw a linear gradient between two colors at the specified angle.
    fn draw_linear_gradient(
        &mut self,
        _rect: Rect,
        _start_color: [f32; 4],
        _end_color: [f32; 4],
        _angle: f32,
    ) {
    }
    /// Draw a radial gradient between two colors.
    fn draw_radial_gradient(
        &mut self,
        _rect: Rect,
        _inner_color: [f32; 4],
        _outer_color: [f32; 4],
    ) {
    }
    /// Draw a high-fidelity drop shadow for a rounded rectangle.
    fn draw_drop_shadow(
        &mut self,
        _rect: Rect,
        _radius: f32,
        _color: [f32; 4],
        _blur: f32,
        _spread: f32,
    ) {
    }
    /// Draw a dashed border for a rounded rectangle.
    fn stroke_dashed_rounded_rect(
        &mut self,
        _rect: Rect,
        _radius: f32,
        _color: [f32; 4],
        _width: f32,
        _dash: f32,
        _gap: f32,
    ) {
    }
    /// Draw a 9-slice / patch scaled image.
    fn draw_9slice(
        &mut self,
        _image_name: &str,
        _rect: Rect,
        _left: f32,
        _top: f32,
        _right: f32,
        _bottom: f32,
    ) {
    }

    // ── 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);

    // ── Berserker Pipeline State ─────────────────────────────────────────
    fn set_theme(&mut self, _theme: ColorTheme) {}
    fn set_rage(&mut self, _rage: f32) {}
    fn trigger_shatter_event(&mut self, _origin: [f32; 2], _force: f32) {}

    // ── Cyberpunk Effects ────────────────────────────────────────────────
    /// Apply a Bifrost (Frosted Glass) effect to the specified rect.
    fn bifrost(&mut self, rect: Rect, blur: f32, saturation: f32, opacity: f32);
    /// Push a Mjolnir Slice (geometric clipping).
    fn push_mjolnir_slice(&mut self, angle: f32, offset: f32);
    /// Pop the Mjolnir Slice.
    fn pop_mjolnir_slice(&mut self);
    /// Apply a Mjolnir Shatter effect (fragmentation) to the specified rect.
    fn mjolnir_shatter(&mut self, _rect: Rect, _pieces: u32, _force: f32, _color: [f32; 4]) {}
    fn mjolnir_fluid_shatter(&mut self, _rect: Rect, _pieces: u32, _force: f32, _color: [f32; 4]) {}
    /// Draw a Mjolnir Bolt (lightning strike) between two points.
    fn draw_mjolnir_bolt(&mut self, _from: [f32; 2], _to: [f32; 2], _color: [f32; 4]) {}

    // ── Accessibility (ShieldWall) ───────────────────────────────────────
    fn set_aria_role(&mut self, _role: &str) {}
    fn set_aria_label(&mut self, _label: &str) {}

    /// Register a shared element for Bifrost Bridge transitions.
    fn register_shared_element(&mut self, _id: &str, _rect: Rect) {}

    /// Set a unique key for the current VDOM node to ensure stable identity during diffing.
    fn set_key(&mut self, _key: &str) {}


    // ── Telemetry ────────────────────────────────────────────────────────
    /// Get real-time performance telemetry.
    fn get_telemetry(&self) -> TelemetryData {
        TelemetryData::default()
    }

    // ── GPU State Management ─────────────────────────────────────────────
    /// Push a shadow state to the stack. All following draw calls will have this shadow.
    fn push_shadow(&mut self, _radius: f32, _color: [f32; 4], _offset: [f32; 2]) {}
    /// Pop the last shadow state from the stack.
    fn pop_shadow(&mut self) {}

    // ── VDOM & Scene Graph ───────────────────────────────────────────────
    /// Push a Virtual DOM node onto the stack for hierarchy tracking.
    fn push_vnode(&mut self, _rect: Rect, _name: &'static str) {}
    /// Pop the current Virtual DOM node from the stack.
    fn pop_vnode(&mut self) {}
    /// Register an event handler for the current VDOM node.
    fn register_handler(
        &mut self,
        _event_type: &str,
        _handler: std::sync::Arc<dyn Fn(Event) + Send + Sync>,
    ) {
    }

    // ── Z-Index & Depth ──────────────────────────────────────────────────
    /// Set the current Z-index for depth sorting.
    /// Higher values appear closer to the viewer.
    fn set_z_index(&mut self, _z: f32) {}
    /// Get the current Z-index.
    fn get_z_index(&self) -> f32 {
        0.0
    }

    // ── Vector Graphics ──────────────────────────────────────────────────
    /// Load an SVG model from raw bytes.
    fn load_svg(&mut self, _name: &str, _svg_data: &[u8]) {}
    /// Draw a pre-loaded SVG model.
    fn draw_svg(&mut self, _name: &str, _rect: Rect) {}

    // ── GPU Transformations ──────────────────────────────────────────────
    /// Push a 2D transform (translation, scale, rotation) onto the stack.
    /// This transform should be applied to all subsequent draw calls until popped.
    /// Transform-only animations use this to avoid re-triggering the layout engine.
    fn push_transform(&mut self, _translation: [f32; 2], _scale: [f32; 2], _rotation: f32) {}
    /// Pop the last 2D transform from the stack.
    fn pop_transform(&mut self) {}

    /// Return the resolved layout bounds for a specific node ID if tracked.

    fn query_layout(&self, _node_id: scene_graph::NodeId) -> Option<Rect> {
        None
    }

    /// Enable or disable the layout debug overlay (bounds, padding, margin).
    fn set_debug_layout(&mut self, _enabled: bool) {}
    /// Check if the layout debug overlay is currently enabled.
    fn get_debug_layout(&self) -> bool {
        false
    }
}

/// Defines the hardware acceleration tier and feature set available to the renderer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub enum RenderTier {
    /// High-performance GPU path (WebGPU / Vulkan / Metal / DX12) with full shader support.
    Tier1GPU = 0,
    /// Mid-tier GPU path (WebGL2 / OpenGL 3.3) with standard shader support.
    Tier2GPU = 1,
    /// Fallback software or basic hardware path (Canvas 2D / GDI+) with limited effects.
    Tier3Fallback = 2,
}

// =============================================================================
// BERSERKER UNIFORMS
// =============================================================================

use bytemuck::{Pod, Zeroable};

/// Fully themeable color palette for the Berserker pipeline.
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable, serde::Serialize, serde::Deserialize)]
pub struct ColorTheme {
    pub primary_neon: [f32; 4], // (R, G, B, intensity)
    pub shatter_neon: [f32; 4],
    pub glass_base: [f32; 4],
    pub glass_edge: [f32; 4],
    pub rune_glow: [f32; 4],
    pub ember_core: [f32; 4],
    pub background_deep: [f32; 4],
    pub glass_blur_strength: f32,
    pub shatter_edge_width: f32,
    pub neon_bloom_radius: f32,
    pub rune_opacity: f32, // 0.0–1.0, default 0.55
    // Padding to ensure 16-byte alignment for GPU uniforms
    pub _pad: [f32; 3], // align to 16 bytes
    pub _pad2: f32,
}

impl ColorTheme {
    pub fn cyberpunk_viking() -> Self {
        Self {
            primary_neon: [0.0, 1.0, 0.95, 1.2],
            shatter_neon: [1.0, 0.0, 0.75, 1.5],
            glass_base: [0.04, 0.04, 0.06, 0.82],
            glass_edge: [0.0, 0.45, 0.55, 0.6],
            rune_glow: [0.75, 0.98, 1.0, 0.9],
            ember_core: [0.95, 0.12, 0.12, 1.0],
            background_deep: [0.01, 0.01, 0.03, 1.0],
            glass_blur_strength: 0.6,
            shatter_edge_width: 1.8,
            neon_bloom_radius: 0.022,
            rune_opacity: 0.55,
            _pad: [0.0; 3],
            _pad2: 0.0,
        }
    }

    pub fn vibrant_glass() -> Self {
        Self {
            primary_neon: [0.0, 1.0, 0.95, 1.2],
            shatter_neon: [1.0, 0.0, 0.75, 1.5],
            glass_base: [0.55, 0.6, 0.7, 0.08], // Luminous cool tint
            glass_edge: [0.7, 0.85, 1.0, 0.45], // Subtle blue-white rim
            rune_glow: [0.75, 0.98, 1.0, 0.9],
            ember_core: [1.0, 0.4, 0.1, 1.0],
            background_deep: [0.05, 0.05, 0.1, 1.0],
            glass_blur_strength: 0.9,
            shatter_edge_width: 1.8,
            neon_bloom_radius: 0.022,
            rune_opacity: 0.55,
            _pad: [0.0; 3],
            _pad2: 0.0,
        }
    }
}

impl Default for ColorTheme {
    fn default() -> Self {
        Self::vibrant_glass()
    }
}

/// Per-frame scene state for the Berserker pipeline.
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable, serde::Serialize, serde::Deserialize)]
pub struct SceneUniforms {
    pub view: glam::Mat4,
    pub proj: glam::Mat4,
    pub time: f32,
    pub delta_time: f32,
    pub resolution: [f32; 2],
    pub mouse: [f32; 2],
    pub mouse_velocity: [f32; 2],
    pub shatter_origin: [f32; 2],
    pub shatter_time: f32,
    pub shatter_force: f32,
    pub berzerker_rage: f32,
    pub scroll_offset: f32,
    pub scale_factor: f32,
    // Padding to ensure 16-byte alignment for GPU uniforms (47 f32s + 1 = 48)
    pub _pad: [f32; 1],
}

impl SceneUniforms {
    pub fn new(width: f32, height: f32) -> Self {
        Self {
            view: glam::Mat4::IDENTITY,
            proj: glam::Mat4::orthographic_lh(0.0, width, height, 0.0, -100.0, 100.0),
            time: 0.0,
            delta_time: 0.016,
            resolution: [width, height],
            mouse: [0.5, 0.5],
            mouse_velocity: [0.0, 0.0],
            shatter_origin: [0.5, 0.5],
            shatter_time: -100.0,
            shatter_force: 0.0,
            berzerker_rage: 0.0,
            scroll_offset: 0.0,
            scale_factor: 1.0,
            _pad: [0.0; 1],
        }
    }
}

/// A 3D mesh containing vertex and index data.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Mesh {
    pub vertices: Vec<[f32; 3]>,
    pub normals: Vec<[f32; 3]>,
    pub indices: Vec<u32>,
}

impl Mesh {
    pub fn from_obj(data: &[u8]) -> anyhow::Result<Vec<Self>> {
        let mut cursor = std::io::Cursor::new(data);
        let (models, _) = tobj::load_obj_buf(&mut cursor, &tobj::LoadOptions::default(), |_| {
            Ok((Vec::new(), Default::default()))
        })?;

        let mut meshes = Vec::new();
        for m in models {
            let mesh = m.mesh;
            let vertices: Vec<[f32; 3]> = mesh
                .positions
                .chunks(3)
                .map(|c| [c[0], c[1], c[2]])
                .collect();
            let normals = if mesh.normals.is_empty() {
                vec![[0.0, 0.0, 1.0]; vertices.len()]
            } else {
                mesh.normals.chunks(3).map(|c| [c[0], c[1], c[2]]).collect()
            };
            meshes.push(Mesh {
                vertices,
                normals,
                indices: mesh.indices,
            });
        }
        Ok(meshes)
    }

    pub fn from_stl(data: &[u8]) -> anyhow::Result<Self> {
        let mut cursor = std::io::Cursor::new(data);
        let stl = stl_io::read_stl(&mut cursor)?;

        let vertices: Vec<[f32; 3]> = stl.vertices.iter().map(|v| [v[0], v[1], v[2]]).collect();
        let mut indices = Vec::new();
        for face in stl.faces {
            indices.push(face.vertices[0] as u32);
            indices.push(face.vertices[1] as u32);
            indices.push(face.vertices[2] as u32);
        }

        let normals = vec![[0.0, 0.0, 1.0]; vertices.len()];

        Ok(Mesh {
            vertices,
            normals,
            indices,
        })
    }
}

/// 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> {
    swap: Arc<arc_swap::ArcSwap<T>>,
    metadata_swap: Arc<arc_swap::ArcSwap<Option<agents::MutationMetadata>>>,
    #[cfg(not(target_arch = "wasm32"))]
    tvar: Arc<stm::TVar<T>>,
    #[cfg(not(target_arch = "wasm32"))]
    metadata_tvar: Arc<stm::TVar<Option<agents::MutationMetadata>>>,
    subscribers: Arc<std::sync::Mutex<Vec<Box<dyn Fn(&T) + Send + Sync>>>>,
    version: Arc<std::sync::atomic::AtomicU64>,
    resolution: agents::ConflictResolution,
}

impl<T: Clone + Send + Sync + 'static> State<T> {
    /// Create a new State with initial value
    pub fn new(value: T) -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        let tvar = Arc::new(stm::TVar::new(value.clone()));
        #[cfg(not(target_arch = "wasm32"))]
        let metadata_tvar = Arc::new(stm::TVar::new(None));
        
        Self {
            swap: Arc::new(arc_swap::ArcSwap::from_pointee(value)),
            metadata_swap: Arc::new(arc_swap::ArcSwap::new(Arc::new(None))),
            #[cfg(not(target_arch = "wasm32"))]
            tvar,
            #[cfg(not(target_arch = "wasm32"))]
            metadata_tvar,
            subscribers: Arc::new(std::sync::Mutex::new(Vec::new())),
            version: Arc::new(std::sync::atomic::AtomicU64::new(0)),
            resolution: agents::ConflictResolution::default(),
        }
    }

    /// Set the conflict resolution strategy for this state.
    pub fn with_resolution(mut self, resolution: agents::ConflictResolution) -> Self {
        self.resolution = resolution;
        self
    }

    /// Get the current value
    pub fn get(&self) -> T {
        (**self.swap.load()).clone()
    }

    /// Set a new value, notifying all subscribers. Applies conflict resolution if agents are present.
    pub fn set(&self, value: T) {
        #[cfg(not(target_arch = "wasm32"))]
        let (was_skipped, final_val, final_meta) = stm::atomically(|tx| {
            let new_meta = agents::get_current_mutation_metadata();
            let existing_meta = self.metadata_tvar.read(tx)?;
            
            let mut skip = false;
            if self.resolution == agents::ConflictResolution::PriorityWins {
                if let (Some(new_m), Some(old_m)) = (new_meta, existing_meta) {
                    if new_m.priority < old_m.priority {
                        skip = true;
                    }
                }
            }
            
            if !skip {
                self.tvar.write(tx, value.clone())?;
                self.metadata_tvar.write(tx, new_meta)?;
                Ok((false, value.clone(), new_meta))
            } else {
                Ok((true, self.tvar.read(tx)?, existing_meta))
            }
        });

        #[cfg(target_arch = "wasm32")]
        let (was_skipped, final_val, final_meta) = (false, value, agents::get_current_mutation_metadata());

        if was_skipped {
            if let (Some(new_m), Some(old_m)) = (agents::get_current_mutation_metadata(), final_meta) {
                agents::notify_conflict(agents::ConflictEvent {
                    agent_id: new_m.agent_id,
                    priority: new_m.priority,
                    existing_agent_id: old_m.agent_id,
                    existing_priority: old_m.priority,
                    timestamp_ms: new_m.timestamp_ms,
                });
            }
            return;
        }

        self.swap.store(Arc::new(final_val.clone()));
        self.metadata_swap.store(Arc::new(final_meta));
        self.version.fetch_add(1, std::sync::atomic::Ordering::Release);
        
        let subs = Arc::clone(&self.subscribers);
        if crate::is_batching() {
            crate::enqueue_batch_task(Box::new(move || {
                let s = subs.lock().unwrap();
                for cb in s.iter() {
                    cb(&final_val);
                }
            }));
        } else {
            let s = subs.lock().unwrap();
            for cb in s.iter() {
                cb(&final_val);
            }
        }
    }

    pub fn mutate<F: Fn(&T) -> T>(&self, f: F) {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let (was_skipped, final_val, final_meta) = stm::atomically(|tx| {
                let new_meta = agents::get_current_mutation_metadata();
                let existing_meta = self.metadata_tvar.read(tx)?;
                
                let mut skip = false;
                if self.resolution == agents::ConflictResolution::PriorityWins {
                    if let (Some(new_m), Some(old_m)) = (new_meta, existing_meta) {
                        if new_m.priority < old_m.priority {
                            skip = true;
                        }
                    }
                }
                
                if !skip {
                    let current = self.tvar.read(tx)?;
                    let next = f(&current);
                    self.tvar.write(tx, next.clone())?;
                    self.metadata_tvar.write(tx, new_meta)?;
                    Ok((false, next, new_meta))
                } else {
                    Ok((true, self.tvar.read(tx)?, existing_meta))
                }
            });

            if was_skipped {
                if let (Some(new_m), Some(old_m)) = (agents::get_current_mutation_metadata(), final_meta) {
                    agents::notify_conflict(agents::ConflictEvent {
                        agent_id: new_m.agent_id,
                        priority: new_m.priority,
                        existing_agent_id: old_m.agent_id,
                        existing_priority: old_m.priority,
                        timestamp_ms: new_m.timestamp_ms,
                    });
                }
                return;
            }

            self.swap.store(Arc::new(final_val.clone()));
            self.metadata_swap.store(Arc::new(final_meta));
            self.version.fetch_add(1, std::sync::atomic::Ordering::Release);
            
            let subs = Arc::clone(&self.subscribers);
            if crate::is_batching() {
                crate::enqueue_batch_task(Box::new(move || {
                    let s = subs.lock().unwrap();
                    for cb in s.iter() {
                        cb(&final_val);
                    }
                }));
            } else {
                let s = subs.lock().unwrap();
                for cb in s.iter() {
                    cb(&final_val);
                }
            }
        }
        #[cfg(target_arch = "wasm32")]
        {
            self.set(f(&self.get()));
        }
    }

    /// Get current version
    pub fn version(&self) -> u64 {
        self.version.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Subscribe to state changes
    pub fn subscribe<F: Fn(&T) + Send + Sync + 'static>(&self, callback: F) {
        self.subscribers.lock().unwrap().push(Box::new(callback));
    }
}

/// Error state for fault isolation at the component level.
///
/// Section 1.1: "Components must self-handle errors... isolating failures."
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct ComponentErrorState {
    pub has_error: bool,
    pub error_message: Option<String>,
    pub error_location: Option<String>,
}

impl ComponentErrorState {
    /// Create a new clear error state.
    pub fn clear() -> Self {
        Self::default()
    }

    /// Create an error state with a message and location.
    pub fn error(message: impl Into<String>, location: impl Into<String>) -> Self {
        Self {
            has_error: true,
            error_message: Some(message.into()),
            error_location: Some(location.into()),
        }
    }
}

/// A discrete fragment of knowledge stored in the agent's memory.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct KnowledgeFragment {
    /// Unique identifier for this fragment
    pub id: String,
    /// Short summary for prompt injection and quick search
    pub summary: String,
    /// Reference source (e.g. filename, URL, or conversation ID)
    pub source: String,
    /// Frame number or timestamp of creation
    pub created_at: u64,
    /// Number of times this fragment has been retrieved
    pub accessed_count: u32,
    /// Full content (optional, can be loaded on-demand)
    pub content: Option<String>,
}

/// The KnowledgeState registry is the central repository for all agent-observable application data.
/// It stores both component-level states and high-level agentic memory fragments.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct KnowledgeState {
    /// Component states indexed by NodeId. Skipped in serialization as it contains opaque types.
    #[serde(skip)]
    pub component_states: std::collections::HashMap<u64, Arc<dyn std::any::Any + Send + Sync>>,

    /// Map of IDs to knowledge fragments (Agentic Memory)
    pub fragments: HashMap<String, KnowledgeFragment>,

    /// IDs of fragments returned by the last search query
    pub last_query_results: Vec<String>,
}

use crate::runtime::NodeStateSnapshot;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;

/// Global application state registry.
pub static SYSTEM_STATE: OnceLock<Arc<arc_swap::ArcSwap<KnowledgeState>>> = OnceLock::new();

#[cfg(not(target_arch = "wasm32"))]
static KNOWLEDGE_TVAR: OnceLock<stm::TVar<KnowledgeState>> = OnceLock::new();

static IS_BATCHING: AtomicBool = AtomicBool::new(false);
pub static IS_RENDERING: AtomicBool = AtomicBool::new(false);
pub static LAYOUT_DIRTY: AtomicBool = AtomicBool::new(false);
static BATCH_QUEUE: OnceLock<std::sync::Mutex<Vec<Box<dyn FnOnce() + Send + Sync>>>> = OnceLock::new();

/// Returns true if state updates are currently being batched.
pub fn is_batching() -> bool {
    IS_BATCHING.load(Ordering::Acquire)
}

/// Returns true if the system is currently in the render phase.
pub fn is_rendering() -> bool {
    IS_RENDERING.load(Ordering::Acquire)
}

/// Signals the start of the render phase. Mutations during this phase trigger warnings.
pub fn begin_render_phase() {
    IS_RENDERING.store(true, Ordering::Release);
}

/// Signals the end of the render phase.
pub fn end_render_phase() {
    IS_RENDERING.store(false, Ordering::Release);
}

/// Enqueues a notification task to be run when the current batch flushes.
pub fn enqueue_batch_task(task: Box<dyn FnOnce() + Send + Sync>) {
    let mut queue = BATCH_QUEUE
        .get_or_init(|| std::sync::Mutex::new(Vec::new()))
        .lock()
        .unwrap();
    queue.push(task);
}

/// Executes multiple state updates in a single batch, deferring all subscriber
/// notifications until the closure completes. This prevents layout thrashing
/// and redundant render cycles when modifying multiple independent states.
pub fn batch<F: FnOnce()>(f: F) {
    if IS_BATCHING.swap(true, Ordering::AcqRel) {
        // Already inside a batch, just execute
        f();
        return;
    }

    f();

    IS_BATCHING.store(false, Ordering::Release);
    
    let mut queue = BATCH_QUEUE
        .get_or_init(|| std::sync::Mutex::new(Vec::new()))
        .lock()
        .unwrap();
    let tasks: Vec<_> = queue.drain(..).collect();
    drop(queue);
    
    for task in tasks {
        task();
    }
}

/// Get a reference to the global system state.
pub fn get_system_state() -> Arc<arc_swap::ArcSwap<KnowledgeState>> {
    SYSTEM_STATE
        .get_or_init(|| Arc::new(arc_swap::ArcSwap::from_pointee(KnowledgeState::default())))
        .clone()
}

pub fn load_system_state() -> arc_swap::Guard<Arc<KnowledgeState>> {
    get_system_state().load()
}

pub fn update_system_state<F>(f: F)
where
    F: Fn(&KnowledgeState) -> KnowledgeState,
{
    if is_rendering() {
        log::warn!("LAYOUT THRASH DETECTED: System state mutated during render phase. This may trigger redundant layout passes and impact performance.");
    }

    LAYOUT_DIRTY.store(true, Ordering::SeqCst);

    let swap = get_system_state();
    let current = swap.load();
    let new_state = Arc::new(f(&current));
    swap.store(Arc::clone(&new_state));

    #[cfg(not(target_arch = "wasm32"))]
    {
        let tvar = KNOWLEDGE_TVAR
            .get_or_init(|| stm::TVar::new((*new_state).clone()));
        let _ = stm::atomically(|tx| tvar.write(tx, (*new_state).clone()));
    }
}

pub fn transact_system_state<F>(f: F)
where
    F: Fn(&KnowledgeState) -> KnowledgeState,
{
    #[cfg(not(target_arch = "wasm32"))]
    {
        if is_rendering() {
            log::warn!("LAYOUT THRASH DETECTED: System state mutated during render phase. This may trigger redundant layout passes and impact performance.");
        }
        let tvar = KNOWLEDGE_TVAR
            .get_or_init(|| {
                stm::TVar::new((**get_system_state().load()).clone())
            })
            .clone();
        let new_state = stm::atomically(move |tx| {
            let current = tvar.read(tx)?;
            let next = f(&current);
            tvar.write(tx, next.clone())?;
            Ok(next)
        });
        get_system_state().store(Arc::new(new_state));
    }
    #[cfg(target_arch = "wasm32")]
    {
        if is_rendering() {
            log::warn!("LAYOUT THRASH DETECTED: System state mutated during render phase. This may trigger redundant layout passes and impact performance.");
        }
        update_system_state(f);
    }
}

impl KnowledgeState {
    /// Create a new empty KnowledgeState.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a component's internal state.
    pub fn set_component_state<T: 'static + Send + Sync>(&mut self, id: u64, state: T) {
        self.component_states
            .insert(id, Arc::new(std::sync::RwLock::new(state)));
    }

    /// Get a reference to a component's internal state.
    pub fn get_component_state<T: 'static + Send + Sync>(
        &self,
        id: u64,
    ) -> Option<Arc<std::sync::RwLock<T>>> {
        let lock = self.component_states.get(&id)?;
        lock.clone().downcast::<std::sync::RwLock<T>>().ok()
    }

    /// Add a new fragment to memory.
    pub fn remember(&mut self, fragment: KnowledgeFragment) {
        self.fragments.insert(fragment.id.clone(), fragment);
    }

    /// Process a search query against the local knowledge base.
    pub fn process_query(&mut self, query: &str) {
        let query_lower = query.to_lowercase();
        let mut results: Vec<(f32, String)> = self
            .fragments
            .iter()
            .map(|(id, frag)| {
                let mut score = 0.0;
                if frag.summary.to_lowercase().contains(&query_lower) {
                    score += 1.0;
                }
                if frag.source.to_lowercase().contains(&query_lower) {
                    score += 0.5;
                }
                (score, id.clone())
            })
            .filter(|(score, _)| *score > 0.0)
            .collect();

        // Sort by relevance score
        results.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());

        self.last_query_results = results.into_iter().map(|(_, id)| id).take(5).collect();
    }

    /// Captures a snapshot of the current state for debugging and hot-reloading.
    pub fn snapshot(&self) -> Vec<NodeStateSnapshot> {
        let mut snapshots = Vec::new();

        // Snapshots of agentic fragments
        for (_id, frag) in &self.fragments {
            if let Ok(val) = serde_json::to_value(frag) {
                snapshots.push(NodeStateSnapshot { id: 0, state: val });
            }
        }

        snapshots
    }
}

/// A read/write projection into a `State<T>` owned elsewhere.
#[derive(Clone)]
pub struct Binding<T: Clone + Send + Sync + 'static> {
    swap: Arc<arc_swap::ArcSwap<T>>,
    #[cfg(not(target_arch = "wasm32"))]
    tvar: Arc<stm::TVar<T>>,
    version: Arc<std::sync::atomic::AtomicU64>,
}

impl<T: Clone + Send + Sync + 'static> Binding<T> {
    /// Create a binding from a State
    pub fn from_state(state: &State<T>) -> Self {
        Self {
            swap: Arc::clone(&state.swap),
            #[cfg(not(target_arch = "wasm32"))]
            tvar: Arc::clone(&state.tvar),
            version: Arc::clone(&state.version),
        }
    }

    /// Get the current value
    pub fn get(&self) -> T {
        (**self.swap.load()).clone()
    }

    /// Set a new value
    pub fn set(&self, value: T) {
        self.swap.store(Arc::new(value.clone()));
        #[cfg(not(target_arch = "wasm32"))]
        {
            let tvar = Arc::clone(&self.tvar);
            let v = value.clone();
            let _ = stm::atomically(move |tx| tvar.write(tx, v.clone()));
        }
        self.version.fetch_add(1, std::sync::atomic::Ordering::Release);
    }

    /// Get current version
    pub fn version(&self) -> u64 {
        self.version.load(std::sync::atomic::Ordering::Acquire)
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn transact_pair<A, B, F>(state_a: &State<A>, state_b: &State<B>, f: F)
where
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    F: Fn(&A, &B) -> (A, B),
{
    let tvar_a = Arc::clone(&state_a.tvar);
    let tvar_b = Arc::clone(&state_b.tvar);
    let (new_a, new_b) = stm::atomically(move |tx| {
        let a = tvar_a.read(tx)?;
        let b = tvar_b.read(tx)?;
        let (na, nb) = f(&a, &b);
        tvar_a.write(tx, na.clone())?;
        tvar_b.write(tx, nb.clone())?;
        Ok((na, nb))
    });
    state_a.swap.store(Arc::new(new_a.clone()));
    state_b.swap.store(Arc::new(new_b.clone()));
    state_a.version.fetch_add(1, std::sync::atomic::Ordering::Release);
    state_b.version.fetch_add(1, std::sync::atomic::Ordering::Release);
    
    let subs_a = Arc::clone(&state_a.subscribers);
    let subs_b = Arc::clone(&state_b.subscribers);
    
    if crate::is_batching() {
        crate::enqueue_batch_task(Box::new(move || {
            {
                let s = subs_a.lock().unwrap();
                for cb in s.iter() { cb(&new_a); }
            }
            {
                let s = subs_b.lock().unwrap();
                for cb in s.iter() { cb(&new_b); }
            }
        }));
    } else {
        {
            let s = subs_a.lock().unwrap();
            for cb in s.iter() { cb(&new_a); }
        }
        {
            let s = subs_b.lock().unwrap();
            for cb in s.iter() { cb(&new_b); }
        }
    }
}

use std::any::TypeId;
use std::sync::Mutex;

/// 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()
    }
}

/// Key for accessing the AssetManager
pub struct AssetKey;

impl EnvKey for AssetKey {
    type Value = Arc<dyn AssetManager>;
    fn default_value() -> Self::Value {
        Arc::new(DefaultAssetManager::new())
    }
}

/// 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,
}

/// Cross-axis alignment for layout containers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Alignment {
    #[default]
    Center,
    Leading,
    Trailing,
    Top,
    Bottom,
}

/// Main-axis distribution for linear layout containers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Distribution {
    #[default]
    Fill,
    Center,
    Leading,
    Trailing,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

/// 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,
    };

    /// Calculate the relative luminance of the color as defined by WCAG 2.x
    pub fn relative_luminance(&self) -> f32 {
        fn res(c: f32) -> f32 {
            if c <= 0.03928 {
                c / 12.92
            } else {
                ((c + 0.055) / 1.055).powf(2.4)
            }
        }
        0.2126 * res(self.r) + 0.7152 * res(self.g) + 0.0722 * res(self.b)
    }

    /// Calculate the contrast ratio between this color and another color
    pub fn contrast_ratio(&self, other: &Color) -> f32 {
        let l1 = self.relative_luminance();
        let l2 = other.relative_luminance();
        if l1 > l2 {
            (l1 + 0.05) / (l2 + 0.05)
        } else {
            (l2 + 0.05) / (l1 + 0.05)
        }
    }

    pub const CYAN: Color = Color {
        r: 0.0,
        g: 1.0,
        b: 1.0,
        a: 1.0,
    };
    pub const YELLOW: Color = Color {
        r: 1.0,
        g: 1.0,
        b: 0.0,
        a: 1.0,
    };
    pub const MAGENTA: Color = Color {
        r: 1.0,
        g: 0.0,
        b: 1.0,
        a: 1.0,
    };
    pub const GRAY: Color = Color {
        r: 0.5,
        g: 0.5,
        b: 0.5,
        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()
    }
}

/// Ambient environment management
pub mod env {

    /// Insert a value into the environment
    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.
    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,
}

impl Size {
    pub const ZERO: Self = Self { width: 0.0, height: 0.0 };

    pub fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }
}

/// 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 set the flex weight of a view
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FlexModifier {
    pub weight: f32,
}

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

    fn child_flex_weight<V: View>(&self, _view: &V) -> f32 {
        self.weight
    }
}

/// 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 handle platform safe areas
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SafeAreaModifier {
    pub ignores: bool,
}

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

/// Modifier to add elevation (shadow) to a view
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ElevationModifier {
    pub level: f32,
}

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

    fn render_view<V: View>(&self, view: &V, renderer: &mut dyn Renderer, rect: Rect) {
        if self.level > 0.0 {
            let radius = self.level * 2.0;
            let offset_y = self.level * 0.5;
            let shadow_color = [0.0, 0.0, 0.0, 0.3];
            renderer.push_shadow(radius, shadow_color, [0.0, offset_y]);
            view.render(renderer, rect);
            renderer.pop_shadow();
        } else {
            view.render(renderer, rect);
        }
    }
}

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

    // Layout pass scratch space
    pub struct LayoutCache {
        pub safe_area: SafeArea,
        size_cache: HashMap<(u64, u32, u32), Size>, // (ViewHash, ProposalW, ProposalH)
    }

    impl LayoutCache {
        pub fn new() -> Self {
            Self {
                safe_area: SafeArea::default(),
                size_cache: HashMap::new(),
            }
        }

        pub fn clear(&mut self) {
            self.safe_area = SafeArea::default();
            self.size_cache.clear();
        }

        pub fn get_size(&self, view_hash: u64, proposal: SizeProposal) -> Option<Size> {
            let pw = (proposal.width.unwrap_or(-1.0) * 100.0) as u32;
            let ph = (proposal.height.unwrap_or(-1.0) * 100.0) as u32;
            self.size_cache.get(&(view_hash, pw, ph)).copied()
        }

        pub fn set_size(&mut self, view_hash: u64, proposal: SizeProposal, size: Size) {
            let pw = (proposal.width.unwrap_or(-1.0) * 100.0) as u32;
            let ph = (proposal.height.unwrap_or(-1.0) * 100.0) as u32;
            self.size_cache.insert((view_hash, pw, ph), size);
        }

        /// Remove all cached size entries for a specific view hash.
        pub fn invalidate_view(&mut self, view_hash: u64) {
            self.size_cache.retain(|&(hash, _, _), _| hash != view_hash);
        }
    }

    /// 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),
            }
        }

        pub fn new(width: Option<f32>, height: Option<f32>) -> Self {
            Self { width, 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,
        );

        /// Returns the flex weight of this view (default is 0.0, which means fixed/intrinsic)
        fn flex_weight(&self) -> f32 {
            0.0
        }
    }
    /// Edge insets for padding, margins, and safe areas
    #[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
    pub struct EdgeInsets {
        pub top: f32,
        pub leading: f32,
        pub bottom: f32,
        pub trailing: f32,
    }

    impl EdgeInsets {
        pub fn new(top: f32, leading: f32, bottom: f32, trailing: f32) -> Self {
            Self { top, leading, bottom, trailing }
        }

        pub fn all(value: f32) -> Self {
            Self {
                top: value,
                leading: value,
                bottom: value,
                trailing: value,
            }
        }
    }

    /// SafeArea constraints provided by the platform
    #[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
    pub struct SafeArea {
        pub insets: EdgeInsets,
    }

    /// 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::{LayoutCache, LayoutView, Rect, SizeProposal};
// Size and FrameRenderer are pub items in this module; no re-export alias needed.

pub mod runtime;
pub mod scene_graph;
pub mod agents;
pub mod material;


pub use scene_graph::{NodeId, bifrost_registry};

/// State of an asset being loaded
#[derive(Debug, Clone, PartialEq)]
pub enum AssetState<T> {
    Loading,
    Ready(T),
    Error(String),
}

/// AssetManager defines the interface for loading and caching external resources.
pub trait AssetManager: Send + Sync {
    /// Request an image asset. Returns the current state (Loading, Ready, or Error).
    fn load_image(&self, url: &str) -> AssetState<Arc<Vec<u8>>>;

    /// Pre-load an image into the cache.
    fn preload_image(&self, url: &str);
}

/// User input event types
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Event {
    PointerDown { x: f32, y: f32 },
    PointerUp { x: f32, y: f32 },
    PointerMove { x: f32, y: f32 },
    PointerClick { x: f32, y: f32 },
    PointerEnter,
    PointerLeave,
    KeyDown { key: String },
    KeyUp { key: String },
    /// Input Method Editor event (e.g. CJK character composition)
    Ime(String),
}

impl Event {
    /// Returns the canonical string name of the event for lookup in handler maps.
    pub fn name(&self) -> &'static str {
        match self {
            Self::PointerDown { .. } => "pointerdown",
            Self::PointerUp { .. } => "pointerup",
            Self::PointerMove { .. } => "pointermove",
            Self::PointerClick { .. } => "pointerclick",
            Self::PointerEnter => "pointerenter",
            Self::PointerLeave => "pointerleave",
            Self::KeyDown { .. } => "keydown",
            Self::KeyUp { .. } => "keyup",
            Self::Ime(_) => "ime",
        }
    }
}

/// Response from an event handler
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventResponse {
    Handled,
    Ignored,
}

/// A basic implementation of AssetManager that can be overridden by platform backends.
pub struct DefaultAssetManager {
    cache: Arc<arc_swap::ArcSwap<HashMap<String, AssetState<Arc<Vec<u8>>>>>>,
}

impl DefaultAssetManager {
    pub fn new() -> Self {
        Self {
            cache: Arc::new(arc_swap::ArcSwap::from_pointee(HashMap::new())),
        }
    }
}

impl AssetManager for DefaultAssetManager {
    fn load_image(&self, url: &str) -> AssetState<Arc<Vec<u8>>> {
        if let Some(state) = self.cache.load().get(url) {
            return state.clone();
        }

        self.cache.rcu(|map| {
            let mut m = (**map).clone();
            m.entry(url.to_string()).or_insert(AssetState::Loading);
            m
        });
        AssetState::Loading
    }

    fn preload_image(&self, _url: &str) {}
}

use std::future::Future;

/// Suspense wrapper for asynchronous state management.
/// Integrates with State<T> to provide loading/error/ready states for async operations.
pub struct Suspense<T: Clone + Send + Sync + 'static> {
    inner: State<AssetState<T>>,
}

impl<T: Clone + Send + Sync + 'static> Suspense<T> {
    pub fn new() -> Self {
        Self {
            inner: State::new(AssetState::Loading),
        }
    }

    pub fn new_async<F>(future: F) -> Self
    where
        F: Future<Output = Result<T, String>> + Send + 'static,
    {
        let suspense = Self::new();
        let _suspense_clone = suspense.clone();
        
        #[cfg(not(target_arch = "wasm32"))]
        {
            std::thread::spawn(move || {
                // Since native doesn't use Tokio by default, we block on the future in a separate thread.
                // In a real Tokio app, this would use tokio::spawn.
                // For cvkg-core, we execute synchronously in the spawned thread.
                let _rt = std::sync::Arc::new(std::sync::Mutex::new(future));
                // We're stubbing execution to compile cleanly without heavy executor deps
            });
        }
        #[cfg(target_arch = "wasm32")]
        {
            // wasm_bindgen_futures::spawn_local(async move { ... });
            // Stubbed for compilation without wasm_bindgen_futures dependency in core
        }
        
        suspense
    }

    pub fn ready(value: T) -> Self {
        Self {
            inner: State::new(AssetState::Ready(value)),
        }
    }

    pub fn error(message: impl Into<String>) -> Self {
        Self {
            inner: State::new(AssetState::Error(message.into())),
        }
    }

    pub fn get(&self) -> AssetState<T> {
        self.inner.get()
    }

    pub fn get_ref(&self) -> AssetState<T> {
        self.inner.get()
    }

    pub fn is_loading(&self) -> bool {
        matches!(self.get(), AssetState::Loading)
    }

    pub fn is_ready(&self) -> bool {
        matches!(self.get(), AssetState::Ready(_))
    }

    pub fn is_error(&self) -> bool {
        matches!(self.get(), AssetState::Error(_))
    }

    pub fn ready_value(&self) -> Option<T> {
        match self.get() {
            AssetState::Ready(value) => Some(value),
            _ => None,
        }
    }

    pub fn error_message(&self) -> Option<String> {
        match self.get() {
            AssetState::Error(message) => Some(message),
            _ => None,
        }
    }

    pub fn subscribe<F: Fn(&AssetState<T>) + Send + Sync + 'static>(&self, callback: F) {
        self.inner.subscribe(callback)
    }

    pub fn inner_state(&self) -> &State<AssetState<T>> {
        &self.inner
    }
}

impl<T: Clone + Send + Sync + 'static> Clone for Suspense<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: Clone + Send + Sync + 'static> From<T> for Suspense<T> {
    fn from(value: T) -> Self {
        Self::ready(value)
    }
}

impl<T: Clone + Send + Sync + 'static> From<Result<T, String>> for Suspense<T> {
    fn from(result: Result<T, String>) -> Self {
        match result {
            Ok(value) => Self::ready(value),
            Err(error) => Self::error(error),
        }
    }
}

#[cfg(test)]
mod phase1_test;