native-theme 0.7.0

Cross-platform native theme detection and loading for Rust GUI applications
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
// Theme model: ThemeMode and Theme, plus sub-module re-exports

/// Light or dark color mode preference.
///
/// Used by [`SystemTheme`](crate::SystemTheme) to indicate the OS color
/// mode and by [`SystemTheme::pick()`](crate::SystemTheme::pick) to select
/// a resolved variant.
///
/// # Examples
///
/// ```
/// use native_theme::theme::ColorMode;
///
/// let mode = ColorMode::Dark;
/// assert!(mode.is_dark());
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ColorMode {
    /// Light appearance.
    Light,
    /// Dark appearance.
    Dark,
}

impl ColorMode {
    /// Returns `true` if this is dark mode.
    #[must_use]
    pub fn is_dark(self) -> bool {
        matches!(self, Self::Dark)
    }
}

/// Animated icon types (frame sequences and transforms).
pub(crate) mod animated;
/// Disclosure arrow placement convention.
pub(crate) mod arrow_side;
/// Border specification sub-struct for widget border properties.
pub(crate) mod border;
/// Bundled SVG icon lookup tables.
pub(crate) mod bundled;
/// Global theme defaults shared across widgets.
pub(crate) mod defaults;
/// Dialog entrance motion convention.
pub(crate) mod dialog_entrance_style;
/// Dialog button ordering convention.
pub(crate) mod dialog_order;
/// Per-widget font specification and text scale.
pub(crate) mod font;
/// Per-context icon sizes.
pub(crate) mod icon_sizes;
/// Icon roles, sets, and provider trait.
pub(crate) mod icons;
/// Resolved (non-optional) theme types produced after resolution.
pub(crate) mod resolved;
/// Active-tab indicator placement convention.
pub(crate) mod tab_indicator_side;
/// Per-widget struct pairs and macros.
pub(crate) mod widgets;

pub use animated::{
    AnimatedIcon, EmptyFrameListError, FrameList, FramesData, TransformAnimation, TransformData,
};
pub use arrow_side::ArrowSide;
pub use border::{
    DefaultsBorderSpec, ResolvedDefaultsBorder, ResolvedPadding, ResolvedWidgetBorder,
    WidgetBorderSpec,
};
// Crate-internal; external code uses the per-set loaders in `crate::icons`.
pub(crate) use bundled::{bundled_icon_by_name, bundled_icon_svg};
pub use defaults::ThemeDefaults;
pub use dialog_entrance_style::DialogEntranceStyle;
pub use dialog_order::DialogButtonOrder;
pub use font::{
    FontSize, FontSpec, FontStyle, ResolvedFontSpec, TextScale, TextScaleEntry, intern_font_family,
};
pub use icon_sizes::IconSizes;
pub use icons::{IconData, IconProvider, IconRole, IconSet, RgbaData, icon_name};
pub use resolved::{
    Resolved, ResolvedDefaults, ResolvedIconSizes, ResolvedTextScale, ResolvedTextScaleEntry,
    ResolvedTheme,
};
pub use tab_indicator_side::TabIndicatorSide;
pub use widgets::*; // 27 XxxTheme + ResolvedXxxTheme pairs: 26 per-variant widgets + LayoutTheme

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

/// A single light or dark theme variant containing all visual properties.
///
/// Composes defaults, per-widget structs, and optional text scale into one coherent set.
/// Empty sub-structs are omitted from serialization to keep TOML files clean.
///
/// # Examples
///
/// ```
/// use native_theme::theme::ThemeMode;
/// use native_theme::color::Rgba;
///
/// let mut variant = ThemeMode::default();
/// variant.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
/// variant.defaults.font.family = Some("Inter".into());
/// assert!(!variant.is_empty());
/// ```
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ThemeMode {
    /// Global defaults inherited by all widgets.
    #[serde(default, skip_serializing_if = "ThemeDefaults::is_empty")]
    pub defaults: ThemeDefaults,

    /// Per-role text scale overrides.
    #[serde(default, skip_serializing_if = "TextScale::is_empty")]
    pub text_scale: TextScale,

    /// Window chrome: background, title bar, radius, shadow.
    #[serde(default, skip_serializing_if = "WindowTheme::is_empty")]
    pub window: WindowTheme,

    /// Push button: colors, sizing, spacing, geometry.
    #[serde(default, skip_serializing_if = "ButtonTheme::is_empty")]
    pub button: ButtonTheme,

    /// Single-line and multi-line text input fields.
    #[serde(default, skip_serializing_if = "InputTheme::is_empty")]
    pub input: InputTheme,

    /// Multi-line text field: its own padding; the rest is `input`'s.
    #[serde(default, skip_serializing_if = "TextAreaTheme::is_empty")]
    pub text_area: TextAreaTheme,

    /// Checkbox and radio button indicator geometry.
    #[serde(default, skip_serializing_if = "CheckboxTheme::is_empty")]
    pub checkbox: CheckboxTheme,

    /// Popup and context menu appearance.
    #[serde(default, skip_serializing_if = "MenuTheme::is_empty")]
    pub menu: MenuTheme,

    /// Tooltip popup appearance.
    #[serde(default, skip_serializing_if = "TooltipTheme::is_empty")]
    pub tooltip: TooltipTheme,

    /// Scrollbar colors and geometry.
    #[serde(default, skip_serializing_if = "ScrollbarTheme::is_empty")]
    pub scrollbar: ScrollbarTheme,

    /// Slider control colors and geometry.
    #[serde(default, skip_serializing_if = "SliderTheme::is_empty")]
    pub slider: SliderTheme,

    /// Progress bar colors and geometry.
    #[serde(default, skip_serializing_if = "ProgressBarTheme::is_empty")]
    pub progress_bar: ProgressBarTheme,

    /// Tab bar colors and sizing.
    #[serde(default, skip_serializing_if = "TabTheme::is_empty")]
    pub tab: TabTheme,

    /// Sidebar panel background and foreground colors.
    #[serde(default, skip_serializing_if = "SidebarTheme::is_empty")]
    pub sidebar: SidebarTheme,

    /// Toolbar sizing, spacing, and font.
    #[serde(default, skip_serializing_if = "ToolbarTheme::is_empty")]
    pub toolbar: ToolbarTheme,

    /// Status bar font.
    #[serde(default, skip_serializing_if = "StatusBarTheme::is_empty")]
    pub status_bar: StatusBarTheme,

    /// List and table colors and row geometry.
    #[serde(default, skip_serializing_if = "ListTheme::is_empty")]
    pub list: ListTheme,

    /// Popover / dropdown panel appearance.
    #[serde(default, skip_serializing_if = "PopoverTheme::is_empty")]
    pub popover: PopoverTheme,

    /// Splitter handle width.
    #[serde(default, skip_serializing_if = "SplitterTheme::is_empty")]
    pub splitter: SplitterTheme,

    /// Separator line color.
    #[serde(default, skip_serializing_if = "SeparatorTheme::is_empty")]
    pub separator: SeparatorTheme,

    /// Toggle switch track, thumb, and geometry.
    #[serde(default, skip_serializing_if = "SwitchTheme::is_empty")]
    pub switch: SwitchTheme,

    /// Dialog sizing, spacing, button order, and title font.
    #[serde(default, skip_serializing_if = "DialogTheme::is_empty")]
    pub dialog: DialogTheme,

    /// Spinner / indeterminate progress indicator.
    #[serde(default, skip_serializing_if = "SpinnerTheme::is_empty")]
    pub spinner: SpinnerTheme,

    /// ComboBox / dropdown trigger sizing.
    #[serde(default, skip_serializing_if = "ComboBoxTheme::is_empty")]
    pub combo_box: ComboBoxTheme,

    /// Segmented control sizing.
    #[serde(default, skip_serializing_if = "SegmentedControlTheme::is_empty")]
    pub segmented_control: SegmentedControlTheme,

    /// Card / container colors and geometry.
    #[serde(default, skip_serializing_if = "CardTheme::is_empty")]
    pub card: CardTheme,

    /// Expander / disclosure row geometry.
    #[serde(default, skip_serializing_if = "ExpanderTheme::is_empty")]
    pub expander: ExpanderTheme,

    /// Hyperlink colors and underline setting.
    #[serde(default, skip_serializing_if = "LinkTheme::is_empty")]
    pub link: LinkTheme,
}

impl_merge!(ThemeMode {
    nested {
        defaults, text_scale, window, button, input, text_area, checkbox, menu,
        tooltip, scrollbar, slider, progress_bar, tab, sidebar,
        toolbar, status_bar, list, popover, splitter, separator,
        switch, dialog, spinner, combo_box, segmented_control,
        card, expander, link
    }
});

