mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
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
//! Design token 层 —— 按 [Astryx](https://astryx.atmeta.com/)(Meta 开源设计系统)的
//! token 命名与取值定义,让 mgui 的主题可以**逐 token 修改**,而不是一整套换掉。
//!
//! 基表取值逐条抓取自 Astryx 站点默认主题(`:root`,即 `Neutral`)编译出的 StyleX CSS,
//! 变量名与字面量都照抄(`--color-accent: light-dark(#0064E0, #2694FE)`)。
//!
//! 三层结构(与 Astryx 一致):
//!
//! 1. **基表** [`BASE_TOKENS`]:Astryx `Neutral` 主题的默认值。颜色一律两档,等价于 CSS 的
//!    `light-dark()`;mgui 没有 CSS 引擎,所以在 `resolve(dark)` 时按档选一边。
//! 2. **scale 配置** [`Scales`]:Astryx 的 `radius` / `typography.scale` / `motion` 三组生成器
//!    参数(半径基准与倍率、字号锚点与台阶比、动效节奏)。
//! 3. **覆盖层** [`TokenOverrides`]:按**变量名**覆盖,值可以是任意 Astryx 字面量
//!    (`#hex` / `rgba()` / `light-dark(a, b)` / `8px` / `1rem` / `175ms` / `var(--x)`),
//!    所以将来可以直接吃 Astryx 导出的主题。
//!
//! 优先级与 Astryx 相同:**显式覆盖 > scale 生成 > 基表**(按 token 逐条比较)。
//!
//! 解析结果 [`Tokens`] 是某个明暗档下的实际取值(带类型),paint 期零解析;拼错变量名或值
//! 形状不对,在 [`ThemeDefinition::token`] 返回的 [`TokenError`] 上就报出来。`ThemeData`
//! (组件实际读的那份)由 `Tokens` 推导,见 `ThemeData::from_tokens`。
//!
//! ```
//! use mgui_core::theme::tokens::{define_theme, ColorToken, LengthToken};
//! // 基于 Neutral:元素圆角 12px、主色换紫色,解析成深色 token 集
//! let def = define_theme()
//!     .named("brand")
//!     .radius_multiplier(1.5)
//!     .token("--color-accent", "#7B61FF")
//!     .unwrap();
//! let tokens = def.resolve(true);
//! assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
//! assert_eq!(tokens.color(ColorToken::Accent), mgui_core::Color::from_rgb8(0x7B, 0x61, 0xFF));
//! // 焦点环引用 --color-accent,所以跟着主色走
//! assert_eq!(tokens.color(ColorToken::FocusOutline), tokens.color(ColorToken::Accent));
//! ```
//!
//! **未实现的 Astryx 域**(后续按需补齐):`color` palette 生成器(种子色 → 整套明暗色阶)、
//! `components` 组件级样式覆盖、`adaptations` 媒体条件规则(视口宽度 / pointer 精度 /
//! 减弱动效)、data-viz 色阶 `--color-data-*`(只收录 Avatar 用到的 categorical 档)。
//!
//! 已实现并按 0.6 Text 2.0 打通到文本服务:`--font-family-*` → `Tokens::font_stack`
//! (CSS 字体栈原文,交给 parley 回退链);`--text-*-leading` → `TextRoleStyle::leading`
//! → `mgui_text::text::set_text_line_height`(布局与绘制同一 shaping 真值,行高进 shape 缓存 key)。

use crate::Color;
use std::collections::BTreeMap;
use std::fmt;
use std::rc::Rc;

// =================================================================
// 明暗两档
// =================================================================

/// 明 / 暗两档取值 —— Astryx `light-dark(明, 暗)` 的对应物。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Variant<T> {
    pub light: T,
    pub dark: T,
}

impl<T> Variant<T> {
    pub fn of(light: T, dark: T) -> Self {
        Self { light, dark }
    }

    pub fn get(&self, dark: bool) -> &T {
        if dark {
            &self.dark
        } else {
            &self.light
        }
    }
}

impl<T: Clone> Variant<T> {
    pub fn both(value: T) -> Self {
        Self { light: value.clone(), dark: value }
    }
}

impl<T: Copy> Variant<T> {
    pub fn value(&self, dark: bool) -> T {
        *self.get(dark)
    }

    pub fn map<U: Copy>(&self, mut f: impl FnMut(&T) -> U) -> Variant<U> {
        Variant { light: f(&self.light), dark: f(&self.dark) }
    }
}

// =================================================================
// token 名(Astryx CSS 变量名的强类型镜像)
// =================================================================

