makeover 2.11.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
//! Shared theme loading + intent resolution for TOML-based theme files.
//!
//! Used by GoingsOn, Balanced Breakfast (Tauri apps), audiofiles (egui), and the
//! MNW web server. Themes are authored by **intent** ("human design"): colors are
//! declared by role (surface / content / action / status / line / category), not
//! by hue. This crate is the single place that resolves an authored theme into a
//! full set of intent tokens — including the derived interactive states
//! (hover/active/selection/row-stripe/contrast) that each app used to recompute
//! itself — and emits them as CSS variables or RGB tuples.
//!
//! Theme file shape:
//! ```text
//! [meta]
//! name = "Nord"
//! variant = "dark"          # or "light"
//!
//! [surface]                 # container backgrounds by role/elevation
//! page = "#2e3440"; raised = "#3b4252"; sunken = "#434c5e"; overlay = "#3b4252"
//!
//! [content]                 # the ink. Its emphasis steps are derived, not authored:
//! primary = "#d8dee9"       # `content-secondary` and `content-muted` are tonal
//!                           # steps of this toward `surface.page`. See `Emphasis`.
//!
//! [action]                  # interactive / brand color
//! primary = "#81a1c1"
//!
//! [status]                  # state semantics
//! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
//!
//! [line]
//! border = "#4c566a"
//!
//! [category]                # distinct decorative colors for tags/badges/charts
//! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
//! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
//! ```

// Color-space math: single-letter channel names (r/g/b/l/m/s) and the published
// high-precision OKLab/sRGB matrix constants are the domain vocabulary here.
#![allow(clippy::many_single_char_names, clippy::unreadable_literal)]

use serde::Serialize;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

/// The color sections an authored theme may declare.
pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];

/// Theme metadata parsed from the `[meta]` section.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeMeta {
    pub id: String,
    pub name: String,
    pub variant: String,
    pub is_custom: bool,
}

/// A loaded theme: metadata plus the authored colors, flattened to dotted keys
/// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeColors {
    pub meta: ThemeMeta,
    pub colors: HashMap<String, String>,
}

// ============================================================================
// Color math — perceptual (OKLab) derivations + WCAG contrast.
//
// Interactive states (hover/active/selection/surfaces) are derived in OKLab so
// equal steps look equal across every theme's hues (Ottosson 2020; the modern
// CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
// luminance threshold, so the choice actually meets AA where achievable.
// This is the single source of truth shared by every product.
// ============================================================================

/// An sRGB color. Hex round-trips losslessly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Rgb {
    /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
    pub fn from_hex(s: &str) -> Option<Rgb> {
        let h = s.strip_prefix('#')?;
        let (r, g, b) = match h.len() {
            6 => (
                u8::from_str_radix(&h[0..2], 16).ok()?,
                u8::from_str_radix(&h[2..4], 16).ok()?,
                u8::from_str_radix(&h[4..6], 16).ok()?,
            ),
            3 => {
                let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
                (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
            }
            _ => return None,
        };
        Some(Rgb { r, g, b })
    }

    /// Lowercase `#rrggbb`.
    pub fn to_hex(self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }

    pub fn tuple(self) -> (u8, u8, u8) {
        (self.r, self.g, self.b)
    }
}

/// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
#[derive(Clone, Copy, Debug)]
pub struct Oklab {
    pub l: f32,
    pub a: f32,
    pub b: f32,
}

fn srgb_to_linear(c: u8) -> f32 {
    let c = c as f32 / 255.0;
    if c <= 0.04045 {
        c / 12.92
    } else {
        ((c + 0.055) / 1.055).powf(2.4)
    }
}

fn linear_to_srgb(c: f32) -> u8 {
    let c = c.clamp(0.0, 1.0);
    let v = if c <= 0.0031308 {
        c * 12.92
    } else {
        1.055 * c.powf(1.0 / 2.4) - 0.055
    };
    (v * 255.0).round().clamp(0.0, 255.0) as u8
}

impl Rgb {
    /// Convert to OKLab (Ottosson's sRGB matrices).
    ///
    /// The matrix coefficients are quoted at their published precision so they
    /// can be diffed against the reference. `f32` rounds them at compile time;
    /// truncating the literals would only make them harder to check.
    #[allow(clippy::excessive_precision)]
    pub fn to_oklab(self) -> Oklab {
        let (r, g, b) = (
            srgb_to_linear(self.r),
            srgb_to_linear(self.g),
            srgb_to_linear(self.b),
        );
        let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
        let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
        let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
        let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
        Oklab {
            l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
            a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
            b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
        }
    }

    /// Convert from OKLab back to the nearest in-gamut sRGB.
    ///
    /// Published precision, as in [`Rgb::to_oklab`].
    #[allow(clippy::excessive_precision)]
    pub fn from_oklab(c: Oklab) -> Rgb {
        let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
        let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
        let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
        let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
        Rgb {
            r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
            g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
            b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
        }
    }
}

/// WCAG 2.x relative luminance of an sRGB color.
fn rel_luminance(c: Rgb) -> f32 {
    0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
}

/// WCAG 2.x contrast ratio between two colors, in [1, 21].
pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
    let (la, lb) = (rel_luminance(a), rel_luminance(b));
    let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
    (hi + 0.05) / (lo + 0.05)
}

/// Pick black or white for legible text on `bg`, by the higher WCAG contrast
/// ratio (so the choice meets AA wherever the background allows it).
pub fn readable_on(bg: Rgb) -> Rgb {
    let white = Rgb {
        r: 255,
        g: 255,
        b: 255,
    };
    let black = Rgb { r: 0, g: 0, b: 0 };
    if wcag_contrast(white, bg) >= wcag_contrast(black, bg) {
        white
    } else {
        black
    }
}

/// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
pub fn lighten(c: Rgb, delta: f32) -> Rgb {
    let mut lab = c.to_oklab();
    lab.l = (lab.l + delta).clamp(0.0, 1.0);
    Rgb::from_oklab(lab)
}

/// Shift OKLab lightness down by `delta` (perceptually uniform).
pub fn darken(c: Rgb, delta: f32) -> Rgb {
    lighten(c, -delta)
}

/// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
    let (x, y) = (a.to_oklab(), b.to_oklab());
    Rgb::from_oklab(Oklab {
        l: x.l + (y.l - x.l) * t,
        a: x.a + (y.a - x.a) * t,
        b: x.b + (y.b - x.b) * t,
    })
}

// ============================================================================
// Tonal steps
// ============================================================================

/// How far a tonal step sits from the token it is a step of.
///
/// The named ratios. [`tonal`] is the same operation with the number written
/// out, and this is the small set of steps the vocabulary has agreed on, so a
/// consumer asking for "the muted form of this" names it rather than picking a
/// number and disagreeing with the next consumer to pick one.
///
/// The rule these encode, stated as the three-tone convention:
///
/// | step | what it means |
/// |------|---------------|
/// | [`Full`](Self::Full) | active, emphasised, the thing itself |
/// | [`Secondary`](Self::Secondary) | inactive but usable: a control that still answers |
/// | [`Muted`](Self::Muted) | inert: disabled, or not a control at all |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Emphasis {
    /// The token unchanged.
    Full,
    /// One step back. Still legible as content, not competing with `Full`.
    Secondary,
    /// Two steps back. Present, and saying it is not the point.
    Muted,
}

impl Emphasis {
    /// The fraction of the way to the ground this step travels.
    ///
    /// Both numbers are the shipped corpus' own, not invented: across the 31
    /// bundled themes, hand-authored `content.secondary` sat at a median 0.115
    /// of the way from `content.primary` to `surface.page`, and `content.muted`
    /// at 0.424. So the derivation reproduces what theme authors converged on
    /// by eye, and the themes that move are the ones that were off the cluster.
    #[must_use]
    pub const fn ratio(self) -> f32 {
        match self {
            Self::Full => 0.0,
            Self::Secondary => 0.12,
            Self::Muted => 0.42,
        }
    }

    /// The suffix a derived token takes, or `None` for the token itself.
    ///
    /// `content` + [`Muted`](Self::Muted) is `content-muted`, which is the
    /// naming every consumer already spells by hand. Grouping a family this way
    /// is what makes `danger-muted` or `action-secondary` nameable without a
    /// second table saying what they mean.
    #[must_use]
    pub const fn suffix(self) -> Option<&'static str> {
        match self {
            Self::Full => None,
            Self::Secondary => Some("-secondary"),
            Self::Muted => Some("-muted"),
        }
    }

    /// The derived token key for `token` at this step.
    #[must_use]
    pub fn token(self, token: &str) -> String {
        match self.suffix() {
            Some(suffix) => format!("{token}{suffix}"),
            None => token.to_string(),
        }
    }
}

/// The contrast a tonal step must clear against the token it is a step of.
///
/// A ratio says how far to travel, not how far that lands, and the two are the
/// same thing only when the base has room to travel in. Across the bundled
/// themes a derived `content.secondary` sits between 1.21 and 1.44 of its ink;
/// the exceptions were the two themes whose ink is `#000000`, where OKLab L is
/// 0, 12 percent of nothing is nothing, and the sRGB transfer curve compresses
/// what is left into a 3/255 move. So the floor is the bottom of the band the
/// healthy themes already reach, and a theme inside it does not move.
///
/// Deliberately below [`DISTINCT`]: that is the 3:1 two *areas* need to read as
/// separate, and an emphasis step is one voice quieter rather than a second
/// region. Asking 3:1 of it would flatten every theme's ramp into three widely
/// spaced greys.
pub const STEP_FLOOR: f32 = 1.21;

/// A tonal step of `base`, `ratio` of the way toward the `ground` it is read
/// against.
///
/// The numerical form of [`Emphasis`], for a consumer that wants a step the
/// named set does not have. `ratio` is clamped to [0,1]: past 1 the step is no
/// longer a step of `base` but a colour beyond the ground, which is a different
/// operation wearing this one's name.
///
/// # Toward the ground, not toward grey
///
/// A tonal step is a *reduction in contrast against what it is read on*, so it
/// interpolates toward the surface rather than desaturating or lightening. That
/// is why it takes two colours: lightening is wrong on a light theme and
/// darkening is wrong on a dark one, and mixing toward the ground is correct on
/// both without asking which theme this is. It is also why the ground is a
/// parameter rather than assumed — text in a well is read against the well.
///
/// # It composes
///
/// Two steps toward the same ground are one step toward that ground, since
/// OKLab interpolation is linear: `tonal(tonal(c, g, a), g, b)` is
/// `tonal(c, g, a + b - a*b)`. So a family can be derived recursively — the
/// muted form of a secondary is a well-defined colour and not a compounding
/// error — and re-deriving a token that was already derived is stable rather
/// than a slow slide into the background.
#[must_use]
pub fn tonal(base: Rgb, ground: Rgb, ratio: f32) -> Rgb {
    mix(base, ground, ratio.clamp(0.0, 1.0))
}

/// A named tonal step of `base` against the `ground` it is read on.
///
/// [`tonal`] with [`Emphasis::ratio`], and the form to reach for: the two
/// spellings of "muted" a pair of consumers pick independently are the drift
/// this replaces.
#[must_use]
pub fn emphasized(base: Rgb, ground: Rgb, emphasis: Emphasis) -> Rgb {
    tonal(base, ground, emphasis.ratio())
}

// ============================================================================
// Low-color terminals
// ============================================================================

/// The 16 colors an ANSI terminal addresses by index, in the PC/VGA
/// arrangement the Linux console and most emulators start from.
///
/// 0-7 are the normal colors and 8-15 the bright ones. Index 7 is a light gray
/// rather than white, which is the entry a themed surface usually lands on, and
/// index 15 is the true white.
///
/// Emulators let the user repaint all sixteen, so this is the standard
/// arrangement rather than a promise about any one terminal. The Linux console
/// keeps it, which is the case that matters: a console app cannot fall back to
/// 24-bit color there.
pub const ANSI_16: [Rgb; 16] = [
    Rgb {
        r: 0x00,
        g: 0x00,
        b: 0x00,
    },
    Rgb {
        r: 0xaa,
        g: 0x00,
        b: 0x00,
    },
    Rgb {
        r: 0x00,
        g: 0xaa,
        b: 0x00,
    },
    Rgb {
        r: 0xaa,
        g: 0x55,
        b: 0x00,
    },
    Rgb {
        r: 0x00,
        g: 0x00,
        b: 0xaa,
    },
    Rgb {
        r: 0xaa,
        g: 0x00,
        b: 0xaa,
    },
    Rgb {
        r: 0x00,
        g: 0xaa,
        b: 0xaa,
    },
    Rgb {
        r: 0xaa,
        g: 0xaa,
        b: 0xaa,
    },
    Rgb {
        r: 0x55,
        g: 0x55,
        b: 0x55,
    },
    Rgb {
        r: 0xff,
        g: 0x55,
        b: 0x55,
    },
    Rgb {
        r: 0x55,
        g: 0xff,
        b: 0x55,
    },
    Rgb {
        r: 0xff,
        g: 0xff,
        b: 0x55,
    },
    Rgb {
        r: 0x55,
        g: 0x55,
        b: 0xff,
    },
    Rgb {
        r: 0xff,
        g: 0x55,
        b: 0xff,
    },
    Rgb {
        r: 0x55,
        g: 0xff,
        b: 0xff,
    },
    Rgb {
        r: 0xff,
        g: 0xff,
        b: 0xff,
    },
];

/// The 256 colors an xterm-compatible terminal addresses by index, so that
/// entry `i` is what the terminal paints for `38;5;i`.
///
/// Three regions, and they are not equally trustworthy. 0-15 are the [`ANSI_16`]
/// system colors, which every emulator lets the user repaint. 16-231 are a
/// 6x6x6 RGB cube and 232-255 a 24-step gray ramp, and those 240 are fixed.
///
/// So a color whose whole job is to be told apart from another should quantize
/// against [`ANSI_240`] rather than against this table: a match landing in the
/// low sixteen is a match against a color the user may have moved.
pub const ANSI_256: [Rgb; 256] = build_ansi_256();

/// The fixed region of [`ANSI_256`]: the 6x6x6 cube and the gray ramp, without
/// the sixteen repaintable system colors.
///
/// Quantizing against this returns an index into *this* slice; add
/// [`ANSI_240_OFFSET`] to get the index the terminal wants.
pub const ANSI_240: &[Rgb] = ANSI_256.split_at(16).1;

/// What to add to an [`ANSI_240`] index to get an [`ANSI_256`] one.
pub const ANSI_240_OFFSET: usize = 16;

/// The twelve chromatic ANSI slots, as the intents that paint them.
///
/// Indexed 1-6 and 9-14. The hues do not depend on whether the theme is light
/// or dark, since red is the theme's danger tone either way, which is exactly
/// why the four achromatic slots are not in this table.
///
/// Lifted from Alloy's `skelgen` on 2026-07-31, which had folded three
/// disagreeing hand-maintained copies into one and is the reason the
/// arrangement is trusted. It moved here so a program that paints its own
/// palette at runtime, rather than reading a generated config, resolves the
/// same slots. Slot 14 was the one the copies disagreed on and is
/// `category.six`, which both the Linux console table and the retired
/// `vtrgb.py` had.
const CHROMATIC: [(usize, &str); 12] = [
    (1, "status.danger"),
    (2, "status.success"),
    (3, "status.warning"),
    (4, "status.info"),
    (5, "category.five"),
    (6, "category.six"),
    (9, "action.primary"), // bright red, the theme's warm accent
    (10, "status.success"),
    (11, "status.warning"),
    (12, "status.info"),
    (13, "category.five"),
    (14, "category.six"),
];