/// A complete native theme with a name and optional light/dark variants.
///
/// This is the top-level type that theme files deserialize into and that
/// platform readers produce.
///
/// # Examples
///
/// ```
/// use native_theme::theme::Theme;
///
/// // Load a bundled preset
/// let theme = Theme::preset("dracula").unwrap();
/// assert_eq!(theme.name, "Dracula");
///
/// // Parse from a TOML string
/// let toml = r##"
/// name = "Custom"
/// [light.defaults]
/// accent_color = "#ff6600"
/// "##;
/// let custom = Theme::from_toml(toml).unwrap();
/// assert_eq!(custom.name, "Custom");
///
/// // Merge themes (overlay wins for populated fields)
/// let mut base = Theme::preset("catppuccin-mocha").unwrap();
/// base.merge(&custom);
/// assert_eq!(base.name, "Catppuccin Mocha"); // base name is preserved
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Theme {
    /// Theme name (e.g., "KDE Breeze", "Adwaita", "Windows 11").
    ///
    /// Uses `Cow<'static, str>` so bundled presets can store borrowed
    /// `&'static str` values without per-load `String` allocations.
    /// User-provided names (from TOML files or runtime detection)
    /// are `Cow::Owned`. A TOML file may omit it (an overlay needs no
    /// name: [`merge`](Self::merge) keeps the base's); it is then empty.
    #[serde(default)]
    pub name: Cow<'static, str>,

    /// Light variant of the theme.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub light: Option<ThemeMode>,

    /// Dark variant of the theme.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dark: Option<ThemeMode>,

    /// Layout spacing constants (shared between light and dark variants).
    #[serde(default, skip_serializing_if = "LayoutTheme::is_empty")]
    pub layout: LayoutTheme,

    /// Which icon loading mechanism to use (`Freedesktop`, `Material`, `Lucide`,
    /// `SfSymbols`, `SegoeFluent`). Shared across light and dark variants.
    /// When `None`, filled during resolution from
    /// [`system_icon_set()`](crate::detect::system_icon_set).
    ///
    /// # Examples
    ///
    /// ```
    /// use native_theme::theme::{Theme, IconSet};
    ///
    /// let theme = Theme::preset("material-3")?;
    /// assert_eq!(theme.icon_set, Some(IconSet::Material));
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_set: Option<IconSet>,

    /// Visual icon theme name (shared across light and dark variants).
    ///
    /// Acts as the default when a variant's
    /// [`ThemeDefaults::icon_theme`](crate::model::ThemeDefaults::icon_theme)
    /// is `None`. Variants that need a different icon theme per color mode
    /// (e.g. KDE Plasma: `"breeze"` light / `"breeze-dark"` dark) set the
    /// override on [`ThemeDefaults::icon_theme`].
    ///
    /// Precedence at resolve time:
    /// 1. [`ThemeMode::defaults.icon_theme`](crate::model::ThemeDefaults::icon_theme) — per-variant override (if set)
    /// 2. `Theme::icon_theme` — this field (if set)
    /// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) — runtime
    ///    detection; none where it fails
    ///
    /// See `docs/archive/v0.5.7_gaps.md` §G4 for the design rationale.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_theme: Option<Cow<'static, str>>,
}

impl Default for Theme {
    fn default() -> Self {
        Self {
            name: Cow::Borrowed(""),
            light: None,
            dark: None,
            layout: LayoutTheme::default(),
            icon_set: None,
            icon_theme: None,
        }
    }
}

impl Theme {
    /// Merge an overlay theme into this theme.
    ///
    /// The base name is kept. For each variant (light/dark):
    /// - If both base and overlay have a variant, they are merged recursively.
    /// - If only the overlay has a variant, it is cloned into the base.
    /// - If only the base has a variant (or neither), no change.
    pub fn merge(&mut self, overlay: &Self) {
        // Keep base name (do not overwrite)

        match (&mut self.light, &overlay.light) {
            (Some(base), Some(over)) => base.merge(over),
            (None, Some(over)) => self.light = Some(over.clone()),
            _ => {}
        }

        match (&mut self.dark, &overlay.dark) {
            (Some(base), Some(over)) => base.merge(over),
            (None, Some(over)) => self.dark = Some(over.clone()),
            _ => {}
        }

        self.layout.merge(&overlay.layout);

        if overlay.icon_set.is_some() {
            self.icon_set = overlay.icon_set;
        }

        if overlay.icon_theme.is_some() {
            self.icon_theme.clone_from(&overlay.icon_theme);
        }
    }

    /// Pick the appropriate variant for the given mode, with cross-fallback.
    ///
    /// When `mode` is [`ColorMode::Dark`], prefers `dark` and falls back to `light`.
    /// When `mode` is [`ColorMode::Light`], prefers `light` and falls back to `dark`.
    /// [`resolve`](Self::resolve) records the variant it took in
    /// [`Resolved::mode`], so a fallback is visible after resolution.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoVariant`](crate::Error::NoVariant) if the theme has
    /// no variants at all.
    pub fn pick_variant(&self, mode: ColorMode) -> crate::Result<&ThemeMode> {
        self.pick_variant_with_mode(mode)
            .map(|(_, variant)| variant)
    }

    /// [`pick_variant`](Self::pick_variant), also returning the mode of the
    /// variant it took (`Dark` iff `self.dark` was used).
    pub(crate) fn pick_variant_with_mode(
        &self,
        mode: ColorMode,
    ) -> crate::Result<(ColorMode, &ThemeMode)> {
        let dark = self.dark.as_ref().map(|v| (ColorMode::Dark, v));
        let light = self.light.as_ref().map(|v| (ColorMode::Light, v));
        match mode {
            ColorMode::Dark => dark.or(light),
            ColorMode::Light => light.or(dark),
        }
        .ok_or(crate::Error::NoVariant { mode })
    }