/// 生成一组带 `ALL` / `as_str()` / `from_name()` 的 token 名枚举。
///
/// 变体名 = Astryx 变量名的大驼峰形式,`as_str()` 给出变量名原文,`from_name()` 供覆盖层
/// 按名反查并做拼写校验。
macro_rules! named_tokens {
    (
        $(#[$meta:meta])*
        pub enum $name:ident { $( $(#[$attr:meta])* $variant:ident => $css:literal ),* $(,)? }
    ) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub enum $name { $( $(#[$attr])* $variant, )* }

        impl $name {
            /// 全部 token(按声明顺序)。
            pub const ALL: &'static [Self] = &[$(Self::$variant),*];

            /// Astryx 变量名原文。
            pub fn as_str(self) -> &'static str {
                match self { $(Self::$variant => $css),* }
            }

            /// 按变量名反查。
            pub fn from_name(text: &str) -> Option<Self> {
                Self::ALL.iter().copied().find(|token| token.as_str() == text)
            }
        }
    };
}

named_tokens! {
    /// 颜色 token。语义命名与 Astryx 完全一致(`on-*` = 该色之上的前景色)。
    pub enum ColorToken {
        Accent => "--color-accent",
        AccentMuted => "--color-accent-muted",
        OnAccent => "--color-on-accent",
        /// 中性提示色(Astryx 用它做低强调描边 / 填充)
        Neutral => "--color-neutral",
        BackgroundSurface => "--color-background-surface",
        BackgroundBody => "--color-background-body",
        BackgroundCard => "--color-background-card",
        BackgroundPopover => "--color-background-popover",
        BackgroundMuted => "--color-background-muted",
        BackgroundInverted => "--color-background-inverted",
        BackgroundErrorInverted => "--color-background-error-inverted",
        TextPrimary => "--color-text-primary",
        TextSecondary => "--color-text-secondary",
        TextDisabled => "--color-text-disabled",
        TextAccent => "--color-text-accent",
        TextBlue => "--color-text-blue",
        TextGreen => "--color-text-green",
        TextYellow => "--color-text-yellow",
        TextRed => "--color-text-red",
        TextInfo => "--color-text-info",
        TextSuccess => "--color-text-success",
        TextWarning => "--color-text-warning",
        TextError => "--color-text-error",
        IconPrimary => "--color-icon-primary",
        IconSecondary => "--color-icon-secondary",
        IconDisabled => "--color-icon-disabled",
        IconAccent => "--color-icon-accent",
        IconInfo => "--color-icon-info",
        IconSuccess => "--color-icon-success",
        IconWarning => "--color-icon-warning",
        IconError => "--color-icon-error",
        /// 常规 1px 描边(带 alpha)
        Border => "--color-border",
        /// 需要被看清的描边(输入框 / 按钮 / 控件)
        BorderEmphasized => "--color-border-emphasized",
        BorderInfo => "--color-border-info",
        BorderSuccess => "--color-border-success",
        BorderWarning => "--color-border-warning",
        BorderError => "--color-border-error",
        Info => "--color-info",
        InfoMuted => "--color-info-muted",
        OnInfo => "--color-on-info",
        OnInfoMuted => "--color-on-info-muted",
        Success => "--color-success",
        SuccessMuted => "--color-success-muted",
        OnSuccess => "--color-on-success",
        OnSuccessMuted => "--color-on-success-muted",
        Error => "--color-error",
        ErrorMuted => "--color-error-muted",
        OnError => "--color-on-error",
        OnErrorMuted => "--color-on-error-muted",
        Warning => "--color-warning",
        WarningMuted => "--color-warning-muted",
        OnWarning => "--color-on-warning",
        OnWarningMuted => "--color-on-warning-muted",
        /// 遮罩(Dialog / Drawer 的 barrier)
        Overlay => "--color-overlay",
        /// hover 叠加色(带 alpha,盖在容器色上)
        OverlayHover => "--color-overlay-hover",
        /// 按下叠加色(带 alpha)
        OverlayPressed => "--color-overlay-pressed",
        Shadow => "--color-shadow",
        /// 骨架屏占位色
        Skeleton => "--color-skeleton",
        /// 滑杆 / 开关的未填充轨道
        Track => "--color-track",
        /// hover 提色调(浅色主题叠黑、深色主题叠白)
        TintHover => "--color-tint-hover",
        OnDark => "--color-on-dark",
        OnLight => "--color-on-light",
        /// 焦点环颜色,默认 `var(--color-accent)`
        FocusOutline => "--focus-outline-color",
        DataCategoricalBlue => "--color-data-categorical-blue",
        DataCategoricalBrown => "--color-data-categorical-brown",
        DataCategoricalCyan => "--color-data-categorical-cyan",
        DataCategoricalGreen => "--color-data-categorical-green",
        DataCategoricalIndigo => "--color-data-categorical-indigo",
        DataCategoricalOrange => "--color-data-categorical-orange",
        DataCategoricalPink => "--color-data-categorical-pink",
        DataCategoricalPurple => "--color-data-categorical-purple",
        DataCategoricalRed => "--color-data-categorical-red",
        DataCategoricalTeal => "--color-data-categorical-teal",
    }
}

named_tokens! {
    /// 长度类 token:圆角、控件尺寸、边框宽度、焦点环。单位统一解析为 px。
    pub enum LengthToken {
        /// 0px —— 不受半径倍率影响
        RadiusNone => "--radius-none",
        /// 4px —— 容器内部的小元素
        RadiusInner => "--radius-inner",
        /// 8px —— 按钮 / 输入框 / 行
        RadiusElement => "--radius-element",
        /// 12px —— 卡片 / 浮层
        RadiusContainer => "--radius-container",
        /// 28px —— 页面级容器
        RadiusPage => "--radius-page",
        /// 28px —— 气泡
        RadiusChat => "--radius-chat",
        /// 9999px —— 完全圆,不受半径倍率影响
        RadiusFull => "--radius-full",
        /// 28px —— 紧凑控件高度
        SizeElementSm => "--size-element-sm",
        /// 32px —— 默认控件高度
        SizeElementMd => "--size-element-md",
        /// 36px —— 触控友好高度
        SizeElementLg => "--size-element-lg",
        /// 1px
        BorderWidth => "--border-width",
        /// 2px
        FocusOutlineWidth => "--focus-outline-width",
        /// 3px
        FocusOutlineOffset => "--focus-outline-offset",
    }
}

named_tokens! {
    /// 间距档位。Astryx 是 `--spacing-0` … `--spacing-12`(每档 `0.25rem` = 4px),
    /// 外加 `--spacing-0-5` / `--spacing-1-5` 两个半步。
    pub enum SpacingStep {
        S0 => "--spacing-0",
        S0_5 => "--spacing-0-5",
        S1 => "--spacing-1",
        S1_5 => "--spacing-1-5",
        S2 => "--spacing-2",
        S3 => "--spacing-3",
        S4 => "--spacing-4",
        S5 => "--spacing-5",
        S6 => "--spacing-6",
        S7 => "--spacing-7",
        S8 => "--spacing-8",
        S9 => "--spacing-9",
        S10 => "--spacing-10",
        S11 => "--spacing-11",
        S12 => "--spacing-12",
    }
}

named_tokens! {
    /// 动效时长(解析后统一为**秒**)。min/max 是同一档的微调区间。
    pub enum DurationToken {
        Fast => "--duration-fast",
        FastMin => "--duration-fast-min",
        FastMax => "--duration-fast-max",
        Medium => "--duration-medium",
        MediumMin => "--duration-medium-min",
        MediumMax => "--duration-medium-max",
        Slow => "--duration-slow",
        SlowMin => "--duration-slow-min",
        SlowMax => "--duration-slow-max",
    }
}

named_tokens! {
    /// 字号阶梯:以 `--font-size-base`(14px)为锚点、按 1.2 倍生成,单位解析为 px。
    pub enum FontSizeToken {
        FourXs => "--font-size-4xs",
        ThreeXs => "--font-size-3xs",
        TwoXs => "--font-size-2xs",
        Xs => "--font-size-xs",
        Sm => "--font-size-sm",
        Base => "--font-size-base",
        Lg => "--font-size-lg",
        Xl => "--font-size-xl",
        TwoXl => "--font-size-2xl",
        ThreeXl => "--font-size-3xl",
        FourXl => "--font-size-4xl",
        FiveXl => "--font-size-5xl",
    }
}

impl FontSizeToken {
    /// 相对 `--font-size-base` 的台阶指数(base = 0,往上为正、往下为负)。
    fn step(self) -> i32 {
        match self {
            Self::FourXs => -5,
            Self::ThreeXs => -4,
            Self::TwoXs => -3,
            Self::Xs => -2,
            Self::Sm => -1,
            Self::Base => 0,
            Self::Lg => 1,
            Self::Xl => 2,
            Self::TwoXl => 3,
            Self::ThreeXl => 4,
            Self::FourXl => 5,
            Self::FiveXl => 6,
        }
    }
}

named_tokens! {
    /// 字重(无单位数值)。
    pub enum FontWeightToken {
        Normal => "--font-weight-normal",
        Medium => "--font-weight-medium",
        Semibold => "--font-weight-semibold",
        Bold => "--font-weight-bold",
    }
}

named_tokens! {
    /// 阴影 token。`low` / `med` / `high` 是两层外阴影,`inset-*` 是 2px 内描边环。
    pub enum ShadowToken {
        Low => "--shadow-low",
        Med => "--shadow-med",
        High => "--shadow-high",
        InsetHover => "--shadow-inset-hover",
        InsetSelected => "--shadow-inset-selected",
        InsetSuccess => "--shadow-inset-success",
        InsetWarning => "--shadow-inset-warning",
        InsetError => "--shadow-inset-error",
    }
}

named_tokens! {
    /// 缓动曲线(三次贝塞尔控制点)。
    pub enum EasingToken {
        Standard => "--ease-standard",
        Entrance => "--ease-entrance",
        Move => "--ease-move",
        Exit => "--ease-exit",
    }
}

named_tokens! {
    /// 文本角色(Astryx `--text-*` 三件套:size / weight / leading)。
    ///
    /// 角色的 size / weight 通过 `var()` 引用字号 / 字重阶梯,所以调
    /// [`Scales::text_base`] 时整套角色跟着变。
    pub enum TextRole {
        DisplayOne => "--text-display-1",
        DisplayTwo => "--text-display-2",
        DisplayThree => "--text-display-3",
        HeadingOne => "--text-heading-1",
        HeadingTwo => "--text-heading-2",
        HeadingThree => "--text-heading-3",
        HeadingFour => "--text-heading-4",
        HeadingFive => "--text-heading-5",
        HeadingSix => "--text-heading-6",
        Large => "--text-large",
        Body => "--text-body",
        Label => "--text-label",
        Supporting => "--text-supporting",
        Code => "--text-code",
    }
}

impl TextRole {
    /// `--text-body` → `body`。
    pub fn stem(self) -> &'static str {
        match self {
            Self::DisplayOne => "display-1",
            Self::DisplayTwo => "display-2",
            Self::DisplayThree => "display-3",
            Self::HeadingOne => "heading-1",
            Self::HeadingTwo => "heading-2",
            Self::HeadingThree => "heading-3",
            Self::HeadingFour => "heading-4",
            Self::HeadingFive => "heading-5",
            Self::HeadingSix => "heading-6",
            Self::Large => "large",
            Self::Body => "body",
            Self::Label => "label",
            Self::Supporting => "supporting",
            Self::Code => "code",
        }
    }

    pub fn size_name(self) -> String {
        format!("{}-size", self.as_str())
    }

    pub fn weight_name(self) -> String {
        format!("{}-weight", self.as_str())
    }

    pub fn leading_name(self) -> String {
        format!("{}-leading", self.as_str())
    }
}

named_tokens! {
    /// 字体栈角色(`--font-family-*`)。值按 CSS `font-family` 字面量原文保留,
    /// 由 `mgui-text` 的 parley/fontique 回退链消费(CJK/emoji 自动落到后备字体)。
    pub enum FontFamilyToken {
        Body => "--font-family-body",
        Display => "--font-family-display",
        Mono => "--font-family-mono",
    }
}

/// token 的值类型 —— 决定覆盖层接受什么形状的字面量。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Color,
    /// 长度 / 时长 / 字号 / 字重 / 行高
    Number,
    Shadow,
    Easing,
    /// CSS 字体栈原文(交给 mgui-text 的 parley 回退链消费)
    FontStack,
}

/// 变量名 → 值类型。未收录的名字视为未知(覆盖层直接报错)。
fn kind_of(name: &str) -> Option<Kind> {
    if ColorToken::from_name(name).is_some() {
        return Some(Kind::Color);
    }
    if LengthToken::from_name(name).is_some()
        || SpacingStep::from_name(name).is_some()
        || DurationToken::from_name(name).is_some()
        || FontSizeToken::from_name(name).is_some()
        || FontWeightToken::from_name(name).is_some()
    {
        return Some(Kind::Number);
    }
    if ShadowToken::from_name(name).is_some() {
        return Some(Kind::Shadow);
    }
    if EasingToken::from_name(name).is_some() {
        return Some(Kind::Easing);
    }
    if name.starts_with("--font-family-") {
        return Some(Kind::FontStack);
    }
    // --text-*-size / -weight / -leading 由 TextRole 拼出来,不在上面的枚举里
    if let Some(stem) = name.strip_prefix("--text-") {
        if stem.ends_with("-size") || stem.ends_with("-weight") || stem.ends_with("-leading") {
            return Some(Kind::Number);
        }
    }
    None
}

// =================================================================
// 字面量解析
// =================================================================

/// 一个 token 字面量的中间表示。
#[derive(Clone, Debug, PartialEq)]
enum Atom {
    Color(Color),
    /// 长度(px) / 时长(秒) / 无单位数字
    Num(f32),
    /// `light-dark(明, 暗)`
    LightDark(Rc<Atom>, Rc<Atom>),
    /// `var(--x)` 或 `var(--x, 回退)`
    Ref {
        name: String,
        fallback: Option<Rc<Atom>>,
    },
    /// 其余按原文留着(缓动曲线、字体族栈等)
    Text(Rc<str>),
}

/// `rem` 的基准。Astryx 的网页基准是 16px;mgui 没有根字号概念,固定按 16px 换算。
const REM_PX: f32 = 16.0;

/// 解析一个 CSS 风格字面量。单位归一:`px` 原值、`rem` × 16、`ms` ÷ 1000、`s` 原值。
fn parse_atom(text: &str) -> Atom {
    let text = text.trim();
    if text.is_empty() {
        return Atom::Text(Rc::from(""));
    }
    let lower = text.to_ascii_lowercase();
    if let Some(inner) = strip_call(&lower, "light-dark") {
        if let Some((light, dark)) = split_top(inner, ',') {
            return Atom::LightDark(Rc::new(parse_atom(light)), Rc::new(parse_atom(dark)));
        }
    }
    if let Some(inner) = strip_call(&lower, "var") {
        let (name, fallback) = match split_top(inner, ',') {
            Some((name, fallback)) => (name.trim().to_string(), Some(Rc::new(parse_atom(fallback)))),
            None => (inner.trim().to_string(), None),
        };
        return Atom::Ref { name, fallback };
    }
    if let Some(color) = parse_color(&lower) {
        return Atom::Color(color);
    }
    if let Some(value) = parse_number(&lower) {
        return Atom::Num(value);
    }
    Atom::Text(Rc::from(text))
}

/// `#RGB` / `#RRGGBB` / `#RRGGBBAA` / `rgb()` / `rgba()` / Astryx 用到的颜色关键字。
fn parse_color(lower: &str) -> Option<Color> {
    if let Some(digits) = lower.strip_prefix('#') {
        return parse_hex(digits);
    }
    for name in ["rgba", "rgb"] {
        if let Some(inner) = strip_call(lower, name) {
            return parse_rgba(inner);
        }
    }
    match lower {
        "black" => Some(Color::BLACK),
        "white" => Some(Color::WHITE),
        "transparent" => Some(Color::TRANSPARENT),
        _ => None,
    }
}

fn parse_hex(digits: &str) -> Option<Color> {
    let byte = |s: &str| u8::from_str_radix(s, 16).ok();
    match digits.len() {
        3 => {
            let r = byte(&digits[0..1])?;
            let g = byte(&digits[1..2])?;
            let b = byte(&digits[2..3])?;
            Some(Color::from_rgb8(r * 17, g * 17, b * 17))
        }
        6 => Some(Color::from_rgb8(byte(&digits[0..2])?, byte(&digits[2..4])?, byte(&digits[4..6])?)),
        // Astryx 用 8 位 hex 表示带 alpha 的叠加色:#RRGGBBAA
        8 => Some(Color::from_rgba8(
            byte(&digits[0..2])?,
            byte(&digits[2..4])?,
            byte(&digits[4..6])?,
            byte(&digits[6..8])?,
        )),
        _ => None,
    }
}

/// `rgba(r, g, b, a)`:r/g/b 是 0–255,a 是 0–1
fn parse_rgba(inner: &str) -> Option<Color> {
    let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
    if parts.len() != 4 {
        return None;
    }
    let r: f32 = parts[0].parse().ok()?;
    let g: f32 = parts[1].parse().ok()?;
    let b: f32 = parts[2].parse().ok()?;
    let a: f32 = parts[3].parse().ok()?;
    Some(Color::rgba(r / 255.0, g / 255.0, b / 255.0, a))
}

/// `12px` / `0.875rem` / `175ms` / `1.4` / `400`
fn parse_number(lower: &str) -> Option<f32> {
    if let Some(px) = lower.strip_suffix("px") {
        return px.trim().parse::<f32>().ok();
    }
    if let Some(rem) = lower.strip_suffix("rem") {
        return rem.trim().parse::<f32>().ok().map(|v| v * REM_PX);
    }
    if let Some(ms) = lower.strip_suffix("ms") {
        return ms.trim().parse::<f32>().ok().map(|v| v / 1000.0);
    }
    if let Some(sec) = lower.strip_suffix('s') {
        return sec.trim().parse::<f32>().ok();
    }
    lower.parse::<f32>().ok()
}

/// `name(a, b)` → `Some("a, b")`(调用方传小写文本,要求括号配平)
fn strip_call<'a>(lower: &'a str, name: &str) -> Option<&'a str> {
    let rest = lower.strip_prefix(name)?.trim_start();
    let rest = rest.strip_prefix('(')?;
    rest.strip_suffix(')')
}

/// 按**顶层**逗号(或其他单字符分隔符)切成两段;括号内的分隔符不算。
fn split_top(text: &str, sep: char) -> Option<(&str, &str)> {
    let mut depth = 0usize;
    for (index, ch) in text.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            c if c == sep && depth == 0 => return Some((&text[..index], &text[index + 1..])),
            _ => {}
        }
    }
    None
}