/// The four achromatic slots, 0, 7, 8 and 15, which invert with the theme.
///
/// These are the slots a naive table gets wrong. ANSI 0 is "black" and 7 is
/// "white", but what a terminal wants there is *the darkest tone* and *the
/// lightest tone*, and which intent that is flips with the theme's polarity. A
/// light theme's darkest tone is its ink; a dark theme's is its deepest
/// surface. Pinning slot 0 to `content.primary` reads correctly on a light
/// theme and hands a dark one a pale cream as "black".
///
/// Slot 7 is a surface and not a text tone, because it is what a program with
/// no way to name anything else draws its container on: a greeter's login card
/// is a light card on the darker field slot 0 paints.
///
/// Anything that is not `dark`, including `high-contrast`, follows the light
/// anchors.
fn achromatic_slot(index: usize, variant: &str) -> Option<&'static str> {
    let dark = variant == "dark";
    Some(match (index, dark) {
        (0, false) => "content.primary",  // darkest text tone
        (0, true) => "surface.sunken",    // darkest surface
        (7, false) => "surface.raised",   // the login card
        (7, true) => "content.secondary", // a readable light tone
        (8, _) => "content.muted",        // muted chrome, either way
        (15, false) => "surface.overlay", // lightest surface
        (15, true) => "content.primary",  // lightest text tone
        _ => return None,
    })
}

/// The authored intent painting ANSI slot `index` under a theme of `variant`,
/// as a dotted key into [`ThemeColors::colors`].
///
/// `None` for an index outside 0-15. Every slot in range resolves, so a caller
/// that has the intent can fill all sixteen.
///
/// This is what makes a bare console, a terminal emulator and a generated
/// config agree on what red means. They disagreed for as long as each kept its
/// own table.
#[must_use]
pub fn ansi_intent(index: usize, variant: &str) -> Option<&'static str> {
    achromatic_slot(index, variant).or_else(|| {
        CHROMATIC
            .iter()
            .find(|(slot, _)| *slot == index)
            .map(|(_, intent)| *intent)
    })
}

const fn build_ansi_256() -> [Rgb; 256] {
    let mut table = [Rgb { r: 0, g: 0, b: 0 }; 256];

    let mut i = 0;
    while i < 16 {
        table[i] = ANSI_16[i];
        i += 1;
    }

    // The cube's six levels are not evenly spaced. The step from black to the
    // first is more than twice any later one, which is xterm's arrangement
    // rather than a choice available here, and it is why the darkest tones a
    // theme can reach on 256 colors come from the gray ramp instead.
    const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
    let mut r = 0;
    while r < 6 {
        let mut g = 0;
        while g < 6 {
            let mut b = 0;
            while b < 6 {
                table[16 + 36 * r + 6 * g + b] = Rgb {
                    r: LEVELS[r],
                    g: LEVELS[g],
                    b: LEVELS[b],
                };
                b += 1;
            }
            g += 1;
        }
        r += 1;
    }

    // 8 to 238 in steps of 10. Neither end is black or white; both of those are
    // in the cube, so the ramp is 24 steps of gray between them rather than 24
    // steps of the whole range.
    let mut k = 0;
    while k < 24 {
        let v = 8 + 10 * k as u8;
        table[232 + k as usize] = Rgb { r: v, g: v, b: v };
        k += 1;
    }

    table
}

/// The contrast ratio two colors must clear to read as separate areas.
///
/// WCAG 2.x asks 3:1 of user interface components and graphics, which is what
/// a border, a rule, or a focus ring is. Text wants more, and a caller drawing
/// text can ask for more by checking [`wcag_contrast`] itself.
pub const DISTINCT: f32 = 3.0;

/// Perceptual distance between two colors, for choosing the closest of a set.
fn oklab_distance(a: Rgb, b: Rgb) -> f32 {
    let (x, y) = (a.to_oklab(), b.to_oklab());
    ((x.l - y.l).powi(2) + (x.a - y.a).powi(2) + (x.b - y.b).powi(2)).sqrt()
}

/// Index of the entry in `palette` that looks most like `c`.
///
/// OKLab distance rather than distance in sRGB, for the same reason [`mix`]
/// interpolates there: sRGB's numbers are not spaced the way seeing is, so a
/// nearest match computed in it picks visibly wrong entries in the mid tones.
///
/// # Panics
///
/// If `palette` is empty.
pub fn quantize(c: Rgb, palette: &[Rgb]) -> usize {
    assert!(!palette.is_empty(), "a palette needs at least one color");
    let mut best = 0;
    let mut best_distance = f32::INFINITY;
    for (index, entry) in palette.iter().enumerate() {
        let distance = oklab_distance(c, *entry);
        if distance < best_distance {
            best = index;
            best_distance = distance;
        }
    }
    best
}

/// Index of the entry in `palette` closest to `fg` that still reads against
/// `bg`.
///
/// [`quantize`] answers about one color at a time, and two colors that differ
/// can quantize to the same entry: a themed page and a border drawn on it are
/// often a few steps apart in a 24-bit theme and land together on a 16-color
/// terminal, leaving one flat area where there was a frame. Alloy's console
/// showed exactly this, and it is not a contrived pairing: a light page and the
/// mid-tone border derived from it both land on index 7.
///
/// So the background is quantized first, because what the border must be
/// distinguished from is the entry the terminal will actually paint, not the
/// color the theme asked for. Then the nearest entry to `fg` clearing
/// [`DISTINCT`] against it wins. When nothing clears it, the entry that gets
/// furthest does: at that point the palette cannot honor the design, and the
/// most legible approximation beats the closest invisible one.
///
/// Only for colors whose whole job is to be told apart from their background.
/// Applied to every token it would push a deliberately quiet one until it
/// shouted.
///
/// # Panics
///
/// If `palette` is empty.
pub fn quantize_against(fg: Rgb, bg: Rgb, palette: &[Rgb]) -> usize {
    assert!(!palette.is_empty(), "a palette needs at least one color");
    let shown = palette[quantize(bg, palette)];

    let mut order: Vec<usize> = (0..palette.len()).collect();
    order.sort_by(|a, b| {
        oklab_distance(fg, palette[*a]).total_cmp(&oklab_distance(fg, palette[*b]))
    });

    order
        .iter()
        .copied()
        .find(|index| wcag_contrast(palette[*index], shown) >= DISTINCT)
        .unwrap_or_else(|| {
            order
                .iter()
                .copied()
                .max_by(|a, b| {
                    wcag_contrast(palette[*a], shown).total_cmp(&wcag_contrast(palette[*b], shown))
                })
                .expect("the palette is not empty")
        })
}

// ============================================================================
// Intent resolution
// ============================================================================

/// Base intents: (TOML dotted source key, canonical token key). The token key
/// is the CSS-var stem (`--{token}`) and the `rgb()` lookup key.
///
/// Read straight from the loaded theme, which is not quite the same as read
/// from the file: `content.secondary` and `content.muted` are tonal steps of
/// `content.primary` and are filled in at load by [`derive_tonal_steps`], so
/// they arrive here already computed and take this path like any other.
pub const BASE_INTENTS: &[(&str, &str)] = &[
    ("surface.page", "surface-page"),
    ("surface.raised", "surface-raised"),
    ("surface.sunken", "surface-sunken"),
    ("surface.overlay", "surface-overlay"),
    ("content.primary", "content"),
    ("content.secondary", "content-secondary"),
    ("content.muted", "content-muted"),
    ("action.primary", "action"),
    ("status.danger", "danger"),
    ("status.success", "success"),
    ("status.warning", "warning"),
    ("status.info", "info"),
    ("line.border", "border"),
    ("category.one", "category-one"),
    ("category.two", "category-two"),
    ("category.three", "category-three"),
    ("category.four", "category-four"),
    ("category.five", "category-five"),
    ("category.six", "category-six"),
];

/// A fully resolved intent layer: every token key → concrete `#rrggbb`.
/// Includes both authored base intents and the computed derived intents.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticTokens {
    pub meta: ThemeMeta,
    /// token-key → resolved hex. Stable, deterministic ordering.
    pub intents: BTreeMap<String, String>,
}

impl SemanticTokens {
    /// Resolved hex for a token key, if present.
    pub fn hex(&self, key: &str) -> Option<&str> {
        self.intents.get(key).map(String::as_str)
    }

    /// Resolved RGB tuple for a token key (for egui / native consumers).
    ///
    /// `None` for a translucent token. Two intents are emitted as `rgba(...)`
    /// rather than hex, `overlay` and `elevation`, and dropping the alpha would
    /// hand a native consumer an opaque near-black where it asked for a scrim.
    /// Those want [`rgba`](Self::rgba).
    pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
        self.intents
            .get(key)
            .and_then(|h| Rgb::from_hex(h))
            .map(Rgb::tuple)
    }

    /// Resolved RGBA tuple for a token key, alpha as 0-255.
    ///
    /// Reads both spellings, so a caller that does not care whether an intent
    /// happens to be translucent can use this for everything: an opaque token
    /// comes back at 255.
    ///
    /// It exists because a CSS consumer can take `rgba(...)` as a string
    /// straight out of [`hex`](Self::hex) and a native one cannot. Without it
    /// the two translucent intents are reachable from a stylesheet and from
    /// nowhere else, which is the coupling deriving in the crate was meant to
    /// avoid.
    pub fn rgba(&self, key: &str) -> Option<(u8, u8, u8, u8)> {
        let value = self.intents.get(key)?;
        if let Some(rgb) = Rgb::from_hex(value) {
            let (r, g, b) = rgb.tuple();
            return Some((r, g, b, 255));
        }
        let inner = value.strip_prefix("rgba(")?.strip_suffix(')')?;
        let mut parts = inner.split(',').map(str::trim);
        let r = parts.next()?.parse().ok()?;
        let g = parts.next()?.parse().ok()?;
        let b = parts.next()?.parse().ok()?;
        let alpha: f32 = parts.next()?.parse().ok()?;
        if parts.next().is_some() || !(0.0..=1.0).contains(&alpha) {
            return None;
        }
        Some((r, g, b, (alpha * 255.0).round() as u8))
    }
}

/// Resolve an authored theme into the full intent token set.
///
/// 1. Copy each present base intent from the authored colors.
/// 2. Compute the derived interactive states from the base intents, using the
///    same math the apps used to apply individually (so output is identical).
///
/// Each derived token is emitted only when its source intents exist, mirroring
/// the skip-missing behavior of the rest of the crate.
pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
    let mut intents: BTreeMap<String, String> = BTreeMap::new();

    // 1. Base intents (authored). Copy only values that parse as a hex color and
    // re-emit them in canonical `#rrggbb` form, so an authored value can never
    // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
    // raw into a `<style>` block by the web server). A malformed value is skipped,
    // mirroring the skip-missing behavior for absent intents.
    for (src, token) in BASE_INTENTS {
        if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
            intents.insert((*token).to_string(), rgb.to_hex());
        }
    }

    // Helper: parse an already-resolved token to Rgb.
    let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));

    // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
    // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
    let mut derived: Vec<(String, Rgb)> = Vec::new();
    if let Some(action) = get(&intents, "action") {
        derived.push(("action-hover".into(), lighten(action, 0.05)));
        derived.push(("content-on-action".into(), readable_on(action)));
        // The focus ring is the action colour itself, not a tint of it: a ring
        // is a statement that the keyboard is here, and a faded one reads as a
        // disabled control rather than an emphatic one.
        //
        // One ring, not one per primitive. Where the ring sits is a depth
        // question and not a per-component choice: a well takes it inside its
        // own edge and a raised surface takes it outside. That is one decision
        // with two renderings rather than one decision per component, which is
        // how the three apps ended up with three rings. This token is the one
        // shared artifact; which thing wears it, and how it is drawn, is each
        // renderer's own (see `makeover_layout`'s crate header, "reach, focus
        // and the focus ring").
        derived.push(("focus-ring".into(), action));
    }
    if let Some(page) = get(&intents, "surface-page") {
        // Modal scrim: a near-black tone carrying a faint hint of the theme's
        // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
        // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
        // it is inserted directly rather than through the hex loop below.
        let mut o = page.to_oklab();
        o.l = 0.08;
        let s = Rgb::from_oklab(o);
        intents.insert(
            "overlay".into(),
            format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b),
        );

        // What a surface that FLOATS OVER the page is cast onto it with.
        //
        // The one intent here about a surface's relationship to the page rather
        // than about the surface itself, which is why it is derived from `page`
        // and not from `surface-raised`. A shadow is not the thing, it is the
        // absence of light on what is behind the thing.
        //
        // SCOPE, and it is the whole point of this intent existing rather than
        // a general "shadow": a surface that overlays the page takes this, a
        // surface IN the page takes a bevel. Menus, toasts, popovers and
        // dropdowns overlay. A card, a plate and a framed image do not, and
        // reaching for this on one of those is how a pre-Platinum look survives
        // a conversion wearing a token's name. `.raised` is the answer there.
        //
        // Same anchor as the scrim above and for the same reason: a tone read
        // off the theme's hue but pinned very dark, so it reads as absence of
        // light on a light theme and on a dark one alike. A shadow tinted to a
        // dark theme's own lightness would not be a shadow.
        //
        // The alpha is the only number here that is a look decision rather than
        // a derivation. 0.18 sits between the two literal scales it replaces:
        // the MNW server's --shadow-2 (0.10) reads as nothing under a menu, and
        // its --shadow-3 (0.15) was measured invisible at plate size. Geometry
        // stays with the consumer, the way bevel thickness does.
        intents.insert(
            "elevation".into(),
            format!("rgba({}, {}, {}, 0.18)", s.r, s.g, s.b),
        );
    }
    if let Some(raised) = get(&intents, "surface-raised") {
        // The two edges of a bevel: a raised control is lit from the top left,
        // so its top and left edges take `bevel-light` and its bottom and right
        // edges `bevel-dark`. Inverting the pair gives a pressed state and an
        // inset well, which is what makes the idiom cheap for a consumer.
        //
        // Derived here rather than composed per-app because the two webviews
        // could do it in `color-mix()` and audiofiles, which is egui, could not.
        // Geometry (thickness, radius, which side gets which) stays app-side.
        //
        // The deltas are asymmetric because the eye is: an equal step down reads
        // as a smaller change than the same step up, so the shadow is cut deeper
        // than the highlight is raised.
        //
        // A face already at the top of the ramp cannot hold a highlight — the
        // lightening clamps and the control bevels on two sides without ever
        // resolving as lit. That is a property of the theme, not of this
        // derivation; `bevel_edges_are_distinct_from_their_face` names the
        // shipped themes it currently bites.
        derived.push(("bevel-light".into(), lighten(raised, 0.14)));
        derived.push(("bevel-dark".into(), darken(raised, 0.18)));

        // An inset well: the content surface inside a raised container, so a
        // list reads as content in a container rather than as bands on a panel.
        // `surface-sunken` cannot serve, because a theme is free to author it
        // darker than raised (goingson does) and a well has to go the other way.
        //
        // Which way is "the other way" depends on the theme, and this is the one
        // derivation here that inverts. A well is lighter than its face on a
        // light theme and darker on a dark one, where the bevel pair sidesteps
        // the question by emitting both directions at once.
        //
        // Read the direction off `content` rather than off `Variant`. A theme
        // whose text is dark is a theme whose surfaces are light, whatever its
        // `variant` field claims, so this resolves correctly even when that
        // field is wrong and it keeps the branch on measured color rather than
        // on metadata.
        //
        // Deltas are asymmetric for the same reason the bevel's are, and smaller
        // than the bevel's because a well is an area rather than an edge. The
        // step up is the specimen's, measured: #D9DDF4 to #F3F5FD is 0.069.
        //
        // A face at the top of its ramp cannot hold a lighter well, the same
        // clamp `bevel-light` hits; `well_is_visible_against_its_face` names the
        // shipped themes where it bites.
        if let Some(content) = get(&intents, "content") {
            let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
            let well = if content_is_darker {
                lighten(raised, 0.07)
            } else {
                darken(raised, 0.09)
            };
            derived.push(("surface-well".into(), well));
        }
    }
    if let Some(sunken) = get(&intents, "surface-sunken") {
        derived.push(("hover-surface".into(), sunken));
    }
    if let Some(border) = get(&intents, "border") {
        derived.push(("border-strong".into(), darken(border, 0.05)));
    }

    for (token, rgb) in derived {
        intents.insert(token, rgb.to_hex());
    }

    SemanticTokens {
        meta: theme.meta.clone(),
        intents,
    }
}