    /// Extract a variant by consuming the theme, avoiding a clone.
    ///
    /// When `mode` is [`ColorMode::Dark`], returns the `dark` variant (falling back to
    /// `light`). When [`ColorMode::Light`], returns `light` (falling back to `dark`).
    ///
    /// Use this when you own the `Theme` and don't need it afterward.
    /// For read-only inspection, use [`pick_variant()`](Self::pick_variant).
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoVariant`](crate::Error::NoVariant) if the theme has
    /// no variants at all.
    ///
    /// # Examples
    ///
    /// ```
    /// use native_theme::theme::ColorMode;
    ///
    /// let theme = native_theme::theme::Theme::preset("dracula")?;
    /// let variant = theme.into_variant(ColorMode::Dark)?;
    /// let resolved = variant.resolve_system()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn into_variant(self, mode: ColorMode) -> crate::Result<ThemeMode> {
        match mode {
            ColorMode::Dark => self.dark.or(self.light),
            ColorMode::Light => self.light.or(self.dark),
        }
        .ok_or(crate::Error::NoVariant { mode })
    }

    /// Resolve this theme for a color mode into a ready-to-render bundle.
    ///
    /// Picks the variant (with cross-fallback), applies inheritance and
    /// validation to produce a [`ResolvedTheme`], and resolves the shared
    /// `icon_set` / `icon_theme` fields. This is the one-call path from a
    /// parsed [`Theme`] to the values a UI framework needs.
    ///
    /// `icon_set` falls back to
    /// [`system_icon_set()`](crate::detect::system_icon_set) when the TOML
    /// omits it. `icon_theme` uses three-tier precedence:
    ///
    /// 1. The picked variant's `defaults.icon_theme` (per-mode override).
    /// 2. [`Theme::icon_theme`] (shared across variants).
    /// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) (runtime
    ///    detect).
    ///
    /// Where no tier gives a name — the TOML states none and detection
    /// fails — [`Resolved::icon_theme`] is `None`; the resolution itself
    /// does not fail over it, and
    /// [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
    /// reason.
    /// [`Resolved::icon_theme_explicit`] reports whether tiers 1 or 2
    /// fired (value came from TOML) versus tier 3 (runtime detection).
    ///
    /// Builds its inputs with
    /// [`ResolutionContext::from_system`](crate::resolve::ResolutionContext::from_system)
    /// on every call, which reads the environment and configuration files.
    /// The font DPI it detects (on Linux by `xrdb -query`, and `xrandr`
    /// where `Xft.dpi` is unset) is cached after the first call until
    /// [`invalidate_caches()`](crate::detect::invalidate_caches). To
    /// resolve several variants or themes with one detection, or with
    /// inputs of your own, build the context once and call
    /// [`resolve_with`](Self::resolve_with).
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::NoVariant`] when the theme has no variants,
    /// or [`crate::Error::ResolutionIncomplete`] /
    /// [`crate::Error::ResolutionInvalid`] when the picked variant cannot
    /// be fully resolved. A value of [`Theme::layout`] out of range is also
    /// [`crate::Error::ResolutionInvalid`].
    ///
    /// # Examples
    ///
    /// ```
    /// use native_theme::theme::{ColorMode, Theme};
    ///
    /// // Theme-level `icon_theme` (tier 2) — applies to both modes.
    /// let material = Theme::preset("material-3")?;
    /// let r = material.resolve(ColorMode::Dark)?;
    /// assert_eq!(r.icon_theme.as_deref(), Some("material"));
    /// assert!(r.icon_theme_explicit);
    ///
    /// // Per-variant `icon_theme` (tier 1) — differs by mode.
    /// let breeze = Theme::preset("kde-breeze")?;
    /// assert_eq!(breeze.resolve(ColorMode::Light)?.icon_theme.as_deref(), Some("breeze"));
    /// assert_eq!(breeze.resolve(ColorMode::Dark)?.icon_theme.as_deref(), Some("breeze-dark"));
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    pub fn resolve(&self, mode: ColorMode) -> crate::Result<Resolved> {
        self.resolve_with(mode, &crate::resolve::ResolutionContext::from_system())
    }

    /// [`resolve`](Self::resolve) with the resolution-time inputs of `ctx`,
    /// whose `icon_theme` is tier 3. It reads nothing from the system: the
    /// font DPI, button order and detected icon theme are `ctx`'s.
    ///
    /// # Errors
    ///
    /// As [`resolve`](Self::resolve).
    ///
    /// # Examples
    ///
    /// ```
    /// use native_theme::resolve::ResolutionContext;
    /// use native_theme::theme::{ColorMode, Theme};
    ///
    /// // One context for both variants; 72 DPI makes a point a pixel.
    /// let ctx = ResolutionContext { font_dpi: 72.0, ..ResolutionContext::for_tests() };
    /// let breeze = Theme::preset("kde-breeze")?;
    /// let light = breeze.resolve_with(ColorMode::Light, &ctx)?;
    /// let dark = breeze.resolve_with(ColorMode::Dark, &ctx)?;
    /// assert_eq!(light.variant.defaults.font.size, 10.0); // `size_pt = 10.0`
    /// assert_eq!(light.icon_theme.as_deref(), Some("breeze"));
    /// assert_eq!(dark.icon_theme.as_deref(), Some("breeze-dark"));
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    pub fn resolve_with(
        &self,
        mode: ColorMode,
        ctx: &crate::resolve::ResolutionContext,
    ) -> crate::Result<Resolved> {
        let (picked_mode, variant_ref) = self.pick_variant_with_mode(mode)?;
        crate::resolve::validate_helpers::check_font_dpi(ctx.font_dpi)?;
        crate::resolve::validate_helpers::check_layout(&self.layout)?;

        let tier1 = variant_ref.defaults.icon_theme.clone();
        let tier2 = self.icon_theme.clone();
        let icon_theme_explicit = tier1.is_some() || tier2.is_some();
        let icon_theme = tier1.or(tier2).or_else(|| ctx.icon_theme.clone());

        let icon_set = self.icon_set.unwrap_or_else(crate::detect::system_icon_set);

        let variant = variant_ref
            .clone()
            .into_resolved(ctx)
            .map_err(|e| e.in_variant(picked_mode))?;

        Ok(Resolved {
            mode: picked_mode,
            variant,
            icon_set,
            icon_theme,
            icon_theme_explicit,
        })
    }

    /// Returns true when the theme states nothing: no variant, no layout
    /// value, no icon set and no icon theme. The name is not checked.
    pub fn is_empty(&self) -> bool {
        self.light.is_none()
            && self.dark.is_none()
            && self.layout.is_empty()
            && self.icon_set.is_none()
            && self.icon_theme.is_none()
    }

    /// Load a bundled theme preset by name.
    ///
    /// Returns the preset as a fully populated [`Theme`] with both
    /// light and dark variants.
    ///
    /// # Errors
    /// Returns [`crate::Error::UnknownPreset`] if the preset name is not recognized.
    ///
    /// # Examples
    /// ```
    /// let theme = native_theme::theme::Theme::preset("catppuccin-mocha")?;
    /// assert!(theme.light.is_some());
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    ///
    /// Bundled preset names are `Cow::Borrowed` (no allocation):
    /// ```
    /// use native_theme::theme::Theme;
    ///
    /// let theme = Theme::preset("dracula")?;
    /// assert!(matches!(theme.name, std::borrow::Cow::Borrowed(_)));
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    pub fn preset(name: &str) -> crate::Result<Self> {
        crate::presets::preset(name)
    }

    /// Parse a TOML string into a [`Theme`].
    ///
    /// # TOML Format
    ///
    /// Theme files use the following structure. Every field is optional,
    /// `name` included --
    /// omit any field you don't need. Unknown fields are silently ignored;
    /// [`lint_toml`](Self::lint_toml) reports them. Hex colors accept
    /// `#RGB`, `#RGBA`, `#RRGGBB` or `#RRGGBBAA` (the `#` is optional). A size carries its unit in its key:
    /// `_px` for logical pixels, and `size_pt` or `size_px` for a font.
    /// A widget border's padding takes one key per side (`padding_top_px`,
    /// `padding_right_px`, `padding_bottom_px`, `padding_left_px`) or one per
    /// axis (`padding_horizontal_px`, `padding_vertical_px`), not both for
    /// the same axis.
    ///
    /// ```
    /// use native_theme::theme::Theme;
    ///
    /// let toml = r##"
    /// name = "My Theme"
    ///
    /// [light.defaults]
    /// accent_color = "#4a90d9"
    /// background_color = "#fafafa"
    /// text_color = "#2e3436"
    /// surface_color = "#ffffff"
    /// muted_color = "#929292"
    /// shadow_color = "#00000018"
    /// danger_color = "#dc3545"
    /// warning_color = "#f0ad4e"
    /// success_color = "#28a745"
    /// info_color = "#4a90d9"
    /// selection_background = "#4a90d9"
    /// selection_text_color = "#ffffff"
    /// link_color = "#2a6cb6"
    /// focus_ring_color = "#4a90d9"
    /// disabled_text_color = "#c0c0c0"
    /// disabled_opacity = 0.5
    ///
    /// [light.defaults.font]
    /// family = "sans-serif"
    /// size_pt = 10.0
    ///
    /// [light.defaults.mono_font]
    /// family = "monospace"
    /// size_pt = 10.0
    ///
    /// [light.defaults.border]
    /// color = "#c0c0c0"
    /// corner_radius_px = 6.0
    /// corner_radius_lg_px = 12.0
    /// line_width_px = 1.0
    /// opacity = 0.15
    /// shadow_enabled = true
    ///
    /// [light.button]
    /// background_color = "#e8e8e8"
    /// min_height_px = 32.0
    ///
    /// [light.button.font]
    /// color = "#2e3436"
    ///
    /// [light.button.border]
    /// padding_horizontal_px = 12.0
    /// padding_vertical_px = 6.0
    ///
    /// [light.tooltip]
    /// background_color = "#2e3436"
    /// max_width_px = 300.0
    ///
    /// [light.tooltip.font]
    /// color = "#f0f0f0"
    ///
    /// ## [dark.*] mirrors the same structure as [light.*]
    /// "##;
    ///
    /// assert!(Theme::lint_toml(toml)?.is_empty());
    /// let theme = Theme::from_toml(toml)?;
    /// let light = theme.light.as_ref();
    /// assert_eq!(light.and_then(|v| v.button.min_height), Some(32.0));
    /// assert_eq!(light.and_then(|v| v.tooltip.max_width), Some(300.0));
    /// assert_eq!(
    ///     light.and_then(|v| v.defaults.border.corner_radius),
    ///     Some(6.0)
    /// );
    /// let button_border = light.and_then(|v| v.button.border.as_ref());
    /// assert_eq!(button_border.and_then(|b| b.padding_left), Some(12.0));
    /// assert_eq!(button_border.and_then(|b| b.padding_bottom), Some(6.0));
    /// # Ok::<(), native_theme::error::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns [`crate::Error::Toml`] if the TOML is invalid.
    ///
    /// # Examples
    /// ```
    /// let toml = r##"
    /// name = "My Theme"
    /// [light.defaults]
    /// accent_color = "#ff0000"
    /// "##;
    /// let theme = native_theme::theme::Theme::from_toml(toml).unwrap();
    /// assert_eq!(theme.name, "My Theme");
    /// ```
    pub fn from_toml(toml_str: &str) -> crate::Result<Self> {
        crate::presets::from_toml(toml_str)
    }

    /// Load a [`Theme`] from a TOML file.
    ///
    /// # Errors
    /// Returns [`crate::Error::Io`] if the file cannot be read, or
    /// [`crate::Error::Toml`] if the TOML content is invalid.
    ///
    /// # Examples
    /// ```no_run
    /// let theme = native_theme::theme::Theme::from_file("my-theme.toml").unwrap();
    /// ```
    pub fn from_file(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
        crate::presets::from_file(path)
    }

    /// List all available bundled presets with structured metadata.
    ///
    /// Returns a static slice of [`PresetInfo`](crate::presets::PresetInfo) entries,
    /// one per bundled preset. Each entry carries the machine-readable key,
    /// human-readable display name, and target platform tags.
    ///
    /// # Examples
    /// ```
    /// let presets = native_theme::theme::Theme::list_presets();
    /// assert_eq!(presets.len(), 17);
    /// assert_eq!(presets[0].key, "kde-breeze");
    /// assert_eq!(presets[0].display_name, "KDE Breeze");
    /// ```
    #[must_use]
    pub fn list_presets() -> &'static [crate::presets::PresetInfo] {
        crate::presets::list_presets()
    }

    /// List presets appropriate for the current platform, with structured metadata.
    ///
    /// Platform presets are included where their platform tag matches:
    /// kde-breeze on KDE, adwaita on Linux, windows-11 on Windows,
    /// macos-monterey and macos-tahoe on macOS, ios-13 on macOS and iOS. `material-3` and the
    /// community themes are always included.
    ///
    /// Note: Unlike [`list_presets()`](Self::list_presets) which returns a static slice,
    /// this method returns `Vec` because it filters the preset list at runtime based
    /// on the detected platform.
    ///
    /// # Examples
    /// ```
    /// let presets = native_theme::theme::Theme::list_presets_for_platform();
    /// // On Linux KDE: kde-breeze, adwaita, material-3 and all community themes
    /// // On Windows: windows-11, material-3 and all community themes
    /// assert!(!presets.is_empty());
    /// ```
    #[must_use]
    pub fn list_presets_for_platform() -> Vec<crate::presets::PresetInfo> {
        crate::presets::list_presets_for_platform()
    }

    /// Serialize this theme to a TOML string.
    ///
    /// # Errors
    /// Returns [`crate::Error::ReaderFailed`] if serialization fails.
    ///
    /// # Examples
    /// ```
    /// let theme = native_theme::theme::Theme::preset("catppuccin-mocha").unwrap();
    /// let toml_str = theme.to_toml().unwrap();
    /// assert!(toml_str.contains("name = \"Catppuccin Mocha\""));
    /// ```
    pub fn to_toml(&self) -> crate::Result<String> {
        crate::presets::to_toml(self)
    }

    /// Check a TOML string for unrecognized field names.
    ///
    /// Parses the TOML as a generic table and walks all keys, comparing
    /// against the known fields for each section. Returns a `Vec<String>`
    /// of warnings for any keys that don't match a known field. An empty
    /// vec means all keys are recognized.
    ///
    /// This is an opt-in linting tool for theme authors. It does NOT affect
    /// `from_toml()` behavior (which silently ignores unknown fields via serde).
    ///
    /// # Errors
    ///
    /// Returns `Err` if the TOML string cannot be parsed at all.
    ///
    /// # Examples
    ///
    /// ```
    /// let warnings = native_theme::theme::Theme::lint_toml(r##"
    /// name = "Test"
    /// [light.defaults]
    /// backround = "#ffffff"
    /// "##).unwrap();
    /// assert_eq!(warnings.len(), 1);
    /// assert!(warnings[0].contains("backround"));
    /// ```
    pub fn lint_toml(toml_str: &str) -> crate::Result<Vec<String>> {
        let value: toml::Value =
            toml::from_str(toml_str).map_err(|e: toml::de::Error| crate::Error::Toml(e))?;

        let mut warnings = Vec::new();

        let top_table = match &value {
            toml::Value::Table(t) => t,
            _ => return Ok(warnings),
        };

        // Known top-level keys
        const TOP_KEYS: &[&str] = &["name", "light", "dark", "layout", "icon_set", "icon_theme"];

        for key in top_table.keys() {
            if !TOP_KEYS.contains(&key.as_str()) {
                warnings.push(format!("unknown field: {key}"));
            }
        }

        // Structural variant-level keys that are NOT widgets
        const STRUCTURAL_KEYS: &[&str] = &["defaults", "text_scale"];

        // Phase 93-05 G5: build BOTH field registries from inventory.
        // - widget_registry: one entry per per-variant widget (ButtonTheme ->
        //   "button", etc.) populated by #[derive(ThemeWidget)].
        // - struct_registry: one entry per plain struct (FontSpec, IconSizes,
        //   ThemeDefaults, LayoutTheme, ...) populated by #[derive(ThemeFields)].
        let widget_registry: std::collections::HashMap<&str, &[&str]> =
            inventory::iter::<crate::resolve::WidgetFieldInfo>()
                .map(|info| (info.widget_name, info.field_names))
                .collect();
        let struct_registry: std::collections::HashMap<&str, &[&str]> =
            inventory::iter::<crate::resolve::FieldInfo>()
                .map(|info| (info.struct_name, info.field_names))
                .collect();

        // Helper: fetch a plain-struct field list by type name. Returns None
        // when the struct did not opt in to ThemeFields -- sub-table linting
        // is silently skipped in that case, matching the former `continue;`
        // behaviour when a sub-table's type wasn't recognised.
        let get_struct_fields =
            |name: &str| -> Option<&[&str]> { struct_registry.get(name).copied() };

        // Lint a text_scale section
        let lint_text_scale = |table: &toml::map::Map<String, toml::Value>,
                               prefix: &str,
                               warnings: &mut Vec<String>| {
            let Some(scale_fields) = get_struct_fields("TextScale") else {
                return;
            };
            let entry_fields = get_struct_fields("TextScaleEntry");
            for key in table.keys() {
                if !scale_fields.contains(&key.as_str()) {
                    warnings.push(format!("unknown field: {prefix}.{key}"));
                } else if let Some(toml::Value::Table(entry_table)) = table.get(key)
                    && let Some(entry_fields) = entry_fields
                {
                    for ekey in entry_table.keys() {
                        if !entry_fields.contains(&ekey.as_str()) {
                            warnings.push(format!("unknown field: {prefix}.{key}.{ekey}"));
                        }
                    }
                }
            }
        };

        // Lint a defaults section (with nested font, mono_font, border, icon_sizes)
        let lint_defaults = |table: &toml::map::Map<String, toml::Value>,
                             prefix: &str,
                             warnings: &mut Vec<String>| {
            let Some(defaults_fields) = get_struct_fields("ThemeDefaults") else {
                return;
            };
            for key in table.keys() {
                if !defaults_fields.contains(&key.as_str()) {
                    warnings.push(format!("unknown field: {prefix}.{key}"));
                    continue;
                }
                // Check sub-tables for nested struct fields
                if let Some(toml::Value::Table(sub)) = table.get(key) {
                    let known = match key.as_str() {
                        "font" | "mono_font" => get_struct_fields("FontSpec"),
                        "border" => get_struct_fields("DefaultsBorderSpec"),
                        "icon_sizes" => get_struct_fields("IconSizes"),
                        _ => continue,
                    };
                    let Some(known) = known else { continue };
                    for skey in sub.keys() {
                        if !known.contains(&skey.as_str()) {
                            warnings.push(format!("unknown field: {prefix}.{key}.{skey}"));
                        }
                    }
                }
            }
        };

        // Lint a variant section (light or dark).
        let lint_variant = |table: &toml::map::Map<String, toml::Value>,
                            prefix: &str,
                            warnings: &mut Vec<String>| {
            for key in table.keys() {
                let key_str = key.as_str();

                // Check structural keys first, then widget registry
                let is_structural = STRUCTURAL_KEYS.contains(&key_str);
                let widget_fields = widget_registry.get(key_str);

                if !is_structural && widget_fields.is_none() {
                    warnings.push(format!("unknown field: {prefix}.{key}"));
                    continue;
                }

                if let Some(toml::Value::Table(sub)) = table.get(key) {
                    let sub_prefix = format!("{prefix}.{key}");
                    match key_str {
                        "defaults" => lint_defaults(sub, &sub_prefix, warnings),
                        "text_scale" => lint_text_scale(sub, &sub_prefix, warnings),
                        _ => {
                            if let Some(fields) = widget_fields {
                                for skey in sub.keys() {
                                    if !fields.contains(&skey.as_str()) {
                                        warnings
                                            .push(format!("unknown field: {sub_prefix}.{skey}"));
                                    }
                                    // Validate sub-tables (font/border nested structs)
                                    if let Some(toml::Value::Table(nested)) = sub.get(skey) {
                                        let nested_known = match skey.as_str() {
                                            s if s == "font" || s.ends_with("_font") => {
                                                get_struct_fields("FontSpec")
                                            }
                                            "border" => get_struct_fields("WidgetBorderSpec"),
                                            _ => None,
                                        };
                                        if let Some(known) = nested_known {
                                            for nkey in nested.keys() {
                                                if !known.contains(&nkey.as_str()) {
                                                    warnings.push(format!(
                                                        "unknown field: {sub_prefix}.{skey}.{nkey}"
                                                    ));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        };

        // Lint light and dark variant sections
        for variant_key in &["light", "dark"] {
            if let Some(toml::Value::Table(variant_table)) = top_table.get(*variant_key) {
                lint_variant(variant_table, variant_key, &mut warnings);
            }
        }

        // Lint top-level [layout] section. LayoutTheme is a "widget" at the
        // macro level (for its Resolved-pair codegen) but skips the widget
        // inventory -- its fields are in the struct registry instead.
        if let Some(toml::Value::Table(layout_table)) = top_table.get("layout")
            && let Some(layout_fields) = get_struct_fields("LayoutTheme")
        {
            for key in layout_table.keys() {
                if !layout_fields.contains(&key.as_str()) {
                    warnings.push(format!("unknown field: layout.{key}"));
                }
            }
        }

        Ok(warnings)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::Rgba;

    // === ThemeMode tests ===

    #[test]
    fn theme_variant_default_is_empty() {
        assert!(ThemeMode::default().is_empty());
    }

    #[test]
    fn theme_variant_not_empty_when_color_set() {
        let mut v = ThemeMode::default();
        v.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
        assert!(!v.is_empty());
    }

    #[test]
    fn theme_variant_not_empty_when_font_set() {
        let mut v = ThemeMode::default();
        v.defaults.font.family = Some("Inter".into());
        assert!(!v.is_empty());
    }

    #[test]
    fn theme_variant_merge_recursively() {
        let mut base = ThemeMode::default();
        base.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
        base.defaults.font.family = Some("Noto Sans".into());

        let mut overlay = ThemeMode::default();
        overlay.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
        overlay.defaults.border.corner_radius = Some(4.0);

        base.merge(&overlay);

        // base background preserved
        assert_eq!(
            base.defaults.background_color,
            Some(Rgba::rgb(255, 255, 255))
        );
        // overlay accent applied
        assert_eq!(base.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
        // base font preserved
        assert_eq!(base.defaults.font.family.as_deref(), Some("Noto Sans"));
        // overlay border applied
        assert_eq!(base.defaults.border.corner_radius, Some(4.0));
    }

    #[test]
    fn theme_variant_has_all_widgets() {
        let mut v = ThemeMode::default();
        // Set a field on each of the 25 widgets
        v.window.background_color = Some(Rgba::rgb(255, 255, 255));
        v.button.min_height = Some(32.0);
        v.input.min_height = Some(32.0);
        v.checkbox.indicator_width = Some(18.0);
        v.menu.row_height = Some(28.0);
        v.tooltip.max_width = Some(300.0);
        v.scrollbar.groove_width = Some(14.0);
        v.slider.track_height = Some(4.0);
        v.progress_bar.track_height = Some(6.0);
        v.tab.min_height = Some(32.0);
        v.sidebar.background_color = Some(Rgba::rgb(240, 240, 240));
        v.toolbar.bar_height = Some(40.0);
        v.status_bar.background_color = Some(Rgba::rgb(240, 240, 240));
        v.list.row_height = Some(28.0);
        v.popover.background_color = Some(Rgba::rgb(255, 255, 255));
        v.splitter.divider_width = Some(4.0);
        v.separator.line_color = Some(Rgba::rgb(200, 200, 200));
        v.switch.track_width = Some(32.0);
        v.dialog.min_width = Some(320.0);
        v.spinner.diameter = Some(24.0);
        v.combo_box.min_height = Some(32.0);
        v.segmented_control.segment_height = Some(28.0);
        v.card.background_color = Some(Rgba::rgb(255, 255, 255));
        v.expander.header_height = Some(32.0);
        v.link.underline_enabled = Some(true);

        assert!(!v.is_empty());
        assert!(!v.window.is_empty());
        assert!(!v.button.is_empty());
        assert!(!v.input.is_empty());
        assert!(!v.checkbox.is_empty());
        assert!(!v.menu.is_empty());
        assert!(!v.tooltip.is_empty());
        assert!(!v.scrollbar.is_empty());
        assert!(!v.slider.is_empty());
        assert!(!v.progress_bar.is_empty());
        assert!(!v.tab.is_empty());
        assert!(!v.sidebar.is_empty());
        assert!(!v.toolbar.is_empty());
        assert!(!v.status_bar.is_empty());
        assert!(!v.list.is_empty());
        assert!(!v.popover.is_empty());
        assert!(!v.splitter.is_empty());
        assert!(!v.separator.is_empty());
        assert!(!v.switch.is_empty());
        assert!(!v.dialog.is_empty());
        assert!(!v.spinner.is_empty());
        assert!(!v.combo_box.is_empty());
        assert!(!v.segmented_control.is_empty());
        assert!(!v.card.is_empty());
        assert!(!v.expander.is_empty());
        assert!(!v.link.is_empty());
    }

    #[test]
    fn theme_variant_merge_per_widget() {
        let mut base = ThemeMode::default();
        base.button.background_color = Some(Rgba::rgb(200, 200, 200));
        base.button.min_height = Some(28.0);
        base.tooltip.background_color = Some(Rgba::rgb(50, 50, 50));

        let mut overlay = ThemeMode::default();
        overlay.button.background_color = Some(Rgba::rgb(255, 255, 255));
        overlay.button.min_width = Some(64.0);

        base.merge(&overlay);

        // overlay background wins
        assert_eq!(base.button.background_color, Some(Rgba::rgb(255, 255, 255)));
        // overlay min_width added
        assert_eq!(base.button.min_width, Some(64.0));
        // base min_height preserved
        assert_eq!(base.button.min_height, Some(28.0));
        // tooltip from base preserved
        assert_eq!(base.tooltip.background_color, Some(Rgba::rgb(50, 50, 50)));
    }

    // === Theme tests ===

    #[test]
    fn native_theme_default_is_empty() {
        let theme = Theme::default();
        assert!(theme.is_empty());
        assert_eq!(theme.name, "");
    }

    #[test]
    fn native_theme_merge_keeps_base_name() {
        let mut base = Theme {
            name: "Base Theme".into(),
            ..Theme::default()
        };
        let overlay = Theme {
            name: "Overlay Theme".into(),
            ..Theme::default()
        };
        base.merge(&overlay);
        assert_eq!(base.name, "Base Theme");
    }

    #[test]
    fn nameless_overlay_parses_and_merges() {
        let toml = "[light.defaults]\naccent_color = \"#ff6600\"";
        assert!(Theme::lint_toml(toml).unwrap().is_empty());
        let overlay = Theme::from_toml(toml).unwrap();
        assert_eq!(overlay.name, "");

        let mut base = Theme::preset("catppuccin-mocha").unwrap();
        base.merge(&overlay);
        assert_eq!(base.name, "Catppuccin Mocha");
        assert_eq!(
            base.light.as_ref().unwrap().defaults.accent_color,
            Some(Rgba::rgb(0xff, 0x66, 0x00))
        );
    }

    #[test]
    fn icon_set_segoe_fluent_toml_round_trip() {
        let theme = Theme::from_toml("name = \"T\"\nicon_set = \"segoe-fluent\"").unwrap();
        assert_eq!(theme.icon_set, Some(IconSet::SegoeFluent));
        let toml_text = theme.to_toml().unwrap();
        assert!(
            toml_text.contains("icon_set = \"segoe-fluent\""),
            "serialized name changed: {toml_text}"
        );
        assert_eq!(
            Theme::from_toml(&toml_text).unwrap().icon_set,
            Some(IconSet::SegoeFluent)
        );
    }

    #[test]
    fn native_theme_merge_overlay_light_into_none() {
        let mut base = Theme {
            name: "Theme".into(),
            ..Theme::default()
        };

        let mut overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        let mut light = ThemeMode::default();
        light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
        overlay.light = Some(light);

        base.merge(&overlay);

        assert!(base.light.is_some());
        assert_eq!(
            base.light.as_ref().unwrap().defaults.accent_color,
            Some(Rgba::rgb(0, 120, 215))
        );
    }

    #[test]
    fn native_theme_merge_both_light_variants() {
        let mut base = Theme {
            name: "Theme".into(),
            ..Theme::default()
        };
        let mut base_light = ThemeMode::default();
        base_light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
        base.light = Some(base_light);

        let mut overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        let mut overlay_light = ThemeMode::default();
        overlay_light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
        overlay.light = Some(overlay_light);

        base.merge(&overlay);

        let light = base.light.as_ref().unwrap();
        // base background preserved
        assert_eq!(
            light.defaults.background_color,
            Some(Rgba::rgb(255, 255, 255))
        );
        // overlay accent merged in
        assert_eq!(light.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
    }

    #[test]
    fn native_theme_merge_base_light_only_preserved() {
        let mut base = Theme {
            name: "Theme".into(),
            ..Theme::default()
        };
        let mut base_light = ThemeMode::default();
        base_light.defaults.font.family = Some("Inter".into());
        base.light = Some(base_light);

        let overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        }; // no light

        base.merge(&overlay);

        assert!(base.light.is_some());
        assert_eq!(
            base.light.as_ref().unwrap().defaults.font.family.as_deref(),
            Some("Inter")
        );
    }

    #[test]
    fn native_theme_merge_dark_variant() {
        let mut base = Theme {
            name: "Theme".into(),
            ..Theme::default()
        };

        let mut overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        let mut dark = ThemeMode::default();
        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
        overlay.dark = Some(dark);

        base.merge(&overlay);

        assert!(base.dark.is_some());
        assert_eq!(
            base.dark.as_ref().unwrap().defaults.background_color,
            Some(Rgba::rgb(30, 30, 30))
        );
    }

    #[test]
    fn native_theme_not_empty_with_light() {
        let mut theme = Theme {
            name: "Theme".into(),
            ..Theme::default()
        };
        theme.light = Some(ThemeMode::default());
        assert!(!theme.is_empty());
    }

    // === pick_variant tests ===

    #[test]
    fn pick_variant_dark_with_both_variants_returns_dark() {
        let mut theme = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        let mut light = ThemeMode::default();
        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
        theme.light = Some(light);
        let mut dark = ThemeMode::default();
        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
        theme.dark = Some(dark);

        let picked = theme.pick_variant(ColorMode::Dark).unwrap();
        assert_eq!(
            picked.defaults.background_color,
            Some(Rgba::rgb(30, 30, 30))
        );
    }

    #[test]
    fn pick_variant_light_with_both_variants_returns_light() {
        let mut theme = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        let mut light = ThemeMode::default();
        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
        theme.light = Some(light);
        let mut dark = ThemeMode::default();
        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
        theme.dark = Some(dark);

        let picked = theme.pick_variant(ColorMode::Light).unwrap();
        assert_eq!(
            picked.defaults.background_color,
            Some(Rgba::rgb(255, 255, 255))
        );
    }

    #[test]
    fn pick_variant_dark_with_only_light_falls_back() {
        let mut theme = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        let mut light = ThemeMode::default();
        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
        theme.light = Some(light);

        let picked = theme.pick_variant(ColorMode::Dark).unwrap();
        assert_eq!(
            picked.defaults.background_color,
            Some(Rgba::rgb(255, 255, 255))
        );
    }

    #[test]
    fn pick_variant_light_with_only_dark_falls_back() {
        let mut theme = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        let mut dark = ThemeMode::default();
        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
        theme.dark = Some(dark);

        let picked = theme.pick_variant(ColorMode::Light).unwrap();
        assert_eq!(
            picked.defaults.background_color,
            Some(Rgba::rgb(30, 30, 30))
        );
    }

    #[test]
    fn pick_variant_with_no_variants_returns_err() {
        let theme = Theme {
            name: "Empty".into(),
            ..Theme::default()
        };
        assert!(theme.pick_variant(ColorMode::Dark).is_err());
        assert!(theme.pick_variant(ColorMode::Light).is_err());
    }

    // === icon_set tests (on Theme, shared across variants) ===

    #[test]
    fn icon_set_default_is_none() {
        assert!(Theme::default().icon_set.is_none());
    }

    #[test]
    fn icon_set_merge_overlay() {
        let mut base = Theme {
            name: "Base".into(),
            ..Theme::default()
        };
        let mut overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        overlay.icon_set = Some(IconSet::Material);
        base.merge(&overlay);
        assert_eq!(base.icon_set, Some(IconSet::Material));
    }

    #[test]
    fn icon_set_merge_none_preserves() {
        let mut base = Theme {
            name: "Base".into(),
            ..Theme::default()
        };
        base.icon_set = Some(IconSet::SfSymbols);
        let overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        base.merge(&overlay);
        assert_eq!(base.icon_set, Some(IconSet::SfSymbols));
    }

    #[test]
    fn icon_set_is_empty_when_set() {
        assert!(Theme::default().is_empty());
        let mut t = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        t.icon_set = Some(IconSet::Material);
        assert!(!t.is_empty());
    }

    #[test]
    fn icon_set_toml_round_trip() {
        let mut theme = Theme {
            name: "Test".into(),
            ..Theme::default()
        };
        theme.icon_set = Some(IconSet::Material);
        let mut light = ThemeMode::default();
        light.defaults.icon_theme = Some("material".into());
        theme.light = Some(light);
        let toml_str = theme.to_toml().unwrap();
        assert!(toml_str.contains("icon_set"));
        let deserialized = Theme::from_toml(&toml_str).unwrap();
        assert_eq!(deserialized.icon_set, Some(IconSet::Material));
        assert_eq!(
            deserialized
                .light
                .as_ref()
                .unwrap()
                .defaults
                .icon_theme
                .as_deref(),
            Some("material")
        );
    }

    #[test]
    fn icon_set_toml_absent_deserializes_to_none() {
        let toml_str = r##"
name = "Bare"
[light.defaults]
accent_color = "#ff0000"
"##;
        let theme = Theme::from_toml(toml_str).unwrap();
        assert!(theme.icon_set.is_none());
        assert!(theme.light.as_ref().unwrap().defaults.icon_theme.is_none());
    }

    #[test]
    fn native_theme_serde_toml_round_trip() {
        // Load a preset, serialize to TOML, deserialize back, and verify equality
        let theme = Theme::preset("material-3").expect("material-3 preset should load");
        let toml_str = theme.to_toml().expect("should serialize");
        let theme2 = Theme::from_toml(&toml_str).expect("should deserialize");
        assert_eq!(theme, theme2, "round-trip should preserve Theme");
    }

    // === Theme::resolve() tests ===

    #[test]
    fn resolve_material_uses_theme_level_icon_theme() {
        // material-3.toml has `icon_theme = "material"` at the root (tier 2).
        // The resolver must fill `icon_theme = "material"` for both modes.
        let theme = Theme::preset("material-3").unwrap();
        for mode in [ColorMode::Light, ColorMode::Dark] {
            let r = theme.resolve(mode).unwrap();
            assert_eq!(
                r.icon_theme.as_deref(),
                Some("material"),
                "material (tier 2) for {mode:?}"
            );
            assert!(
                r.icon_theme_explicit,
                "explicit flag must be true for {mode:?}"
            );
            assert_eq!(r.icon_set, IconSet::Material);
        }
    }

    #[test]
    fn resolve_kde_breeze_uses_per_variant_icon_theme() {
        // kde-breeze.toml has `icon_theme` under each [light.defaults] /
        // [dark.defaults] (tier 1). Light → "breeze", Dark → "breeze-dark".
        let theme = Theme::preset("kde-breeze").unwrap();

        let light = theme.resolve(ColorMode::Light).unwrap();
        assert_eq!(light.icon_theme.as_deref(), Some("breeze"));
        assert!(light.icon_theme_explicit);

        let dark = theme.resolve(ColorMode::Dark).unwrap();
        assert_eq!(dark.icon_theme.as_deref(), Some("breeze-dark"));
        assert!(dark.icon_theme_explicit);

        assert_eq!(light.icon_set, IconSet::Freedesktop);
        assert_eq!(dark.icon_set, IconSet::Freedesktop);
    }

    /// adwaita with no icon theme stated anywhere, so tier 3 decides.
    fn adwaita_without_icon_theme() -> Theme {
        let mut theme = Theme::preset("adwaita").unwrap();
        theme.icon_theme = None;
        if let Some(v) = theme.light.as_mut() {
            v.defaults.icon_theme = None;
        }
        if let Some(v) = theme.dark.as_mut() {
            v.defaults.icon_theme = None;
        }
        theme
    }

    #[test]
    fn resolve_minimal_theme_takes_the_detected_icon_theme() {
        // No icon_theme anywhere → tier 3, the context's detected theme.
        let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Ok(
            "detected-theme".to_string()
        ));
        let r = adwaita_without_icon_theme()
            .resolve_with(ColorMode::Light, &ctx)
            .unwrap();
        assert_eq!(r.icon_theme.as_deref(), Some("detected-theme"));
        assert!(
            !r.icon_theme_explicit,
            "tier 3 fallback must report explicit = false"
        );
    }

    #[test]
    fn resolve_minimal_theme_without_detection_has_no_icon_theme() {
        // No icon_theme anywhere and detection failed → None, and the
        // resolution itself still succeeds.
        let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Err(
            crate::Error::PlatformUnsupported {
                platform: "the test's failing detection",
            },
        ));
        let r = adwaita_without_icon_theme()
            .resolve_with(ColorMode::Light, &ctx)
            .expect("a failed icon-theme detection must not fail resolution");
        assert_eq!(r.icon_theme, None);
        assert!(!r.icon_theme_explicit);
    }

    #[test]
    fn resolve_minimal_theme_resolves_whatever_detection_gives() {
        // Through `resolve` itself: detection's outcome is host-dependent,
        // but the resolution succeeds and reports tier 3 either way.
        let r = adwaita_without_icon_theme()
            .resolve(ColorMode::Light)
            .unwrap();
        assert!(!r.icon_theme_explicit);
        assert_eq!(
            r.icon_theme.as_deref(),
            crate::detect::system_icon_theme().ok().as_deref()
        );
    }

    #[test]
    fn resolve_tier1_wins_over_tier2() {
        // When BOTH Theme::icon_theme (tier 2) and variant.defaults.icon_theme
        // (tier 1) are set, tier 1 wins.
        let mut theme = Theme::preset("adwaita").unwrap();
        theme.icon_theme = Some(Cow::Borrowed("theme-level"));
        theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("per-variant"));
        let r = theme.resolve(ColorMode::Light).unwrap();
        assert_eq!(r.icon_theme.as_deref(), Some("per-variant"));
        assert!(r.icon_theme_explicit);
    }

    #[test]
    fn resolve_cross_mode_fallback_picks_available_variant() {
        // Theme with only a light variant, asked for dark → pick_variant
        // cross-falls-back to light and reports light's icon_theme.
        let mut theme = Theme::preset("adwaita").unwrap();
        theme.dark = None;
        theme.icon_theme = None;
        theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("only-one"));
        let r = theme.resolve(ColorMode::Dark).unwrap();
        assert_eq!(r.icon_theme.as_deref(), Some("only-one"));
        assert!(r.icon_theme_explicit);
    }

    #[test]
    fn resolve_light_only_asked_dark_reports_light_mode() {
        let mut theme = Theme::preset("adwaita").unwrap();
        theme.dark = None;
        let r = theme.resolve(ColorMode::Dark).unwrap();
        assert_eq!(r.mode, ColorMode::Light);
    }

    #[test]
    fn resolve_reports_requested_mode_when_variant_present() {
        let theme = Theme::preset("adwaita").unwrap();
        assert_eq!(
            theme.resolve(ColorMode::Dark).unwrap().mode,
            ColorMode::Dark
        );
        assert_eq!(
            theme.resolve(ColorMode::Light).unwrap().mode,
            ColorMode::Light
        );
    }

    #[test]
    fn resolve_empty_theme_returns_no_variant_error() {
        let theme = Theme {
            name: "Empty".into(),
            ..Theme::default()
        };
        assert!(matches!(
            theme.resolve(ColorMode::Light),
            Err(crate::Error::NoVariant {
                mode: ColorMode::Light
            })
        ));
    }

    #[test]
    fn resolve_all_presets_succeed() {
        // Every bundled preset must resolve in both modes.
        for info in Theme::list_presets() {
            let theme = Theme::preset(info.key).unwrap();
            for mode in [ColorMode::Light, ColorMode::Dark] {
                theme.resolve(mode).unwrap_or_else(|e| {
                    panic!("preset '{}' failed to resolve({mode:?}): {e}", info.key)
                });
            }
        }
    }

    // === lint_toml tests ===

    #[test]
    fn lint_toml_valid_returns_empty() {
        let toml = r##"
name = "Valid Theme"
[light.defaults]
accent_color = "#ff0000"
background_color = "#ffffff"
[light.defaults.font]
family = "Inter"
size_px = 14.0
[light.button]
min_height_px = 32.0
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert!(
            warnings.is_empty(),
            "Expected no warnings, got: {warnings:?}"
        );
    }

    #[test]
    fn lint_toml_detects_unknown_top_level() {
        let toml = r##"
name = "Test"
theme_version = 2
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("theme_version"));
    }

    #[test]
    fn lint_toml_detects_misspelled_defaults_field() {
        let toml = r##"
name = "Test"
[light.defaults]
backround = "#ffffff"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("backround"));
        assert!(warnings[0].contains("light.defaults.backround"));
    }

    #[test]
    fn lint_toml_detects_unknown_widget_field() {
        let toml = r##"
name = "Test"
[dark.button]
primary_bg = "#0078d7"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("primary_bg"));
    }

    #[test]
    fn lint_toml_detects_unknown_variant_section() {
        let toml = r##"
name = "Test"
[light.badges]
color = "#ff0000"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("badges"));
    }

    #[test]
    fn lint_toml_detects_unknown_font_subfield() {
        let toml = r##"
name = "Test"
[light.defaults.font]
famly = "Inter"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("famly"));
    }

    #[test]
    fn lint_toml_detects_unknown_border_subfield() {
        let toml = r##"
name = "Test"
[light.defaults.border]
radiusss = 4.0
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("radiusss"));
    }

    #[test]
    fn lint_toml_detects_unknown_text_scale_entry() {
        let toml = r##"
name = "Test"
[light.text_scale.headline]
size = 24.0
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("headline"));
    }

    #[test]
    fn lint_toml_detects_unknown_text_scale_entry_field() {
        let toml = r##"
name = "Test"
[light.text_scale.caption]
font_size = 12.0
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("font_size"));
    }

    #[test]
    fn lint_toml_multiple_errors() {
        let toml = r##"
name = "Test"
author = "Me"
[light.defaults]
backround = "#ffffff"
[light.button]
primay_bg = "#0078d7"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 3);
    }

    #[test]
    fn lint_toml_invalid_toml_returns_error() {
        let result = Theme::lint_toml("{{{{invalid");
        assert!(result.is_err());
    }

    #[test]
    fn lint_toml_preset_has_no_warnings() {
        // Spot-check one preset for lint cleanliness via round-trip
        let theme = Theme::preset("material-3").expect("material-3 preset should load");
        let toml_str = theme.to_toml().expect("should serialize");
        let warnings = Theme::lint_toml(&toml_str).expect("should parse");
        assert!(
            warnings.is_empty(),
            "material-3 preset should have no lint warnings, got: {warnings:?}"
        );
    }

    #[test]
    fn lint_toml_all_presets_clean() {
        for info in Theme::list_presets() {
            let name = info.key;
            // Load the raw TOML source for each preset via include_str
            // by loading via preset() + to_toml() round-trip
            let theme = Theme::preset(name).unwrap_or_else(|e| {
                panic!("preset {name} should load: {e}");
            });
            let toml_str = theme.to_toml().unwrap_or_else(|e| {
                panic!("preset {name} should serialize: {e}");
            });
            let warnings = Theme::lint_toml(&toml_str).unwrap_or_else(|e| {
                panic!("preset {name} should lint: {e}");
            });
            assert!(
                warnings.is_empty(),
                "preset {name} should have no lint warnings, got: {warnings:?}"
            );
        }
    }

    #[test]
    fn lint_toml_accepts_padding_sides_and_shorthand() {
        let toml = r##"
name = "Test"
[light.button.border]
padding_top_px = 1.0
padding_right_px = 2.0
padding_bottom_px = 3.0
padding_left_px = 4.0
[light.input.border]
padding_horizontal_px = 6.0
padding_vertical_px = 0.0
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert!(warnings.is_empty(), "got: {warnings:?}");
        let warnings =
            Theme::lint_toml("name = \"T\"\n[light.input.border]\npadding_sideways_px = 1.0\n")
                .unwrap();
        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    }

    #[test]
    fn lint_toml_rejects_unknown_field_on_registered_widget() {
        // Verify that lint_toml discovers widget field names from inventory.
        // If a field name is not in the registered FIELD_NAMES for a widget,
        // lint_toml should report it as unknown.
        let toml = r##"
name = "Test"
[light.button]
nonexistent_field = "#ff0000"
"##;
        let warnings = Theme::lint_toml(toml).unwrap();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("nonexistent_field"));
        assert!(warnings[0].contains("light.button"));
    }

    #[test]
    fn lint_toml_recognizes_all_registered_widgets() {
        // Every widget registered via inventory::submit! should be accepted
        // as a valid variant-level section key.
        for entry in inventory::iter::<crate::resolve::WidgetFieldInfo> {
            let toml_str = format!("name = \"Test\"\n[light.{}]\n", entry.widget_name,);
            let warnings = Theme::lint_toml(&toml_str).unwrap();
            assert!(
                warnings.is_empty(),
                "widget '{}' should be recognized, got: {:?}",
                entry.widget_name,
                warnings,
            );
        }
    }

    // === Theme layout integration tests ===

    #[test]
    fn theme_spec_layout_merge() {
        let mut base = Theme {
            name: "Base".into(),
            ..Theme::default()
        };
        base.layout.widget_gap = Some(6.0);

        let mut overlay = Theme {
            name: "Overlay".into(),
            ..Theme::default()
        };
        overlay.layout.container_margin = Some(8.0);

        base.merge(&overlay);
        assert_eq!(base.layout.widget_gap, Some(6.0));
        assert_eq!(base.layout.container_margin, Some(8.0));
    }

    #[test]
    fn theme_spec_layout_toml_round_trip() {
        let mut theme = Theme {
            name: "Layout Test".into(),
            ..Theme::default()
        };
        theme.layout.widget_gap = Some(8.0);
        theme.layout.container_margin = Some(12.0);
        theme.layout.window_margin = Some(16.0);
        theme.layout.section_gap = Some(24.0);

        let toml_str = theme.to_toml().unwrap();
        let theme2 = Theme::from_toml(&toml_str).unwrap();
        assert_eq!(theme.layout, theme2.layout);
    }

    #[test]
    fn theme_spec_is_empty_with_layout() {
        let mut theme = Theme {
            name: "Layout Only".into(),
            ..Theme::default()
        };
        assert!(theme.is_empty()); // name doesn't count
        theme.layout.widget_gap = Some(8.0);
        assert!(!theme.is_empty());
    }

    #[test]
    fn theme_spec_layout_top_level_toml() {
        let mut theme = Theme {
            name: "Top Level".into(),
            ..Theme::default()
        };
        theme.layout.widget_gap = Some(8.0);

        let toml_str = theme.to_toml().unwrap();
        // [layout] must be at top level, not under [light.layout] or [dark.layout]
        assert!(
            toml_str.contains("[layout]"),
            "TOML should have [layout] section"
        );
        assert!(!toml_str.contains("[light.layout]"));
        assert!(!toml_str.contains("[dark.layout]"));
    }

    // === Phase 93-05 G5: ThemeFields inventory baseline-equality tests ===
    //
    // Each struct that is expected to register via #[derive(ThemeFields)]
    // must produce a FieldInfo entry whose `field_names` matches the
    // pre-migration hand-authored FIELD_NAMES list bit-for-bit. Failure means
    // either the derive emission path is wrong (serde rename drift) or
    // the derive was not applied to the struct.

    fn field_info_entry(name: &'static str) -> Option<&'static [&'static str]> {
        inventory::iter::<crate::resolve::FieldInfo>()
            .find(|info| info.struct_name == name)
            .map(|info| info.field_names)
    }

    #[test]
    fn font_spec_field_info_matches_baseline() {
        let baseline: &[&str] = &["family", "size_pt", "size_px", "weight", "style", "color"];
        assert_eq!(field_info_entry("FontSpec"), Some(baseline));
    }

    #[test]
    fn text_scale_entry_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "size_pt",
            "size_px",
            "weight",
            "line_height_pt",
            "line_height_px",
        ];
        assert_eq!(field_info_entry("TextScaleEntry"), Some(baseline));
    }

    #[test]
    fn text_scale_field_info_matches_baseline() {
        let baseline: &[&str] = &["caption", "section_heading", "dialog_title", "display"];
        assert_eq!(field_info_entry("TextScale"), Some(baseline));
    }

    #[test]
    fn defaults_border_spec_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "color",
            "corner_radius_px",
            "corner_radius_lg_px",
            "line_width_px",
            "opacity",
            "shadow_enabled",
        ];
        assert_eq!(field_info_entry("DefaultsBorderSpec"), Some(baseline));
    }

    #[test]
    fn widget_border_spec_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "color",
            "corner_radius_px",
            "line_width_px",
            "shadow_enabled",
            "padding_top_px",
            "padding_right_px",
            "padding_bottom_px",
            "padding_left_px",
            "padding_horizontal_px",
            "padding_vertical_px",
        ];
        assert_eq!(field_info_entry("WidgetBorderSpec"), Some(baseline));
    }

    #[test]
    fn theme_defaults_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "font",
            "line_height",
            "mono_font",
            "background_color",
            "text_color",
            "accent_color",
            "accent_text_color",
            "surface_color",
            "muted_color",
            "shadow_color",
            "link_color",
            "selection_background",
            "selection_text_color",
            "selection_inactive_background",
            "text_selection_background",
            "text_selection_color",
            "disabled_text_color",
            "danger_color",
            "danger_text_color",
            "warning_color",
            "warning_text_color",
            "success_color",
            "success_text_color",
            "info_color",
            "info_text_color",
            "border",
            "disabled_opacity",
            "focus_ring_color",
            "focus_ring_width_px",
            "focus_ring_offset_px",
            "icon_sizes",
            "icon_theme",
        ];
        assert_eq!(field_info_entry("ThemeDefaults"), Some(baseline));
    }

    #[test]
    fn icon_sizes_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "toolbar_px",
            "small_px",
            "large_px",
            "dialog_px",
            "panel_px",
        ];
        assert_eq!(field_info_entry("IconSizes"), Some(baseline));
    }

    #[test]
    fn layout_theme_field_info_matches_baseline() {
        let baseline: &[&str] = &[
            "widget_gap_px",
            "container_margin_px",
            "window_margin_px",
            "section_gap_px",
        ];
        assert_eq!(field_info_entry("LayoutTheme"), Some(baseline));
    }

    #[test]
    fn widget_registry_still_has_all_widgets() {
        // Regression guard: the existing WidgetFieldInfo inventory must remain
        // populated after ThemeFields migration. LayoutTheme is NOT a widget
        // (it uses `skip_inventory`), so we expect at least the 25 per-variant
        // widgets registered through ThemeWidget.
        let widget_count = inventory::iter::<crate::resolve::WidgetFieldInfo>().count();
        assert!(
            widget_count >= 25,
            "expected >=25 widgets in WidgetFieldInfo, got {widget_count}"
        );
    }

    // === docs/property-registry.toml key sets against the inventory ===
    //
    // The registry lists every property per table by its serialized TOML key;
    // the inventory records the same keys from the structs. Types stay
    // hand-kept and are not compared. `[theme_variant]` is skipped: `Theme`
    // and `ThemeMode` do not register in the inventory.

    #[test]
    fn property_registry_keys_match_derive_inventory() {
        use std::collections::BTreeSet;

        let registry: toml::Table = include_str!("../../../docs/property-registry.toml")
            .parse()
            .expect("docs/property-registry.toml is valid TOML");

        let struct_fields = |names: &[&'static str]| -> BTreeSet<String> {
            names
                .iter()
                .filter_map(|name| field_info_entry(name))
                .flat_map(|fields| fields.iter().map(|f| (*f).to_string()))
                .collect()
        };
        let table_keys = |value: Option<&toml::Value>| -> Option<BTreeSet<String>> {
            value
                .and_then(|v| v.as_table())
                .map(|t| t.keys().cloned().collect())
        };

        // `Border` is one table for both border structs; its comments say
        // which keys belong to defaults and which to widget borders.
        const STRUCTURES: &[(&str, &[&str])] = &[
            ("Font", &["FontSpec"]),
            ("Border", &["DefaultsBorderSpec", "WidgetBorderSpec"]),
            ("IconSizes", &["IconSizes"]),
            ("TextScaleEntry", &["TextScaleEntry"]),
        ];
        const STRUCT_TABLES: &[(&str, &[&str])] = &[
            ("defaults", &["ThemeDefaults"]),
            ("text_scale", &["TextScale"]),
            ("layout", &["LayoutTheme"]),
        ];
        const SKIPPED_TABLES: &[&str] = &["theme_variant"];

        fn compare(
            drift: &mut Vec<String>,
            table: &str,
            registry: Option<BTreeSet<String>>,
            code: &BTreeSet<String>,
        ) {
            let Some(registry) = registry else {
                drift.push(format!("[{table}] is missing"));
                return;
            };
            for key in registry.difference(code) {
                drift.push(format!("[{table}] {key}: in the registry, not in the code"));
            }
            for key in code.difference(&registry) {
                drift.push(format!("[{table}] {key}: in the code, not in the registry"));
            }
        }

        let mut drift: Vec<String> = Vec::new();

        let structures = registry
            .get("_structures")
            .and_then(|v| v.as_table())
            .expect("[_structures] exists");
        for name in structures.keys() {
            if !STRUCTURES.iter().any(|(n, _)| n == name) {
                drift.push(format!(
                    "[_structures.{name}] maps to no struct in the test"
                ));
            }
        }
        for (name, structs) in STRUCTURES {
            let code = struct_fields(structs);
            assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
            compare(
                &mut drift,
                &format!("_structures.{name}"),
                table_keys(structures.get(*name)),
                &code,
            );
        }

        for (table, structs) in STRUCT_TABLES {
            let code = struct_fields(structs);
            assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
            compare(&mut drift, table, table_keys(registry.get(*table)), &code);
        }

        let mut widget_count = 0usize;
        for info in inventory::iter::<crate::resolve::WidgetFieldInfo>() {
            widget_count += 1;
            let code: BTreeSet<String> =
                info.field_names.iter().map(|f| (*f).to_string()).collect();
            compare(
                &mut drift,
                info.widget_name,
                table_keys(registry.get(info.widget_name)),
                &code,
            );
        }
        assert!(
            widget_count >= 25,
            "expected >=25 widgets, got {widget_count}"
        );

        for table in registry.keys() {
            let known = table == "_structures"
                || SKIPPED_TABLES.contains(&table.as_str())
                || STRUCT_TABLES.iter().any(|(t, _)| t == table)
                || inventory::iter::<crate::resolve::WidgetFieldInfo>()
                    .any(|info| info.widget_name == table);
            if !known {
                drift.push(format!(
                    "[{table}] is in the registry, but no widget or struct"
                ));
            }
        }

        assert!(
            drift.is_empty(),
            "docs/property-registry.toml diverges from the derive inventory:\n{}",
            drift.join("\n")
        );
    }
}