/// 按顶层逗号切成任意多段(box-shadow 的多层列表)。
fn split_top_all(text: &str, sep: char) -> Vec<&str> {
    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    for (index, ch) in text.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            c if c == sep && depth == 0 => {
                out.push(text[start..index].trim());
                start = index + 1;
            }
            _ => {}
        }
    }
    out.push(text[start..].trim());
    out
}

/// 按顶层空白切分(`0px 1px 1px light-dark(...)` → 4 段)。
fn split_top_space(text: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut depth = 0usize;
    let mut start: Option<usize> = None;
    for (index, ch) in text.char_indices() {
        if ch == '(' {
            depth += 1;
            continue;
        }
        if ch == ')' {
            depth = depth.saturating_sub(1);
            continue;
        }
        if depth != 0 {
            continue;
        }
        if ch.is_whitespace() {
            if let Some(from) = start.take() {
                out.push(&text[from..index]);
            }
        } else if start.is_none() {
            start = Some(index);
        }
    }
    if let Some(from) = start {
        out.push(&text[from..]);
    }
    out
}

// =================================================================
// 阴影
// =================================================================

/// 一层 box-shadow。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShadowLayer {
    pub inset: bool,
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur: f32,
    pub spread: f32,
    pub color: Color,
}

/// 一组阴影(Astryx 的 `--shadow-low/med/high` 是两层,`--shadow-inset-*` 是一层内描边)。
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Shadow {
    pub layers: Vec<ShadowLayer>,
}

impl Shadow {
    /// 第一层投影(桌面端绘制最常用的取法)。
    pub fn first(&self) -> Option<ShadowLayer> {
        self.layers.first().copied()
    }

    /// `inset` + 纯 spread 构成的"描边环"(Astryx 用它表达 hover / selected 的内圈)。
    pub fn ring(&self) -> Option<ShadowLayer> {
        self.layers.iter().copied().find(|layer| layer.inset && layer.blur == 0.0)
    }

    pub fn is_empty(&self) -> bool {
        self.layers.is_empty()
    }
}

/// 解析 `0px 1px 1px <color>, 0px 2px 8px <color>` 形式。
fn parse_shadow(text: &str, table: &TokenTable, dark: bool) -> Shadow {
    let mut layers = Vec::new();
    for part in split_top_all(text, ',') {
        if part.is_empty() {
            continue;
        }
        layers.push(parse_shadow_layer(part, table, dark));
    }
    Shadow { layers }
}

fn parse_shadow_layer(text: &str, table: &TokenTable, dark: bool) -> ShadowLayer {
    let mut inset = false;
    let mut numbers: Vec<f32> = Vec::new();
    let mut color_source = String::new();
    for part in split_top_space(text) {
        if part.eq_ignore_ascii_case("inset") {
            inset = true;
            continue;
        }
        if let Some(value) = parse_number(&part.to_ascii_lowercase()) {
            numbers.push(value);
            continue;
        }
        if !color_source.is_empty() {
            color_source.push(' ');
        }
        color_source.push_str(part);
    }
    let color = if color_source.is_empty() {
        Color::TRANSPARENT
    } else {
        table.color_from_source(&color_source, dark).unwrap_or(Color::TRANSPARENT)
    };
    ShadowLayer {
        inset,
        offset_x: numbers.first().copied().unwrap_or(0.0),
        offset_y: numbers.get(1).copied().unwrap_or(0.0),
        blur: numbers.get(2).copied().unwrap_or(0.0),
        spread: numbers.get(3).copied().unwrap_or(0.0),
        color,
    }
}

// =================================================================
// 基表:Astryx `Neutral` 主题默认值
// =================================================================