/// Emit the resolved intent layer as CSS declarations (no selector), one
/// `  --token: #hex;` line each, in deterministic (BTreeMap) order.
pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
    let mut out = String::new();
    for (token, hex) in &tokens.intents {
        out.push_str("  --");
        out.push_str(token);
        out.push_str(": ");
        out.push_str(hex);
        out.push_str(";\n");
    }
    out
}

/// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
/// CSS mapping every web surface injects.
pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
    format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
}

// ============================================================================
// Typography — layer 1 of the house font model.
//
// Wiki `typography-standard`. The model is three layers: an app override, the
// house default, then a system generic, and this is the middle one. Two needs,
// two names, and no others in the suite:
//
//     --font-mono   Quasi Mono   ->  monospace
//     --font-sans   Quasi Body   ->  sans-serif
//
// Both are cut by `quasi-type` from the Atkinson Hyperlegible superfamily plus
// the house glyph set. This crate does not cut them and cannot: quasi-type is
// `publish = false` and makeover is on crates.io, so the cut lives in each
// consumer's own build script (`quasi_type::cut`, taken as a git dependency,
// the way `shop-font` does it). What lives here is the vocabulary, which is
// the half that was scattered.
//
// Font is not a theme's business and none of this is themeable. A theme
// declares colour by role; nothing in a theme file names a face, and the two
// tokens below are the same in every theme. That is why they are constants
// rather than another section of `SemanticTokens`, and why they belong in a
// stylesheet generated once at build time rather than in the block that gets
// re-injected on a theme switch.
//
// The brand/display tier is out of scope, per product and by decision: Young
// Serif on MNW, Reglo in GoingsOn, Departure Mono on Alloy, audiofiles' logo
// face. No renderer emits them and no described screen resolves a token to
// one, so they keep their own `font-family` until the app-override layer
// lands and gives them a place to be declared.
// ============================================================================

/// The mono slot: code, data, identifiers, cell grids, anything monospaced.
pub const FONT_MONO: &str = "\"Quasi Mono\", monospace";

/// The body / UI slot. Everything that is not the mono slot or brand tier.
pub const FONT_SANS: &str = "\"Quasi Body\", sans-serif";

/// The family name inside [`FONT_MONO`], on its own, for a consumer that needs
/// the name rather than the stack. A test asserts the two agree.
pub const HOUSE_MONO_FAMILY: &str = "Quasi Mono";

/// The family name inside [`FONT_SANS`]. See [`HOUSE_MONO_FAMILY`].
pub const HOUSE_SANS_FAMILY: &str = "Quasi Body";

/// The weight range both house faces carry.
///
/// They are variable, `wght` 200-800, and a declaration that omits the range
/// makes every weight resolve to the file's default instance — which is
/// ExtraLight, because a cut keeps its base's default.
pub const HOUSE_WEIGHT_RANGE: &str = "200 800";

/// Filename a consumer writes the cut mono face to, under its own font URL.
///
/// `quasi-type` writes `QuasiMono[wght].woff2`, naming the variable axis the
/// way a font tool expects. Those brackets have to be percent-encoded to
/// survive a URL and are a bug waiting to be written, so the web copy takes a
/// plain name and the two places that have to agree — the build script that
/// writes the file and the `@font-face` that fetches it — agree through this
/// constant rather than by both spelling it out.
pub const WEBFONT_MONO_FILE: &str = "QuasiMono.woff2";

/// Filename a consumer writes the cut body face to. See [`WEBFONT_MONO_FILE`].
pub const WEBFONT_SANS_FILE: &str = "QuasiBody.woff2";

/// The house font tokens as CSS declarations (no selector), for a caller that
/// is composing its own block.
pub fn typography_css_declarations() -> String {
    format!("  --font-mono: {FONT_MONO};\n  --font-sans: {FONT_SANS};\n")
}

/// The house font tokens as a `:root { … }` block.
///
/// Inlined by surfaces that cannot link a stylesheet — the MNW embeds are the
/// live case — and written to a file by everything else, through
/// `makeover_build::typography_css`.
pub fn typography_css_vars() -> String {
    format!(":root {{\n{}}}\n", typography_css_declarations())
}

/// The `@font-face` rules for both slots, fetching from `base_url`.
///
/// `base_url` is the directory the consumer serves its fonts from, without a
/// trailing slash: `/static/fonts` on the MNW server, `fonts` for a Tauri
/// frontend loading relative to its index.
///
/// # `font-weight: 200 800`, which is the part that bites
///
/// Both faces are variable over `wght` 200-800 in one file, and the mono
/// face's **default instance is ExtraLight** — that is upstream Atkinson's
/// default and the cut keeps the axis rather than pinning a master, so a
/// consumer that loads the file and takes what it opens at draws its whole UI
/// at 200. Declaring the range here is what makes the browser resolve `normal`
/// to 400 and `bold` to 700 instead. shop hit the same trap from the other
/// side and names `wght` 400 explicitly in its shaper; this is the web's
/// version of that fix, stated once for every consumer.
///
/// `font-display: swap` on both: the faces are 31KB and 50KB, they are cached
/// hard after the first paint, and a flash of the fallback beats invisible
/// text either way.
pub fn font_face_css(base_url: &str) -> String {
    // Rendered from the same `FontFace` a product override uses, rather than
    // written out here a second time. It used to be a format string, which is
    // why the house tier could be emitted and not read.
    let base = base_url.trim_end_matches('/');
    FontSlot::ALL
        .iter()
        .filter_map(|slot| slot.house_face())
        .map(|face| face.css(base))
        .collect()
}

// ============================================================================
// Typography — layer 0, the app override.
//
// Wiki `typography-standard`, GO makeover `174ab3c1`. Layer 1 above is what
// every product shares; this is the one declaration a product is allowed to
// make for itself:
//
//     layer 0   app override     per product, optional   MNW display -> Young Serif
//     layer 1   house default    the quasi-* slot font   quasi-mono  -> Quasi Mono
//     layer 2   system generic   one hop, no further     monospace / sans-serif
//
// The brand tier was already exempt by decision (`cdf8ac09`), and the exemption
// was enforced by those faces simply not being in the vocabulary — so each
// product reached its own face through a hardcoded `font-family` and an
// `@font-face` block it maintained by hand, which is the exact shape the
// unification is deleting everywhere else. This turns the carve-out into a
// mechanism: the per-product face is declared once, in the build script that
// already writes the typography layer, and is readable as an override rather
// than as a stylesheet nobody unified.
//
// It permits overriding `mono` and `sans` too. No product wants that today,
// and a layer that only allows overriding the slot nobody describes is not a
// layer, it is the exemption restated.
//
// **One declaration per product per slot.** [`Typography::with_override`]
// panics on a second override of the same slot rather than letting the last
// one win: a product with two answers for a slot has the vocabulary wrong, and
// that is the thing to fix.
//
// # What a renderer does when it cannot honour one
//
// Declare once, renderers honour what they can. Today only the webview surface
// has a face to honour at all — neither `makeover-tui` nor `makeover-immediate`
// emits a `font-family` from anywhere, because the terminal owns the face in
// one and the app loads its own font stack in the other. So an override is
// honoured by the generated stylesheet and ignored, silently and correctly, by
// the other two. That last clause was too strong and 2.10.0 corrected it: egui
// can reach a face perfectly well, it just needs the file rather than a stack.
// audiofiles honours its override with no stylesheet anywhere in the path. A renderer that gains font control later reads
// [`Typography::resolve`] rather than the CSS, which is why the resolution is
// a method on the data and not a string-building detail. Loading a file needs
// one thing more than the stack — the family name and the source to load it
// from — so [`Typography::faces`] is the same data read the other way, and
// between them an egui or TUI surface can honour an override without a
// stylesheet anywhere in the path. audiofiles is the first to do it.
// ============================================================================

/// A slot in the house font vocabulary — the unit an override replaces.
///
/// Three, and the third is deliberately empty by default: `display` is the
/// brand tier, it has no house answer, and a product that does not override it
/// leaves the token undefined so whatever the consumer wrote as a fallback
/// renders. The MNW embeds rely on exactly that.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FontSlot {
    /// Code, data, identifiers, cell grids. [`FONT_MONO`] by default.
    Mono,
    /// Body and UI text: everything that is not mono or brand. [`FONT_SANS`].
    Sans,
    /// The brand / display tier. No house default, per `cdf8ac09`.
    Display,
}

impl FontSlot {
    /// Every slot, in the order they are emitted.
    pub const ALL: [FontSlot; 3] = [FontSlot::Mono, FontSlot::Sans, FontSlot::Display];

    /// The custom property this slot is read through.
    pub fn token(self) -> &'static str {
        match self {
            FontSlot::Mono => "--font-mono",
            FontSlot::Sans => "--font-sans",
            FontSlot::Display => "--font-display",
        }
    }

    /// The house stack, or `None` for the brand tier.
    pub fn house_default(self) -> Option<&'static str> {
        match self {
            FontSlot::Mono => Some(FONT_MONO),
            FontSlot::Sans => Some(FONT_SANS),
            FontSlot::Display => None,
        }
    }

    /// The house face behind that stack, or `None` for the brand tier.
    ///
    /// The counterpart of [`house_default`](Self::house_default), and the same
    /// split as [`Typography::resolve`] against [`Typography::faces`]: one
    /// names the family that wins, the other names the file behind it. The
    /// house tier was a format string until this existed, so it could be
    /// emitted and not read — which made [`Typography::faces`] answer for the
    /// brand tier and stay silent about the other two.
    ///
    /// The sources are the **web** copies, and that is the whole of what the
    /// house tier ships today. A renderer loading a face directly wants a
    /// `ttf`, and there is no house `ttf` under any name to hand it.
    pub fn house_face(self) -> Option<FontFace> {
        let (family, file) = match self {
            FontSlot::Mono => (HOUSE_MONO_FAMILY, WEBFONT_MONO_FILE),
            FontSlot::Sans => (HOUSE_SANS_FAMILY, WEBFONT_SANS_FILE),
            FontSlot::Display => return None,
        };
        Some(
            FontFace::new(family, [file])
                .weight(HOUSE_WEIGHT_RANGE)
                .style("normal"),
        )
    }
}

/// One `@font-face` an override brings with it.
///
/// A product overriding a slot usually has to ship the face too, and the two
/// halves have to agree on a family name. Declaring them together is what
/// makes that agreement structural rather than a string typed twice.
#[derive(Debug, Clone)]
pub struct FontFace {
    family: String,
    sources: Vec<String>,
    weight: Option<String>,
    style: Option<String>,
}

impl FontFace {
    /// A face named `family`, fetched from `sources`.
    ///
    /// Each source is either a bare filename, resolved against the
    /// [`Typography`] base URL, or an absolute one (`/…` or `https://…`) taken
    /// as written. The `format()` hint is inferred from the extension —
    /// `woff2`, `woff`, `ttf`, `otf` — and omitted for anything else rather
    /// than guessed, since a wrong hint is worse than none.
    pub fn new<S: Into<String>>(
        family: impl Into<String>,
        sources: impl IntoIterator<Item = S>,
    ) -> Self {
        Self {
            family: family.into(),
            sources: sources.into_iter().map(Into::into).collect(),
            weight: None,
            style: None,
        }
    }

    /// `font-weight`, as CSS writes it: `"700"`, or `"200 800"` for a variable
    /// axis. Omitted when unset, which means `normal`.
    ///
    /// A variable face MUST name its range here for the same reason the house
    /// faces do: a `@font-face` with no range makes the browser resolve every
    /// weight to the file's default instance.
    #[must_use]
    pub fn weight(mut self, weight: impl Into<String>) -> Self {
        self.weight = Some(weight.into());
        self
    }

    /// `font-style`. Omitted when unset, which means `normal`.
    #[must_use]
    pub fn style(mut self, style: impl Into<String>) -> Self {
        self.style = Some(style.into());
        self
    }

    /// The family name, as the stack has to spell it.
    ///
    /// For a renderer that loads faces rather than emitting CSS this is the
    /// name it registers the file under, and reading it here is what keeps
    /// that name from being typed a second time.
    pub fn family(&self) -> &str {
        &self.family
    }

    /// The sources, unresolved — bare filenames as they were declared, not
    /// joined to any base URL. A renderer loading from disk or from an
    /// `include_bytes!` wants the filename; only the CSS wants the URL.
    pub fn sources(&self) -> &[String] {
        &self.sources
    }

    fn css(&self, base: &str) -> String {
        use std::fmt::Write as _;

        let src = self
            .sources
            .iter()
            .map(|s| {
                let url = if s.starts_with('/') || s.contains("://") {
                    s.clone()
                } else {
                    format!("{base}/{s}")
                };
                match font_format(s) {
                    Some(fmt) => format!("url(\"{url}\") format(\"{fmt}\")"),
                    None => format!("url(\"{url}\")"),
                }
            })
            .collect::<Vec<_>>()
            .join(",\n       ");

        let mut out = format!(
            "@font-face {{\n  font-family: \"{}\";\n  src: {src};\n",
            self.family
        );
        if let Some(w) = &self.weight {
            let _ = writeln!(out, "  font-weight: {w};");
        }
        if let Some(s) = &self.style {
            let _ = writeln!(out, "  font-style: {s};");
        }
        out.push_str("  font-display: swap;\n}\n\n");
        out
    }
}

/// The `format()` hint for a source, by extension. `None` when unrecognised.
fn font_format(source: &str) -> Option<&'static str> {
    match source.rsplit('.').next()?.to_ascii_lowercase().as_str() {
        "woff2" => Some("woff2"),
        "woff" => Some("woff"),
        "ttf" => Some("truetype"),
        "otf" => Some("opentype"),
        _ => None,
    }
}

/// One product's answer for one slot: the stack, and any faces it ships.
#[derive(Debug, Clone)]
pub struct FontOverride {
    slot: FontSlot,
    stack: String,
    faces: Vec<FontFace>,
}

impl FontOverride {
    /// Point `slot` at `stack`.
    ///
    /// `stack` is the CSS value the token takes, written the way the house
    /// stacks are: the family, then one hop to a system generic. Layer 2 is
    /// still one hop and no further — an override is a different answer to the
    /// slot, not a licence to write the fallback chain the standard deleted.
    pub fn new(slot: FontSlot, stack: impl Into<String>) -> Self {
        Self {
            slot,
            stack: stack.into(),
            faces: Vec::new(),
        }
    }

    /// Ship a face with the override.
    #[must_use]
    pub fn with_face(mut self, face: FontFace) -> Self {
        self.faces.push(face);
        self
    }

    /// The slot this answers.
    pub fn slot(&self) -> FontSlot {
        self.slot
    }

    /// The stack it resolves to.
    pub fn stack(&self) -> &str {
        &self.stack
    }

    /// The faces it ships, in declaration order.
    pub fn faces(&self) -> &[FontFace] {
        &self.faces
    }
}

/// The whole typography layer for one product: the house defaults, plus
/// whatever it overrides.
///
/// This is what a build script composes and what
/// `makeover_build::typography_css_from` writes. [`typography_css_vars`] and
/// [`font_face_css`] are the no-override case of it and stay for callers that
/// have nothing to declare.
#[derive(Debug, Clone)]
pub struct Typography {
    base_url: String,
    overrides: Vec<FontOverride>,
}

impl Typography {
    /// The house layer alone, fetching faces from `base_url` — the directory
    /// the consumer serves fonts from, with or without a trailing slash.
    pub fn house(base_url: impl Into<String>) -> Self {
        Self {
            base_url: base_url.into(),
            overrides: Vec::new(),
        }
    }

    /// Add one product override.
    ///
    /// # Panics
    ///
    /// If the slot is already overridden. One declaration per product per
    /// slot: a second is not a merge to resolve, it is two answers to a
    /// question that has one, and the vocabulary is what wants fixing.
    #[must_use]
    pub fn with_override(mut self, ov: FontOverride) -> Self {
        assert!(
            !self.overrides.iter().any(|o| o.slot == ov.slot),
            "{} is overridden twice; one declaration per product per slot",
            ov.slot.token()
        );
        self.overrides.push(ov);
        self
    }

    /// What `slot` resolves to under this layer, or `None` for a brand slot
    /// nobody overrode.
    ///
    /// The resolution, for a renderer that has a face to choose rather than a
    /// stylesheet to emit.
    pub fn resolve(&self, slot: FontSlot) -> Option<&str> {
        self.overrides
            .iter()
            .find(|o| o.slot == slot)
            .map(|o| o.stack.as_str())
            .or_else(|| slot.house_default())
    }

    /// The faces a product ships for `slot`, in declaration order, or an
    /// empty slice for a slot it did not override.
    ///
    /// The other half of [`resolve`](Self::resolve), for a renderer that has
    /// to load a file rather than name a stack: `resolve` says which family
    /// wins, this says where the bytes come from and what to call them. The
    /// house faces are not here — they belong to the slot rather than to any
    /// one product, and [`FontSlot::house_face`] is where they answer.
    pub fn faces(&self, slot: FontSlot) -> &[FontFace] {
        self.overrides
            .iter()
            .find(|o| o.slot == slot)
            .map_or(&[], |o| o.faces())
    }

    /// The `@font-face` rules: the two house faces, then each override's.
    pub fn font_face_css(&self) -> String {
        let base = self.base_url.trim_end_matches('/');
        let mut out = font_face_css(base);
        for ov in &self.overrides {
            for face in &ov.faces {
                out.push_str(&face.css(base));
            }
        }
        out
    }

    /// The resolved tokens as CSS declarations, no selector.
    pub fn css_declarations(&self) -> String {
        use std::fmt::Write as _;

        let mut out = String::new();
        for slot in FontSlot::ALL {
            if let Some(stack) = self.resolve(slot) {
                let _ = writeln!(out, "  {}: {stack};", slot.token());
            }
        }
        out
    }

    /// The resolved tokens as a `:root { … }` block.
    pub fn css_vars(&self) -> String {
        format!(":root {{\n{}}}\n", self.css_declarations())
    }

    /// Faces then tokens, in the order a stylesheet wants them.
    pub fn css(&self) -> String {
        format!("{}{}", self.font_face_css(), self.css_vars())
    }
}

// ============================================================================
// Loading / parsing
// ============================================================================

/// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
pub fn validate_theme_id(id: &str) -> Result<(), String> {
    if !id
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Err(format!("Invalid theme ID: {id}"));
    }
    Ok(())
}

/// Parse the `[meta]` section into `ThemeMeta`.
///
/// Falls back to the file ID as the name and `"dark"` as the variant.
pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
    let meta = table.get("meta").and_then(|m| m.as_table());
    let name = meta
        .and_then(|m| m.get("name"))
        .and_then(|v| v.as_str())
        .unwrap_or(id)
        .to_string();
    let variant = meta
        .and_then(|m| m.get("variant"))
        .and_then(|v| v.as_str())
        .unwrap_or("dark")
        .to_string();

    ThemeMeta {
        id: id.to_string(),
        name,
        variant,
        is_custom,
    }
}

// ============================================================================
// Choosing a theme.
//
// The file half of this crate was always shared; the *selection* half was not,
// and four apps re-rolled it four ways. GoingsOn stores a "system" sentinel in
// localStorage, Balanced Breakfast treats an absent value as follow-the-system
// and hardcodes two theme ids as its light/dark pair, audiofiles keeps the id
// in a synced SQLite table, and the Alloy console parses COLORFGBG. They also
// disagreed about what a variant string means: this crate defaults a missing
// one to "dark" while alloy_tui parsed an unrecognized one as light.
//
// What cannot be shared is the store — localStorage, a synced config table and
// a TOML file are genuinely different places. What can be shared, and is here,
// is the *meaning*: one vocabulary for variants, one encoding for "what did the
// user choose", and one rule for turning that into an id that exists.
// ============================================================================

/// A theme's kind, as declared by `meta.variant`.
///
/// Three, not two: one shipped theme is `high-contrast`, and an app that
/// matched on light-or-dark alone would quietly file it under the wrong one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Variant {
    Light,
    Dark,
    HighContrast,
}

impl Variant {
    /// The spelling used in a theme file and in [`ThemeMeta::variant`].
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Variant::Light => "light",
            Variant::Dark => "dark",
            Variant::HighContrast => "high-contrast",
        }
    }

    /// Read a variant string, or `None` if it names none of them.
    #[must_use]
    pub fn parse(raw: &str) -> Option<Self> {
        match raw {
            "light" => Some(Variant::Light),
            "dark" => Some(Variant::Dark),
            "high-contrast" => Some(Variant::HighContrast),
            _ => None,
        }
    }
}

impl std::fmt::Display for Variant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Anything unrecognized reads as dark, which is what [`parse_meta`] already
/// does with a missing one. Consumers that guessed light for an unknown string
/// were disagreeing with the crate that produced it.
impl From<&str> for Variant {
    fn from(raw: &str) -> Self {
        Variant::parse(raw).unwrap_or(Variant::Dark)
    }
}

impl ThemeMeta {
    /// This theme's variant as a value rather than a string.
    #[must_use]
    pub fn kind(&self) -> Variant {
        Variant::from(self.variant.as_str())
    }
}

/// The spelling of "follow whatever the system is doing", in every store.
pub const FOLLOW: &str = "system";

/// What the user chose, as opposed to what is being rendered.
///
/// The distinction is the whole point: `Follow` is a standing instruction that
/// resolves differently as the ambient mode changes, and a `Fixed` id is an
/// answer that does not. An app that stored only the rendered id could not tell
/// the two apart the next time the system flipped to dark.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ThemeSelection {
    /// Track the ambient light/dark mode.
    #[default]
    Follow,
    /// Always this theme.
    Fixed(String),
}

impl ThemeSelection {
    /// Read a stored selection. An empty or absent value is [`Follow`], which
    /// is what an app with nothing saved yet should do.
    ///
    /// [`Follow`]: ThemeSelection::Follow
    #[must_use]
    pub fn parse(raw: Option<&str>) -> Self {
        match raw.map(str::trim) {
            None | Some("" | FOLLOW) => ThemeSelection::Follow,
            Some(id) => ThemeSelection::Fixed(id.to_string()),
        }
    }

    /// The string to persist, whatever the store is.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            ThemeSelection::Follow => FOLLOW,
            ThemeSelection::Fixed(id) => id,
        }
    }

    /// Turn a selection into a theme id that exists.
    ///
    /// `ambient` is the light/dark mode the app learned however it can: a
    /// `prefers-color-scheme` media query, an OS appearance API, `COLORFGBG`
    /// from a terminal. `available` is what [`list_themes_from_dirs`] found.
    ///
    /// A `Fixed` id that is no longer on disk falls through to the same path as
    /// `Follow` rather than being returned anyway. Themes are deletable in
    /// three of the four apps, and handing back an id that will fail to load
    /// only moves the error somewhere less helpful.
    ///
    /// The fallback chain is: the app's own default for the ambient mode if it
    /// is installed, then any installed theme of that variant, then the app's
    /// default regardless. The last step means this always returns something,
    /// and an app with no theme directory at all gets the id it ships with and
    /// the load error it would have had anyway.
    #[must_use]
    pub fn resolve(
        &self,
        ambient: Variant,
        defaults: &ThemeDefaults,
        available: &[ThemeMeta],
    ) -> String {
        let installed = |id: &str| available.iter().any(|meta| meta.id == id);

        if let ThemeSelection::Fixed(id) = self
            && installed(id)
        {
            return id.clone();
        }

        let preferred = defaults.for_variant(ambient);
        if installed(preferred) {
            return preferred.to_string();
        }
        available
            .iter()
            .find(|meta| meta.kind() == ambient)
            .map_or_else(|| preferred.to_string(), |meta| meta.id.clone())
    }
}

impl std::fmt::Display for ThemeSelection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The themes an app falls back to, one per ambient mode.
///
/// App-specific on purpose: which theme is "the app's own" is the app's
/// identity, not this crate's business. What is shared is everything around it.
#[derive(Debug, Clone)]
pub struct ThemeDefaults {
    light: String,
    dark: String,
    high_contrast: Option<String>,
}

impl ThemeDefaults {
    pub fn new(light: impl Into<String>, dark: impl Into<String>) -> Self {
        Self {
            light: light.into(),
            dark: dark.into(),
            high_contrast: None,
        }
    }

    /// Name a theme for a high-contrast ambient mode. Without one, that mode
    /// falls back to the dark default, which is the safer of the two to read.
    #[must_use]
    pub fn high_contrast(mut self, id: impl Into<String>) -> Self {
        self.high_contrast = Some(id.into());
        self
    }

    #[must_use]
    pub fn for_variant(&self, variant: Variant) -> &str {
        match variant {
            Variant::Light => &self.light,
            Variant::Dark => &self.dark,
            Variant::HighContrast => self.high_contrast.as_ref().unwrap_or(&self.dark),
        }
    }
}

// ============================================================================
// Where themes are looked for.
//
// Four apps built this vector by hand, two of them byte-for-byte identically,
// and one of them built it backwards: the Alloy console pushed the user's own
// directory first, under a comment saying "highest precedence first", when both
// consumers of the vector resolve *last* wins. A user's custom theme lost to
// the packaged one of the same id.
//
// Hence a builder that names the tiers rather than a function taking a vector.
// The precedence is stated once, here, and a caller cannot express it backwards
// because the order is not theirs to choose.
// ============================================================================

/// Builds the search path [`load_theme`] and [`list_themes_from_dirs`] take.
///
/// Tiers are added in whatever order is convenient and always end up in
/// precedence order: the user's own themes win, then whatever the system
/// ships, then whatever the app bundles.
///
/// A directory that does not exist is dropped rather than carried, so callers
/// can offer every tier they might have without checking each one.
#[derive(Debug, Default, Clone)]
pub struct ThemeDirs {
    bundled: Vec<PathBuf>,
    system: Vec<PathBuf>,
    custom: Option<PathBuf>,
}

impl ThemeDirs {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Themes the app ships with. Lowest precedence.
    ///
    /// Takes more than one because a Tauri app has two: the bundled resource
    /// directory in production, and the tree `build.rs` materialized for a
    /// `cargo run` that has no resource directory at all.
    #[must_use]
    pub fn bundled(mut self, dir: Option<PathBuf>) -> Self {
        self.bundled.extend(dir);
        self
    }

    /// Themes the machine ships, from an image or a package. Overrides bundled.
    #[must_use]
    pub fn system(mut self, dir: Option<PathBuf>) -> Self {
        self.system.extend(dir);
        self
    }

    /// The user's own themes. Highest precedence, and the only tier flagged
    /// custom, which is what makes them exportable and deletable.
    #[must_use]
    pub fn custom(mut self, dir: Option<PathBuf>) -> Self {
        self.custom = dir;
        self
    }

    /// The search path, lowest precedence first.
    #[must_use]
    pub fn build(self) -> Vec<(PathBuf, bool)> {
        let mut dirs = Vec::new();
        for dir in self.bundled.into_iter().chain(self.system) {
            if dir.is_dir() {
                dirs.push((dir, false));
            }
        }
        if let Some(dir) = self.custom
            && dir.is_dir()
        {
            dirs.push((dir, true));
        }
        dirs
    }
}

/// Extract the intent color sections into a flat `HashMap` with dotted keys
/// like `"surface.page"`, `"status.danger"`, `"category.one"`.
///
/// The tonal steps of `content.primary` are filled in here rather than read, by
/// [`derive_tonal_steps`]. Anything a theme authored under those keys is
/// replaced.
pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
    let mut colors = HashMap::new();
    for section in COLOR_SECTIONS {
        if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
            for (key, val) in sect {
                if let Some(color) = val.as_str() {
                    colors.insert(format!("{section}.{key}"), color.to_string());
                }
            }
        }
    }
    derive_tonal_steps(&mut colors);
    colors
}

/// Fill in the tonal steps of `content.primary`, overwriting whatever the theme
/// authored under those keys.
///
/// # Why they are not authored
///
/// `content.secondary` and `content.muted` are not independent colours. They are
/// the ink, one step and two steps back, and a theme that names them separately
/// is stating three times something it stated once — which is how three of the
/// bundled themes came to author a `secondary` *lighter* than their own
/// `primary` (nord, solarized-dark) or identical to it (dracula), inverting the
/// emphasis ramp the whole vocabulary rests on. Deriving them makes
/// `content` > `content-secondary` > `content-muted` true by construction in
/// every theme, including one a user writes.
///
/// Applied at load rather than in [`resolve`] so that there is one answer: the
/// resolved token layer, the ANSI table ([`ansi_intent`] reads authored keys),
/// and every consumer holding a [`ThemeColors`] all see the same value. A
/// derivation visible from only one of those is how a terminal and a webview
/// come to disagree about what muted means.
///
/// Both keys need `content.primary` and `surface.page` to exist and parse. When
/// either is missing the step is skipped and anything authored is left where it
/// is, mirroring the skip-missing behaviour of the rest of the crate — a
/// half-written theme keeps whatever it has rather than losing it.
///
/// # The ratio is a starting point, not the answer
///
/// Each step is pushed further toward the page until it clears [`STEP_FLOOR`]
/// against the ink, so what the theme gets is a step that can be seen rather
/// than a step of the agreed size. The two are the same number in every bundled
/// theme but the two with a pure-black ink, where the ratio has no range to
/// travel in and the nominal step lands 3/255 from where it started.
pub fn derive_tonal_steps<S: std::hash::BuildHasher>(colors: &mut HashMap<String, String, S>) {
    let ink = colors.get("content.primary").and_then(|v| Rgb::from_hex(v));
    let page = colors.get("surface.page").and_then(|v| Rgb::from_hex(v));
    let (Some(ink), Some(page)) = (ink, page) else {
        return;
    };
    // Each step starts no nearer than the one before it landed, so pushing
    // secondary out cannot carry it past muted and invert the ramp.
    let mut reached = 0.0;
    for (key, step) in [
        ("content.secondary", Emphasis::Secondary),
        ("content.muted", Emphasis::Muted),
    ] {
        let (color, ratio) = step_clearing_floor(ink, page, step.ratio().max(reached));
        reached = ratio;
        colors.insert(key.to_string(), color.to_hex());
    }
}

/// The step `from` of the way from `ink` to `page`, pushed toward `page` until
/// it clears [`STEP_FLOOR`] against the ink it is a step of. Returns the colour
/// and the ratio it was found at.
///
/// A forward scan rather than a solve, because it wants the *first* ratio that
/// clears: contrast against the base rises with the distance travelled, but it
/// rises through sRGB's transfer curve and OKLab's chroma path, and a bisection
/// would trust a monotonicity nothing here guarantees.
///
/// Travel stops at the ground. A theme whose ink and page are the same colour
/// has no step to take, and the ground is the honest answer — nothing past it
/// is a step of the ink any more.
fn step_clearing_floor(ink: Rgb, page: Rgb, from: f32) -> (Rgb, f32) {
    // Finer than 8-bit sRGB can resolve on the shortest ramp in the corpus, so
    // the scan never steps over the first colour that clears.
    const PROBE: f32 = 0.005;
    let mut ratio = from.clamp(0.0, 1.0);
    loop {
        let color = tonal(ink, page, ratio);
        if wcag_contrast(color, ink) >= STEP_FLOOR || ratio >= 1.0 {
            return (color, ratio);
        }
        ratio = (ratio + PROBE).min(1.0);
    }
}