/// 与 Astryx 站点 `:root`(`Neutral` 主题)编译产物逐条一致。
pub const BASE_TOKENS: &[(&str, &str)] = &[
    // ---- 品牌 / 中性 ----
    ("--color-accent", "light-dark(#0064E0, #2694FE)"),
    ("--color-accent-muted", "light-dark(#0082FB33, #0082FB3F)"),
    ("--color-on-accent", "light-dark(#FFFFFF, #FFFFFF)"),
    ("--color-neutral", "light-dark(rgba(5, 54, 89, 0.1), rgba(223, 226, 229, 0.2))"),
    // ---- 背景 ----
    ("--color-background-surface", "light-dark(#FFFFFF, #1F1F22)"),
    ("--color-background-body", "light-dark(#F1F4F7, #111112)"),
    ("--color-background-card", "light-dark(#FFFFFF, #1F1F22)"),
    ("--color-background-popover", "light-dark(#FFFFFF, #28292C)"),
    ("--color-background-muted", "light-dark(#0536590C, #1111127F)"),
    ("--color-background-inverted", "light-dark(#0A1317, #FFFFFF)"),
    ("--color-background-error-inverted", "light-dark(#AA071E, #E3193B)"),
    // ---- 文本 ----
    ("--color-text-primary", "light-dark(#0A1317, #DFE2E5)"),
    ("--color-text-secondary", "light-dark(#4E606F, #AAAFB5)"),
    ("--color-text-disabled", "light-dark(#A4B0BC, #6F747C)"),
    ("--color-text-accent", "light-dark(#0064E0, #3E9EFB)"),
    ("--color-text-blue", "light-dark(#042F97, #AFD7FF)"),
    ("--color-text-green", "light-dark(#09441F, #A5F690)"),
    ("--color-text-yellow", "light-dark(#753F07, #FBCE03)"),
    ("--color-text-red", "light-dark(#7B0210, #FFB2B8)"),
    ("--color-text-info", "var(--color-text-blue)"),
    ("--color-text-success", "var(--color-text-green)"),
    ("--color-text-warning", "var(--color-text-yellow)"),
    ("--color-text-error", "var(--color-text-red)"),
    // ---- 图标 ----
    ("--color-icon-primary", "light-dark(#0A1317, #DFE2E5)"),
    ("--color-icon-secondary", "light-dark(#4E606F, #AAAFB5)"),
    ("--color-icon-disabled", "light-dark(#A4B0BC, #6F747C)"),
    ("--color-icon-accent", "light-dark(#0064E0, #2694FE)"),
    ("--color-icon-info", "var(--color-text-info)"),
    ("--color-icon-success", "var(--color-text-success)"),
    ("--color-icon-warning", "var(--color-text-warning)"),
    ("--color-icon-error", "var(--color-text-error)"),
    // ---- 描边 ----
    ("--color-border", "light-dark(#05365919, #F2F4F619)"),
    ("--color-border-emphasized", "light-dark(#CCD3DB, #494D53)"),
    ("--color-border-info", "var(--color-text-info)"),
    ("--color-border-success", "var(--color-text-success)"),
    ("--color-border-warning", "var(--color-text-warning)"),
    ("--color-border-error", "var(--color-text-error)"),
    // ---- 状态 ----
    ("--color-info", "light-dark(#0064E0, #0064E0)"),
    ("--color-info-muted", "light-dark(#0082FB33, #0082FB3F)"),
    ("--color-on-info", "light-dark(#FFFFFF, #FFFFFF)"),
    ("--color-on-info-muted", "var(--color-text-blue)"),
    ("--color-success", "light-dark(#0D8626, #0D8626)"),
    ("--color-success-muted", "light-dark(#0B991F33, #0B991F3F)"),
    ("--color-on-success", "light-dark(#FFFFFF, #FFFFFF)"),
    ("--color-on-success-muted", "var(--color-text-green)"),
    ("--color-error", "light-dark(#E3193B, #F5394F)"),
    ("--color-error-muted", "light-dark(#E3193B33, #F5394F3F)"),
    // 深色 error 太亮,白字达不到 4.5:1,所以它上面的文字用深色
    ("--color-on-error", "light-dark(#FFFFFF, #0A1317)"),
    ("--color-on-error-muted", "var(--color-text-red)"),
    ("--color-warning", "light-dark(#E9AF08, #F2C00B)"),
    ("--color-warning-muted", "light-dark(#E2A40033, #E2A4003F)"),
    ("--color-on-warning", "light-dark(#0A1317, #0A1317)"),
    ("--color-on-warning-muted", "var(--color-text-yellow)"),
    // ---- 叠加层 / 阴影色 / 轨道 ----
    ("--color-overlay", "light-dark(#01122866, #11111299)"),
    ("--color-overlay-hover", "light-dark(#0536590C, #FFFFFF0C)"),
    ("--color-overlay-pressed", "light-dark(#05365919, #FFFFFF19)"),
    ("--color-shadow", "light-dark(rgba(5, 54, 89, 0.1), rgba(0, 0, 0, 0.3))"),
    ("--color-skeleton", "light-dark(#CCD3DB, #5A5E66)"),
    ("--color-track", "light-dark(#CCD3DB, #5A5E66)"),
    ("--color-tint-hover", "light-dark(black, white)"),
    ("--color-on-dark", "light-dark(#FFFFFF, #FFFFFF)"),
    ("--color-on-light", "light-dark(#000000, #000000)"),
    // ---- 分类色(Avatar 轮换池用到) ----
    ("--color-data-categorical-blue", "light-dark(#0171E3, #0171E3)"),
    ("--color-data-categorical-brown", "light-dark(#965E03, #965E03)"),
    ("--color-data-categorical-cyan", "light-dark(#0171A4, #0171A4)"),
    ("--color-data-categorical-green", "light-dark(#0B991F, #0B991F)"),
    ("--color-data-categorical-indigo", "light-dark(#6F8AFF, #6F8AFF)"),
    ("--color-data-categorical-orange", "light-dark(#EB6E00, #EB6E00)"),
    ("--color-data-categorical-pink", "light-dark(#F351C0, #F351C0)"),
    ("--color-data-categorical-purple", "light-dark(#6B1EFD, #6B1EFD)"),
    ("--color-data-categorical-red", "light-dark(#F5394F, #F5394F)"),
    ("--color-data-categorical-teal", "light-dark(#08A3A3, #08A3A3)"),
    // ---- 圆角 / 尺寸 / 边框 / 焦点 ----
    ("--radius-none", "0px"),
    ("--radius-inner", "4px"),
    ("--radius-element", "8px"),
    ("--radius-container", "12px"),
    ("--radius-page", "28px"),
    ("--radius-chat", "28px"),
    ("--radius-full", "9999px"),
    ("--size-element-sm", "28px"),
    ("--size-element-md", "32px"),
    ("--size-element-lg", "36px"),
    ("--border-width", "1px"),
    ("--focus-outline-width", "2px"),
    ("--focus-outline-offset", "3px"),
    // 焦点环颜色引用主色:覆盖 --color-accent 时它跟着走
    ("--focus-outline-color", "var(--color-accent)"),
    // ---- 阴影(Astryx 是两层外阴影;inset-* 是 2px 内描边环) ----
    (
        "--shadow-low",
        "0px 1px 1px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
         0px 2px 8px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
    ),
    (
        "--shadow-med",
        "0px 1px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
         0px 2px 12px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
    ),
    (
        "--shadow-high",
        "0px 2px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
         0px 8px 24px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3))",
    ),
    ("--shadow-inset-hover", "inset 0px 0px 0px 2px light-dark(rgba(5, 54, 89, 0.15), rgba(223, 226, 229, 0.2))"),
    ("--shadow-inset-selected", "inset 0px 0px 0px 2px rgba(1, 113, 227, 0.5)"),
    ("--shadow-inset-success", "inset 0px 0px 0px 2px rgba(38, 167, 86, 0.3)"),
    ("--shadow-inset-warning", "inset 0px 0px 0px 2px rgba(226, 164, 0, 0.3)"),
    ("--shadow-inset-error", "inset 0px 0px 0px 2px rgba(227, 25, 59, 0.3)"),
    // ---- 间距:0–12 档(每档 0.25rem = 4px),含两个半步 ----
    ("--spacing-0", "0rem"),
    ("--spacing-0-5", "0.125rem"),
    ("--spacing-1", "0.25rem"),
    ("--spacing-1-5", "0.375rem"),
    ("--spacing-2", "0.5rem"),
    ("--spacing-3", "0.75rem"),
    ("--spacing-4", "1rem"),
    ("--spacing-5", "1.25rem"),
    ("--spacing-6", "1.5rem"),
    ("--spacing-7", "1.75rem"),
    ("--spacing-8", "2rem"),
    ("--spacing-9", "2.25rem"),
    ("--spacing-10", "2.5rem"),
    ("--spacing-11", "2.75rem"),
    ("--spacing-12", "3rem"),
    // ---- 动效 ----
    ("--duration-fast-min", "130ms"),
    ("--duration-fast", "175ms"),
    ("--duration-fast-max", "230ms"),
    ("--duration-medium-min", "310ms"),
    ("--duration-medium", "410ms"),
    ("--duration-medium-max", "550ms"),
    ("--duration-slow-min", "730ms"),
    ("--duration-slow", "975ms"),
    ("--duration-slow-max", "1300ms"),
    ("--ease-standard", "cubic-bezier(0.24, 1, 0.4, 1)"),
    ("--ease-entrance", "cubic-bezier(0.24, 1, 0.4, 1)"),
    ("--ease-move", "cubic-bezier(0.24, 1, 0.4, 1)"),
    ("--ease-exit", "cubic-bezier(0.3, 0, 0.6, 0.6)"),
    // ---- 字号(1.2 台阶,锚点 14px)与字重 ----
    ("--font-size-4xs", "0.375rem"),
    ("--font-size-3xs", "0.4375rem"),
    ("--font-size-2xs", "0.5rem"),
    ("--font-size-xs", "0.625rem"),
    ("--font-size-sm", "0.75rem"),
    ("--font-size-base", "0.875rem"),
    ("--font-size-lg", "1.0625rem"),
    ("--font-size-xl", "1.25rem"),
    ("--font-size-2xl", "1.5rem"),
    ("--font-size-3xl", "1.8125rem"),
    ("--font-size-4xl", "2.1875rem"),
    ("--font-size-5xl", "2.625rem"),
    ("--font-weight-normal", "400"),
    ("--font-weight-medium", "500"),
    ("--font-weight-semibold", "600"),
    ("--font-weight-bold", "700"),
    // ---- 文本角色:引用阶梯,所以调 base / ratio 时整套角色跟着变 ----
    ("--text-display-1-size", "var(--font-size-5xl)"),
    ("--text-display-1-weight", "var(--font-weight-normal)"),
    ("--text-display-1-leading", "1.2381"),
    ("--text-display-2-size", "var(--font-size-4xl)"),
    ("--text-display-2-weight", "var(--font-weight-normal)"),
    ("--text-display-2-leading", "1.2571"),
    ("--text-display-3-size", "var(--font-size-3xl)"),
    ("--text-display-3-weight", "var(--font-weight-normal)"),
    ("--text-display-3-leading", "1.2414"),
    ("--text-heading-1-size", "var(--font-size-2xl)"),
    ("--text-heading-1-weight", "var(--font-weight-semibold)"),
    ("--text-heading-1-leading", "1.3333"),
    ("--text-heading-2-size", "var(--font-size-xl)"),
    ("--text-heading-2-weight", "var(--font-weight-semibold)"),
    ("--text-heading-2-leading", "1.4"),
    ("--text-heading-3-size", "var(--font-size-lg)"),
    ("--text-heading-3-weight", "var(--font-weight-semibold)"),
    ("--text-heading-3-leading", "1.4118"),
    ("--text-heading-4-size", "var(--font-size-base)"),
    ("--text-heading-4-weight", "var(--font-weight-semibold)"),
    ("--text-heading-4-leading", "1.4286"),
    ("--text-heading-5-size", "var(--font-size-sm)"),
    ("--text-heading-5-weight", "var(--font-weight-semibold)"),
    ("--text-heading-5-leading", "1.6667"),
    ("--text-heading-6-size", "var(--font-size-xs)"),
    ("--text-heading-6-weight", "var(--font-weight-semibold)"),
    ("--text-heading-6-leading", "1.6"),
    ("--text-large-size", "var(--font-size-lg)"),
    ("--text-large-weight", "var(--font-weight-semibold)"),
    ("--text-large-leading", "1.4118"),
    ("--text-body-size", "var(--font-size-base)"),
    ("--text-body-weight", "var(--font-weight-normal)"),
    ("--text-body-leading", "1.4286"),
    ("--text-label-size", "var(--font-size-base)"),
    ("--text-label-weight", "var(--font-weight-medium)"),
    ("--text-label-leading", "1.4286"),
    ("--text-supporting-size", "var(--font-size-sm)"),
    ("--text-supporting-weight", "var(--font-weight-normal)"),
    ("--text-supporting-leading", "1.6667"),
    ("--font-family-body", "system-ui, 'Segoe UI', Tahoma, Arial, 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif"),
    ("--font-family-display", "system-ui, 'Segoe UI', Arial, 'Microsoft YaHei UI', sans-serif"),
    ("--font-family-mono", "Cascadia Code, Consolas, 'SF Mono', Menlo, 'Microsoft YaHei UI', monospace"),
    ("--text-code-size", "var(--font-size-base)"),
    ("--text-code-weight", "var(--font-weight-normal)"),
    ("--text-code-leading", "1.4286"),
];