/// Scan directories for `.toml` theme files and return metadata for each.
///
/// Directories are checked in order; later entries override earlier ones by ID.
/// Each entry in `dirs` is `(path, is_custom)`.
pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
    let mut seen: HashMap<String, ThemeMeta> = HashMap::new();

    for (dir, is_custom) in dirs {
        let Ok(entries) = std::fs::read_dir(dir) else {
            continue;
        };

        for entry in entries {
            let Ok(entry) = entry else {
                continue;
            };
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("toml") {
                continue;
            }

            let id = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or_default()
                .to_string();

            let Ok(content) = std::fs::read_to_string(&path) else {
                continue;
            };
            let table: toml::Table = match content.parse() {
                Ok(t) => t,
                Err(_) => continue,
            };

            seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
        }
    }

    let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
    themes.sort_by(|a, b| a.name.cmp(&b.name));
    themes
}

/// Find a theme file by ID in the given directories.
///
/// Checks directories in reverse order so the highest-priority directory wins.
/// Returns `(path, is_custom)` or `None` if not found.
pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
    let filename = format!("{id}.toml");

    for (dir, is_custom) in dirs.iter().rev() {
        let path = dir.join(&filename);
        if path.is_file() {
            return Some((path, *is_custom));
        }
    }

    None
}

/// Parse a complete theme (metadata + colors) from raw TOML content, with no
/// filesystem access. For callers that embed themes at compile time.
pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
    validate_theme_id(id)?;
    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse theme '{id}': {e}"))?;
    let meta = parse_meta(id, &table, is_custom);
    let colors = extract_colors(&table);
    Ok(ThemeColors { meta, colors })
}

/// Load a complete theme (metadata + colors) by ID from the given directories.
pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
    validate_theme_id(id)?;

    let (path, is_custom) =
        find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;

    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;

    let meta = parse_meta(id, &table, is_custom);
    let colors = extract_colors(&table);

    Ok(ThemeColors { meta, colors })
}

/// Load a theme and resolve it to the full intent token set in one step.
pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
    Ok(resolve(&load_theme(dirs, id)?))
}

/// Import a theme TOML file into the custom themes directory.
///
/// Validates that the file is parseable TOML with at least one intent color
/// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
    let content = std::fs::read_to_string(source_path)
        .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;

    let table: toml::Table = content.parse().map_err(|e| format!("Invalid TOML: {e}"))?;

    let has_colors = COLOR_SECTIONS
        .iter()
        .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
    if !has_colors {
        return Err(format!(
            "Theme file must have at least one color section ({})",
            COLOR_SECTIONS.join(", ")
        ));
    }

    let id = source_path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or("Invalid file name")?
        .to_string();
    validate_theme_id(&id)?;

    std::fs::create_dir_all(custom_dir)
        .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;

    let dest = custom_dir.join(format!("{id}.toml"));
    std::fs::copy(source_path, &dest).map_err(|e| format!("Failed to copy theme: {e}"))?;

    Ok(parse_meta(&id, &table, true))
}

/// Delete a custom theme by ID.
///
/// Only operates on `custom_dir` — bundled themes are not deletable through
/// this entry point.
pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
    validate_theme_id(id)?;

    let path = custom_dir.join(format!("{id}.toml"));
    if !path.is_file() {
        return Err(format!("Custom theme '{id}' not found"));
    }

    std::fs::remove_file(&path).map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
}

/// A four-color preview for theme thumbnails: the representative swatch from
/// each of the principal roles.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemePreview {
    pub meta: ThemeMeta,
    /// Page background (`surface.page`).
    pub background: Option<String>,
    /// Body text (`content.primary`).
    pub foreground: Option<String>,
    /// Brand/interactive color (`action.primary`).
    pub accent: Option<String>,
    /// Divider/outline color (`line.border`).
    pub border: Option<String>,
}

fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
    table
        .get(section)
        .and_then(|s| s.as_table())
        .and_then(|s| s.get(key))
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string)
}

/// Load just the preview swatches for a theme — for UI thumbnails.
pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
    validate_theme_id(id)?;

    let (path, is_custom) =
        find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;

    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;

    Ok(ThemePreview {
        meta: parse_meta(id, &table, is_custom),
        background: color_at(&table, "surface", "page"),
        foreground: color_at(&table, "content", "primary"),
        accent: color_at(&table, "action", "primary"),
        border: color_at(&table, "line", "border"),
    })
}

/// Export a theme to a user-chosen path.
pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
    validate_theme_id(id)?;

    let (source, _) = find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;

    std::fs::copy(&source, dest_path).map_err(|e| format!("Failed to export theme: {e}"))?;

    Ok(())
}

/// The themes this crate ships, embedded at compile time.
///
/// `include_dir` is an implementation detail: the public API hands back plain
/// `(id, toml_source)` pairs, so how the data is embedded can change without
/// a breaking release.
static EMBEDDED: include_dir::Dir<'static> =
    include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");

/// The themes this crate ships, as `(id, toml_source)` pairs.
///
/// This is the path-free way to reach the bundled set, for consumers that
/// cannot rely on a directory existing at runtime: a crate pulled from
/// crates.io lives in a registry checkout whose location is not knowable at
/// compile time, so `include_dir!` and asset-bundling globs in the depending
/// crate have nothing stable to point at. Embedding here and re-exporting the
/// contents gives them one source of truth without a path.
///
/// Ordering follows the embedded directory and is not guaranteed; collect and
/// sort by id where a stable order matters (a theme picker, say).
pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
    EMBEDDED.files().filter_map(|file| {
        let path = file.path();
        if path.extension().and_then(|e| e.to_str()) != Some("toml") {
            return None;
        }
        let id = path.file_stem()?.to_str()?;
        Some((id, file.contents_utf8()?))
    })
}

/// The theme directory this crate ships, for use as a build-from-source
/// fallback.
///
/// Resolves against `makeover`'s own manifest directory, fixed at compile
/// time, so it works from a path dependency and from a cargo git checkout
/// alike. Installed systems should put their packaged theme directory ahead
/// of this in the search path; this is the entry that keeps `cargo run` in a
/// fresh clone from coming up with no themes at all.
///
/// Returns `None` when the directory is absent — a cargo cache that has been
/// cleaned, or a vendored copy that dropped the data — so callers degrade to
/// their remaining search path rather than failing.
pub fn bundled_themes_dir() -> Option<PathBuf> {
    let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
    if themes.is_dir() { Some(themes) } else { None }
}

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

    // ---- id validation ----

    #[test]
    fn validate_theme_id_alphanumeric() {
        assert!(validate_theme_id("darkmode").is_ok());
        assert!(validate_theme_id("Theme123").is_ok());
    }

    #[test]
    fn validate_theme_id_hyphens_underscores() {
        assert!(validate_theme_id("dark-mode").is_ok());
        assert!(validate_theme_id("my_theme_v2").is_ok());
    }

    #[test]
    fn validate_theme_id_rejects_path_traversal() {
        assert!(validate_theme_id("../etc/passwd").is_err());
        assert!(validate_theme_id("foo/bar").is_err());
        assert!(validate_theme_id("theme.toml").is_err());
    }

    // ---- low-color terminals ----

    #[test]
    fn the_ansi_palette_is_sixteen_distinct_colors() {
        let mut seen: Vec<(u8, u8, u8)> = ANSI_16.iter().map(|c| c.tuple()).collect();
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(seen.len(), 16);
    }

    // ---- the intent-to-slot table ----

    // Sixteen slots, every one of them answered. A caller filling a terminal
    // palette has no fallback for a hole: the slot would keep whatever the
    // emulator started with, and one raw ANSI colour in a themed table is more
    // obviously wrong than all sixteen would be.
    #[test]
    fn every_ansi_slot_names_an_intent_on_either_polarity() {
        for variant in ["light", "dark", "high-contrast"] {
            for index in 0..16 {
                assert!(
                    ansi_intent(index, variant).is_some(),
                    "slot {index} unanswered on {variant}"
                );
            }
            assert_eq!(ansi_intent(16, variant), None);
        }
    }

    // The property the four achromatic slots exist to hold: 0 is the darkest
    // tone the theme offers and 15 the lightest, in either polarity. A table
    // that pins slot 0 to `content.primary` passes this on a light theme and
    // inverts on a dark one, which is the bug the polarity split fixes.
    #[test]
    fn ansi_zero_is_darker_than_ansi_fifteen_on_either_polarity() {
        for id in ["akari-dawn", "akari-night"] {
            let theme = bundled(id);
            let slot = |i: usize| -> Rgb {
                let key = ansi_intent(i, &theme.meta.variant).expect("in range");
                Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
            };
            assert!(
                rel_luminance(slot(0)) < rel_luminance(slot(15)),
                "{id}: ANSI 0 {} should be darker than ANSI 15 {}",
                slot(0).to_hex(),
                slot(15).to_hex(),
            );
        }
    }

    // The pair a greeter draws with: its container on 7, its text on 0. If
    // those collapse the login screen is one flat block, and slot 7 being a
    // surface rather than a text tone is what keeps them apart.
    #[test]
    fn the_container_slot_and_the_text_slot_stay_legible() {
        for id in ["akari-dawn", "akari-night"] {
            let theme = bundled(id);
            let slot = |i: usize| -> Rgb {
                let key = ansi_intent(i, &theme.meta.variant).expect("in range");
                Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
            };
            let contrast = wcag_contrast(slot(0), slot(7));
            assert!(contrast >= 4.5, "{id}: ANSI 0 on ANSI 7 is {contrast:.2}:1");
        }
    }

    // The hues do not move with polarity. Red is the theme's danger tone on a
    // light theme and on a dark one, which is why only four slots are in the
    // polarity table at all.
    #[test]
    fn the_chromatic_slots_do_not_vary_with_polarity() {
        for index in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14] {
            assert_eq!(
                ansi_intent(index, "light"),
                ansi_intent(index, "dark"),
                "slot {index} moved with polarity"
            );
        }
    }

    fn bundled(id: &str) -> ThemeColors {
        let dir = bundled_themes_dir().expect("makeover ships its themes");
        load_theme(&[(dir, false)], id).expect("the akari pair ships")
    }

    #[test]
    fn quantize_picks_the_obvious_entry() {
        let black = Rgb { r: 0, g: 0, b: 0 };
        let white = Rgb {
            r: 255,
            g: 255,
            b: 255,
        };
        assert_eq!(quantize(black, &ANSI_16), 0);
        assert_eq!(quantize(white, &ANSI_16), 15);
    }

    // Nearest-entry quantization is per-color, so two colors a theme keeps
    // apart can arrive as one. These two are both closest to the palette's
    // light gray, and a border drawn in one on a page painted the other is not
    // drawn at all.
    #[test]
    fn two_colors_can_quantize_to_one_entry() {
        let page = Rgb::from_hex("#a8a8a8").unwrap();
        let border = Rgb::from_hex("#b4b4b4").unwrap();

        assert_eq!(quantize(page, &ANSI_16), quantize(border, &ANSI_16));
        assert_ne!(
            quantize_against(border, page, &ANSI_16),
            quantize(page, &ANSI_16)
        );
    }

    #[test]
    fn quantize_against_keeps_the_border_off_the_page() {
        let page = Rgb::from_hex("#e4ded6").unwrap();
        let border = Rgb::from_hex("#7f786d").unwrap();

        let shown_page = ANSI_16[quantize(page, &ANSI_16)];
        let shown_border = ANSI_16[quantize_against(border, page, &ANSI_16)];

        assert!(
            wcag_contrast(shown_border, shown_page) >= DISTINCT,
            "border {} on page {} is {:.2}:1",
            shown_border.to_hex(),
            shown_page.to_hex(),
            wcag_contrast(shown_border, shown_page)
        );
    }

    // A color that already reads against its background is left where it is,
    // so this can be applied without redesigning what already worked.
    #[test]
    fn quantize_against_leaves_a_readable_color_alone() {
        let page = Rgb::from_hex("#e4ded6").unwrap();
        let text = Rgb::from_hex("#1a1816").unwrap();

        assert_eq!(
            quantize_against(text, page, &ANSI_16),
            quantize(text, &ANSI_16)
        );
    }

    // With nothing in the palette to satisfy the request, the most legible
    // entry is the answer. Returning the nearest one would return the
    // background itself, which is the failure this function exists to avoid.
    #[test]
    fn an_impossible_palette_gets_the_most_legible_entry() {
        let page = Rgb::from_hex("#ffffff").unwrap();
        let border = Rgb::from_hex("#fefefe").unwrap();
        let palette = [
            Rgb::from_hex("#ffffff").unwrap(),
            Rgb::from_hex("#fdfdfd").unwrap(),
        ];

        let chosen = palette[quantize_against(border, page, &palette)];
        assert_eq!(chosen.to_hex(), "#fdfdfd");
    }

    // ---- meta ----

    #[test]
    fn parse_meta_with_name_and_variant() {
        let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
            .parse()
            .unwrap();
        let meta = parse_meta("nord", &table, false);
        assert_eq!(meta.id, "nord");
        assert_eq!(meta.name, "Nord");
        assert_eq!(meta.variant, "light");
        assert!(!meta.is_custom);
    }

    #[test]
    fn parse_meta_defaults_to_id_and_dark() {
        let table: toml::Table = "".parse().unwrap();
        let meta = parse_meta("fallback", &table, true);
        assert_eq!(meta.name, "fallback");
        assert_eq!(meta.variant, "dark");
        assert!(meta.is_custom);
    }

    // ---- color math (formulas must match the apps they came from) ----

    #[test]
    fn rgb_hex_roundtrip() {
        assert_eq!(
            Rgb::from_hex("#6196FF").unwrap(),
            Rgb {
                r: 0x61,
                g: 0x96,
                b: 0xff
            }
        );
        assert_eq!(
            Rgb::from_hex("#abc").unwrap(),
            Rgb {
                r: 0xaa,
                g: 0xbb,
                b: 0xcc
            }
        );
        assert_eq!(
            Rgb {
                r: 0x61,
                g: 0x96,
                b: 0xff
            }
            .to_hex(),
            "#6196ff"
        );
        assert!(Rgb::from_hex("not-a-color").is_none());
    }

    #[test]
    fn oklab_roundtrips_within_tolerance() {
        for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
            let c = Rgb::from_hex(hex).unwrap();
            let back = Rgb::from_oklab(c.to_oklab());
            // Gamut round-trip is near-exact (±1 per channel from rounding).
            assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
            assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
            assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
        }
    }

    #[test]
    fn wcag_contrast_known_pairs() {
        let white = Rgb {
            r: 255,
            g: 255,
            b: 255,
        };
        let black = Rgb { r: 0, g: 0, b: 0 };
        assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
        assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
    }

    #[test]
    fn readable_on_picks_by_wcag() {
        assert_eq!(
            readable_on(Rgb {
                r: 255,
                g: 255,
                b: 255
            }),
            Rgb { r: 0, g: 0, b: 0 }
        );
        assert_eq!(
            readable_on(Rgb { r: 0, g: 0, b: 0 }),
            Rgb {
                r: 255,
                g: 255,
                b: 255
            }
        );
        // A light blue action -> black text reads better.
        let action = Rgb::from_hex("#6196ff").unwrap();
        assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
    }

    #[test]
    fn lighten_darken_move_oklab_lightness() {
        let c = Rgb::from_hex("#6196ff").unwrap();
        let l0 = c.to_oklab().l;
        assert!(lighten(c, 0.05).to_oklab().l > l0);
        assert!(darken(c, 0.05).to_oklab().l < l0);
    }

    #[test]
    fn mix_endpoints_and_midpoint() {
        let a = Rgb::from_hex("#000000").unwrap();
        let b = Rgb::from_hex("#6196ff").unwrap();
        assert_eq!(mix(a, b, 0.0), a);
        assert_eq!(mix(a, b, 1.0), b);
        // Midpoint sits between the endpoints in OKLab lightness.
        let mid = mix(a, b, 0.5).to_oklab().l;
        assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
    }

    // ---- extract + resolve ----

    fn nord_toml() -> &'static str {
        r##"
[meta]
name = "Nord"
variant = "dark"

[surface]
page = "#2e3440"
raised = "#3b4252"
sunken = "#434c5e"
overlay = "#3b4252"

[content]
primary = "#d8dee9"
secondary = "#e5e9f0"
muted = "#616e88"

[action]
primary = "#81a1c1"

[status]
danger = "#bf616a"
success = "#a3be8c"
warning = "#ebcb8b"
info = "#88c0d0"

[line]
border = "#4c566a"

[category]
one = "#bf616a"
two = "#a3be8c"
three = "#81a1c1"
four = "#ebcb8b"
five = "#b48ead"
six = "#88c0d0"
"##
    }

    #[test]
    fn extract_colors_reads_intent_sections() {
        let table: toml::Table = nord_toml().parse().unwrap();
        let colors = extract_colors(&table);
        assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
        assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
        assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
        assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
        assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
        assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
        assert_eq!(colors.len(), 19);
    }

    #[test]
    fn resolve_base_intents_passthrough() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.hex("surface-page"), Some("#2e3440"));
        assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
        // Not a passthrough: a tonal step of the ink, whatever the file said.
        assert_eq!(
            t.hex("content-muted").unwrap(),
            emphasized(
                Rgb::from_hex("#d8dee9").unwrap(),
                Rgb::from_hex("#2e3440").unwrap(),
                Emphasis::Muted
            )
            .to_hex()
        );
        assert_eq!(t.hex("action"), Some("#81a1c1"));
        assert_eq!(t.hex("danger"), Some("#bf616a"));
        assert_eq!(t.hex("border"), Some("#4c566a"));
        assert_eq!(t.hex("category-five"), Some("#b48ead"));
    }

    #[test]
    fn a_tonal_step_lands_between_its_base_and_its_ground() {
        let ink = Rgb::from_hex("#d8dee9").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        for step in [Emphasis::Full, Emphasis::Secondary, Emphasis::Muted] {
            let out = emphasized(ink, page, step).to_oklab().l;
            assert!(
                out <= ink.to_oklab().l && out >= page.to_oklab().l,
                "{step:?} left the interval between the ink and the page"
            );
        }
        assert_eq!(emphasized(ink, page, Emphasis::Full).to_hex(), ink.to_hex());
    }

    #[test]
    fn tonal_steps_compose_rather_than_compound() {
        // Two steps toward one ground are one step toward it, which is what
        // makes deriving a family recursively well-defined. Within a rounding
        // step, since each hop lands back in 8-bit sRGB.
        let ink = Rgb::from_hex("#d8dee9").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        let (a, b) = (0.12f32, 0.42f32);
        let twice = tonal(tonal(ink, page, a), page, b);
        let once = tonal(ink, page, a + b - a * b);
        let (x, y) = (twice.tuple(), once.tuple());
        for (l, r) in [(x.0, y.0), (x.1, y.1), (x.2, y.2)] {
            assert!(l.abs_diff(r) <= 1, "{twice:?} is not {once:?}");
        }
    }

    #[test]
    fn a_ratio_outside_the_interval_is_clamped_rather_than_extrapolated() {
        let ink = Rgb::from_hex("#d8dee9").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        assert_eq!(tonal(ink, page, -1.0).to_hex(), ink.to_hex());
        assert_eq!(tonal(ink, page, 2.0).to_hex(), page.to_hex());
    }

    #[test]
    fn a_derived_token_key_is_the_family_plus_the_step() {
        assert_eq!(Emphasis::Muted.token("content"), "content-muted");
        assert_eq!(Emphasis::Secondary.token("content"), "content-secondary");
        assert_eq!(Emphasis::Full.token("content"), "content");
        // The point of the suffix being a property of the step: any family can
        // be grouped the same way without a second table saying what it means.
        assert_eq!(Emphasis::Muted.token("danger"), "danger-muted");
    }

    #[test]
    fn every_shipped_theme_ramps_one_way() {
        // The property authoring the steps separately could not hold: three
        // themes had shipped a secondary lighter than their own primary, so a
        // renderer reading the emphasis order got the reverse of it.
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(id, toml, false).unwrap();
            let t = resolve(&theme);
            let page = Rgb::from_hex(t.hex("surface-page").unwrap()).unwrap();
            let steps = ["content", "content-secondary", "content-muted"]
                .map(|k| wcag_contrast(Rgb::from_hex(t.hex(k).unwrap()).unwrap(), page));
            assert!(
                steps[0] > steps[1] && steps[1] > steps[2],
                "{id}: emphasis does not fall monotonically: {steps:?}"
            );
        }
    }

    #[test]
    fn every_shipped_theme_takes_a_visible_first_step() {
        // The property that was missing when 2.6.0 derived these, and the
        // reason a pure-black ink shipped a secondary 3/255 away from it: the
        // ramp falling monotonically says nothing about how far it falls, and
        // a step nobody can see is not a step.
        for (id, toml) in embedded_themes() {
            let theme = parse_theme_str(id, toml, false).unwrap();
            let t = resolve(&theme);
            let ink = Rgb::from_hex(t.hex("content").unwrap()).unwrap();
            let secondary = Rgb::from_hex(t.hex("content-secondary").unwrap()).unwrap();
            let step = wcag_contrast(ink, secondary);
            assert!(
                step >= STEP_FLOOR,
                "{id}: secondary is {step:.2} from its ink, under the {STEP_FLOOR} floor"
            );
        }
    }

    #[test]
    fn an_authored_emphasis_step_does_not_survive_loading() {
        // `nord_toml` still authors both, because a user's theme file might and
        // the answer has to be the same one.
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        assert_ne!(theme.colors.get("content.muted").unwrap(), "#616e88");
        assert_ne!(theme.colors.get("content.secondary").unwrap(), "#e5e9f0");
    }

    #[test]
    fn a_theme_with_no_page_keeps_what_it_authored() {
        // Skip-missing: there is nothing to read the step against, so the step
        // is not taken and a half-written theme does not lose a colour.
        let mut colors = HashMap::new();
        colors.insert("content.primary".to_string(), "#d8dee9".to_string());
        colors.insert("content.muted".to_string(), "#616e88".to_string());
        derive_tonal_steps(&mut colors);
        assert_eq!(colors.get("content.muted").unwrap(), "#616e88");
    }

    #[test]
    fn resolve_derived_intents() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let action = Rgb::from_hex("#81a1c1").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        let _ = page;
        assert_eq!(
            t.hex("action-hover").unwrap(),
            lighten(action, 0.05).to_hex()
        );
        assert_eq!(
            t.hex("content-on-action").unwrap(),
            readable_on(action).to_hex()
        );
        assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
        assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
        // Pruned by the usage audit (0 consumers): action-active, the *-surface
        // tints, selection, row-stripe. Apps that need them derive inline via
        // the shared mix().
        assert!(t.hex("action-active").is_none());
        assert!(t.hex("danger-surface").is_none());
        assert!(t.hex("selection").is_none());
        assert!(t.hex("row-stripe").is_none());
    }

    #[test]
    fn resolve_bevel_intents() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let raised = Rgb::from_hex("#3b4252").unwrap();
        assert_eq!(
            t.hex("bevel-light").unwrap(),
            lighten(raised, 0.14).to_hex()
        );
        assert_eq!(t.hex("bevel-dark").unwrap(), darken(raised, 0.18).to_hex());
    }

    // A bevel is two edges around one face, so both edges have to be visibly off
    // that face or the control never resolves as lit. The lightening clamps at
    // the top of the ramp, which means a theme authoring a white raised surface
    // gets a highlight identical to the surface it is meant to sit on.
    //
    // The list is asserted rather than merely reported so that changing a theme
    // has to come here and say so. Shrinking it is the fix; growing it is a
    // regression in the theme, not in this derivation.
    #[test]
    fn bevel_edges_are_distinct_from_their_face() {
        const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];

        let mut degenerate: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let Some(raised) = t.hex("surface-raised") else {
                continue;
            };
            let light = t.hex("bevel-light").expect("raised implies bevel-light");
            let dark = t.hex("bevel-dark").expect("raised implies bevel-dark");
            if light == raised || dark == raised {
                degenerate.push(id.to_string());
            }
        }
        degenerate.sort();

        assert_eq!(
            degenerate, CANNOT_BEVEL,
            "themes whose raised surface cannot hold both bevel edges"
        );
    }

    // The well inverts by theme, so assert both directions explicitly rather
    // than only the one the light themes happen to take.
    #[test]
    fn resolve_well_intent_follows_the_content_direction() {
        // nord is dark: light text on a dark raised surface, so the well goes
        // down and away from the text.
        let dark = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
        let dark_raised = Rgb::from_hex("#3b4252").unwrap();
        assert_eq!(
            dark.hex("surface-well").unwrap(),
            darken(dark_raised, 0.09).to_hex()
        );

        // The shipped light themes take the other branch.
        let goingson = embedded_themes()
            .into_iter()
            .find(|(id, _)| *id == "goingson")
            .expect("goingson is embedded")
            .1;
        let light = resolve(&parse_theme_str("goingson", goingson, false).unwrap());
        let light_raised = light
            .hex("surface-raised")
            .and_then(Rgb::from_hex)
            .expect("goingson authors a raised surface");
        assert_eq!(
            light.hex("surface-well").unwrap(),
            lighten(light_raised, 0.07).to_hex()
        );
    }

    // A well is a fill, not an edge, so the only thing that makes it read is
    // being a different color from the surface it is cut into.
    //
    // Same shape and the same asserted-list discipline as
    // `bevel_edges_are_distinct_from_their_face`, and it bites the same two
    // themes for the same reason: a raised surface already at the top of the
    // ramp has nothing lighter to go to.
    #[test]
    fn well_is_distinct_from_its_face() {
        const CANNOT_WELL: &[&str] = &["neobrute", "oxocarbon-light"];

        let mut degenerate: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let Some(raised) = t.hex("surface-raised") else {
                continue;
            };
            let well = t.hex("surface-well").expect("raised implies surface-well");
            if well == raised {
                degenerate.push(id.to_string());
            }
        }
        degenerate.sort();

        assert_eq!(
            degenerate, CANNOT_WELL,
            "themes whose raised surface cannot hold a well"
        );
    }

    // Distinct is not the same as visible. A face near the top of the ramp
    // clamps partway rather than exactly, which yields a well that differs from
    // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
    // authors raised at L=0.987 and gets 0.009 of the 0.07 it asked for.
    //
    // Worth a separate test from the one above because the fix differs: an
    // exactly-degenerate theme needs its raised surface off the ramp end, while
    // these need it merely lowered. Both fixes are the theme's, not this
    // derivation's, which is why the list is asserted rather than warned about.
    #[test]
    fn well_is_visible_against_its_face() {
        // Below this, the well and its face are the same surface to a reader.
        const MIN_DELTA_L: f32 = 0.02;
        const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] =
            &["neobrute", "oxocarbon-light", "rosepine-dawn"];

        let mut invisible: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let (Some(raised), Some(well)) = (
                t.hex("surface-raised").and_then(Rgb::from_hex),
                t.hex("surface-well").and_then(Rgb::from_hex),
            ) else {
                continue;
            };
            if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_DELTA_L {
                invisible.push(id.to_string());
            }
        }
        invisible.sort();

        assert_eq!(
            invisible, CANNOT_HOLD_A_VISIBLE_WELL,
            "themes whose well is too close to its face to read as one"
        );
    }

    // The three tests above each measure a derived color against the face it was
    // derived from, so a theme can pass all of them and still have nothing lift
    // off anything: the face itself sits on the page, and that relationship is
    // the one a bevel needs in order to read as an object rather than as a
    // rectangle with decorated edges. makenot.work passed all three and could
    // not hold a bevel, which is what this covers.
    //
    // The threshold is picked against the ramps already ruled on rather than
    // against a round number. makenot.work shipped at 0.024 and was invisible,
    // was tried at 0.036 and rejected as marginal on badges and chips, and was
    // accepted at 0.058; goingson and audiofiles sit at 0.119 and 0.065. Every
    // ramp judged inadequate is below 0.036 and every one judged adequate is
    // above 0.058, so the line goes in the gap between them. Note the unit: this
    // is oklab L on 0 to 1, not the CIE L* on 0 to 100 that the theme files quote
    // in their comments, and the two are not interchangeable.
    //
    // Most of the list is imported palettes, which were authored for syntax
    // highlighting and owe our depth model nothing. Failing here says a theme
    // cannot hold a bevel, not that it is wrong. Shrinking the list is the fix;
    // growing it is a regression in the theme, not in this derivation.
    //
    // tokyonight left the list on 2026-08-15, and it is the only entry that could
    // leave without a judgment call about someone else's palette. Its page and
    // raised were the identical hex, so it had no ramp at all rather than a
    // shallow one, and the fix is upstream's own `bg_highlight` (#292e42, 0.079
    // above the page) rather than a color we picked. The other nineteen are
    // shallow ramps in published palettes, which is a different claim, and they
    // stay deferred until every app is migrated and eyeballed.
    #[test]
    fn raised_is_distinct_from_page() {
        // Below this, a raised surface and the page under it are one surface to
        // a reader, whichever direction the theme ramps in.
        const MIN_DELTA_L: f32 = 0.05;
        const CANNOT_LIFT_OFF_THE_PAGE: &[&str] = &[
            "akari-dawn",
            "akari-night",
            "ayu-light",
            "ayu-mirage",
            "catppuccin-latte",
            "catppuccin-mocha",
            "dawnfox",
            "dracula",
            "everforest",
            "flatwhite",
            "gruvbox-light",
            "neobrute",
            "one-dark",
            "oxocarbon-dark",
            "oxocarbon-light",
            "poimandres",
            "rosepine",
            "rosepine-dawn",
            "solarized-dark",
        ];

        let mut flat: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let (Some(page), Some(raised)) = (
                t.hex("surface-page").and_then(Rgb::from_hex),
                t.hex("surface-raised").and_then(Rgb::from_hex),
            ) else {
                continue;
            };
            if (raised.to_oklab().l - page.to_oklab().l).abs() < MIN_DELTA_L {
                flat.push(id.to_string());
            }
        }
        flat.sort();

        assert_eq!(
            flat, CANNOT_LIFT_OFF_THE_PAGE,
            "themes whose raised surface is too close to the page to lift off it"
        );
    }

    // What the bevel pair does on a sixteen-color terminal, measured across the
    // shipped set rather than assumed. Two results, both load-bearing for a
    // consumer that has to render one there.
    //
    // Exactly one edge survives, never both. A raised face quantizes onto one of
    // the palette's three grays, and the palette is too coarse to hold anything
    // between that entry and its neighbour, so whichever edge is pushed toward
    // the end of the ramp the face already sits on lands back on the face. Light
    // themes and most dark ones keep the shadow and lose the highlight; a face
    // that quantizes to black keeps the highlight and loses the shadow.
    //
    // So a low-color consumer draws the single edge it can render, on the side
    // the palette left it, rather than a bevel that resolves on two sides.
    //
    // And `quantize_against` is the wrong function for this pair, though it is
    // the right one for a border. It answers "nearest entry that clears DISTINCT
    // against the background", which has no notion of direction, so both edges
    // are pushed onto the same contrasting entry and the bevel inverts on one
    // side. Plain `quantize` keeps them apart and in the right order.
    #[test]
    fn a_sixteen_color_terminal_gets_one_bevel_edge_and_not_two() {
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let (Some(face), Some(light), Some(dark)) = (
                t.hex("surface-raised").and_then(Rgb::from_hex),
                t.hex("bevel-light").and_then(Rgb::from_hex),
                t.hex("bevel-dark").and_then(Rgb::from_hex),
            ) else {
                continue;
            };

            let face_index = quantize(face, &ANSI_16);
            let light_survives = quantize(light, &ANSI_16) != face_index;
            let dark_survives = quantize(dark, &ANSI_16) != face_index;
            assert!(
                light_survives != dark_survives,
                "{id}: expected exactly one bevel edge to survive 16 colors, \
                 highlight {light_survives} shadow {dark_survives}"
            );

            // Direction-blind, so it collapses the pair it is asked to separate.
            assert_eq!(
                quantize_against(light, face, &ANSI_16),
                quantize_against(dark, face, &ANSI_16),
                "{id}: quantize_against is expected to be unusable for a bevel pair"
            );
        }
    }

    // 256 colors is where the bevel starts working. At 16 every shipped theme
    // loses an edge; here all but the five whose raised surface sits at the very
    // top of the ramp keep both, and those five fail for the reason they fail in
    // truecolor rather than for a palette reason.
    //
    // Three of them cannot bevel at any depth, so they are the
    // `bevel_edges_are_distinct_from_their_face` set. The other two are new here:
    // they hold a highlight in 24-bit, but not one wide enough to survive
    // rounding onto the cube.
    #[test]
    fn two_hundred_fifty_six_colors_keep_both_bevel_edges() {
        const LOSES_AN_EDGE: &[&str] = &[
            "gruvbox-light",
            "neobrute",
            "oxocarbon-light",
            "rosepine-dawn",
        ];

        let mut lost: Vec<String> = Vec::new();
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let (Some(face), Some(light), Some(dark)) = (
                t.hex("surface-raised").and_then(Rgb::from_hex),
                t.hex("bevel-light").and_then(Rgb::from_hex),
                t.hex("bevel-dark").and_then(Rgb::from_hex),
            ) else {
                continue;
            };

            // Against the fixed region, which is what a consumer should use: a
            // match in the low sixteen is a match against a repaintable color.
            let f = quantize(face, ANSI_240);
            let l = quantize(light, ANSI_240);
            let d = quantize(dark, ANSI_240);
            if l == f || d == f || l == d {
                lost.push(id.to_string());
            }
        }
        lost.sort();

        assert_eq!(
            lost, LOSES_AN_EDGE,
            "themes that cannot hold a two-tone bevel on a 256-color terminal"
        );
    }

    #[test]
    fn the_256_table_has_its_three_regions() {
        // Index is the escape-sequence index, so the low sixteen must match.
        assert_eq!(ANSI_256[..16], ANSI_16);
        // The cube's corners, at both ends and one interior level.
        assert_eq!(ANSI_256[16].tuple(), (0, 0, 0));
        assert_eq!(ANSI_256[231].tuple(), (255, 255, 255));
        assert_eq!(ANSI_256[16 + 36 * 2 + 6 * 3 + 4].tuple(), (135, 175, 215));
        // The gray ramp runs 8 to 238 and contains neither black nor white.
        assert_eq!(ANSI_256[232].tuple(), (8, 8, 8));
        assert_eq!(ANSI_256[255].tuple(), (238, 238, 238));
        // The fixed region is the table minus the repaintable colors.
        assert_eq!(ANSI_240.len(), 240);
        assert_eq!(ANSI_240[0], ANSI_256[ANSI_240_OFFSET]);
    }

    #[test]
    fn resolve_overlay_is_dark_translucent_scrim() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let overlay = t.hex("overlay").unwrap();
        assert!(
            overlay.starts_with("rgba("),
            "overlay is translucent: {overlay}"
        );
        assert!(overlay.ends_with(", 0.5)"));
        // The scrim tone is anchored very dark regardless of theme.
        let inner = overlay
            .trim_start_matches("rgba(")
            .trim_end_matches(", 0.5)");
        let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
        let scrim = Rgb {
            r: parts[0],
            g: parts[1],
            b: parts[2],
        };
        assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
    }

    /// Every shipped theme derives it, on both polarities, and it is always a
    /// near-black translucent tone. A shadow tinted to a dark theme's own
    /// lightness would not read as one.
    #[test]
    fn elevation_is_a_near_black_cast_on_every_theme() {
        for (id, source) in embedded_themes() {
            let theme = parse_theme_str(id, source, false).unwrap();
            let t = resolve(&theme);
            let Some(elevation) = t.hex("elevation") else {
                panic!("{id} derives no elevation");
            };
            assert!(
                elevation.starts_with("rgba(") && elevation.ends_with(", 0.18)"),
                "{id}: elevation is translucent: {elevation}"
            );
            let inner = elevation
                .trim_start_matches("rgba(")
                .trim_end_matches(", 0.18)");
            let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
            let cast = Rgb {
                r: parts[0],
                g: parts[1],
                b: parts[2],
            };
            assert!(
                cast.to_oklab().l < 0.2,
                "{id}: a cast shadow must be near-black, got {elevation}"
            );
        }
    }

    /// The scrim and the cast share an anchor and differ only in weight. Stated
    /// as a test because the two are easy to drift apart, and a scrim that
    /// stopped matching the shadow under the thing it dims would show.
    #[test]
    fn elevation_and_the_scrim_are_the_same_tone() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let scrim = t.hex("overlay").unwrap();
        let cast = t.hex("elevation").unwrap();
        assert_eq!(
            scrim.trim_end_matches(", 0.5)"),
            cast.trim_end_matches(", 0.18)"),
        );
    }

    /// The accessor that makes a translucent intent reachable from something
    /// that is not a stylesheet. Both spellings, and an opaque token answers
    /// 255 so a caller need not know which kind it asked for.
    #[test]
    fn rgba_reads_both_spellings() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);

        let (_, _, _, opaque) = t.rgba("surface-page").expect("page is a hex token");
        assert_eq!(opaque, 255);

        let (r, g, b, alpha) = t.rgba("elevation").expect("elevation is translucent");
        assert_eq!(alpha, 46, "0.18 of 255");
        assert_eq!(t.rgb("elevation"), None, "rgb declines to drop the alpha");

        let (sr, sg, sb, scrim) = t.rgba("overlay").expect("overlay is translucent");
        assert_eq!((sr, sg, sb), (r, g, b), "one tone, two weights");
        assert_eq!(scrim, 128);
    }

    #[test]
    fn resolve_drops_non_hex_base_intent() {
        // A base intent that isn't a hex color must never reach the resolved
        // token set (it would otherwise be inlined verbatim into a <style>
        // block). Skipped like a missing intent; valid siblings survive.
        let theme = parse_theme_str(
            "x",
            "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(
            t.hex("surface-page").is_none(),
            "non-hex base intent leaked"
        );
        assert_eq!(t.hex("content").unwrap(), "#111111");
        // The injected markup appears in no resolved value.
        assert!(!t.intents.values().any(|v| v.contains('<')));
    }

    #[test]
    fn resolve_skips_derived_when_source_missing() {
        // No [action] => no action-derived tokens.
        let theme = parse_theme_str(
            "x",
            "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(t.hex("action").is_none());
        assert!(t.hex("action-hover").is_none());
        assert!(t.hex("selection").is_none());
        assert_eq!(
            t.hex("border-strong").unwrap(),
            darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
        );
    }

    #[test]
    fn rgb_accessor_for_native_consumers() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
        assert_eq!(t.rgb("nonexistent"), None);
    }

    // ---- css emit ----

    #[test]
    fn intent_css_vars_wraps_root_and_includes_tokens() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let css = intent_css_vars(&resolve(&theme));
        assert!(css.starts_with(":root {\n"));
        assert!(css.contains("  --surface-page: #2e3440;\n"));
        assert!(css.contains("  --danger: #bf616a;\n"));
        assert!(css.contains("  --action-hover: "));
        assert!(css.trim_end().ends_with('}'));
    }

    // ---- typography ----

    #[test]
    fn the_font_tokens_are_two_names_and_each_ends_at_a_system_generic() {
        let css = typography_css_vars();
        assert!(css.starts_with(":root {\n"));
        assert!(css.contains("  --font-mono: \"Quasi Mono\", monospace;\n"));
        assert!(css.contains("  --font-sans: \"Quasi Body\", sans-serif;\n"));

        // Layer 2 is one hop and no further. A third entry in either stack is
        // the shape the standard exists to delete: a chain nobody can predict
        // the metrics of, which is what `--font-sans: -apple-system,
        // BlinkMacSystemFont, 'Segoe UI', Roboto, ...` was in three apps.
        for stack in [FONT_MONO, FONT_SANS] {
            assert_eq!(stack.split(',').count(), 2, "{stack} is not one hop");
        }

        // Two tokens, and no others. `--font-body`, `--font-heading` and
        // `--font-display` are gone or out of scope; a token appearing here
        // is a fifth answer to a question that has two.
        assert_eq!(css.matches("--font-").count(), 2);
    }

    #[test]
    fn every_font_face_names_the_weight_range_because_the_mono_opens_at_200() {
        let css = font_face_css("/static/fonts");

        assert_eq!(css.matches("@font-face").count(), 2);
        assert!(css.contains("src: url(\"/static/fonts/QuasiMono.woff2\") format(\"woff2\");"));
        assert!(css.contains("src: url(\"/static/fonts/QuasiBody.woff2\") format(\"woff2\");"));

        // The trap. Atkinson Hyperlegible Mono's default instance is
        // ExtraLight and the cut keeps the axis, so a `@font-face` that omits
        // the range draws the whole UI at 200.
        assert_eq!(css.matches("font-weight: 200 800;").count(), 2);

        // The families have to be exactly what the tokens ask for, or the
        // stack falls through to the generic and the face is dead weight.
        for family in [FONT_MONO, FONT_SANS] {
            let quoted = family.split(',').next().unwrap();
            assert!(css.contains(&format!("font-family: {quoted};")));
        }
    }

    #[test]
    fn a_trailing_slash_on_the_base_url_does_not_double_it() {
        assert_eq!(font_face_css("fonts/"), font_face_css("fonts"));
        assert!(font_face_css("fonts").contains("url(\"fonts/QuasiMono.woff2\")"));
    }

    // ---- typography, layer 0 ----

    /// The live case: MNW's Young Serif, which reached the page through a
    /// hand-maintained `@font-face` and a `--font-heading` nothing else knew
    /// about.
    fn young_serif() -> FontOverride {
        FontOverride::new(FontSlot::Display, "\"Young Serif\", serif")
            .with_face(FontFace::new("Young Serif", ["ysrf.woff2", "ysrf.ttf"]))
    }

    #[test]
    fn the_house_layer_alone_is_exactly_what_the_free_functions_emit() {
        let t = Typography::house("/static/fonts");
        assert_eq!(t.font_face_css(), font_face_css("/static/fonts"));
        assert_eq!(t.css_vars(), typography_css_vars());
    }

    #[test]
    fn an_unoverridden_display_slot_defines_no_token_at_all() {
        // Not "defined empty": undefined, so the consumer's own fallback in
        // `var(--font-display, …)` renders. The MNW embeds depend on it.
        let t = Typography::house("fonts");
        assert!(!t.css_vars().contains("--font-display"));
        assert_eq!(t.resolve(FontSlot::Display), None);
        assert_eq!(t.css_vars().matches("--font-").count(), 2);
    }

    #[test]
    fn an_override_adds_its_token_and_its_face_without_touching_the_house_two() {
        let t = Typography::house("/static/fonts").with_override(young_serif());

        assert!(
            t.css_vars()
                .contains("  --font-display: \"Young Serif\", serif;\n")
        );
        assert!(
            t.css_vars()
                .contains("  --font-mono: \"Quasi Mono\", monospace;\n")
        );
        assert!(
            t.css_vars()
                .contains("  --font-sans: \"Quasi Body\", sans-serif;\n")
        );
        assert_eq!(t.resolve(FontSlot::Display), Some("\"Young Serif\", serif"));

        let faces = t.font_face_css();
        assert_eq!(faces.matches("@font-face").count(), 3);
        assert!(faces.contains("font-family: \"Young Serif\";"));
        assert!(faces.contains("url(\"/static/fonts/ysrf.woff2\") format(\"woff2\")"));
        assert!(faces.contains("url(\"/static/fonts/ysrf.ttf\") format(\"truetype\")"));

        // The house faces still come first, so a product face never shadows a
        // slot it did not claim.
        assert!(faces.find("Quasi Mono").unwrap() < faces.find("Young Serif").unwrap());
    }

    #[test]
    fn overriding_mono_or_sans_replaces_the_house_stack_rather_than_adding_to_it() {
        // Nobody wants this today. A layer that only permits overriding the
        // slot nobody describes is the exemption restated, not a layer.
        let t = Typography::house("fonts").with_override(FontOverride::new(
            FontSlot::Mono,
            "\"Departure Mono\", monospace",
        ));

        assert!(
            t.css_vars()
                .contains("  --font-mono: \"Departure Mono\", monospace;\n")
        );
        assert!(!t.css_vars().contains("Quasi Mono"));
        assert_eq!(t.css_vars().matches("--font-").count(), 2);
    }

    #[test]
    #[should_panic(expected = "--font-display is overridden twice")]
    fn a_second_override_of_one_slot_is_a_vocabulary_bug_and_says_so() {
        let _ = Typography::house("fonts")
            .with_override(young_serif())
            .with_override(FontOverride::new(FontSlot::Display, "\"Reglo\", serif"));
    }

    #[test]
    fn an_absolute_source_is_taken_as_written_and_a_relative_one_joins_the_base() {
        let t = Typography::house("/static/fonts").with_override(
            FontOverride::new(FontSlot::Display, "\"Reglo\", serif").with_face(
                FontFace::new(
                    "Reglo",
                    ["Reglo-Bold.woff2", "https://cdn.example/reglo.woff2"],
                )
                .weight("700"),
            ),
        );
        let faces = t.font_face_css();
        assert!(faces.contains("url(\"/static/fonts/Reglo-Bold.woff2\")"));
        assert!(faces.contains("url(\"https://cdn.example/reglo.woff2\")"));
        assert!(faces.contains("  font-weight: 700;\n"));
    }

    #[test]
    fn the_house_tier_renders_byte_for_byte_what_the_format_string_wrote() {
        // The house faces became `FontFace` values so they could be read as
        // well as emitted. Nothing about the sheet was meant to move, and this
        // is the whole of that claim: the literal the format string produced.
        let expected = concat!(
            "@font-face {\n",
            "  font-family: \"Quasi Mono\";\n",
            "  src: url(\"/static/fonts/QuasiMono.woff2\") format(\"woff2\");\n",
            "  font-weight: 200 800;\n",
            "  font-style: normal;\n",
            "  font-display: swap;\n",
            "}\n\n",
            "@font-face {\n",
            "  font-family: \"Quasi Body\";\n",
            "  src: url(\"/static/fonts/QuasiBody.woff2\") format(\"woff2\");\n",
            "  font-weight: 200 800;\n",
            "  font-style: normal;\n",
            "  font-display: swap;\n",
            "}\n\n",
        );
        assert_eq!(font_face_css("/static/fonts"), expected);
    }

    #[test]
    fn a_house_slot_names_the_same_family_in_its_stack_and_in_its_face() {
        // The family is spelled once as a bare name and once inside a CSS
        // stack, because a stack cannot be built from a const at compile time.
        // A face whose family is not the one the stack names loads and is
        // never asked for.
        for (slot, family) in [
            (FontSlot::Mono, HOUSE_MONO_FAMILY),
            (FontSlot::Sans, HOUSE_SANS_FAMILY),
        ] {
            let face = slot.house_face().expect("a house slot has a house face");
            assert_eq!(face.family(), family);
            assert!(
                slot.house_default()
                    .unwrap()
                    .starts_with(&format!("\"{family}\""))
            );
        }
    }

    #[test]
    fn the_brand_tier_has_no_house_face_the_way_it_has_no_house_stack() {
        assert!(FontSlot::Display.house_face().is_none());
        assert!(FontSlot::Display.house_default().is_none());
    }

    #[test]
    fn a_face_loading_renderer_reads_the_family_and_the_source_off_the_layer() {
        // The egui case, which has no stylesheet in the path at all: the
        // renderer registers the file under a name, and the name has to be
        // the one the stack spells or the two halves drift.
        let t = Typography::house("fonts").with_override(
            FontOverride::new(FontSlot::Display, "\"RecursiveMono\", monospace").with_face(
                FontFace::new("RecursiveMono", ["RecursiveMonoLnrSt-Bold.ttf"]).weight("700"),
            ),
        );

        let [face] = t.faces(FontSlot::Display) else {
            panic!("the display slot ships exactly one face");
        };
        assert_eq!(face.family(), "RecursiveMono");
        assert_eq!(face.sources(), ["RecursiveMonoLnrSt-Bold.ttf"]);
        assert!(
            t.resolve(FontSlot::Display)
                .unwrap()
                .contains(face.family())
        );
    }

    #[test]
    fn a_source_is_read_back_unresolved_because_only_the_css_wants_a_url() {
        let t = Typography::house("/static/fonts").with_override(young_serif());
        assert_eq!(
            t.faces(FontSlot::Display)[0].sources(),
            ["ysrf.woff2", "ysrf.ttf"]
        );
        // The same face, joined to the base, in the sheet.
        assert!(
            t.font_face_css()
                .contains("url(\"/static/fonts/ysrf.woff2\")")
        );
    }

    #[test]
    fn a_slot_nobody_overrode_ships_no_faces_including_the_house_two() {
        let t = Typography::house("fonts").with_override(young_serif());
        assert!(t.faces(FontSlot::Mono).is_empty());
        assert!(t.faces(FontSlot::Sans).is_empty());
        assert_eq!(t.faces(FontSlot::Display).len(), 1);
    }

    #[test]
    fn an_unrecognised_extension_gets_no_format_hint_rather_than_a_guessed_one() {
        let t = Typography::house("fonts").with_override(
            FontOverride::new(FontSlot::Display, "\"Odd\", serif")
                .with_face(FontFace::new("Odd", ["odd.eot"])),
        );
        assert!(t.font_face_css().contains("url(\"fonts/odd.eot\");"));
        assert!(!t.font_face_css().contains("format(\"eot\")"));
    }

    #[test]
    fn css_puts_the_faces_before_the_tokens_that_name_them() {
        let t = Typography::house("fonts").with_override(young_serif());
        let css = t.css();
        assert!(css.starts_with("@font-face"));
        assert!(css.find("@font-face").unwrap() < css.find(":root").unwrap());
    }

    // ---- loading / fs ----

    #[test]
    fn load_and_resolve_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let t = load_semantic(&dirs, "nord").unwrap();
        assert_eq!(t.meta.name, "Nord");
        assert_eq!(t.hex("action"), Some("#81a1c1"));
    }

    #[test]
    fn load_theme_rejects_invalid_id() {
        assert!(load_theme(&[], "../evil").is_err());
    }

    fn meta(id: &str, variant: &str) -> ThemeMeta {
        ThemeMeta {
            id: id.to_string(),
            name: id.to_string(),
            variant: variant.to_string(),
            is_custom: false,
        }
    }

    fn defaults() -> ThemeDefaults {
        ThemeDefaults::new("flatwhite", "nord")
    }

    // The three the shipped themes actually declare.
    #[test]
    fn every_shipped_variant_parses() {
        assert_eq!(Variant::parse("light"), Some(Variant::Light));
        assert_eq!(Variant::parse("dark"), Some(Variant::Dark));
        assert_eq!(Variant::parse("high-contrast"), Some(Variant::HighContrast));
        assert_eq!(Variant::parse("sepia"), None);
    }

    // parse_meta already defaults a *missing* variant to dark, so an
    // unrecognized one reading as light would have the crate disagreeing with
    // itself. alloy_tui did exactly that before this existed.
    #[test]
    fn an_unrecognized_variant_reads_the_way_a_missing_one_does() {
        assert_eq!(Variant::from("sepia"), Variant::Dark);
        assert_eq!(Variant::from(""), Variant::Dark);

        let missing: toml::Table = "[meta]\nname = \"X\"\n".parse().unwrap();
        assert_eq!(parse_meta("x", &missing, false).kind(), Variant::Dark);
    }

    #[test]
    fn a_selection_round_trips_through_any_store() {
        for (stored, expect) in [
            (Some("system"), ThemeSelection::Follow),
            (None, ThemeSelection::Follow),
            (Some(""), ThemeSelection::Follow),
            (Some("  "), ThemeSelection::Follow),
            (Some("nord"), ThemeSelection::Fixed("nord".into())),
        ] {
            let parsed = ThemeSelection::parse(stored);
            assert_eq!(parsed, expect, "{stored:?}");
            assert_eq!(
                ThemeSelection::parse(Some(parsed.as_str())),
                expect,
                "what is written reads back as what was meant",
            );
        }
    }

    // Nothing saved is follow-the-system, which is what Balanced Breakfast
    // expressed as an absent value and GoingsOn as a sentinel. Both are now the
    // same thing.
    #[test]
    fn nothing_chosen_yet_is_follow() {
        assert_eq!(ThemeSelection::default(), ThemeSelection::Follow);
    }

    #[test]
    fn a_fixed_selection_wins_when_its_theme_is_installed() {
        let available = [meta("nord", "dark"), meta("flatwhite", "light")];
        let fixed = ThemeSelection::Fixed("nord".into());
        assert_eq!(
            fixed.resolve(Variant::Light, &defaults(), &available),
            "nord",
            "a chosen theme is not overridden by the ambient mode",
        );
    }

    // Themes are deletable in three of the four apps. Handing back an id that
    // will fail to load only moves the error somewhere less helpful.
    #[test]
    fn a_fixed_selection_whose_theme_is_gone_falls_back() {
        let available = [meta("nord", "dark"), meta("flatwhite", "light")];
        let fixed = ThemeSelection::Fixed("deleted".into());
        assert_eq!(
            fixed.resolve(Variant::Light, &defaults(), &available),
            "flatwhite",
        );
    }

    #[test]
    fn follow_picks_the_apps_default_for_the_ambient_mode() {
        let available = [meta("nord", "dark"), meta("flatwhite", "light")];
        let follow = ThemeSelection::Follow;
        assert_eq!(
            follow.resolve(Variant::Dark, &defaults(), &available),
            "nord",
        );
        assert_eq!(
            follow.resolve(Variant::Light, &defaults(), &available),
            "flatwhite",
        );
    }

    // The behaviour Balanced Breakfast could not have: following the system
    // into a theme the user installed, when the app's own default is absent.
    #[test]
    fn follow_uses_any_installed_theme_of_the_right_variant() {
        let available = [meta("solarized-light", "light"), meta("mine", "dark")];
        assert_eq!(
            ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &available),
            "mine",
            "the app's `nord` is not installed, but a dark theme is",
        );
    }

    // Always returns something: an app with no theme directory gets the id it
    // ships with, and the load error it would have had anyway.
    #[test]
    fn an_empty_catalog_still_names_the_apps_default() {
        assert_eq!(
            ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &[]),
            "nord",
        );
    }

    #[test]
    fn high_contrast_falls_back_to_dark_unless_named() {
        let plain = defaults();
        assert_eq!(plain.for_variant(Variant::HighContrast), "nord");

        let named = defaults().high_contrast("sharp");
        assert_eq!(named.for_variant(Variant::HighContrast), "sharp");
    }

    // The bug this builder exists to prevent: the Alloy console pushed the
    // user's directory first under a comment reading "highest precedence
    // first", when both consumers of this vector resolve last-wins. A custom
    // theme lost to the packaged one of the same id.
    #[test]
    fn the_users_own_themes_outrank_everything() {
        let root = tempfile::tempdir().unwrap();
        let make = |name: &str| {
            let dir = root.path().join(name);
            std::fs::create_dir_all(&dir).unwrap();
            dir
        };
        let (bundled, system, custom) = (make("bundled"), make("system"), make("custom"));

        let dirs = ThemeDirs::new()
            .custom(Some(custom.clone()))
            .bundled(Some(bundled.clone()))
            .system(Some(system.clone()))
            .build();

        assert_eq!(
            dirs,
            vec![(bundled, false), (system, false), (custom.clone(), true)],
            "lowest precedence first, whatever order the tiers were added in",
        );
        assert!(dirs.last().unwrap().1, "only the user's tier is custom");

        // And the ordering means what the consumers think it means.
        for dir in dirs.iter().map(|(dir, _)| dir) {
            std::fs::write(dir.join("shared.toml"), "[meta]\nname = \"x\"\n").unwrap();
        }
        assert_eq!(
            find_theme_path(&dirs, "shared").unwrap().0,
            custom.join("shared.toml"),
            "the user's copy is the one that loads",
        );
    }

    #[test]
    fn a_directory_that_does_not_exist_is_dropped() {
        let root = tempfile::tempdir().unwrap();
        let real = root.path().join("real");
        std::fs::create_dir_all(&real).unwrap();

        let dirs = ThemeDirs::new()
            .bundled(Some(root.path().join("nope")))
            .system(None)
            .custom(Some(real.clone()))
            .build();

        assert_eq!(dirs, vec![(real, true)]);
    }

    // A Tauri app has two bundled tiers: the resource dir in production and the
    // tree build.rs materialized for a dev run with no resource dir.
    #[test]
    fn more_than_one_bundled_tier_is_allowed() {
        let root = tempfile::tempdir().unwrap();
        let (first, second) = (root.path().join("a"), root.path().join("b"));
        std::fs::create_dir_all(&first).unwrap();
        std::fs::create_dir_all(&second).unwrap();

        let dirs = ThemeDirs::new()
            .bundled(Some(first.clone()))
            .bundled(Some(second.clone()))
            .build();
        assert_eq!(dirs, vec![(first, false), (second, false)]);
    }

    #[test]
    fn list_themes_from_dirs_finds_toml_files() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
        fs::write(dir.path().join("x.txt"), "ignored").unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let themes = list_themes_from_dirs(&dirs);
        assert_eq!(themes.len(), 1);
        assert_eq!(themes[0].id, "t");
    }

    #[test]
    fn find_theme_path_reverse_priority() {
        let d1 = tempfile::tempdir().unwrap();
        let d2 = tempfile::tempdir().unwrap();
        fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
        fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
        let dirs = vec![
            (d1.path().to_path_buf(), false),
            (d2.path().to_path_buf(), true),
        ];
        let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
        assert!(is_custom);
        assert_eq!(path, d2.path().join("s.toml"));
    }

    #[test]
    fn import_theme_valid_and_rejects_empty() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();

        let good = src_dir.path().join("my-theme.toml");
        fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
        let meta = import_theme(&good, custom_dir.path()).unwrap();
        assert_eq!(meta.id, "my-theme");
        assert!(custom_dir.path().join("my-theme.toml").exists());

        let empty = src_dir.path().join("empty.toml");
        fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
        assert!(import_theme(&empty, custom_dir.path()).is_err());
    }

    #[test]
    fn import_theme_rejects_invalid_toml() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("bad.toml");
        fs::write(&src, "this is not [valid toml [[[").unwrap();
        assert!(import_theme(&src, custom_dir.path()).is_err());
    }

    #[test]
    fn delete_theme_removes_and_guards() {
        let custom = tempfile::tempdir().unwrap();
        let path = custom.path().join("doomed.toml");
        fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
        delete_theme(custom.path(), "doomed").unwrap();
        assert!(!path.exists());
        assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
        assert!(delete_theme(custom.path(), "ghost").is_err());
    }

    #[test]
    fn export_theme_copies_file() {
        let src_dir = tempfile::tempdir().unwrap();
        let dest_dir = tempfile::tempdir().unwrap();
        let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
        fs::write(src_dir.path().join("e.toml"), content).unwrap();
        let dirs = vec![(src_dir.path().to_path_buf(), false)];
        let dest = dest_dir.path().join("out.toml");
        export_theme(&dirs, "e", &dest).unwrap();
        assert_eq!(fs::read_to_string(&dest).unwrap(), content);
        assert!(export_theme(&dirs, "missing", &dest).is_err());
    }

    #[test]
    fn load_theme_preview_returns_role_swatches() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let p = load_theme_preview(&dirs, "nord").unwrap();
        assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
        assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
        assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
        assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
    }

    #[test]
    fn bundled_themes_dir_resolves_to_shipped_themes() {
        // The crate ships its themes, so this must resolve in-tree and the
        // Akari defaults the console falls back to must be present.
        let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
        assert!(dir.join("akari-dawn.toml").is_file());
        assert!(dir.join("akari-night.toml").is_file());
    }

    #[test]
    fn every_theme_is_accounted_for_in_third_party_notices() {
        // Attribution is a redistribution obligation, not a nicety: adding a
        // theme without a notice entry silently ships someone's work
        // uncredited. Fail here instead.
        let notices = std::fs::read_to_string(
            Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
        )
        .expect("THIRD-PARTY-NOTICES.md must exist");
        let missing: Vec<&str> = embedded_themes()
            .map(|(id, _)| id)
            .filter(|id| !notices.contains(*id))
            .collect();
        assert!(
            missing.is_empty(),
            "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
        );
    }

    #[test]
    fn adapted_themes_carry_inline_attribution() {
        // Each adapted file must name its upstream in-file, so the credit
        // survives someone copying a single .toml out of the crate.
        const ORIGINALS: [&str; 5] = [
            "makenotwork",
            "goingson",
            "audiofiles",
            "high-contrast",
            "neobrute",
        ];
        for (id, source) in embedded_themes() {
            if ORIGINALS.contains(&id) {
                continue;
            }
            assert!(
                source.contains("adapted from"),
                "adapted theme `{id}` is missing its inline attribution header"
            );
        }
    }

    #[test]
    fn embedded_themes_match_the_directory() {
        // The embedded copy and themes/ are two views of one source. If they
        // ever disagree, path-based and path-free consumers render different
        // theme sets, which is exactly the drift shipping the data was meant
        // to prevent.
        let dir = bundled_themes_dir().unwrap();
        let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| {
                let path = e.ok()?.path();
                if path.extension()? != "toml" {
                    return None;
                }
                Some(path.file_stem()?.to_str()?.to_string())
            })
            .collect();
        let mut embedded: Vec<String> = embedded_themes().map(|(id, _)| id.to_string()).collect();
        on_disk.sort();
        embedded.sort();
        assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
    }

    #[test]
    fn every_embedded_theme_parses() {
        // Guards the path-free consumers (MNW server, the Tauri build steps)
        // the same way every_shipped_theme_loads guards the path-based ones.
        let mut count = 0;
        for (id, source) in embedded_themes() {
            parse_theme_str(id, source, false)
                .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
            count += 1;
        }
        assert!(count >= 30, "expected the full theme set, got {count}");
    }

    #[test]
    fn every_shipped_theme_loads() {
        // Guards the data, not just the loader: a malformed or truncated
        // .toml in themes/ is a shipping bug, and it should fail here rather
        // than at a user's first launch.
        let dir = bundled_themes_dir().unwrap();
        let dirs = vec![(dir.clone(), false)];
        let themes = list_themes_from_dirs(&dirs);
        assert!(
            themes.len() >= 30,
            "expected the full theme set, got {}",
            themes.len()
        );
        for meta in &themes {
            load_theme(&dirs, &meta.id)
                .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
        }
    }
}