// =================================================================
// scale 配置(Astryx 的 radius / typography.scale / motion 生成器)
// =================================================================

/// 三组 scale 参数,默认值 = Astryx `Neutral`。
///
/// 用默认值生成的 token 与 [`BASE_TOKENS`] 逐条等值(有测试兜住),所以这里只做"按参数
/// 重新生成",不引入第二套事实。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Scales {
    /// `radius.base`:半径基准(px,Astryx = 4)
    pub radius_base: f32,
    /// `radius.multiplier`:0–2,1 = Astryx 默认
    pub radius_multiplier: f32,
    /// `typography.scale.base`:字号锚点(px)
    pub text_base: f32,
    /// `typography.scale.ratio`:台阶比(Astryx = 1.2)
    pub text_ratio: f32,
    /// `motion.fast`(ms)
    pub motion_fast_ms: f32,
    /// `motion.medium`(ms)
    pub motion_medium_ms: f32,
    /// `motion.slow`(ms)
    pub motion_slow_ms: f32,
    /// `motion.ratio`:min/max 相对中心的收缩比(Astryx = 0.75)
    pub motion_ratio: f32,
}

impl Default for Scales {
    fn default() -> Self {
        Self {
            radius_base: 4.0,
            radius_multiplier: 1.0,
            text_base: 14.0,
            text_ratio: 1.2,
            motion_fast_ms: 175.0,
            motion_medium_ms: 410.0,
            motion_slow_ms: 975.0,
            motion_ratio: 0.75,
        }
    }
}

/// `12px` 形式的长度字符串(整数值不留小数点,避免与基表字面量无谓漂移)。
fn px(value: f32) -> String {
    let rounded = value.round();
    if (value - rounded).abs() < 0.005 {
        format!("{rounded:.0}px")
    } else {
        format!("{value:.2}px")
    }
}

/// duration 的 min/max 就近取到 10ms 整数倍(Astryx 的 duration 表都是整十)。
fn ms10(value: f32) -> f32 {
    (value / 10.0).round() * 10.0
}

impl Scales {
    /// 需要按参数重算的 token 字面量。
    ///
    /// 半径只生成 `inner` / `element` / `container` / `page` / `chat`(Astryx 同);
    /// `none` 恒为 0、`full` 恒为 9999px,倍率不该动它们。
    fn generate(&self) -> Vec<(&'static str, String)> {
        let mut out = Vec::new();
        let unit = self.radius_base * self.radius_multiplier;
        for (token, factor) in [
            (LengthToken::RadiusInner, 1.0),
            (LengthToken::RadiusElement, 2.0),
            (LengthToken::RadiusContainer, 3.0),
            (LengthToken::RadiusPage, 7.0),
            (LengthToken::RadiusChat, 7.0),
        ] {
            out.push((token.as_str(), px(unit * factor)));
        }
        for token in FontSizeToken::ALL {
            let size = self.text_base * self.text_ratio.powi(token.step());
            out.push((token.as_str(), px(size.round())));
        }
        for (center, name, min_name, max_name) in [
            (self.motion_fast_ms, "--duration-fast", "--duration-fast-min", "--duration-fast-max"),
            (self.motion_medium_ms, "--duration-medium", "--duration-medium-min", "--duration-medium-max"),
            (self.motion_slow_ms, "--duration-slow", "--duration-slow-min", "--duration-slow-max"),
        ] {
            out.push((name, format!("{center:.0}ms")));
            out.push((min_name, format!("{:.0}ms", ms10(center * self.motion_ratio))));
            out.push((max_name, format!("{:.0}ms", ms10(center / self.motion_ratio))));
        }
        out
    }
}

// =================================================================
// 覆盖层
// =================================================================

/// 按 Astryx 变量名记录的 token 覆盖。
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TokenOverrides {
    entries: BTreeMap<String, String>,
}

impl TokenOverrides {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// 记录一条覆盖;值先过一遍形状校验,写错立刻报错(而不是到 paint 期才发现)。
    pub fn set(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
        let name = name.trim();
        let kind = kind_of(name).ok_or_else(|| TokenError::UnknownName(name.to_string()))?;
        let atom = parse_atom(value.trim());
        let shaped = match kind {
            Kind::Color => matches!(atom, Atom::Color(_) | Atom::Ref { .. } | Atom::LightDark(..)),
            Kind::Number => matches!(atom, Atom::Num(_) | Atom::Ref { .. } | Atom::LightDark(..)),
            // 阴影、缓动与字体栈按原文保留,解析失败只会在 resolve 时退化
            Kind::Shadow | Kind::Easing | Kind::FontStack => true,
        };
        if !shaped {
            return Err(TokenError::BadValue { name: name.to_string(), value: value.to_string() });
        }
        self.entries.insert(name.to_string(), value.trim().to_string());
        Ok(())
    }

    pub fn get(&self, name: &str) -> Option<&str> {
        self.entries.get(name).map(String::as_str)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.entries.iter().map(|(key, value)| (key.as_str(), value.as_str()))
    }
}

/// token 覆盖的错误。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TokenError {
    /// 不认识的变量名(mgui 实现的是 Astryx 核心 token 集,见模块文档)
    UnknownName(String),
    /// 值的形状与该 token 的类型不符
    BadValue { name: String, value: String },
}

impl fmt::Display for TokenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownName(name) => write!(f, "未知的主题 token 名: {name}"),
            Self::BadValue { name, value } => write!(f, "token {name} 的值无法解析: {value}"),
        }
    }
}

impl std::error::Error for TokenError {}

// =================================================================
// 主题定义(Astryx `defineTheme` 的对应物)
// =================================================================

/// 一份主题定义:基表 + scale + 覆盖。
///
/// 只描述"改了什么",不预先算结果 —— [`ThemeDefinition::resolve`] 才是实际取值,
/// 所以一份定义可以同时服务明暗两档。
#[derive(Clone, Debug, PartialEq)]
pub struct ThemeDefinition {
    ident: String,
    scales: Scales,
    overrides: TokenOverrides,
}

/// 以 Astryx `Neutral` 为基底开一份主题定义。
pub fn define_theme() -> ThemeDefinition {
    ThemeDefinition { ident: "neutral".to_string(), scales: Scales::default(), overrides: TokenOverrides::new() }
}

impl ThemeDefinition {
    /// 主题名(Astryx `defineTheme({ name })`)。
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.ident = name.into();
        self
    }

    pub fn name(&self) -> &str {
        &self.ident
    }

    /// 半径倍率(Astryx `radius.multiplier`,0–2)。`--radius-none` / `--radius-full` 不受影响。
    pub fn radius_multiplier(mut self, multiplier: f32) -> Self {
        self.scales.radius_multiplier = multiplier.clamp(0.0, 2.0);
        self
    }

    /// 半径基准(Astryx `radius.base`,px)。
    pub fn radius_base(mut self, base: f32) -> Self {
        self.scales.radius_base = base.max(0.0);
        self
    }

    /// 字号锚点 + 台阶比(Astryx `typography.scale`)。
    pub fn text_scale(mut self, base: f32, ratio: f32) -> Self {
        self.scales.text_base = base.max(1.0);
        self.scales.text_ratio = ratio.clamp(1.01, 2.0);
        self
    }

    /// 动效节奏(Astryx `motion`;单位 ms,min/max 按 `ratio` 生成)。
    pub fn motion_scale(mut self, fast_ms: f32, medium_ms: f32, slow_ms: f32, ratio: f32) -> Self {
        self.scales.motion_fast_ms = fast_ms.max(0.0);
        self.scales.motion_medium_ms = medium_ms.max(0.0);
        self.scales.motion_slow_ms = slow_ms.max(0.0);
        self.scales.motion_ratio = ratio.clamp(0.1, 1.0);
        self
    }

    pub fn scales(&self) -> Scales {
        self.scales
    }

    /// 覆盖单个 token(Astryx 变量名 + 字面量)。
    pub fn token(mut self, name: &str, value: &str) -> Result<Self, TokenError> {
        self.overrides.set(name, value)?;
        Ok(self)
    }

    /// [`ThemeDefinition::token`] 的 `&mut self` 版本 —— 循环里构造主题时不用来回搬 `self`。
    pub fn set_token(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
        self.overrides.set(name, value)
    }

    /// [`ThemeDefinition::color`] 的 `&mut self` 版本。
    pub fn set_color(&mut self, token: ColorToken, light: Color, dark: Color) {
        let value = format!("light-dark({}, {})", hex_of(light), hex_of(dark));
        // 值由本方法拼装,形状必然合法
        let _ = self.overrides.set(token.as_str(), &value);
    }

    /// 覆盖 color token 的便捷写法:明暗两档分别给 `Color`。
    pub fn color(mut self, token: ColorToken, light: Color, dark: Color) -> Self {
        self.set_color(token, light, dark);
        self
    }

    pub fn tokens(mut self, overrides: TokenOverrides) -> Self {
        self.overrides = overrides;
        self
    }

    pub fn overrides(&self) -> &TokenOverrides {
        &self.overrides
    }

    /// 解析成某个明暗档下的实际 token 取值。
    pub fn resolve(&self, dark: bool) -> Tokens {
        Tokens::resolve(self, dark)
    }
}

/// `Color` → Astryx 颜色字面量(`#RRGGBB`,带 alpha 时写 8 位)。
fn hex_of(color: Color) -> String {
    let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
    let (r, g, b) = (channel(color.r), channel(color.g), channel(color.b));
    if color.a >= 0.999 {
        format!("#{r:02X}{g:02X}{b:02X}")
    } else {
        format!("#{r:02X}{g:02X}{b:02X}{:02X}", channel(color.a))
    }
}

// =================================================================
// 解析
// =================================================================

/// 字面量表(变量名 → 原文):基表已被 scale 与覆盖改写过。
struct TokenTable {
    sources: BTreeMap<String, String>,
}

/// `var()` 展开深度上限,用来兜住成环引用。
const MAX_REF_DEPTH: u32 = 12;

impl TokenTable {
    fn build(definition: &ThemeDefinition) -> Self {
        let mut sources: BTreeMap<String, String> =
            BASE_TOKENS.iter().map(|(name, value)| ((*name).to_string(), (*value).to_string())).collect();
        for (name, value) in definition.scales.generate() {
            sources.insert(name.to_string(), value);
        }
        for (name, value) in definition.overrides.iter() {
            sources.insert(name.to_string(), value.to_string());
        }
        Self { sources }
    }

    fn source(&self, name: &str) -> Option<&str> {
        self.sources.get(name).map(String::as_str)
    }

    /// 取字面量并展开成单值。
    fn expand(&self, text: &str, dark: bool, depth: u32) -> Option<Atom> {
        self.expand_atom(&parse_atom(text), dark, depth)
    }

    /// 按明暗档选一边、按 `var()` 追引用;成环或断链返回 `None`。
    fn expand_atom(&self, atom: &Atom, dark: bool, depth: u32) -> Option<Atom> {
        if depth > MAX_REF_DEPTH {
            return None;
        }
        match atom {
            Atom::LightDark(light, dark_value) => {
                let chosen = if dark { dark_value } else { light };
                self.expand_atom(chosen, dark, depth + 1)
            }
            Atom::Ref { name, fallback } => match self.source(name) {
                Some(source) => self.expand(source, dark, depth + 1),
                None => match fallback {
                    Some(atom) => self.expand_atom(atom, dark, depth + 1),
                    None => None,
                },
            },
            other => Some(other.clone()),
        }
    }

    fn color(&self, name: &str, dark: bool) -> Option<Color> {
        self.color_from_source(self.source(name)?, dark)
    }

    /// 阴影里的颜色段可能是 `light-dark(...)` / `var(--color-shadow)` / 直接 hex。
    fn color_from_source(&self, text: &str, dark: bool) -> Option<Color> {
        match self.expand(text, dark, 0)? {
            Atom::Color(color) => Some(color),
            _ => None,
        }
    }

    fn number(&self, name: &str, dark: bool) -> Option<f32> {
        match self.expand(self.source(name)?, dark, 0)? {
            Atom::Num(value) => Some(value),
            _ => None,
        }
    }

    fn easing(&self, name: &str, dark: bool) -> Option<[f32; 4]> {
        let Atom::Text(text) = self.expand(self.source(name)?, dark, 0)? else {
            return None;
        };
        let lower = text.to_ascii_lowercase();
        let inner = strip_call(&lower, "cubic-bezier")?;
        let parts: Vec<f32> = inner.split(',').filter_map(|part| part.trim().parse::<f32>().ok()).collect();
        if parts.len() != 4 {
            return None;
        }
        let mut points = [0.0f32; 4];
        points.copy_from_slice(&parts);
        Some(points)
    }
}

// =================================================================
// 解析结果
// =================================================================

/// 一个 token 在某个明暗档下的实际取值。
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Color(Color),
    /// 长度(px) / 时长(秒) / 字号(px) / 字重与行高(无单位)
    Number(f32),
    Shadow(Shadow),
    /// 三次贝塞尔控制点
    Easing([f32; 4]),
    Text(Rc<str>),
}

/// 文本角色解析结果。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextRoleStyle {
    pub size: f32,
    pub weight: f32,
    pub leading: f32,
}

/// 一份主题在某一明暗档下的全部实际取值。
#[derive(Clone, Debug, PartialEq)]
pub struct Tokens {
    ident: Rc<str>,
    dark: bool,
    scales: Scales,
    values: BTreeMap<String, Value>,
}

impl Tokens {
    fn resolve(definition: &ThemeDefinition, dark: bool) -> Self {
        let table = TokenTable::build(definition);
        let mut values: BTreeMap<String, Value> = BTreeMap::new();
        for name in table.sources.keys() {
            let value = match kind_of(name) {
                Some(Kind::Color) => Value::Color(table.color(name, dark).unwrap_or(Color::TRANSPARENT)),
                Some(Kind::Number) => Value::Number(table.number(name, dark).unwrap_or(0.0)),
                Some(Kind::Shadow) => Value::Shadow(parse_shadow(table.source(name).unwrap_or_default(), &table, dark)),
                Some(Kind::Easing) => match table.easing(name, dark) {
                    Some(points) => Value::Easing(points),
                    None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
                },
                Some(Kind::FontStack) | None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
            };
            values.insert(name.clone(), value);
        }
        Self { ident: Rc::from(definition.name()), dark, scales: definition.scales(), values }
    }

    /// 主题名(Astryx `defineTheme({ name })`)。
    pub fn name(&self) -> &str {
        &self.ident
    }

    pub fn is_dark(&self) -> bool {
        self.dark
    }

    pub fn scales(&self) -> Scales {
        self.scales
    }

    /// 按变量名原文读任意 token(DevTools / showcase 用)。
    pub fn value(&self, name: &str) -> Option<&Value> {
        self.values.get(name)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.values.iter().map(|(key, value)| (key.as_str(), value))
    }

    fn number(&self, name: &str, fallback: f32) -> f32 {
        match self.value(name) {
            Some(Value::Number(value)) => *value,
            _ => fallback,
        }
    }

    /// CSS 字体栈原文(`--font-family-*`)。交给 `mgui-text` 的 shaped-line API 消费;
    /// 字体栈 hash 已进入 shape 缓存 key,切换不会串缓存。
    pub fn font_stack(&self, token: FontFamilyToken) -> &str {
        match self.value(token.as_str()) {
            Some(Value::Text(text)) => text,
            _ => "",
        }
    }

    pub fn color(&self, token: ColorToken) -> Color {
        match self.value(token.as_str()) {
            Some(Value::Color(color)) => *color,
            _ => Color::TRANSPARENT,
        }
    }

    pub fn length(&self, token: LengthToken) -> f32 {
        self.number(token.as_str(), 0.0)
    }

    pub fn spacing(&self, step: SpacingStep) -> f32 {
        self.number(step.as_str(), 0.0)
    }

    pub fn duration(&self, token: DurationToken) -> f32 {
        self.number(token.as_str(), 0.0)
    }

    pub fn font_size(&self, token: FontSizeToken) -> f32 {
        self.number(token.as_str(), self.scales.text_base)
    }

    pub fn font_weight(&self, token: FontWeightToken) -> f32 {
        self.number(token.as_str(), 400.0)
    }

    pub fn shadow(&self, token: ShadowToken) -> Shadow {
        match self.value(token.as_str()) {
            Some(Value::Shadow(shadow)) => shadow.clone(),
            _ => Shadow::default(),
        }
    }

    pub fn easing(&self, token: EasingToken) -> [f32; 4] {
        match self.value(token.as_str()) {
            Some(Value::Easing(points)) => *points,
            _ => [0.24, 1.0, 0.4, 1.0],
        }
    }

    pub fn text_role(&self, role: TextRole) -> TextRoleStyle {
        TextRoleStyle {
            size: self.number(&role.size_name(), self.font_size(FontSizeToken::Base)),
            weight: self.number(&role.weight_name(), 400.0),
            leading: self.number(&role.leading_name(), 1.4),
        }
    }

    /// 边框宽度(`--border-width`)。
    pub fn border_width(&self) -> f32 {
        self.length(LengthToken::BorderWidth)
    }

    pub fn focus(&self) -> FocusTokens {
        FocusTokens {
            width: self.length(LengthToken::FocusOutlineWidth),
            offset: self.length(LengthToken::FocusOutlineOffset),
            color: self.color(ColorToken::FocusOutline),
        }
    }

    pub fn radius(&self) -> RadiusTokens {
        RadiusTokens {
            none: self.length(LengthToken::RadiusNone),
            inner: self.length(LengthToken::RadiusInner),
            element: self.length(LengthToken::RadiusElement),
            container: self.length(LengthToken::RadiusContainer),
            page: self.length(LengthToken::RadiusPage),
            chat: self.length(LengthToken::RadiusChat),
            full: self.length(LengthToken::RadiusFull),
        }
    }

    /// 控件三档高度(`--size-element-sm/md/lg`)。
    pub fn element_size(&self) -> SizeTokens {
        SizeTokens {
            sm: self.length(LengthToken::SizeElementSm),
            md: self.length(LengthToken::SizeElementMd),
            lg: self.length(LengthToken::SizeElementLg),
        }
    }

    /// `base` 上盖 `--color-overlay-hover`。
    pub fn hovered(&self, base: Color) -> Color {
        overlay(base, self.color(ColorToken::OverlayHover))
    }

    /// `base` 上盖 `--color-overlay-pressed`。
    pub fn pressed(&self, base: Color) -> Color {
        overlay(base, self.color(ColorToken::OverlayPressed))
    }

    /// 全部颜色 token 的当前值(showcase / DevTools 的 token 表格用)。
    pub fn color_rows(&self) -> Vec<(&'static str, Color)> {
        ColorToken::ALL.iter().map(|token| (token.as_str(), self.color(*token))).collect()
    }
}

/// 焦点环打包(宽度 / 外扩 / 颜色)。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FocusTokens {
    pub width: f32,
    pub offset: f32,
    pub color: Color,
}

/// 圆角打包。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadiusTokens {
    pub none: f32,
    pub inner: f32,
    pub element: f32,
    pub container: f32,
    pub page: f32,
    pub chat: f32,
    pub full: f32,
}

/// 控件三档尺寸。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SizeTokens {
    pub sm: f32,
    pub md: f32,
    pub lg: f32,
}

/// 叠加色合成:把带 alpha 的 token(hover / pressed / overlay)盖在底色上。
///
/// Astryx 的 hover / pressed 是"叠加层"而不是"另一个色值",桌面绘制要先合成再填。
pub fn overlay(base: Color, top: Color) -> Color {
    if top.a >= 1.0 {
        return top;
    }
    let keep = 1.0 - top.a;
    Color {
        r: top.r * top.a + base.r * keep,
        g: top.g * top.a + base.g * keep,
        b: top.b * top.a + base.b * keep,
        a: base.a + top.a * (1.0 - base.a),
    }
}

// =================================================================
// 测试
// =================================================================

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

    /// WCAG 对比度(断言用)。
    fn luminance(color: Color) -> f32 {
        let channel = |v: f32| {
            if v <= 0.04045 {
                v / 12.92
            } else {
                ((v + 0.055) / 1.055).powf(2.4)
            }
        };
        0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
    }

    fn contrast(a: Color, b: Color) -> f32 {
        let (la, lb) = (luminance(a), luminance(b));
        let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
        (hi + 0.05) / (lo + 0.05)
    }

    #[test]
    fn parses_color_shapes() {
        let table = TokenTable::build(&define_theme());
        let cases = [
            ("#0064E0", Color::from_rgb8(0x00, 0x64, 0xE0)),
            ("#abc", Color::from_rgb8(0xAA, 0xBB, 0xCC)),
            ("#0536590C", Color::from_rgba8(0x05, 0x36, 0x59, 0x0C)),
            ("rgba(5, 54, 89, 0.1)", Color::rgba(5.0 / 255.0, 54.0 / 255.0, 89.0 / 255.0, 0.1)),
            ("black", Color::BLACK),
            ("white", Color::WHITE),
            ("light-dark(#111111, #EEEEEE)", Color::from_rgb8(0x11, 0x11, 0x11)),
        ];
        for (text, expect) in cases {
            let light = table.color_from_source(text, false).unwrap_or_else(|| panic!("解析失败: {text}"));
            assert_eq!(light, expect, "明档 {text}");
        }
        let dark = table.color_from_source("light-dark(#111111, #EEEEEE)", true).unwrap();
        assert_eq!(dark, Color::from_rgb8(0xEE, 0xEE, 0xEE), "暗档取第二边");
    }

    #[test]
    fn font_family_tokens_resolve_css_stacks() {
        let tokens = define_theme().resolve(true);
        for role in FontFamilyToken::ALL {
            let stack = tokens.font_stack(*role);
            assert!(!stack.is_empty(), "{} 应有 CSS 字体栈", role.as_str());
            assert!(stack.contains("sans-serif") || stack.contains("monospace"), "{stack}");
        }
        let custom =
            define_theme().token("--font-family-body", "'My Font', sans-serif").expect("token override").resolve(false);
        assert_eq!(custom.font_stack(FontFamilyToken::Body), "'My Font', sans-serif");
    }

    #[test]
    fn leading_values_are_positive_numbers() {
        let tokens = define_theme().resolve(false);
        for role in TextRole::ALL {
            let style = tokens.text_role(*role);
            assert!(style.leading > 0.0 && style.leading.is_finite(), "{role:?} leading={}", style.leading);
        }
    }

    #[test]
    fn parses_units() {
        assert_eq!(parse_atom("8px"), Atom::Num(8.0));
        assert_eq!(parse_atom("1.0625rem"), Atom::Num(17.0));
        assert_eq!(parse_atom("175ms"), Atom::Num(0.175));
        assert_eq!(parse_atom("1.4286"), Atom::Num(1.4286));
        assert_eq!(parse_atom("400"), Atom::Num(400.0));
        assert_eq!(parse_atom("#0064E0"), Atom::Color(Color::from_rgb8(0x00, 0x64, 0xE0)));
    }

    #[test]
    fn neutral_defaults_match_astryx() {
        let light = define_theme().resolve(false);
        let dark = define_theme().resolve(true);
        assert_eq!(light.color(ColorToken::Accent), Color::from_rgb8(0x00, 0x64, 0xE0));
        assert_eq!(dark.color(ColorToken::Accent), Color::from_rgb8(0x26, 0x94, 0xFE));
        assert_eq!(light.color(ColorToken::TextPrimary), Color::from_rgb8(0x0A, 0x13, 0x17));
        assert_eq!(dark.color(ColorToken::BackgroundBody), Color::from_rgb8(0x11, 0x11, 0x12));
        assert_eq!(light.length(LengthToken::RadiusElement), 8.0);
        assert_eq!(light.length(LengthToken::SizeElementMd), 32.0);
        assert_eq!(light.length(LengthToken::RadiusFull), 9999.0);
        assert_eq!(light.font_size(FontSizeToken::Base), 14.0);
        assert_eq!(light.font_size(FontSizeToken::FiveXl), 42.0);
        assert_eq!(light.font_size(FontSizeToken::FourXs), 6.0);
        assert_eq!(light.spacing(SpacingStep::S4), 16.0);
        assert_eq!(light.spacing(SpacingStep::S1_5), 6.0);
        assert!((light.duration(DurationToken::Fast) - 0.175).abs() < 1e-6);
        assert_eq!(light.font_weight(FontWeightToken::Semibold), 600.0);
        assert_eq!(light.text_role(TextRole::HeadingOne).size, 24.0);
        assert_eq!(light.text_role(TextRole::HeadingOne).weight, 600.0);
        assert_eq!(light.text_role(TextRole::Body).size, 14.0);
        assert_eq!(light.text_role(TextRole::Supporting).size, 12.0);
        assert_eq!(light.easing(EasingToken::Standard), [0.24, 1.0, 0.4, 1.0]);
        assert_eq!(light.easing(EasingToken::Exit), [0.3, 0.0, 0.6, 0.6]);
        assert_eq!(light.name(), "neutral");
    }

    #[test]
    fn scale_generation_reproduces_neutral_base() {
        // scale 默认参数必须逐条还原基表取值,否则等于引入第二套事实
        let base: BTreeMap<&str, &str> = BASE_TOKENS.iter().copied().collect();
        let generated = Scales::default().generate();
        assert!(!generated.is_empty());
        for (name, value) in &generated {
            let literal = base.get(*name).unwrap_or_else(|| panic!("基表缺少 {name}"));
            assert_eq!(&parse_atom(value), &parse_atom(literal), "scale 默认值改变了 {name}");
        }
        // 显式覆盖仍然优先于 scale 生成
        let overridden =
            define_theme().radius_multiplier(2.0).token("--radius-element", "10px").unwrap().resolve(false);
        assert_eq!(overridden.length(LengthToken::RadiusElement), 10.0);
        assert_eq!(overridden.length(LengthToken::RadiusContainer), 24.0);
    }

    #[test]
    fn radius_multiplier_scales_named_radii_but_not_none_or_full() {
        let tokens = define_theme().radius_multiplier(1.5).resolve(false);
        assert_eq!(tokens.length(LengthToken::RadiusInner), 6.0);
        assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
        assert_eq!(tokens.length(LengthToken::RadiusContainer), 18.0);
        assert_eq!(tokens.length(LengthToken::RadiusPage), 42.0);
        assert_eq!(tokens.length(LengthToken::RadiusNone), 0.0, "0 不该被放大");
        assert_eq!(tokens.length(LengthToken::RadiusFull), 9999.0, "完全圆不该被放大");
        assert_eq!(tokens.radius().element, 12.0);
    }

    #[test]
    fn text_and_motion_scales_move_the_whole_ladder() {
        let tokens = define_theme().text_scale(16.0, 1.25).resolve(false);
        assert_eq!(tokens.font_size(FontSizeToken::Base), 16.0);
        assert_eq!(tokens.font_size(FontSizeToken::Lg), 20.0);
        // 角色通过 var() 引用阶梯,所以自动跟
        assert_eq!(tokens.text_role(TextRole::Body).size, 16.0);
        assert_eq!(tokens.text_role(TextRole::HeadingOne).size, 31.0);

        let slow = define_theme().motion_scale(200.0, 500.0, 1000.0, 0.8).resolve(false);
        assert!((slow.duration(DurationToken::Fast) - 0.2).abs() < 1e-6);
        assert!((slow.duration(DurationToken::FastMin) - 0.16).abs() < 1e-6);
        assert!((slow.duration(DurationToken::FastMax) - 0.25).abs() < 1e-6);
        assert!((slow.duration(DurationToken::Slow) - 1.0).abs() < 1e-6);
    }

    #[test]
    fn overriding_accent_also_moves_the_focus_ring() {
        // --focus-outline-color 是 var(--color-accent)
        let tokens = define_theme().token("--color-accent", "#7B61FF").unwrap().resolve(false);
        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x7B, 0x61, 0xFF));
        assert_eq!(tokens.focus().color, Color::from_rgb8(0x7B, 0x61, 0xFF));
    }

    #[test]
    fn status_colors_follow_the_hue_chain() {
        // --color-text-error → var(--color-text-red)
        let tokens = define_theme().resolve(true);
        assert_eq!(tokens.color(ColorToken::TextError), tokens.color(ColorToken::TextRed));
        assert_eq!(tokens.color(ColorToken::IconError), tokens.color(ColorToken::TextError));
        assert_eq!(tokens.color(ColorToken::BorderError), tokens.color(ColorToken::TextError));
        // 覆盖链条上的锚点,语义色一起变
        let tokens = define_theme().token("--color-text-red", "#FF0000").unwrap().resolve(false);
        assert_eq!(tokens.color(ColorToken::TextError), Color::from_rgb8(0xFF, 0x00, 0x00));
        assert_eq!(tokens.color(ColorToken::BorderError), Color::from_rgb8(0xFF, 0x00, 0x00));
    }

    #[test]
    fn override_beats_base_for_both_modes() {
        let def = define_theme().token("--color-background-surface", "light-dark(#111111, #EEEEEE)").unwrap();
        assert_eq!(def.resolve(false).color(ColorToken::BackgroundSurface), Color::from_rgb8(0x11, 0x11, 0x11));
        assert_eq!(def.resolve(true).color(ColorToken::BackgroundSurface), Color::from_rgb8(0xEE, 0xEE, 0xEE));
    }

    #[test]
    fn color_helper_writes_two_variants() {
        let tokens = define_theme()
            .color(ColorToken::Accent, Color::from_rgb8(0x10, 0x20, 0x30), Color::from_rgb8(0xF0, 0xE0, 0xD0))
            .resolve(false);
        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x10, 0x20, 0x30));
        assert_eq!(tokens.color(ColorToken::FocusOutline), Color::from_rgb8(0x10, 0x20, 0x30));
        assert_eq!(hex_of(Color::from_rgb8(0x10, 0x20, 0x30)), "#102030");
    }

    #[test]
    fn bad_token_names_and_values_are_rejected() {
        assert!(matches!(define_theme().token("--color-nope", "#fff"), Err(TokenError::UnknownName(_))));
        assert!(matches!(define_theme().token("--radius-element", "not-a-length"), Err(TokenError::BadValue { .. })));
        assert!(matches!(define_theme().token("--color-accent", "8px"), Err(TokenError::BadValue { .. })));
        assert!(matches!(define_theme().token("--font-size-base", "#FFFFFF"), Err(TokenError::BadValue { .. })));
    }

    /// 逐枚举检查基表覆盖情况(不同 token 枚举没法直接 chain 起来)。
    macro_rules! assert_tokens_present {
        ($tokens:expr, $($enum:ident),* $(,)?) => {
            $(
                for token in $enum::ALL {
                    assert!(
                        $tokens.value(token.as_str()).is_some(),
                        "基表缺少 token {}",
                        token.as_str()
                    );
                }
            )*
        };
    }

    #[test]
    fn every_typed_token_has_a_base_value() {
        // 基表漏一个 token,resolve 会静默给透明 / 0 —— 这里兜住
        let tokens = define_theme().resolve(false);
        assert_tokens_present!(
            tokens,
            ColorToken,
            LengthToken,
            SpacingStep,
            DurationToken,
            FontSizeToken,
            FontWeightToken,
            ShadowToken,
            EasingToken,
        );
        for role in TextRole::ALL {
            for name in [role.size_name(), role.weight_name(), role.leading_name()] {
                assert!(tokens.value(&name).is_some(), "基表缺少 {name}");
            }
        }
    }

    #[test]
    fn every_base_token_name_is_known_to_the_override_layer() {
        let mut unknown = Vec::new();
        for (name, _) in BASE_TOKENS {
            if kind_of(name).is_none() {
                unknown.push(*name);
            }
        }
        assert!(unknown.is_empty(), "覆盖层不认识的基表名: {unknown:?}");
    }

    #[test]
    fn shadows_are_multi_layer_with_mode_specific_colors() {
        let light = define_theme().resolve(false);
        let dark = define_theme().resolve(true);
        let low = light.shadow(ShadowToken::Low);
        assert_eq!(low.layers.len(), 2);
        let first = low.first().unwrap();
        assert_eq!((first.offset_x, first.offset_y, first.blur, first.spread), (0.0, 1.0, 1.0, 0.0));
        assert!(!first.inset);
        assert_eq!(first.color, Color::rgba(0.0, 0.0, 0.0, 0.1));
        assert_eq!(dark.shadow(ShadowToken::Low).first().unwrap().color, Color::rgba(0.0, 0.0, 0.0, 0.2));
        let ring = light.shadow(ShadowToken::InsetHover).ring().expect("inset 描边环");
        assert!(ring.inset && ring.blur == 0.0 && ring.spread == 2.0);
        assert!(light.shadow(ShadowToken::Low).ring().is_none());
    }

    #[test]
    fn shadow_can_reference_color_shadow_token() {
        let mut overrides = TokenOverrides::new();
        overrides.set("--shadow-low", "0px 2px 4px var(--color-shadow)").unwrap();
        let tokens = define_theme().tokens(overrides).resolve(true);
        let layer = tokens.shadow(ShadowToken::Low).first().unwrap();
        assert_eq!(layer.color, tokens.color(ColorToken::Shadow));
        assert_eq!(layer.blur, 4.0);
    }

    #[test]
    fn overlay_helpers_composite_alpha_tokens() {
        for dark in [false, true] {
            let tokens = define_theme().resolve(dark);
            let base = tokens.color(ColorToken::BackgroundSurface);
            let hover = tokens.hovered(base);
            let pressed = tokens.pressed(base);
            assert!(hover.a > 0.99, "叠加后仍是不透明底色");
            assert_ne!(hover, base, "hover 必须看得见");
            assert_ne!(hover, pressed, "hover 与 pressed 不同档");
            // pressed 比 hover 更强
            let strength = |a: Color, b: Color| (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs();
            assert!(strength(base, pressed) > strength(base, hover), "dark={dark}");
        }
    }

    #[test]
    fn neutral_text_on_surface_meets_aa_contrast() {
        for dark in [false, true] {
            let tokens = define_theme().resolve(dark);
            let on_surface =
                contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundSurface));
            assert!(on_surface >= 4.5, "正文/表面 对比度 {on_surface:.2} < 4.5 (dark={dark})");
            let on_body = contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundBody));
            assert!(on_body >= 4.5, "正文/画布 对比度 {on_body:.2} < 4.5 (dark={dark})");
            let secondary =
                contrast(tokens.color(ColorToken::TextSecondary), tokens.color(ColorToken::BackgroundSurface));
            assert!(secondary >= 4.5, "次要文本/表面 对比度 {secondary:.2} < 4.5 (dark={dark})");
        }
    }

    #[test]
    fn ref_cycles_and_unknown_refs_fall_back_without_panicking() {
        let mut overrides = TokenOverrides::new();
        overrides.set("--color-accent", "var(--color-accent)").unwrap();
        overrides.set("--color-text-red", "var(--nope)").unwrap();
        let tokens = define_theme().tokens(overrides).resolve(false);
        // 成环 → 透明;断链 → 透明;都不 panic
        assert_eq!(tokens.color(ColorToken::Accent), Color::TRANSPARENT);
        assert_eq!(tokens.color(ColorToken::TextError), Color::TRANSPARENT);
        // var() 的回退值会被用上
        let mut overrides = TokenOverrides::new();
        overrides.set("--color-accent", "var(--nope, #123456)").unwrap();
        let tokens = define_theme().tokens(overrides).resolve(false);
        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x12, 0x34, 0x56));
    }
}