hephaestus 0.1.0

Backend-agnostic 2D scene renderer for data visualization.
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
//! Hephaestus's `Scale` bundle, `ScaleRegistry`, and the ggplot-style
//! free-function constructors (`scale::continuous(...)`,
//! `scale::ordinal(...)`, etc.).
//!
//! The algorithms themselves (map, breaks, band width, transform forward
//! / inverse) live in [`crate::scales`] as plain enums + free functions.
//! `Scale` is a thin bundle that holds the configured pieces and exposes
//! convenience methods that match on the enum tags and delegate.
//!
//! This file is **hephaestus-only** — `Scale`, `ScaleRegistry`, and the
//! constructors don't ship in the lift-ready scales crate. Consumers of
//! that crate roll their own bundle and call the free functions
//! directly.

pub mod constructors;
pub use constructors::*;

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::color::{Color, ColorSpace};
#[cfg(test)]
use crate::scales::value::DataColumn;
use crate::scales::value::{LinetypeStep, Value};
use crate::scales::Locale;

// The scales-layer surface, re-exported so `crate::plot::scale::*`
// reaches both this bundle and the algorithms it delegates to. The
// submodules (`breaks`, `transform`, etc.) come through wholesale;
// selected free functions and types are pulled to the top level.
pub use crate::scales::{
    binned_band_width, binned_band_width_at, binned_breaks, binned_map, binned_map_break, breaks,
    chrome, continuous_breaks, continuous_map, continuous_minor_breaks, discrete_band_width,
    discrete_breaks, discrete_map, extended_breaks, identity_map, input, linear_breaks,
    linear_minor_breaks_between, log_minor_breaks, log_pretty_breaks, ordinal_map, output,
    scale_type, sqrt_breaks, symlog_breaks, symlog_minor_breaks, temporal_breaks,
    temporal_breaks_with_interval, temporal_minor_breaks, temporal_minor_breaks_with_interval,
    transform, transform_allowed_domain, transform_forward, transform_inverse, value,
    wrap_temporal_value, AxisSide, CalendarUnit, Direction, InputRange, LegendSide, OutputRange,
    ScaleTypeKind, TemporalInterval, TemporalUnit, Transform, TransformKind, DEFAULT_BREAK_COUNT,
};

/// Tick-label formatter closure stored on a [`Scale`]. Receives a break
/// value and the active [`Locale`], and returns its rendered label.
///
/// The default formatter consults only `locale.decimal`. Grouping
/// separators and the month / weekday name tables are vocabulary for
/// formatters that want them — a calendar-native axis is built by
/// supplying a closure, not by switching locale.
pub type LabelFormatter = dyn Fn(&Value, &Locale) -> String + Send + Sync;

/// Reject a bin-edge list that can't describe a bin ladder. Bin lookup
/// assumes strictly increasing finite edges; a list that violates that
/// silently misplaces rows, so it's caught where the caller sets it.
fn validate_bin_edges(edges: &[f64]) {
    assert!(
        edges.len() >= 2,
        "binned scale needs at least two bin edges, got {}",
        edges.len()
    );
    assert!(
        edges.iter().all(|e| e.is_finite()),
        "binned scale bin edges must all be finite: {edges:?}"
    );
    assert!(
        edges.windows(2).all(|w| w[0] < w[1]),
        "binned scale bin edges must be strictly increasing: {edges:?}"
    );
}

// ─── BreaksSpec ──────────────────────────────────────────────────────────────

/// User-supplied break specification. When set on a [`Scale`], replaces
/// the scale-type's automatic break algorithm at
/// [`Scale::breaks`]. The [`BreaksSpec::Labeled`] variant additionally
/// supplies fixed label strings that bypass the formatter.
#[derive(Clone, Debug)]
pub enum BreaksSpec {
    /// Pin exact break positions; labels still flow through the
    /// formatter / default per-variant rules.
    Explicit(Vec<Value>),
    /// Pin exact positions paired with explicit label strings. The two
    /// vectors are index-aligned and have equal length by construction
    /// (built via `unzip` in the setter). Labels here take priority
    /// over any custom formatter for the listed values.
    Labeled {
        /// Break positions, in input-space.
        breaks: Vec<Value>,
        /// Labels paired index-wise with [`Self::Labeled::breaks`].
        labels: Vec<String>,
    },
    /// Numeric "every N" — emit multiples of `step` across the
    /// continuous domain (`..., k * step, (k+1) * step, ...`
    /// intersected with `[min, max]`). Used by continuous numeric
    /// scales; falls back to the default algorithm on non-continuous
    /// scales.
    NumericInterval(f64),
    /// Calendar interval (e.g. every 2 weeks). Used by temporal
    /// scales; falls back to the default algorithm on non-temporal
    /// scales.
    TemporalInterval(TemporalInterval),
}

// ─── MinorBreaksSpec ─────────────────────────────────────────────────────────

/// User-supplied minor-break specification. When set on a [`Scale`],
/// replaces the scale-type's automatic minor-break algorithm at
/// [`Scale::minor_breaks`]. Minor breaks carry no labels, so there is no
/// counterpart to [`BreaksSpec::Labeled`].
#[derive(Clone, Debug)]
pub enum MinorBreaksSpec {
    /// Pin exact minor positions. An empty vector suppresses minor
    /// breaks entirely.
    Explicit(Vec<Value>),
    /// Subdivide each consecutive pair of major breaks into
    /// `n + 1` gaps, placing `n` evenly-spaced minors per interval and
    /// none on the majors themselves. `0` suppresses minor breaks.
    CountBetween(usize),
    /// Numeric "every N" — multiples of `step` across the continuous
    /// domain, minus the positions already carrying a major break.
    /// Falls back to the automatic algorithm on scales without a
    /// continuous domain.
    NumericInterval(f64),
    /// Calendar interval (e.g. weekly minors under monthly majors),
    /// minus the positions already carrying a major break. Used by
    /// temporal scales; falls back to the automatic algorithm on
    /// non-temporal scales.
    TemporalInterval(TemporalInterval),
}

// ─── Scale ───────────────────────────────────────────────────────────────────

/// A configurable value mapper. Bundles a [`ScaleTypeKind`] with optional
/// input/output ranges, a [`Transform`], and a monotonic generation
/// counter for invalidating downstream caches.
///
/// `Scale` is hephaestus's aggregate — the lift-ready `scales` crate
/// exposes only the underlying enums + free functions. The methods on
/// `Scale` (`map`, `breaks`, `band_width`, …) match-dispatch on the
/// scale type and delegate to those free functions.
pub struct Scale {
    scale_type: ScaleTypeKind,
    transform: Transform,
    input_range: Option<InputRange>,
    output_range: Option<OutputRange>,
    /// Bin edges for a [`ScaleTypeKind::Binned`] scale — strictly
    /// increasing, length ≥ 2, bin count `len() - 1`. Ignored by every
    /// other family; a binned scale without them maps everything to
    /// `Null`.
    bins: Option<Vec<f64>>,
    /// User-supplied break override, if any. `None` ⇒ use the scale
    /// type's automatic break algorithm.
    breaks_spec: Option<BreaksSpec>,
    /// User-supplied minor-break override, if any. `None` ⇒ use the
    /// scale type's automatic minor-break algorithm. Independent of
    /// [`Self::breaks_spec`]: pinned majors still get automatic minors
    /// and vice versa.
    minor_breaks_spec: Option<MinorBreaksSpec>,
    /// The space a colour output range interpolates through. Ignored by
    /// every other output type, and by discrete scales, whose palette is a
    /// one-to-one lookup with nothing to interpolate.
    color_space: ColorSpace,
    /// Which way the mapping runs across the domain. Applied to the
    /// normalised fraction / domain index, so it reverses a position
    /// axis and a palette alike. Ignored by
    /// [`ScaleTypeKind::Identity`], which normalises nothing.
    direction: Direction,
    /// User-supplied tick-label formatter, if any. `None` ⇒ use the
    /// default per-variant formatter (see [`Scale::default_format`]).
    formatter: Option<Arc<LabelFormatter>>,
    /// Bumped on every mutation. Keys the break memo below, and is
    /// plumbed for the same job in future per-channel caches.
    generation: u64,
    /// Memoized result of the last [`Self::breaks`] call, keyed on the
    /// generation it was computed at and the tick target. Chrome asks
    /// for the same breaks a dozen times per frame — axis measure, axis
    /// draw, gridlines, legend — and every miss re-runs a
    /// Wilkinson-extended search.
    ///
    /// A `Mutex` rather than a `RefCell` so `Scale` stays `Sync`; the
    /// lock is uncontended and far cheaper than the search it skips.
    breaks_cache: Mutex<Option<(u64, usize, Vec<Value>)>>,
}

impl Clone for Scale {
    /// The break memo is not carried over — it's a pure function of the
    /// cloned configuration, so the clone refills it on first use.
    fn clone(&self) -> Self {
        Scale {
            scale_type: self.scale_type,
            transform: self.transform,
            input_range: self.input_range.clone(),
            output_range: self.output_range.clone(),
            bins: self.bins.clone(),
            breaks_spec: self.breaks_spec.clone(),
            minor_breaks_spec: self.minor_breaks_spec.clone(),
            color_space: self.color_space,
            direction: self.direction,
            formatter: self.formatter.clone(),
            generation: self.generation,
            breaks_cache: Mutex::new(None),
        }
    }
}

impl Scale {
    /// Build a fresh scale of the given type. Domain and range are unset
    /// until configured via the builder methods.
    pub fn new(scale_type: ScaleTypeKind) -> Self {
        Scale {
            scale_type,
            transform: Transform::default(),
            input_range: None,
            output_range: None,
            bins: None,
            breaks_spec: None,
            minor_breaks_spec: None,
            color_space: ColorSpace::default(),
            direction: Direction::default(),
            formatter: None,
            generation: 0,
            breaks_cache: Mutex::new(None),
        }
    }

    // ── Builders (consume self) ──

    /// Configure a continuous numeric / temporal domain.
    ///
    /// `T` is anything that converts into a [`Value`] whose `as_number()`
    /// projection yields a finite f64. That covers `f64`, `f32`, `i32`,
    /// `i64`, and the temporal newtypes ([`Date`](crate::scales::value::Date),
    /// [`DateTime`](crate::scales::value::DateTime),
    /// [`Time`](crate::scales::value::Time),
    /// [`Duration`](crate::scales::value::Duration)) — each projects to
    /// its canonical unit (days / microseconds). Non-numeric endpoints
    /// (`String`, `Bool`, `Color`, `Null`) panic at the call site since
    /// they have no continuous ordering.
    /// # Panics
    ///
    /// If either endpoint has no numeric or temporal projection —
    /// there's no continuous ordering on strings or colours. Use
    /// [`Self::try_domain_continuous`] for endpoints that come from
    /// data rather than literals, or `domain_discrete` for categories.
    pub fn domain_continuous<T>(self, min: T, max: T) -> Self
    where
        T: Into<Value>,
    {
        match self.try_domain_continuous(min, max) {
            Ok(scale) => scale,
            Err(v) => {
                panic!("domain_continuous: expected numeric or temporal endpoints, got {v:?}")
            }
        }
    }

    /// [`Self::domain_continuous`] but hands back the offending value
    /// instead of panicking.
    pub fn try_domain_continuous<T>(mut self, min: T, max: T) -> Result<Self, Value>
    where
        T: Into<Value>,
    {
        let (min, max) = (min.into(), max.into());
        let lo = min.as_number().ok_or(min)?;
        let hi = max.as_number().ok_or(max)?;
        self.input_range = Some(InputRange::Continuous { min: lo, max: hi });
        Ok(self)
    }

    /// Configure a discrete domain — explicit ordered list of input
    /// values. Used by [`ScaleTypeKind::Discrete`] and
    /// [`ScaleTypeKind::Ordinal`].
    pub fn domain_discrete(mut self, values: impl IntoIterator<Item = Value>) -> Self {
        self.input_range = Some(InputRange::Discrete(values.into_iter().collect()));
        self
    }

    /// Configure the bin edges of a [`ScaleTypeKind::Binned`] scale —
    /// strictly increasing, length ≥ 2, giving `edges.len() - 1` bins.
    /// Bins live in input space, alongside the domain: the output range
    /// stays free to carry a palette (colours, sizes, linetypes) that the
    /// bin index selects from.
    ///
    /// # Panics
    ///
    /// If the edges don't form a bin ladder: fewer than two edges, a
    /// non-finite edge, or a pair that doesn't strictly increase.
    pub fn with_bins(mut self, edges: impl IntoIterator<Item = f64>) -> Self {
        let edges: Vec<f64> = edges.into_iter().collect();
        validate_bin_edges(&edges);
        self.bins = Some(edges);
        self
    }

    /// Configure a numeric output range (pt for absolute sizes;
    /// unitless otherwise).
    pub fn range_numbers(mut self, vs: impl IntoIterator<Item = f64>) -> Self {
        self.output_range = Some(OutputRange::Numbers(vs.into_iter().collect()));
        self
    }

    /// Configure a colour output range.
    pub fn range_colors(mut self, vs: impl IntoIterator<Item = Color>) -> Self {
        self.output_range = Some(OutputRange::Colors(vs.into_iter().collect()));
        self
    }

    /// Configure a string output range.
    pub fn range_strings(mut self, vs: impl IntoIterator<Item = Arc<str>>) -> Self {
        self.output_range = Some(OutputRange::Strings(vs.into_iter().collect()));
        self
    }

    /// Configure a linetype output range. Each entry is a
    /// [`LinetypeStep`] pattern (alternating Dash|Marker and Gap; empty =
    /// solid). Pairs naturally with the named helpers in
    /// [`crate::plot::geom::linetype`].
    pub fn range_linetypes(mut self, vs: impl IntoIterator<Item = Arc<[LinetypeStep]>>) -> Self {
        self.output_range = Some(OutputRange::Linetypes(vs.into_iter().collect()));
        self
    }

    /// Configure the scale's [`Transform`]. Currently only
    /// [`TransformKind::Identity`] is implemented.
    pub fn with_transform(mut self, t: TransformKind) -> Self {
        self.transform = Transform::of(t);
        self
    }

    /// Configure the space a colour output range interpolates through.
    /// Defaults to [`ColorSpace::Oklab`], so a two-stop ramp reads as an
    /// even perceptual progression rather than dipping dark through the
    /// middle.
    pub fn with_color_space(mut self, space: ColorSpace) -> Self {
        self.color_space = space;
        self
    }

    /// Configure which way the mapping runs across the domain.
    ///
    /// [`Direction::Reversed`] mirrors the normalised fraction (or the
    /// domain index) before the output range is consulted: a position
    /// scale's axis runs backwards, and a material scale walks its
    /// palette from the far end. The domain itself keeps its natural
    /// order, so [`Self::breaks`] returns the same tick values either
    /// way — only where they land changes.
    pub fn with_direction(mut self, direction: Direction) -> Self {
        self.direction = direction;
        self
    }

    // ── Mutators (`&mut self`; bump generation) ──

    /// Replace the continuous domain in place. Bumps the generation
    /// counter.
    ///
    /// # Panics
    ///
    /// If either endpoint has no numeric or temporal projection. See
    /// [`Self::try_set_domain_continuous`].
    pub fn set_domain_continuous<T>(&mut self, min: T, max: T)
    where
        T: Into<Value>,
    {
        if let Err(v) = self.try_set_domain_continuous(min, max) {
            panic!("set_domain_continuous: expected numeric or temporal endpoints, got {v:?}");
        }
    }

    /// [`Self::set_domain_continuous`] but hands back the offending
    /// value instead of panicking. The domain is left untouched on
    /// error.
    pub fn try_set_domain_continuous<T>(&mut self, min: T, max: T) -> Result<(), Value>
    where
        T: Into<Value>,
    {
        let (min, max) = (min.into(), max.into());
        let lo = min.as_number().ok_or(min)?;
        let hi = max.as_number().ok_or(max)?;
        self.input_range = Some(InputRange::Continuous { min: lo, max: hi });
        self.bump_generation();
        Ok(())
    }

    /// Replace the discrete domain in place. Bumps the generation
    /// counter.
    pub fn set_domain_discrete(&mut self, values: Vec<Value>) {
        self.input_range = Some(InputRange::Discrete(values));
        self.bump_generation();
    }

    /// Replace the bin edges in place. Bumps the generation counter.
    ///
    /// # Panics
    ///
    /// If the edges don't form a bin ladder: fewer than two edges, a
    /// non-finite edge, or a pair that doesn't strictly increase.
    pub fn set_bins(&mut self, edges: Vec<f64>) {
        validate_bin_edges(&edges);
        self.bins = Some(edges);
        self.bump_generation();
    }

    /// Replace the numeric output range in place. Bumps the generation
    /// counter.
    pub fn set_range_numbers(&mut self, vs: Vec<f64>) {
        self.output_range = Some(OutputRange::Numbers(vs));
        self.bump_generation();
    }

    /// Replace the colour output range in place. Bumps the generation
    /// counter.
    pub fn set_range_colors(&mut self, vs: Vec<Color>) {
        self.output_range = Some(OutputRange::Colors(vs));
        self.bump_generation();
    }

    /// Replace the string output range in place. Bumps the generation
    /// counter.
    pub fn set_range_strings(&mut self, vs: Vec<Arc<str>>) {
        self.output_range = Some(OutputRange::Strings(vs));
        self.bump_generation();
    }

    /// Replace the linetype output range in place. Bumps the generation
    /// counter.
    pub fn set_range_linetypes(&mut self, vs: Vec<Arc<[LinetypeStep]>>) {
        self.output_range = Some(OutputRange::Linetypes(vs));
        self.bump_generation();
    }

    /// Replace the transform in place. Bumps the generation counter.
    pub fn set_transform(&mut self, t: TransformKind) {
        self.transform = Transform::of(t);
        self.bump_generation();
    }

    /// Replace the colour interpolation space in place. Bumps the
    /// generation counter.
    pub fn set_color_space(&mut self, space: ColorSpace) {
        self.color_space = space;
        self.bump_generation();
    }

    /// Replace the mapping direction in place. Bumps the generation
    /// counter.
    pub fn set_direction(&mut self, direction: Direction) {
        self.direction = direction;
        self.bump_generation();
    }

    // ── Break overrides (`&mut self`; bump generation) ──

    /// Pin exact break positions, overriding the scale-type's automatic
    /// algorithm. Labels still flow through the formatter / default
    /// per-variant rules; to pin labels too, use
    /// [`Self::with_breaks_labeled`].
    pub fn with_breaks(mut self, breaks: Vec<Value>) -> Self {
        self.breaks_spec = Some(BreaksSpec::Explicit(breaks));
        self
    }

    /// Replace the break override with the given pinned positions.
    /// Bumps the generation counter.
    pub fn set_breaks(&mut self, breaks: Vec<Value>) {
        self.breaks_spec = Some(BreaksSpec::Explicit(breaks));
        self.bump_generation();
    }

    /// Pin exact break positions paired with explicit label strings.
    /// Each pair contributes one tick at the given value labelled with
    /// the given string; labels take priority over any formatter for
    /// the listed values.
    pub fn with_breaks_labeled(mut self, pairs: Vec<(Value, String)>) -> Self {
        let (breaks, labels): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();
        self.breaks_spec = Some(BreaksSpec::Labeled { breaks, labels });
        self
    }

    /// Replace the break override with pinned positions + labels.
    /// Bumps the generation counter.
    pub fn set_breaks_labeled(&mut self, pairs: Vec<(Value, String)>) {
        let (breaks, labels): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();
        self.breaks_spec = Some(BreaksSpec::Labeled { breaks, labels });
        self.bump_generation();
    }

    /// Numeric "every N" breaks: emit multiples of `step` across the
    /// continuous domain. Applies to continuous numeric scales (and to
    /// temporal scales constructed via the plain
    /// [`continuous`]`(date_a..=date_b)` path, which treats the domain
    /// as raw f64); for calendar-aware ticks on a `temporal(...)`
    /// scale use [`Self::with_temporal_interval`].
    pub fn with_interval(mut self, step: f64) -> Self {
        self.breaks_spec = Some(BreaksSpec::NumericInterval(step));
        self
    }

    /// Replace the break override with a numeric interval. Bumps the
    /// generation counter.
    pub fn set_interval(&mut self, step: f64) {
        self.breaks_spec = Some(BreaksSpec::NumericInterval(step));
        self.bump_generation();
    }

    /// Calendar interval breaks (e.g. every 2 weeks). Applies to scales
    /// constructed via [`temporal`]; on a non-temporal scale this falls
    /// back to the default algorithm (no panic).
    pub fn with_temporal_interval(mut self, interval: TemporalInterval) -> Self {
        self.breaks_spec = Some(BreaksSpec::TemporalInterval(interval));
        self
    }

    /// Replace the break override with a calendar interval. Bumps the
    /// generation counter.
    pub fn set_temporal_interval(&mut self, interval: TemporalInterval) {
        self.breaks_spec = Some(BreaksSpec::TemporalInterval(interval));
        self.bump_generation();
    }

    /// Clear any pinned breaks / labels / interval; revert to the
    /// scale type's automatic algorithm. Bumps the generation counter.
    pub fn clear_breaks(&mut self) {
        self.breaks_spec = None;
        self.bump_generation();
    }

    // ── Minor-break overrides (`&mut self`; bump generation) ──

    /// Pin exact minor (sub-tick) positions, overriding the scale-type's
    /// automatic minor algorithm. An empty vector draws no minors at all.
    pub fn with_minor_breaks(mut self, breaks: Vec<Value>) -> Self {
        self.minor_breaks_spec = Some(MinorBreaksSpec::Explicit(breaks));
        self
    }

    /// Replace the minor-break override with the given pinned positions.
    /// Bumps the generation counter.
    pub fn set_minor_breaks(&mut self, breaks: Vec<Value>) {
        self.minor_breaks_spec = Some(MinorBreaksSpec::Explicit(breaks));
        self.bump_generation();
    }

    /// Place `per_interval` evenly-spaced minors between each
    /// consecutive pair of major breaks. `0` draws no minors.
    pub fn with_minor_count(mut self, per_interval: usize) -> Self {
        self.minor_breaks_spec = Some(MinorBreaksSpec::CountBetween(per_interval));
        self
    }

    /// Replace the minor-break override with a per-interval count.
    /// Bumps the generation counter.
    pub fn set_minor_count(&mut self, per_interval: usize) {
        self.minor_breaks_spec = Some(MinorBreaksSpec::CountBetween(per_interval));
        self.bump_generation();
    }

    /// Numeric "every N" minors: multiples of `step` across the
    /// continuous domain, skipping positions that already carry a major
    /// break. For calendar-aware minors on a [`temporal`] scale use
    /// [`Self::with_minor_temporal_interval`].
    pub fn with_minor_interval(mut self, step: f64) -> Self {
        self.minor_breaks_spec = Some(MinorBreaksSpec::NumericInterval(step));
        self
    }

    /// Replace the minor-break override with a numeric interval. Bumps
    /// the generation counter.
    pub fn set_minor_interval(&mut self, step: f64) {
        self.minor_breaks_spec = Some(MinorBreaksSpec::NumericInterval(step));
        self.bump_generation();
    }

    /// Calendar interval minors (e.g. every week), skipping positions
    /// that already carry a major break. Applies to scales constructed
    /// via [`temporal`]; on a non-temporal scale this falls back to the
    /// automatic algorithm (no panic).
    pub fn with_minor_temporal_interval(mut self, interval: TemporalInterval) -> Self {
        self.minor_breaks_spec = Some(MinorBreaksSpec::TemporalInterval(interval));
        self
    }

    /// Replace the minor-break override with a calendar interval. Bumps
    /// the generation counter.
    pub fn set_minor_temporal_interval(&mut self, interval: TemporalInterval) {
        self.minor_breaks_spec = Some(MinorBreaksSpec::TemporalInterval(interval));
        self.bump_generation();
    }

    /// Clear any pinned minor breaks / count / interval; revert to the
    /// scale type's automatic algorithm. Bumps the generation counter.
    pub fn clear_minor_breaks(&mut self) {
        self.minor_breaks_spec = None;
        self.bump_generation();
    }

    // ── Formatter override ──

    /// Set a custom formatter applied to each break value before
    /// rendering. Overrides the default per-variant formatter. The
    /// closure receives `(&Value, &Locale)` — consult the locale's
    /// decimal / grouping separators or month / day arrays as needed,
    /// or ignore it for locale-insensitive labels. Explicit labels
    /// set via [`Self::with_breaks_labeled`] still take priority over
    /// this closure for the values they cover.
    pub fn with_format<F>(mut self, f: F) -> Self
    where
        F: Fn(&Value, &Locale) -> String + Send + Sync + 'static,
    {
        self.formatter = Some(Arc::new(f));
        self
    }

    /// Replace the formatter in place. Bumps the generation counter.
    /// See [`Self::with_format`] for the closure shape.
    pub fn set_format<F>(&mut self, f: F)
    where
        F: Fn(&Value, &Locale) -> String + Send + Sync + 'static,
    {
        self.formatter = Some(Arc::new(f));
        self.bump_generation();
    }

    /// Clear the custom formatter; revert to the default per-variant
    /// rules. Bumps the generation counter.
    pub fn clear_format(&mut self) {
        self.formatter = None;
        self.bump_generation();
    }

    fn bump_generation(&mut self) {
        self.generation += 1;
    }

    // ── Operations ──

    /// Map an input value to its scaled output. Dispatches on
    /// [`Self::scale_type_kind`] into the matching free function from
    /// [`crate::scales`].
    pub fn map(&self, input: &Value) -> Value {
        match self.scale_type {
            ScaleTypeKind::Continuous | ScaleTypeKind::Temporal(_) => continuous_map(
                input,
                self.input_range.as_ref(),
                self.output_range.as_ref(),
                &self.transform,
                self.color_space,
                self.direction,
            ),
            ScaleTypeKind::Discrete => discrete_map(
                input,
                self.input_range.as_ref(),
                self.output_range.as_ref(),
                self.direction,
            ),
            ScaleTypeKind::Ordinal => ordinal_map(
                input,
                self.input_range.as_ref(),
                self.output_range.as_ref(),
                self.color_space,
                self.direction,
            ),
            ScaleTypeKind::Binned => binned_map(
                input,
                self.input_range.as_ref(),
                self.bins.as_deref(),
                self.output_range.as_ref(),
                self.color_space,
                self.direction,
            ),
            ScaleTypeKind::Identity => identity_map(input),
        }
    }

    /// Position a break value on the panel, for axis ticks, gridlines and
    /// other chrome that anchors a label to the value it names.
    ///
    /// Differs from [`Self::map`] only for [`ScaleTypeKind::Binned`],
    /// whose data mapping sends every value to the centre of its bin. A
    /// binned scale's breaks are its bin edges, so mapping them as data
    /// would draw each edge inside a bin — and collapse two edges of the
    /// same bin onto one position. This returns the value's own domain
    /// fraction instead. Every other family positions breaks exactly
    /// where it positions data, and delegates.
    pub fn map_break(&self, input: &Value) -> Value {
        match self.scale_type {
            ScaleTypeKind::Binned => {
                binned_map_break(input, self.input_range.as_ref(), self.direction)
            }
            _ => self.map(input),
        }
    }

    /// Like [`Self::map`] but additionally applies a band-fraction offset
    /// in the scale's band space. The offset is multiplied by the band
    /// width of the bin containing `input` (see
    /// [`Self::band_width_at`]) before being added to the nominal mapped
    /// fraction.
    ///
    /// - `band_offset` units: fraction of the input's own band width.
    ///   `0.0` is the band centre; `±0.5` reaches the band's left/right
    ///   edge. The offset isn't clamped — values outside `[-0.5, 0.5]`
    ///   extend past the band into neighbouring slots.
    /// - Continuous scales return `0.0` from `band_width_at`, so the
    ///   offset is a no-op there.
    /// - Non-numeric `map()` outputs (e.g. Color) ignore the offset and
    ///   pass through unchanged.
    /// - Under [`Direction::Reversed`] the offset points the other way,
    ///   so it stays anchored to the domain rather than to the panel: a
    ///   reversed axis mirrors within-band placement along with
    ///   everything else drawn on it.
    pub fn map_with_offset(&self, input: &Value, band_offset: f64) -> Value {
        let base = self.map(input);
        if band_offset == 0.0 {
            return base;
        }
        let band_offset = if self.direction.is_reversed() {
            -band_offset
        } else {
            band_offset
        };
        match base {
            Value::Number(f) => {
                let bw = self.band_width_at(input);
                Value::Number(f + band_offset * bw)
            }
            other => other,
        }
    }

    /// Tick / category positions in **input** space. `n` is a target for
    /// continuous scales; discrete / ordinal ignore it and return every
    /// domain entry.
    ///
    /// When a [`BreaksSpec`] has been set via [`Self::with_breaks`] /
    /// [`Self::with_interval`] / etc., the override takes precedence
    /// and `n` is ignored. A mismatch between override variant and
    /// scale type (e.g. [`BreaksSpec::TemporalInterval`] on a numeric
    /// scale) silently falls back to the automatic algorithm.
    pub fn breaks(&self, n: usize) -> Vec<Value> {
        if let Ok(cache) = self.breaks_cache.lock() {
            if let Some((gen, cached_n, values)) = cache.as_ref() {
                if *gen == self.generation && *cached_n == n {
                    return values.clone();
                }
            }
        }
        let computed = self
            .breaks_spec
            .as_ref()
            .and_then(|spec| self.breaks_from_spec(spec))
            .unwrap_or_else(|| self.breaks_auto(n));
        if let Ok(mut cache) = self.breaks_cache.lock() {
            *cache = Some((self.generation, n, computed.clone()));
        }
        computed
    }

    // Scale-type's automatic break algorithm — extracted so `breaks`
    // can short-circuit on a `breaks_spec` override and fall back here
    // for mismatches.
    fn breaks_auto(&self, n: usize) -> Vec<Value> {
        match self.scale_type {
            ScaleTypeKind::Continuous => {
                continuous_breaks(self.input_range.as_ref(), &self.transform, n)
            }
            ScaleTypeKind::Temporal(unit) => temporal_breaks(self.input_range.as_ref(), unit, n),
            ScaleTypeKind::Discrete | ScaleTypeKind::Ordinal => {
                discrete_breaks(self.input_range.as_ref())
            }
            ScaleTypeKind::Binned => binned_breaks(self.bins.as_deref()),
            ScaleTypeKind::Identity => Vec::new(),
        }
    }

    // Apply a user-supplied `BreaksSpec`. Returns `None` when the spec
    // is incompatible with the scale type (caller falls back to
    // `breaks_auto`).
    fn breaks_from_spec(&self, spec: &BreaksSpec) -> Option<Vec<Value>> {
        match spec {
            BreaksSpec::Explicit(vs) => Some(vs.clone()),
            BreaksSpec::Labeled { breaks, .. } => Some(breaks.clone()),
            BreaksSpec::NumericInterval(step) => self.breaks_numeric_interval(*step),
            BreaksSpec::TemporalInterval(interval) => match self.scale_type {
                ScaleTypeKind::Temporal(unit) => Some(temporal_breaks_with_interval(
                    self.input_range.as_ref(),
                    unit,
                    *interval,
                )),
                _ => None,
            },
        }
    }

    // Numeric "every N" — multiples of `step` intersected with the
    // continuous domain. Returns `None` on non-continuous scales or
    // invalid steps so the caller falls back.
    fn breaks_numeric_interval(&self, step: f64) -> Option<Vec<Value>> {
        Some(
            self.numeric_interval_positions(step)?
                .into_iter()
                .map(Value::Number)
                .collect(),
        )
    }

    // Raw f64 positions for a numeric "every N" spec, shared by the
    // major and minor paths.
    fn numeric_interval_positions(&self, step: f64) -> Option<Vec<f64>> {
        if !step.is_finite() || step <= 0.0 {
            return None;
        }
        let (min, max) = match self.input_range.as_ref()? {
            InputRange::Continuous { min, max } => (*min, *max),
            _ => return None,
        };
        if !min.is_finite() || !max.is_finite() || min > max {
            return None;
        }
        let first_k = (min / step).ceil();
        let last_k = (max / step).floor();
        if last_k < first_k {
            return Some(Vec::new());
        }
        let count = ((last_k - first_k) as usize).saturating_add(1);
        let mut out = Vec::with_capacity(count);
        let mut k = first_k;
        while k <= last_k {
            out.push(k * step);
            k += 1.0;
        }
        Some(out)
    }

    /// Minor (sub-tick) positions in input space. Empty for non-continuous
    /// scale types. For continuous scales the algorithm is transform-
    /// aware: log scales emit geometric 2..9 between decades; sqrt /
    /// identity / etc. emit one midpoint between consecutive majors.
    /// For temporal scales it emits sub-unit calendar ticks (year →
    /// quarter, month → week, …) — subdividing the interval pinned by
    /// [`Self::with_temporal_interval`] when there is one, and the
    /// interval the tick target `n` implies otherwise.
    ///
    /// When a [`MinorBreaksSpec`] has been set via
    /// [`Self::with_minor_breaks`] / [`Self::with_minor_count`] / etc.,
    /// the override takes precedence. A mismatch between override
    /// variant and scale type (e.g.
    /// [`MinorBreaksSpec::TemporalInterval`] on a numeric scale)
    /// silently falls back to the automatic algorithm.
    pub fn minor_breaks(&self, n: usize) -> Vec<Value> {
        if let Some(spec) = &self.minor_breaks_spec {
            if let Some(ms) = self.minor_breaks_from_spec(spec, n) {
                return ms;
            }
        }
        self.minor_breaks_auto(n)
    }

    // Scale-type's automatic minor-break algorithm — extracted so
    // `minor_breaks` can short-circuit on a `minor_breaks_spec` override
    // and fall back here for mismatches.
    fn minor_breaks_auto(&self, n: usize) -> Vec<Value> {
        match self.scale_type {
            ScaleTypeKind::Continuous => {
                let majors = self.breaks(n);
                continuous_minor_breaks(self.input_range.as_ref(), &self.transform, &majors)
            }
            ScaleTypeKind::Temporal(unit) => {
                // A calendar interval pinned on the majors drives the
                // minors too: subdivide the interval the caller asked
                // for, not the one the target tick count would pick.
                if let Some(BreaksSpec::TemporalInterval(interval)) = &self.breaks_spec {
                    return temporal_minor_breaks_with_interval(
                        self.input_range.as_ref(),
                        unit,
                        *interval,
                    );
                }
                let majors = self.breaks(n);
                temporal_minor_breaks(self.input_range.as_ref(), unit, &majors, n)
            }
            _ => Vec::new(),
        }
    }

    // Apply a user-supplied `MinorBreaksSpec`. Returns `None` when the
    // spec is incompatible with the scale type (caller falls back to
    // `minor_breaks_auto`).
    fn minor_breaks_from_spec(&self, spec: &MinorBreaksSpec, n: usize) -> Option<Vec<Value>> {
        match spec {
            MinorBreaksSpec::Explicit(vs) => Some(vs.clone()),
            MinorBreaksSpec::CountBetween(per_interval) => {
                self.minor_breaks_count_between(*per_interval, n)
            }
            MinorBreaksSpec::NumericInterval(step) => {
                let raw = self.numeric_interval_positions(*step)?;
                let raw = self.drop_major_positions(raw, n, step.abs() * 1e-9);
                Some(self.wrap_positions(raw))
            }
            MinorBreaksSpec::TemporalInterval(interval) => match self.scale_type {
                ScaleTypeKind::Temporal(unit) => {
                    let raw: Vec<f64> =
                        temporal_breaks_with_interval(self.input_range.as_ref(), unit, *interval)
                            .iter()
                            .filter_map(|v| v.as_number())
                            .collect();
                    let raw = self.drop_major_positions(raw, n, 0.0);
                    Some(self.wrap_positions(raw))
                }
                _ => None,
            },
        }
    }

    // Evenly subdivide the gaps between consecutive major breaks.
    // Non-numeric majors (a discrete domain) leave nothing to subdivide.
    fn minor_breaks_count_between(&self, per_interval: usize, n: usize) -> Option<Vec<Value>> {
        if per_interval == 0 {
            return Some(Vec::new());
        }
        let majors: Vec<f64> = self
            .breaks(n)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        if majors.len() < 2 {
            return Some(Vec::new());
        }
        let raw = linear_minor_breaks_between(&majors, per_interval);
        Some(self.wrap_positions(raw))
    }

    // Drop positions that already carry a major break: minor ticks sit
    // *between* majors by convention (log minors skip the decade powers,
    // calendar minors skip the aligned major), so an interval that
    // divides the major spacing evenly must not double-draw.
    fn drop_major_positions(&self, positions: Vec<f64>, n: usize, tol: f64) -> Vec<f64> {
        let majors: Vec<f64> = self
            .breaks(n)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        positions
            .into_iter()
            .filter(|p| !majors.iter().any(|m| (m - p).abs() <= tol))
            .collect()
    }

    // Type raw f64 positions as break values: temporal scales get their
    // calendar variant back, every other family stays numeric.
    fn wrap_positions(&self, positions: Vec<f64>) -> Vec<Value> {
        match self.scale_type {
            ScaleTypeKind::Temporal(unit) => positions
                .into_iter()
                .map(|raw| wrap_temporal_value(raw, unit))
                .collect(),
            _ => positions.into_iter().map(Value::Number).collect(),
        }
    }

    /// Format a value as its tick label, in the given locale.
    ///
    /// Precedence (highest first): an explicit [`BreaksSpec::Labeled`]
    /// label for `v`, a custom formatter set via [`Self::with_format`]
    /// (passed `(v, locale)`), then the built-in per-variant default
    /// ([`Self::default_format`]). Numeric values render via Rust's
    /// shortest round-trip `Display` after a 12-sig-fig snap (so
    /// `0.30000000000000004` reads as `"0.3"`), then the decimal
    /// mark is swapped to `locale.decimal`. Temporal variants render
    /// as compact `YYYY-MM-DD` / `HH:MM:SS` and are locale-insensitive;
    /// a formatter that wants language-specific layouts builds them
    /// from the locale's `month_short` / `month_long` / `day_*` arrays.
    pub fn format(&self, v: &Value, locale: &Locale) -> String {
        if let Some(BreaksSpec::Labeled { breaks, labels }) = &self.breaks_spec {
            if let Some(i) = breaks.iter().position(|b| b.key_eq(v)) {
                return labels[i].clone();
            }
        }
        if let Some(f) = &self.formatter {
            return f(v, locale);
        }
        format_value(v, locale)
    }

    /// Band width as a fraction of the panel (in `[0, 1]`). Continuous
    /// scales return `0.0`; discrete-family scales return `1.0 / n_bands`.
    pub fn band_width(&self) -> f64 {
        match self.scale_type {
            ScaleTypeKind::Continuous | ScaleTypeKind::Temporal(_) => 0.0,
            ScaleTypeKind::Discrete | ScaleTypeKind::Ordinal => {
                discrete_band_width(self.input_range.as_ref())
            }
            ScaleTypeKind::Binned => binned_band_width(self.bins.as_deref()),
            ScaleTypeKind::Identity => 0.0,
        }
    }

    /// Width (as panel fraction) of the band containing `input`. For
    /// uniform-band scales this matches [`Self::band_width`]; for
    /// [`ScaleTypeKind::Binned`] with non-uniform widths it returns the
    /// specific bin's width. Used by [`Self::map_with_offset`].
    pub fn band_width_at(&self, input: &Value) -> f64 {
        match self.scale_type {
            ScaleTypeKind::Binned => {
                binned_band_width_at(input, self.input_range.as_ref(), self.bins.as_deref())
            }
            _ => self.band_width(),
        }
    }

    // ── Accessors ──

    /// Discriminator for this scale's family.
    pub fn scale_type_kind(&self) -> ScaleTypeKind {
        self.scale_type
    }

    /// Borrow the [`Transform`].
    pub fn transform(&self) -> &Transform {
        &self.transform
    }

    /// Borrow the configured input domain, if any.
    pub fn input_range(&self) -> Option<&InputRange> {
        self.input_range.as_ref()
    }

    /// Borrow the configured output range, if any.
    pub fn output_range(&self) -> Option<&OutputRange> {
        self.output_range.as_ref()
    }

    /// Which way this scale's mapping runs across its domain.
    pub fn direction(&self) -> Direction {
        self.direction
    }

    /// The space this scale's colour output range interpolates through.
    pub fn color_space(&self) -> ColorSpace {
        self.color_space
    }

    /// Borrow the configured bin edges. Only [`ScaleTypeKind::Binned`]
    /// consults them.
    pub fn bins(&self) -> Option<&[f64]> {
        self.bins.as_deref()
    }

    /// Borrow the configured break override, if any. `None` ⇒ the scale
    /// uses its automatic break algorithm.
    pub fn breaks_spec(&self) -> Option<&BreaksSpec> {
        self.breaks_spec.as_ref()
    }

    /// Borrow the configured minor-break override, if any. `None` ⇒ the
    /// scale uses its automatic minor-break algorithm.
    pub fn minor_breaks_spec(&self) -> Option<&MinorBreaksSpec> {
        self.minor_breaks_spec.as_ref()
    }

    /// Built-in per-variant tick-label formatter, given a locale.
    /// Exposed so user closures supplied to [`Self::with_format`]
    /// can fall through to the default for variants they don't care
    /// to customise:
    ///
    /// ```ignore
    /// scale.with_format(|v, locale| match v {
    ///     Value::Number(n) => format!("${n:.2}"),
    ///     other => Scale::default_format(other, locale),
    /// })
    /// ```
    pub fn default_format(v: &Value, locale: &Locale) -> String {
        format_value(v, locale)
    }

    /// Monotonic counter incremented on every mutation. Keys
    /// [`Self::breaks`]'s memo, and is the invalidation signal any
    /// further per-channel cache should use rather than comparing
    /// values.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// True when `other` lays out the same legend domain as this scale:
    /// same family, transform, input domain and bin edges, and the same
    /// break values carrying the same labels under `locale`.
    ///
    /// This is deliberately blind to the **output** range — a colour
    /// scale and a shape scale over one shared domain are equivalent,
    /// which is exactly the case where their legends should collapse
    /// into a single set of rows drawn with both key glyphs. Two
    /// separately configured scales that end up describing the same
    /// values compare equal, so collapse doesn't depend on the two
    /// legends naming the same registry entry. [`Direction`] counts as
    /// part of the output mapping for the same reason: a legend lists
    /// its domain in domain order whichever way the scale runs, so a
    /// reversed scale lays out the same rows.
    pub fn legend_equivalent_to(&self, other: &Scale, locale: &Locale) -> bool {
        if self.scale_type != other.scale_type
            || self.transform != other.transform
            || self.input_range != other.input_range
            || self.bins != other.bins
        {
            return false;
        }
        let mine = self.breaks(DEFAULT_BREAK_COUNT);
        let theirs = other.breaks(DEFAULT_BREAK_COUNT);
        mine.len() == theirs.len()
            && mine
                .iter()
                .zip(theirs.iter())
                .all(|(a, b)| a.key_eq(b) && self.format(a, locale) == other.format(b, locale))
    }

    /// True when `other` both lays out the same legend domain (see
    /// [`Self::legend_equivalent_to`]) **and** carries the same output
    /// range, so the two scales map every input to the same visual.
    ///
    /// This is the check for legends that display the range itself
    /// rather than one glyph per break — a colorbar over a viridis ramp
    /// and one over a magma ramp share a domain but draw different bars.
    /// Two scales carrying the same colour stops but interpolating them
    /// in different spaces draw different bars too, so the interpolation
    /// space counts as part of the visual — as does the direction the
    /// ramp runs in.
    pub fn visual_equivalent_to(&self, other: &Scale, locale: &Locale) -> bool {
        self.output_range == other.output_range
            && self.color_space == other.color_space
            && self.direction == other.direction
            && self.legend_equivalent_to(other, locale)
    }
}

impl std::fmt::Debug for Scale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scale")
            .field("scale_type", &self.scale_type)
            .field("transform", &self.transform)
            .field("input_range", &self.input_range)
            .field("output_range", &self.output_range)
            .field("bins", &self.bins)
            .field("breaks_spec", &self.breaks_spec)
            .field("minor_breaks_spec", &self.minor_breaks_spec)
            .field("color_space", &self.color_space)
            .field("direction", &self.direction)
            .field(
                "formatter",
                &self.formatter.as_ref().map(|_| "<fn>").unwrap_or("none"),
            )
            .field("generation", &self.generation)
            .finish()
    }
}

// ─── Format helper ───────────────────────────────────────────────────────────

/// Best-effort tick-label formatter.
///
/// - `Number(n)` → `format!("{n}")` (Rust's f64 Display; strips trailing
///   zeros for clean values).
/// - `Date(d)` → `YYYY-MM-DD`.
/// - `DateTime(us)` → `YYYY-MM-DD HH:MM:SS` (UTC).
/// - `Time(us)` → `HH:MM:SS.fff` (or `HH:MM:SS` if sub-second is 0).
/// - `Duration(us)` → compact `Hh Mm Ss` or `MM:SS` depending on magnitude.
/// - `String(s)` → `s`.
/// - Others → debug-formatted.
fn format_value(v: &Value, locale: &Locale) -> String {
    use crate::scales::value::Date;
    match v {
        Value::Number(n) => format_number(*n, locale),
        Value::String(s) => (**s).to_string(),
        Value::Bool(b) => format!("{b}"),
        Value::Null => "NA".to_string(),
        Value::Color(c) => format!("{c:?}"),
        Value::Date(d) => {
            let (y, m, dd) = Date::from_days(*d).to_ymd();
            format!("{y:04}-{m:02}-{dd:02}")
        }
        Value::DateTime(us) => {
            let dt = crate::scales::value::DateTime::from_micros(*us);
            let (date, time_us) = dt.split();
            let (y, m, dd) = date.to_ymd();
            let (h, mi, s, _us) = split_time_micros(time_us);
            format!("{y:04}-{m:02}-{dd:02} {h:02}:{mi:02}:{s:02}")
        }
        Value::Time(ns) => {
            let (h, mi, s, sub_ns) = split_time_nanos(*ns);
            if sub_ns == 0 {
                format!("{h:02}:{mi:02}:{s:02}")
            } else {
                let millis = sub_ns / 1_000_000;
                format!("{h:02}:{mi:02}:{s:02}.{millis:03}")
            }
        }
        Value::Duration(us) => {
            let neg = *us < 0;
            let mut abs = us.unsigned_abs();
            let micros = (abs % 1_000_000) as u32;
            abs /= 1_000_000;
            let seconds = (abs % 60) as u32;
            abs /= 60;
            let minutes = (abs % 60) as u32;
            abs /= 60;
            let hours = abs;
            let sign = if neg { "-" } else { "" };
            if hours > 0 {
                format!("{sign}{hours}h {minutes:02}m {seconds:02}s")
            } else if minutes > 0 {
                format!("{sign}{minutes}m {seconds:02}s")
            } else if micros == 0 {
                format!("{sign}{seconds}s")
            } else {
                let millis = micros / 1000;
                format!("{sign}{seconds}.{millis:03}s")
            }
        }
        Value::Linetype(p) => {
            if p.is_empty() {
                "solid".to_string()
            } else {
                let parts: Vec<String> = p
                    .iter()
                    .map(|s| match s {
                        LinetypeStep::Dash(f) => format!("dash({f})"),
                        LinetypeStep::Gap(f) => format!("gap({f})"),
                        LinetypeStep::Marker(name) => format!("marker({name:?})"),
                    })
                    .collect();
                format!("[{}]", parts.join(", "))
            }
        }
        Value::Geometry(g) => format!("{g:?}"),
    }
}

/// Format a finite f64 as its tick label, scrubbing accumulated
/// floating-point noise. Break-generation algorithms accumulate a few
/// ULPs of error which surface as digits in the 14th-16th position;
/// rounding at 12 significant figures wipes that noise while preserving
/// any precision a plot label could plausibly need.
///
/// The round-trip via 12-significant-digit scientific form snaps to a
/// nearby f64 that Rust's shortest-round-trip `Display` then prints
/// cleanly: `0.30000000000000004` → `"0.3"`; `0.6000000000001` → `"0.6"`.
fn format_number(n: f64, locale: &Locale) -> String {
    let raw = if !n.is_finite() {
        format!("{n}")
    } else if n == 0.0 {
        "0".to_string()
    } else {
        let cleaned: f64 = format!("{n:.11e}")
            .parse()
            .expect("formatted scientific f64 round-trips");
        format!("{cleaned}")
    };
    if locale.decimal == '.' {
        raw
    } else {
        // Tick-label numbers carry at most one decimal point (Rust's
        // shortest-round-trip Display); a flat replace is correct.
        raw.replace('.', &locale.decimal.to_string())
    }
}

/// Project a continuous-domain endpoint to its canonical f64. Accepts
/// numeric and temporal `Value` variants; panics for other variants since
/// they have no continuous ordering.
/// Split microseconds-since-midnight into (hour, minute, second, sub_us).
/// Used by the DateTime formatter (DateTime stays μs even though Time
/// switched to ns).
fn split_time_micros(us: i64) -> (u8, u8, u8, u32) {
    let us = us.rem_euclid(86_400_000_000);
    let micros_of_sec = (us % 1_000_000) as u32;
    let total_secs = us / 1_000_000;
    let s = (total_secs % 60) as u8;
    let total_mins = total_secs / 60;
    let mi = (total_mins % 60) as u8;
    let h = ((total_mins / 60) % 24) as u8;
    (h, mi, s, micros_of_sec)
}

/// Split nanoseconds-since-midnight into (hour, minute, second, sub_ns).
/// Used by the Time formatter.
fn split_time_nanos(ns: i64) -> (u8, u8, u8, u32) {
    let ns = ns.rem_euclid(86_400_000_000_000);
    let nanos_of_sec = (ns % 1_000_000_000) as u32;
    let total_secs = ns / 1_000_000_000;
    let s = (total_secs % 60) as u8;
    let total_mins = total_secs / 60;
    let mi = (total_mins % 60) as u8;
    let h = ((total_mins / 60) % 24) as u8;
    (h, mi, s, nanos_of_sec)
}

// ─── ScaleRegistry ───────────────────────────────────────────────────────────

/// Named registry of scales — the single source of truth for scale state
/// in a [`PlotComposition`](crate::plot) orchestrator. Plots reference
/// scales by name through their channel bindings; the registry owns the
/// `Scale` instances.
///
/// A thin `HashMap` wrapper. The orchestrator owns the registry and
/// exposes mutators that flip dirty flags; callers building one by hand
/// (e.g. for tests or orchestrator-free renders) can use the
/// [`Self::insert`] / [`Self::remove`] surface directly.
#[derive(Default, Clone, Debug)]
pub struct ScaleRegistry {
    scales: HashMap<String, Scale>,
}

impl ScaleRegistry {
    /// Empty registry — no scales registered.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a scale under `name`, replacing any previous entry.
    pub fn insert(&mut self, name: impl Into<String>, scale: Scale) {
        self.scales.insert(name.into(), scale);
    }

    /// Chainable variant of [`Self::insert`].
    pub fn with(mut self, name: impl Into<String>, scale: Scale) -> Self {
        self.insert(name, scale);
        self
    }

    /// Remove a scale by name. Returns the removed scale if present.
    pub fn remove(&mut self, name: &str) -> Option<Scale> {
        self.scales.remove(name)
    }

    /// Read a scale by name.
    pub fn get(&self, name: &str) -> Option<&Scale> {
        self.scales.get(name)
    }

    /// Mutable read by name — used by the orchestrator's `update_scale`.
    pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut Scale> {
        self.scales.get_mut(name)
    }

    /// Iterate `(name, scale)` pairs. Order is unspecified.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Scale)> + '_ {
        self.scales.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Iterate just the registered names. Order is unspecified.
    pub fn names(&self) -> impl Iterator<Item = &str> + '_ {
        self.scales.keys().map(|s| s.as_str())
    }

    /// True if a scale with `name` is registered.
    pub fn contains(&self, name: &str) -> bool {
        self.scales.contains_key(name)
    }

    /// Number of registered scales.
    pub fn len(&self) -> usize {
        self.scales.len()
    }

    /// True when no scales are registered.
    pub fn is_empty(&self) -> bool {
        self.scales.is_empty()
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn a_comma_decimal_locale_reaches_the_default_formatter() {
        // `decimal` is the one `Locale` field the default formatter
        // consults, and every other format test uses `EN_US` — where a
        // dropped swap is invisible.
        let s = continuous(0.0..=1.0);
        assert_eq!(s.format(&Value::Number(0.5), &Locale::EN_US), "0.5");
        assert_eq!(s.format(&Value::Number(0.5), &Locale::DE_DE), "0,5");
        assert_eq!(s.format(&Value::Number(0.5), &Locale::FR_FR), "0,5");
        // Negative and integral values take the same path.
        assert_eq!(s.format(&Value::Number(-1.25), &Locale::DE_DE), "-1,25");
        assert_eq!(s.format(&Value::Number(3.0), &Locale::DE_DE), "3");
    }

    #[test]
    fn temporal_labels_are_locale_insensitive() {
        // Dates render ISO regardless of locale — the calendar-name
        // tables are vocabulary for user formatters, not something the
        // default one reaches for.
        let s = Scale::new(ScaleTypeKind::Temporal(TemporalUnit::Date));
        let v = Value::Date(crate::scales::value::Date::from_ymd(2024, 3, 7).to_days());
        assert_eq!(s.format(&v, &Locale::EN_US), "2024-03-07");
        assert_eq!(s.format(&v, &Locale::DE_DE), "2024-03-07");
    }

    #[test]
    fn breaks_memo_follows_the_generation_counter() {
        // The memo is keyed on `(generation, n)`, so a domain change has
        // to invalidate it and a different tick target must not collide
        // with a cached one.
        let nums =
            |vs: Vec<Value>| -> Vec<f64> { vs.iter().filter_map(|v| v.as_number()).collect() };
        let mut s = continuous(0.0..=10.0);
        let first = nums(s.breaks(5));
        assert_eq!(
            first,
            nums(s.breaks(5)),
            "a repeat call must agree with itself"
        );

        let coarser = nums(s.breaks(3));
        assert_eq!(
            coarser,
            nums(s.breaks(3)),
            "the tick target is part of the key"
        );

        s.set_domain_continuous(0.0, 1000.0);
        let after = nums(s.breaks(5));
        assert_ne!(
            first, after,
            "a domain change must not serve the stale break set"
        );
        assert_eq!(after, nums(s.breaks(5)));
    }

    #[test]
    fn scale_and_registry_are_send_and_sync() {
        // A `Scale` is a plain value bundle plus an `Arc<LabelFormatter>`
        // whose bound requires `Send + Sync`, so scales can be built on a
        // worker thread and shared across threads. `Plot` is not — geoms
        // memoize shaped text behind `RefCell` — which is why the
        // registry is the sharing boundary.
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Scale>();
        assert_send_sync::<ScaleRegistry>();
    }
    use crate::scales::value::{Date, DateTime, Time};

    fn approx(a: f64, b: f64, tol: f64, msg: &str) {
        assert!((a - b).abs() < tol, "{msg}: {a} ≠ {b}");
    }

    // ── Continuous ──

    #[test]
    fn continuous_map_normalised() {
        let s = continuous(0.0..=10.0);
        approx(
            s.map(&Value::Number(0.0)).as_number().unwrap(),
            0.0,
            1e-12,
            "lo",
        );
        approx(
            s.map(&Value::Number(5.0)).as_number().unwrap(),
            0.5,
            1e-12,
            "mid",
        );
        approx(
            s.map(&Value::Number(10.0)).as_number().unwrap(),
            1.0,
            1e-12,
            "hi",
        );
    }

    #[test]
    fn continuous_extrapolates_outside_domain() {
        let s = continuous(0.0..=10.0);
        approx(
            s.map(&Value::Number(-5.0)).as_number().unwrap(),
            -0.5,
            1e-12,
            "below",
        );
        approx(
            s.map(&Value::Number(15.0)).as_number().unwrap(),
            1.5,
            1e-12,
            "above",
        );
    }

    #[test]
    fn continuous_with_numeric_range() {
        let s = continuous(0.0..=1.0).range_numbers([2.0, 12.0]);
        approx(
            s.map(&Value::Number(0.0)).as_number().unwrap(),
            2.0,
            1e-12,
            "lo",
        );
        approx(
            s.map(&Value::Number(0.5)).as_number().unwrap(),
            7.0,
            1e-12,
            "mid",
        );
        approx(
            s.map(&Value::Number(1.0)).as_number().unwrap(),
            12.0,
            1e-12,
            "hi",
        );
    }

    #[test]
    fn continuous_with_degenerate_domain() {
        let s = continuous(5.0..=5.0);
        assert_eq!(s.map(&Value::Number(5.0)).as_number(), Some(0.0));
    }

    #[test]
    fn continuous_non_numeric_input_returns_null() {
        let s = continuous(0.0..=10.0);
        assert!(s.map(&Value::Null).is_null());
        assert!(s.map(&Value::String("nope".into())).is_null());
    }

    #[test]
    fn continuous_breaks_use_extended() {
        let s = continuous(0.0..=10.0);
        let bs = s.breaks(5);
        assert!(bs.len() >= 4 && bs.len() <= 7);
        assert!(bs.first().unwrap().key_eq(&Value::Number(0.0)));
        assert!(bs.last().unwrap().key_eq(&Value::Number(10.0)));
    }

    // ── Discrete / Ordinal ──

    #[test]
    fn discrete_band_centres_no_range() {
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into));
        approx(
            s.map(&Value::from("a")).as_number().unwrap(),
            1.0 / 6.0,
            1e-12,
            "a",
        );
        approx(
            s.map(&Value::from("b")).as_number().unwrap(),
            0.5,
            1e-12,
            "b",
        );
        approx(
            s.map(&Value::from("c")).as_number().unwrap(),
            5.0 / 6.0,
            1e-12,
            "c",
        );
    }

    #[test]
    fn discrete_unknown_category_is_null() {
        let s = discrete(["a", "b"].into_iter().map(Into::into));
        assert!(s.map(&Value::from("missing")).is_null());
    }

    #[test]
    fn discrete_band_width() {
        let s = discrete(["a", "b", "c", "d"].into_iter().map(Into::into));
        approx(s.band_width(), 0.25, 1e-12, "1/4");
    }

    #[test]
    fn ordinal_color_round_trip() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let green = Color::new([0.0, 1.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = ordinal(["A", "B", "C"]).range_colors([red, green, blue]);
        assert_eq!(s.map(&Value::from("A")).as_color(), Some(red));
        assert_eq!(s.map(&Value::from("B")).as_color(), Some(green));
        assert_eq!(s.map(&Value::from("C")).as_color(), Some(blue));
        assert!(s.map(&Value::from("D")).is_null());
    }

    #[test]
    fn ordinal_with_numeric_range_returns_pt() {
        let s = Scale::new(ScaleTypeKind::Ordinal)
            .domain_discrete(["S", "M", "L"].into_iter().map(Into::into))
            .range_numbers([4.0, 8.0, 12.0]);
        assert_eq!(s.map(&Value::from("S")).as_number(), Some(4.0));
        assert_eq!(s.map(&Value::from("L")).as_number(), Some(12.0));
    }

    fn lt_dash_gap(d: f64, g: f64) -> Arc<[LinetypeStep]> {
        Arc::from(vec![LinetypeStep::Dash(d), LinetypeStep::Gap(g)])
    }

    fn lt_solid() -> Arc<[LinetypeStep]> {
        Arc::from(Vec::<LinetypeStep>::new())
    }

    #[test]
    fn discrete_with_linetype_range_steps_by_index() {
        let solid = lt_solid();
        let dashed = lt_dash_gap(8.0, 4.0);
        let dotted = lt_dash_gap(2.0, 3.0);
        let s = discrete(["A", "B", "C"].into_iter().map(Into::into)).range_linetypes([
            solid.clone(),
            dashed.clone(),
            dotted.clone(),
        ]);
        assert!(s
            .map(&Value::from("A"))
            .key_eq(&Value::Linetype(solid.clone())));
        assert!(s
            .map(&Value::from("B"))
            .key_eq(&Value::Linetype(dashed.clone())));
        assert!(s.map(&Value::from("C")).key_eq(&Value::Linetype(dotted)));
        assert!(s.map(&Value::from("D")).is_null());
    }

    #[test]
    fn ordinal_with_linetype_range_steps_by_nearest_index() {
        let solid = lt_solid();
        let dashed = lt_dash_gap(8.0, 4.0);
        let s = ordinal(["L1", "L2", "L3", "L4"]).range_linetypes([solid.clone(), dashed.clone()]);
        assert!(s
            .map(&Value::from("L1"))
            .key_eq(&Value::Linetype(solid.clone())));
        assert!(s.map(&Value::from("L2")).key_eq(&Value::Linetype(solid)));
        assert!(s
            .map(&Value::from("L3"))
            .key_eq(&Value::Linetype(dashed.clone())));
        assert!(s.map(&Value::from("L4")).key_eq(&Value::Linetype(dashed)));
    }

    #[test]
    fn continuous_with_linetype_range_steps() {
        let solid = lt_solid();
        let dashed = lt_dash_gap(8.0, 4.0);
        let dotted = lt_dash_gap(2.0, 3.0);
        let s =
            continuous(0.0..=10.0).range_linetypes([solid.clone(), dashed.clone(), dotted.clone()]);
        assert!(s
            .map(&Value::Number(0.0))
            .key_eq(&Value::Linetype(solid.clone())));
        assert!(s.map(&Value::Number(5.0)).key_eq(&Value::Linetype(dashed)));
        assert!(s.map(&Value::Number(10.0)).key_eq(&Value::Linetype(dotted)));
    }

    #[test]
    fn ordinal_color_interpolates_when_stops_lt_levels() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = ordinal(["L1", "L2", "L3", "L4"])
            .range_colors([red, blue])
            .with_color_space(ColorSpace::Srgb);
        assert_eq!(s.map(&Value::from("L1")).as_color(), Some(red));
        assert_eq!(s.map(&Value::from("L4")).as_color(), Some(blue));
        let c2 = s.map(&Value::from("L2")).as_color().unwrap();
        approx(c2.components[0] as f64, 2.0 / 3.0, 1e-5, "L2.r");
        approx(c2.components[2] as f64, 1.0 / 3.0, 1e-5, "L2.b");
        let c3 = s.map(&Value::from("L3")).as_color().unwrap();
        approx(c3.components[0] as f64, 1.0 / 3.0, 1e-5, "L3.r");
        approx(c3.components[2] as f64, 2.0 / 3.0, 1e-5, "L3.b");
    }

    #[test]
    fn ordinal_numeric_interpolates_when_stops_lt_levels() {
        let s = Scale::new(ScaleTypeKind::Ordinal)
            .domain_discrete(["A", "B", "C", "D", "E"].into_iter().map(Into::into))
            .range_numbers([2.0, 10.0]);
        approx(
            s.map(&Value::from("A")).as_number().unwrap(),
            2.0,
            1e-12,
            "A",
        );
        approx(
            s.map(&Value::from("B")).as_number().unwrap(),
            4.0,
            1e-12,
            "B",
        );
        approx(
            s.map(&Value::from("C")).as_number().unwrap(),
            6.0,
            1e-12,
            "C",
        );
        approx(
            s.map(&Value::from("D")).as_number().unwrap(),
            8.0,
            1e-12,
            "D",
        );
        approx(
            s.map(&Value::from("E")).as_number().unwrap(),
            10.0,
            1e-12,
            "E",
        );
    }

    #[test]
    fn continuous_with_color_range() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        // sRGB so the channel values read directly as the ramp
        // fraction each input lands on.
        let s = continuous(0.0..=10.0)
            .range_colors([red, blue])
            .with_color_space(ColorSpace::Srgb);
        assert_eq!(s.map(&Value::Number(0.0)).as_color(), Some(red));
        assert_eq!(s.map(&Value::Number(10.0)).as_color(), Some(blue));
        let mid = s.map(&Value::Number(5.0)).as_color().unwrap();
        approx(mid.components[0] as f64, 0.5, 1e-5, "mid.r");
        approx(mid.components[2] as f64, 0.5, 1e-5, "mid.b");
    }

    #[test]
    fn color_range_interpolates_in_oklab_by_default() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = continuous(0.0..=10.0).range_colors([red, blue]);
        assert_eq!(s.color_space(), ColorSpace::Oklab);
        // Endpoints still land on their stops exactly, so a palette's
        // extremes survive the round trip through the interpolation space.
        assert_eq!(s.map(&Value::Number(0.0)).as_color(), Some(red));
        assert_eq!(s.map(&Value::Number(10.0)).as_color(), Some(blue));
        // The midpoint departs from the channel average — that departure
        // is the point of interpolating perceptually.
        let mid = s.map(&Value::Number(5.0)).as_color().unwrap();
        assert!(
            (mid.components[0] as f64 - 0.5).abs() > 0.02,
            "oklab midpoint {mid:?} should not be the channel average"
        );
        let srgb_mid = continuous(0.0..=10.0)
            .range_colors([red, blue])
            .with_color_space(ColorSpace::Srgb)
            .map(&Value::Number(5.0))
            .as_color()
            .unwrap();
        assert_ne!(mid, srgb_mid);
    }

    #[test]
    fn color_space_survives_mutation_and_bumps_generation() {
        let mut s = continuous(0.0..=1.0).range_colors([
            Color::new([1.0, 0.0, 0.0, 1.0]),
            Color::new([0.0, 0.0, 1.0, 1.0]),
        ]);
        let before = s.generation();
        s.set_color_space(ColorSpace::Srgb);
        assert_eq!(s.color_space(), ColorSpace::Srgb);
        assert!(s.generation() > before);
    }

    #[test]
    fn colorbars_over_different_spaces_are_not_visually_equivalent() {
        let stops = [
            Color::new([1.0, 0.0, 0.0, 1.0]),
            Color::new([0.0, 0.0, 1.0, 1.0]),
        ];
        let a = continuous(0.0..=1.0).range_colors(stops);
        let b = continuous(0.0..=1.0)
            .range_colors(stops)
            .with_color_space(ColorSpace::Srgb);
        let locale = Locale::default();
        // Same domain and breaks, so the legend rows still collapse …
        assert!(a.legend_equivalent_to(&b, &locale));
        // … but the bars they'd draw differ.
        assert!(!a.visual_equivalent_to(&b, &locale));
    }

    #[test]
    fn continuous_piecewise_three_stops() {
        let s = continuous(0.0..=1.0).range_numbers([2.0, 8.0, 12.0]);
        approx(
            s.map(&Value::Number(0.0)).as_number().unwrap(),
            2.0,
            1e-12,
            "0",
        );
        approx(
            s.map(&Value::Number(0.25)).as_number().unwrap(),
            5.0,
            1e-12,
            "0.25",
        );
        approx(
            s.map(&Value::Number(0.5)).as_number().unwrap(),
            8.0,
            1e-12,
            "0.5",
        );
        approx(
            s.map(&Value::Number(0.75)).as_number().unwrap(),
            10.0,
            1e-12,
            "0.75",
        );
        approx(
            s.map(&Value::Number(1.0)).as_number().unwrap(),
            12.0,
            1e-12,
            "1",
        );
    }

    #[test]
    fn ordinal_with_matched_stops_is_one_to_one() {
        let s = Scale::new(ScaleTypeKind::Ordinal)
            .domain_discrete(["S", "M", "L"].into_iter().map(Into::into))
            .range_numbers([4.0, 8.0, 12.0]);
        assert_eq!(s.map(&Value::from("S")).as_number(), Some(4.0));
        assert_eq!(s.map(&Value::from("M")).as_number(), Some(8.0));
        assert_eq!(s.map(&Value::from("L")).as_number(), Some(12.0));
    }

    #[test]
    fn discrete_breaks_return_domain() {
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into));
        let bs = s.breaks(0);
        assert_eq!(bs.len(), 3);
        assert!(bs[0].key_eq(&Value::from("a")));
        assert!(bs[2].key_eq(&Value::from("c")));
    }

    // ── Binned ──

    #[test]
    fn binned_map_proportional() {
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]);
        approx(
            s.map(&Value::Number(1.0)).as_number().unwrap(),
            0.1,
            1e-12,
            "bin 0",
        );
        approx(
            s.map(&Value::Number(3.0)).as_number().unwrap(),
            0.35,
            1e-12,
            "bin 1",
        );
        approx(
            s.map(&Value::Number(8.0)).as_number().unwrap(),
            0.75,
            1e-12,
            "bin 2",
        );
        approx(
            s.map(&Value::Number(2.0)).as_number().unwrap(),
            0.35,
            1e-12,
            "boundary",
        );
        approx(
            s.map(&Value::Number(10.0)).as_number().unwrap(),
            0.75,
            1e-12,
            "top",
        );
    }

    #[test]
    fn binned_map_break_lands_on_own_domain_fraction() {
        let s = binned(
            2500.0..=6500.0,
            vec![2500.0, 3500.0, 4500.0, 5500.0, 6500.0],
        );
        let breaks = s.breaks(5);
        let positions: Vec<f64> = breaks
            .iter()
            .map(|b| s.map_break(b).as_number().unwrap())
            .collect();
        for (b, p) in breaks.iter().zip(&positions) {
            let v = b.as_number().unwrap();
            approx(*p, (v - 2500.0) / 4000.0, 1e-12, "edge break position");
        }
        // Distinct edges must not collapse onto each other — mapping them
        // as data would put both 5500 and 6500 at the last bin's centre.
        for (i, a) in positions.iter().enumerate() {
            for b in &positions[i + 1..] {
                assert!((a - b).abs() > 1e-9, "breaks collided at {a}");
            }
        }
    }

    #[test]
    fn map_break_matches_map_off_binned() {
        let c = continuous(0.0..=10.0);
        for v in c.breaks(5) {
            assert!(c.map_break(&v).key_eq(&c.map(&v)), "continuous {v:?}");
        }
        let d = discrete(vec![Value::from("a"), Value::from("b"), Value::from("c")]);
        for v in d.breaks(0) {
            assert!(d.map_break(&v).key_eq(&d.map(&v)), "discrete {v:?}");
        }
    }

    #[test]
    fn binned_band_width_at_per_bin() {
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]);
        approx(s.band_width_at(&Value::Number(1.0)), 0.2, 1e-12, "bin 0");
        approx(s.band_width_at(&Value::Number(3.0)), 0.3, 1e-12, "bin 1");
        approx(s.band_width_at(&Value::Number(8.0)), 0.5, 1e-12, "bin 2");
    }

    #[test]
    fn binned_map_with_offset_uses_per_bin_width() {
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]);
        approx(
            s.map_with_offset(&Value::Number(3.0), 0.5)
                .as_number()
                .unwrap(),
            0.5,
            1e-12,
            "bin 1 right edge",
        );
        approx(
            s.map_with_offset(&Value::Number(8.0), -0.5)
                .as_number()
                .unwrap(),
            0.5,
            1e-12,
            "bin 2 left edge",
        );
    }

    #[test]
    fn binned_out_of_range_is_null() {
        let s = binned(0.0..=10.0, vec![0.0, 5.0, 10.0]);
        assert!(s.map(&Value::Number(-1.0)).is_null());
        assert!(s.map(&Value::Number(11.0)).is_null());
    }

    #[test]
    fn binned_without_bins_is_null() {
        let s = Scale::new(ScaleTypeKind::Binned).domain_continuous(0.0, 10.0);
        assert!(s.map(&Value::Number(5.0)).is_null());
        assert!(s.breaks(5).is_empty());
        approx(s.band_width(), 0.0, 1e-12, "no bins");
    }

    #[test]
    fn binned_color_range_indexes_by_bin() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let green = Color::new([0.0, 1.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0]).range_colors([red, green, blue]);
        assert_eq!(s.map(&Value::Number(5.0)).as_color(), Some(red));
        assert_eq!(s.map(&Value::Number(15.0)).as_color(), Some(green));
        assert_eq!(s.map(&Value::Number(25.0)).as_color(), Some(blue));
        // A palette doesn't disturb the bin definition.
        let bs = s.breaks(5);
        assert_eq!(bs.len(), 4);
        assert!(bs[1].key_eq(&Value::Number(10.0)));
        approx(s.band_width(), 1.0 / 3.0, 1e-12, "3 bins");
    }

    #[test]
    fn binned_numeric_range_is_a_per_bin_palette() {
        let s = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0]).range_numbers([1.0, 3.0, 5.0]);
        approx(
            s.map(&Value::Number(5.0)).as_number().unwrap(),
            1.0,
            1e-12,
            "bin 0",
        );
        approx(
            s.map(&Value::Number(15.0)).as_number().unwrap(),
            3.0,
            1e-12,
            "bin 1",
        );
        approx(
            s.map(&Value::Number(25.0)).as_number().unwrap(),
            5.0,
            1e-12,
            "bin 2",
        );
    }

    #[test]
    fn binned_color_range_interpolates_when_stops_lt_bins() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = binned(0.0..=40.0, vec![0.0, 10.0, 20.0, 30.0, 40.0])
            .range_colors([red, blue])
            .with_color_space(ColorSpace::Srgb);
        assert_eq!(s.map(&Value::Number(5.0)).as_color(), Some(red));
        assert_eq!(s.map(&Value::Number(35.0)).as_color(), Some(blue));
        let c2 = s.map(&Value::Number(15.0)).as_color().unwrap();
        approx(c2.components[0] as f64, 2.0 / 3.0, 1e-5, "bin 1 r");
        approx(c2.components[2] as f64, 1.0 / 3.0, 1e-5, "bin 1 b");
    }

    #[test]
    fn binned_linetype_range_indexes_by_bin() {
        let solid = lt_solid();
        let dashed = lt_dash_gap(8.0, 4.0);
        let dotted = lt_dash_gap(2.0, 3.0);
        let s = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0]).range_linetypes([
            solid.clone(),
            dashed.clone(),
            dotted.clone(),
        ]);
        assert!(s
            .map(&Value::Number(5.0))
            .key_eq(&Value::Linetype(solid.clone())));
        assert!(s.map(&Value::Number(15.0)).key_eq(&Value::Linetype(dashed)));
        assert!(s.map(&Value::Number(25.0)).key_eq(&Value::Linetype(dotted)));
    }

    #[test]
    fn binned_palette_keeps_positional_band_offsets() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]).range_colors([red, blue]);
        approx(s.band_width_at(&Value::Number(3.0)), 0.3, 1e-12, "bin 1");
        // A Color output has no numeric offset to apply — it passes through.
        assert_eq!(
            s.map_with_offset(&Value::Number(3.0), 0.5).as_color(),
            s.map(&Value::Number(3.0)).as_color()
        );
    }

    #[test]
    fn binned_legend_equivalence_distinguishes_bin_edges() {
        let locale = Locale::default();
        let a = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0]);
        let b = binned(0.0..=30.0, vec![0.0, 15.0, 30.0]);
        assert!(!a.legend_equivalent_to(&b, &locale));
        let c = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0])
            .range_colors([Color::new([1.0, 0.0, 0.0, 1.0])]);
        assert!(a.legend_equivalent_to(&c, &locale));
    }

    // ── Direction ──

    #[test]
    fn reversed_continuous_mirrors_the_fraction() {
        let s = continuous(0.0..=10.0).with_direction(Direction::Reversed);
        approx(
            s.map(&Value::Number(0.0)).as_number().unwrap(),
            1.0,
            1e-12,
            "lo",
        );
        approx(
            s.map(&Value::Number(2.5)).as_number().unwrap(),
            0.75,
            1e-12,
            "quarter",
        );
        approx(
            s.map(&Value::Number(10.0)).as_number().unwrap(),
            0.0,
            1e-12,
            "hi",
        );
    }

    #[test]
    fn reversed_continuous_walks_its_palette_backwards() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = continuous(0.0..=10.0)
            .range_colors([red, blue])
            .with_direction(Direction::Reversed);
        assert_eq!(s.map(&Value::Number(0.0)).as_color(), Some(blue));
        assert_eq!(s.map(&Value::Number(10.0)).as_color(), Some(red));
    }

    #[test]
    fn reversed_continuous_composes_with_a_transform() {
        let s = continuous(1.0..=1000.0)
            .with_transform(TransformKind::Log10)
            .with_direction(Direction::Reversed);
        approx(
            s.map(&Value::Number(10.0)).as_number().unwrap(),
            2.0 / 3.0,
            1e-12,
            "one decade up, from the far end",
        );
    }

    #[test]
    fn reversed_scale_keeps_its_break_values() {
        let fwd = continuous(0.0..=10.0);
        let rev = continuous(0.0..=10.0).with_direction(Direction::Reversed);
        let (a, b) = (fwd.breaks(5), rev.breaks(5));
        assert_eq!(a.len(), b.len());
        for (x, y) in a.iter().zip(&b) {
            assert!(x.key_eq(y), "break values differ: {x:?} vs {y:?}");
        }
        // Only where they land changes.
        for v in &a {
            approx(
                rev.map_break(v).as_number().unwrap(),
                1.0 - fwd.map_break(v).as_number().unwrap(),
                1e-12,
                "mirrored break position",
            );
        }
    }

    #[test]
    fn reversed_discrete_mirrors_bands_and_palette() {
        let levels = vec![Value::from("a"), Value::from("b"), Value::from("c")];
        let s = discrete(levels.clone()).with_direction(Direction::Reversed);
        approx(
            s.map(&levels[0]).as_number().unwrap(),
            5.0 / 6.0,
            1e-12,
            "first",
        );
        approx(
            s.map(&levels[2]).as_number().unwrap(),
            1.0 / 6.0,
            1e-12,
            "last",
        );

        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let green = Color::new([0.0, 1.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let c = discrete(levels.clone())
            .range_colors([red, green, blue])
            .with_direction(Direction::Reversed);
        assert_eq!(c.map(&levels[0]).as_color(), Some(blue));
        assert_eq!(c.map(&levels[2]).as_color(), Some(red));
    }

    #[test]
    fn reversed_ordinal_mirrors_the_gradient() {
        let s = ordinal(["a", "b", "c"])
            .range_numbers([2.0, 12.0])
            .with_direction(Direction::Reversed);
        approx(
            s.map(&Value::from("a")).as_number().unwrap(),
            12.0,
            1e-12,
            "first",
        );
        approx(
            s.map(&Value::from("b")).as_number().unwrap(),
            7.0,
            1e-12,
            "middle",
        );
        approx(
            s.map(&Value::from("c")).as_number().unwrap(),
            2.0,
            1e-12,
            "last",
        );
    }

    #[test]
    fn reversed_binned_position_mirrors_bin_centres() {
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]).with_direction(Direction::Reversed);
        // Uneven bins keep their proportional widths, measured from the
        // far end of the panel.
        approx(
            s.map(&Value::Number(1.0)).as_number().unwrap(),
            0.9,
            1e-12,
            "bin 0",
        );
        approx(
            s.map(&Value::Number(3.0)).as_number().unwrap(),
            0.65,
            1e-12,
            "bin 1",
        );
        approx(
            s.map(&Value::Number(8.0)).as_number().unwrap(),
            0.25,
            1e-12,
            "bin 2",
        );
        approx(
            s.band_width_at(&Value::Number(3.0)),
            0.3,
            1e-12,
            "band width is unsigned",
        );
    }

    #[test]
    fn reversed_binned_palette_counts_from_the_far_end() {
        let red = Color::new([1.0, 0.0, 0.0, 1.0]);
        let green = Color::new([0.0, 1.0, 0.0, 1.0]);
        let blue = Color::new([0.0, 0.0, 1.0, 1.0]);
        let s = binned(0.0..=30.0, vec![0.0, 10.0, 20.0, 30.0])
            .range_colors([red, green, blue])
            .with_direction(Direction::Reversed);
        assert_eq!(s.map(&Value::Number(5.0)).as_color(), Some(blue));
        assert_eq!(s.map(&Value::Number(15.0)).as_color(), Some(green));
        assert_eq!(s.map(&Value::Number(25.0)).as_color(), Some(red));
    }

    #[test]
    fn reversed_binned_breaks_stay_with_the_bins_they_bound() {
        let s = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]).with_direction(Direction::Reversed);
        let positions: Vec<f64> = s
            .breaks(5)
            .iter()
            .map(|b| s.map_break(b).as_number().unwrap())
            .collect();
        assert_eq!(positions, vec![1.0, 0.8, 0.5, 0.0]);
    }

    #[test]
    fn reversed_band_offset_points_the_other_way() {
        // The offset stays anchored to the domain: +0.5 still reaches the
        // edge shared with the next category / bin, which is now the
        // lower panel fraction.
        let d = discrete(vec![Value::from("a"), Value::from("b"), Value::from("c")])
            .with_direction(Direction::Reversed);
        approx(
            d.map_with_offset(&Value::from("a"), 0.5)
                .as_number()
                .unwrap(),
            2.0 / 3.0,
            1e-12,
            "a's upper edge",
        );
        let b = binned(0.0..=10.0, vec![0.0, 2.0, 5.0, 10.0]).with_direction(Direction::Reversed);
        approx(
            b.map_with_offset(&Value::Number(3.0), 0.5)
                .as_number()
                .unwrap(),
            0.5,
            1e-12,
            "bin 1's upper edge",
        );
    }

    #[test]
    fn identity_ignores_direction() {
        let s = identity().with_direction(Direction::Reversed);
        assert!(s.map(&Value::Number(3.0)).key_eq(&Value::Number(3.0)));
    }

    #[test]
    fn direction_is_part_of_a_scale_visual_but_not_its_legend_layout() {
        let loc = Locale::default();
        let stops = [
            Color::new([1.0, 0.0, 0.0, 1.0]),
            Color::new([0.0, 0.0, 1.0, 1.0]),
        ];
        let fwd = continuous(0.0..=10.0).range_colors(stops);
        let rev = continuous(0.0..=10.0)
            .range_colors(stops)
            .with_direction(Direction::Reversed);
        assert!(
            fwd.legend_equivalent_to(&rev, &loc),
            "same domain, same rows, same labels"
        );
        assert!(
            !fwd.visual_equivalent_to(&rev, &loc),
            "a mirrored ramp is a different bar"
        );
    }

    #[test]
    fn direction_bumps_the_generation_counter() {
        let mut s = continuous(0.0..=1.0);
        let before = s.generation();
        s.set_direction(Direction::Reversed);
        assert!(s.generation() > before);
    }

    // ── Descending domains ──

    #[test]
    fn descending_domain_still_generates_breaks() {
        // Reversal is `Direction`'s job, but a domain written backwards
        // must still tick — every algorithm past the linear one bails on
        // `min >= max`, so the endpoints are ordered on the way in.
        assert!(!continuous(100.0..=0.0).breaks(5).is_empty(), "linear");
        assert!(
            !continuous(1000.0..=1.0)
                .with_transform(TransformKind::Log10)
                .breaks(5)
                .is_empty(),
            "log10"
        );
        assert!(
            !continuous(100.0..=0.0)
                .with_transform(TransformKind::Sqrt)
                .breaks(5)
                .is_empty(),
            "sqrt"
        );
        assert!(
            !continuous(100.0..=-100.0)
                .with_transform(TransformKind::Asinh)
                .breaks(5)
                .is_empty(),
            "asinh"
        );
        assert!(
            !temporal(Date(20000)..=Date(19000)).breaks(5).is_empty(),
            "date"
        );
        assert!(
            !continuous(100.0..=0.0).minor_breaks(5).is_empty(),
            "linear minors"
        );
    }

    // ── Identity ──

    #[test]
    fn identity_passes_through() {
        let s = identity();
        let c = Color::new([0.5, 0.5, 0.5, 1.0]);
        assert_eq!(s.map(&Value::Number(42.0)).as_number(), Some(42.0));
        assert_eq!(s.map(&Value::Color(c)).as_color(), Some(c));
        assert!(s.map(&Value::from("hi")).key_eq(&Value::from("hi")));
    }

    #[test]
    fn identity_passes_color_through() {
        let s = identity();
        let c = Color::new([0.25, 0.5, 0.75, 1.0]);
        assert_eq!(s.map(&Value::Color(c)).as_color(), Some(c));
    }

    // ── Temporal ──

    #[test]
    fn continuous_dates_maps_via_days() {
        let s = continuous(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31));
        let mid = Date::from_ymd(2024, 7, 1);
        let frac = s.map(&Value::Date(mid.to_days())).as_number().unwrap();
        assert!(frac > 0.0 && frac < 1.0, "mid-year frac was {frac}");
    }

    #[test]
    fn temporal_format_dates() {
        let s = continuous(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31));
        assert_eq!(
            s.format(
                &Value::Date(Date::from_ymd(2024, 1, 15).to_days()),
                &Locale::EN_US
            ),
            "2024-01-15"
        );
    }

    #[test]
    fn temporal_format_datetime() {
        let s = continuous(
            DateTime::from_ymd_hms_micros(2024, 1, 1, 0, 0, 0, 0)
                ..=DateTime::from_ymd_hms_micros(2024, 12, 31, 23, 59, 59, 0),
        );
        let dt = DateTime::from_ymd_hms_micros(2024, 6, 15, 12, 34, 56, 0);
        assert_eq!(
            s.format(&Value::DateTime(dt.to_micros()), &Locale::EN_US),
            "2024-06-15 12:34:56"
        );
    }

    #[test]
    fn temporal_format_time_sub_second() {
        // Time is now stored as nanoseconds; Value::Time(ns) is the raw
        // ns count. `from_hms_micros` is a μs-input convenience that
        // promotes to ns internally.
        let s = continuous(
            Time::from_hms_micros(0, 0, 0, 0)..=Time::from_hms_micros(23, 59, 59, 999_999),
        );
        let t = Time::from_hms_micros(7, 8, 9, 123_000);
        assert_eq!(
            s.format(&Value::Time(t.to_nanos()), &Locale::EN_US),
            "07:08:09.123"
        );
        let t_exact = Time::from_hms_micros(7, 8, 9, 0);
        assert_eq!(
            s.format(&Value::Time(t_exact.to_nanos()), &Locale::EN_US),
            "07:08:09"
        );

        // ns-input constructor: 7:08:09 + 456 ns sub-second.
        let t_ns = Time::from_hms_nanos(7, 8, 9, 456_000_000);
        assert_eq!(
            s.format(&Value::Time(t_ns.to_nanos()), &Locale::EN_US),
            "07:08:09.456"
        );
    }

    #[test]
    fn binned_accepts_temporal_domain() {
        let start = Date::from_ymd(2024, 1, 1);
        let end = Date::from_ymd(2024, 12, 31);
        let q1 = Date::from_ymd(2024, 4, 1).to_days() as f64;
        let q2 = Date::from_ymd(2024, 7, 1).to_days() as f64;
        let q3 = Date::from_ymd(2024, 10, 1).to_days() as f64;
        let s = binned(
            start..=end,
            vec![start.to_days() as f64, q1, q2, q3, end.to_days() as f64],
        );
        let start_f = start.to_days() as f64;
        let end_f = end.to_days() as f64;
        let span = end_f - start_f;
        let expected = ((start_f + q1) * 0.5 - start_f) / span;

        let jan = Date::from_ymd(2024, 1, 15).to_days() as f64;
        let frac = s.map(&Value::Date(jan as i32)).as_number().unwrap();
        approx(frac, expected, 1e-12, "jan in bin 0 (proportional)");
    }

    #[test]
    fn temporal_format_duration() {
        let s = identity();
        assert_eq!(
            s.format(
                &Value::Duration(3 * 3600 * 1_000_000 + 25 * 60 * 1_000_000 + 12 * 1_000_000),
                &Locale::EN_US
            ),
            "3h 25m 12s"
        );
        assert_eq!(
            s.format(&Value::Duration(-90 * 1_000_000), &Locale::EN_US),
            "-1m 30s"
        );
        assert_eq!(
            s.format(&Value::Duration(45 * 1_000_000), &Locale::EN_US),
            "45s"
        );
    }

    // ── Generation counter ──

    #[test]
    fn mutation_bumps_generation() {
        let mut s = continuous(0.0..=10.0);
        let g0 = s.generation();
        s.set_domain_continuous(0.0, 20.0);
        let g1 = s.generation();
        assert!(g1 > g0);
        s.set_range_numbers(vec![0.0, 1.0]);
        let g2 = s.generation();
        assert!(g2 > g1);
    }

    #[test]
    fn builder_chaining_does_not_bump_generation() {
        let s = continuous(0.0..=10.0)
            .range_numbers([0.0, 1.0])
            .with_transform(TransformKind::Identity);
        assert_eq!(s.generation(), 0);
    }

    // ── Auto-fit from data ──

    #[test]
    fn continuous_from_data_fits_numeric_extent() {
        let col: DataColumn = vec![1.0_f64, 3.5, -2.0, 7.0].into();
        let s = continuous_from_data(&col);
        match s.input_range() {
            Some(InputRange::Continuous { min, max }) => {
                approx(*min, -2.0, 1e-12, "min");
                approx(*max, 7.0, 1e-12, "max");
            }
            _ => panic!("expected Continuous input range"),
        }
    }

    #[test]
    fn continuous_from_data_empty_unconfigured() {
        let col: DataColumn = DataColumn::F64(vec![]);
        let s = continuous_from_data(&col);
        assert!(s.input_range().is_none());
    }

    // ── Transform-aware breaks ──

    #[test]
    fn log10_scale_breaks_emit_decade_powers() {
        let s = continuous(1.0..=1000.0).with_transform(TransformKind::Log10);
        let bs = s.breaks(5);
        let nums: Vec<f64> = bs.iter().filter_map(|v| v.as_number()).collect();
        for v in [1.0, 10.0, 100.0, 1000.0] {
            assert!(nums.contains(&v), "{nums:?} missing {v}");
        }
    }

    #[test]
    fn log10_scale_minor_breaks_emit_2_to_9() {
        let s = continuous(1.0..=10.0).with_transform(TransformKind::Log10);
        let m = s.minor_breaks(5);
        let nums: Vec<f64> = m.iter().filter_map(|v| v.as_number()).collect();
        for v in [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] {
            assert!(nums.contains(&v), "{nums:?} missing {v}");
        }
    }

    #[test]
    fn log10_scale_maps_decade_to_normalised_third() {
        // Log10 maps 1, 10, 100, 1000 to 0, 1/3, 2/3, 1 in normalised
        // panel space.
        let s = continuous(1.0..=1000.0).with_transform(TransformKind::Log10);
        approx(
            s.map(&Value::Number(1.0)).as_number().unwrap(),
            0.0,
            1e-9,
            "1",
        );
        approx(
            s.map(&Value::Number(10.0)).as_number().unwrap(),
            1.0 / 3.0,
            1e-9,
            "10",
        );
        approx(
            s.map(&Value::Number(100.0)).as_number().unwrap(),
            2.0 / 3.0,
            1e-9,
            "100",
        );
        approx(
            s.map(&Value::Number(1000.0)).as_number().unwrap(),
            1.0,
            1e-9,
            "1000",
        );
    }

    #[test]
    fn sqrt_scale_compresses_high_values() {
        let s = continuous(0.0..=100.0).with_transform(TransformKind::Sqrt);
        // Sqrt(50) / Sqrt(100) ≈ 0.707, not 0.5 like linear.
        approx(
            s.map(&Value::Number(50.0)).as_number().unwrap(),
            (50f64.sqrt()) / 10.0,
            1e-9,
            "50",
        );
    }

    #[test]
    fn sqrt_scale_minor_breaks_are_linear_midpoints() {
        let s = continuous(0.0..=100.0).with_transform(TransformKind::Sqrt);
        let m = s.minor_breaks(5);
        // Identity / sqrt / other use the linear midpoint algorithm: one
        // minor per consecutive-major interval.
        let majors = s.breaks(5);
        if majors.len() >= 2 {
            assert_eq!(m.len(), majors.len() - 1);
        }
    }

    #[test]
    fn identity_transform_breaks_match_extended() {
        // Default transform (Identity) on a continuous scale still uses
        // the Wilkinson Extended algorithm — no behavioural change from
        let s = continuous(0.0..=10.0);
        let bs = s.breaks(5);
        let nums: Vec<f64> = bs.iter().filter_map(|v| v.as_number()).collect();
        // Should include 0 and 10, with evenly-spaced steps in between.
        assert!(nums.first() == Some(&0.0));
        assert!(nums.last() == Some(&10.0));
    }

    #[test]
    fn identity_transform_minor_breaks_are_midpoints() {
        let s = continuous(0.0..=10.0);
        let majors = s.breaks(5);
        let minors = s.minor_breaks(5);
        if majors.len() >= 2 {
            assert_eq!(minors.len(), majors.len() - 1);
        }
    }

    #[test]
    fn asinh_scale_handles_negative_domain() {
        let s = continuous(-10.0..=10.0).with_transform(TransformKind::Asinh);
        // map(0) should be the midpoint.
        approx(
            s.map(&Value::Number(0.0)).as_number().unwrap(),
            0.5,
            1e-9,
            "asinh midpoint",
        );
        // Negative values map to fractions < 0.5; positive > 0.5.
        assert!(s.map(&Value::Number(-1.0)).as_number().unwrap() < 0.5);
        assert!(s.map(&Value::Number(1.0)).as_number().unwrap() > 0.5);
    }

    #[test]
    fn discrete_scale_has_no_minor_breaks() {
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into));
        assert!(s.minor_breaks(5).is_empty());
    }

    #[test]
    fn pseudo_log10_can_be_constructed() {
        let s = continuous(0.1..=1000.0).with_transform(TransformKind::PseudoLog10);
        let bs = s.breaks(5);
        assert!(!bs.is_empty());
    }

    // ── Calendar-aware temporal ──

    #[test]
    fn temporal_date_year_span_emits_year_starts() {
        // 5-year span → ticks at Jan 1 of each year.
        let s = temporal(Date::from_ymd(2020, 1, 1)..=Date::from_ymd(2024, 12, 31));
        let bs = s.breaks(5);
        let dates: Vec<(i32, u8, u8)> = bs
            .iter()
            .filter_map(|v| {
                if let Value::Date(d) = v {
                    Some(Date::from_days(*d).to_ymd())
                } else {
                    None
                }
            })
            .collect();
        // All ticks should be Jan 1 of some year inside the span.
        for (_, m, d) in &dates {
            assert_eq!(*m, 1, "month != 1: {dates:?}");
            assert_eq!(*d, 1, "day != 1: {dates:?}");
        }
        // Should include at least 2021-01-01 and 2024-01-01.
        assert!(dates.iter().any(|(y, _, _)| *y == 2021));
        assert!(dates.iter().any(|(y, _, _)| *y == 2024));
    }

    #[test]
    fn temporal_date_six_month_span_emits_month_starts() {
        let s = temporal(Date::from_ymd(2024, 3, 15)..=Date::from_ymd(2024, 9, 15));
        let bs = s.breaks(5);
        let dates: Vec<(i32, u8, u8)> = bs
            .iter()
            .filter_map(|v| match v {
                Value::Date(d) => Some(Date::from_days(*d).to_ymd()),
                _ => None,
            })
            .collect();
        assert!(!dates.is_empty());
        // All ticks should be on day 1 of some month.
        for (_, _, d) in &dates {
            assert_eq!(*d, 1, "month-start tick has day {d}: {dates:?}");
        }
    }

    #[test]
    fn temporal_date_ten_day_span_emits_day_ticks() {
        let s = temporal(Date::from_ymd(2024, 6, 1)..=Date::from_ymd(2024, 6, 10));
        let bs = s.breaks(5);
        // 10 days → expect every day (Day-level enumeration) or at
        // least multiple unique day ticks.
        assert!(bs.len() >= 5, "expected ~10 day ticks, got {}", bs.len());
        // All variants should be Value::Date.
        assert!(bs.iter().all(|v| matches!(v, Value::Date(_))));
    }

    #[test]
    fn temporal_breaks_return_date_variant_not_number() {
        // The formatter relies on the Date variant to render as
        // YYYY-MM-DD; if breaks come back as Value::Number the labels
        // render as raw day numbers.
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31));
        for v in s.breaks(5) {
            assert!(matches!(v, Value::Date(_)), "{v:?} is not Date");
        }
    }

    #[test]
    fn temporal_minor_breaks_subdivide_majors() {
        // Year-spaced majors → quarter-spaced minors.
        let s = temporal(Date::from_ymd(2020, 1, 1)..=Date::from_ymd(2024, 12, 31));
        let minors = s.minor_breaks(5);
        let minor_dates: Vec<(i32, u8, u8)> = minors
            .iter()
            .filter_map(|v| match v {
                Value::Date(d) => Some(Date::from_days(*d).to_ymd()),
                _ => None,
            })
            .collect();
        // Quarter starts are Jan, Apr, Jul, Oct.
        for (_, m, d) in &minor_dates {
            assert_eq!(*d, 1, "quarter minor has day {d}: {minor_dates:?}");
            assert!(
                [1, 4, 7, 10].contains(m),
                "month {m} not a quarter start: {minor_dates:?}"
            );
        }
        // Minor ticks should NOT coincide with the major Jan-1 ticks.
        // (Quarter minors at Apr/Jul/Oct only — Jan is already a major.)
        for (_, m, _) in &minor_dates {
            assert_ne!(*m, 1, "minor coincides with major Jan 1");
        }
    }

    #[test]
    fn temporal_datetime_year_span_emits_year_starts() {
        let start = DateTime::from_ymd_hms_micros(2020, 1, 1, 0, 0, 0, 0);
        let end = DateTime::from_ymd_hms_micros(2024, 12, 31, 23, 59, 59, 0);
        let s = temporal(start..=end);
        let bs = s.breaks(5);
        assert!(!bs.is_empty());
        // All variants should be Value::DateTime.
        assert!(bs.iter().all(|v| matches!(v, Value::DateTime(_))));
        // Each tick should be at midnight UTC (so the sub-day μs are
        // multiples of DAY_US).
        for v in &bs {
            if let Value::DateTime(us) = v {
                let day_us = 86_400_000_000_i64;
                assert_eq!(us % day_us, 0, "tick not at midnight: {us}");
            }
        }
    }

    #[test]
    fn temporal_continuous_with_date_endpoints_still_works_numerically() {
        // The plain path: scale::continuous(Date..=Date) — keeps
        // numeric breaks (Value::Number containing days).
        let s = continuous(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31));
        let bs = s.breaks(5);
        // Expect Value::Number, not Value::Date.
        assert!(
            bs.iter().all(|v| matches!(v, Value::Number(_))),
            "continuous-with-date-endpoints should produce numeric breaks: {bs:?}"
        );
    }

    #[test]
    fn temporal_scale_map_is_continuous_linear() {
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31));
        // Midpoint should land near 0.5.
        let mid = Date::from_ymd(2024, 7, 2);
        let frac = s.map(&Value::Date(mid.to_days())).as_number().unwrap();
        assert!((0.4..=0.6).contains(&frac), "frac was {frac}");
    }

    #[test]
    fn temporal_panics_on_non_temporal_endpoint() {
        let result = std::panic::catch_unwind(|| {
            // f64 isn't temporal — should panic.
            let _ = temporal(0.0_f64..=10.0_f64);
        });
        assert!(result.is_err(), "expected panic on non-temporal endpoint");
    }

    // ── Float-precision-safe default number formatter ──

    #[test]
    fn default_number_formatter_scrubs_floating_point_noise() {
        let s = identity();
        assert_eq!(s.format(&Value::Number(0.1 + 0.2), &Locale::EN_US), "0.3");
        assert_eq!(
            s.format(&Value::Number(0.6000000000001), &Locale::EN_US),
            "0.6"
        );
        assert_eq!(s.format(&Value::Number(1.0), &Locale::EN_US), "1");
        assert_eq!(s.format(&Value::Number(1.5), &Locale::EN_US), "1.5");
        assert_eq!(s.format(&Value::Number(0.0), &Locale::EN_US), "0");
        assert_eq!(s.format(&Value::Number(-0.0), &Locale::EN_US), "0");
        // 12-sig-fig snap preserves real precision (9 sig figs here).
        assert_eq!(
            s.format(&Value::Number(0.123456789), &Locale::EN_US),
            "0.123456789"
        );
        // Non-finite values pass through.
        assert_eq!(
            s.format(&Value::Number(f64::INFINITY), &Locale::EN_US),
            "inf"
        );
        assert_eq!(
            s.format(&Value::Number(f64::NEG_INFINITY), &Locale::EN_US),
            "-inf"
        );
        assert_eq!(s.format(&Value::Number(f64::NAN), &Locale::EN_US), "NaN");
    }

    // ── Custom formatter ──

    #[test]
    fn custom_formatter_overrides_default() {
        let s = identity().with_format(|v, locale| match v {
            Value::Number(n) => format!("${n:.2}"),
            other => Scale::default_format(other, locale),
        });
        assert_eq!(s.format(&Value::Number(12.345), &Locale::EN_US), "$12.35");
        // Non-numeric variants fall through to the default delegate.
        assert_eq!(s.format(&Value::from("abc"), &Locale::EN_US), "abc");
    }

    #[test]
    fn clear_format_reverts_to_default() {
        let mut s = identity().with_format(|_, _| "X".to_string());
        assert_eq!(s.format(&Value::Number(1.0), &Locale::EN_US), "X");
        s.clear_format();
        assert_eq!(s.format(&Value::Number(1.0), &Locale::EN_US), "1");
    }

    #[test]
    fn formatter_survives_clone() {
        let s = identity().with_format(|v, locale| match v {
            Value::Number(n) => format!("n={n}"),
            other => Scale::default_format(other, locale),
        });
        let s2 = s.clone();
        assert_eq!(s.format(&Value::Number(3.0), &Locale::EN_US), "n=3");
        assert_eq!(s2.format(&Value::Number(3.0), &Locale::EN_US), "n=3");
    }

    // ── Explicit break overrides ──

    #[test]
    fn explicit_breaks_pin_positions() {
        let s = continuous(0.0..=100.0).with_breaks(vec![
            Value::Number(25.0),
            Value::Number(50.0),
            Value::Number(75.0),
        ]);
        let bs = s.breaks(5);
        let nums: Vec<f64> = bs.iter().filter_map(|v| v.as_number()).collect();
        assert_eq!(nums, vec![25.0, 50.0, 75.0]);
    }

    #[test]
    fn labeled_breaks_pin_labels() {
        let s = continuous(0.0..=1.0).with_breaks_labeled(vec![
            (Value::Number(0.0), "low".to_string()),
            (Value::Number(1.0), "high".to_string()),
        ]);
        assert_eq!(s.format(&Value::Number(0.0), &Locale::EN_US), "low");
        assert_eq!(s.format(&Value::Number(1.0), &Locale::EN_US), "high");
        // Unlisted values fall through to formatter / default.
        assert_eq!(s.format(&Value::Number(0.5), &Locale::EN_US), "0.5");
    }

    #[test]
    fn labeled_breaks_take_priority_over_formatter() {
        let s = continuous(0.0..=1.0)
            .with_format(|_, _| "FORMATTED".to_string())
            .with_breaks_labeled(vec![(Value::Number(0.5), "MID".to_string())]);
        assert_eq!(s.format(&Value::Number(0.5), &Locale::EN_US), "MID");
        // Outside the labeled set, formatter wins.
        assert_eq!(s.format(&Value::Number(0.7), &Locale::EN_US), "FORMATTED");
    }

    #[test]
    fn clear_breaks_reverts_to_auto() {
        let mut s = continuous(0.0..=10.0).with_breaks(vec![Value::Number(5.0)]);
        assert_eq!(s.breaks(5).len(), 1);
        s.clear_breaks();
        let bs = s.breaks(5);
        assert!(bs.len() > 1, "expected automatic breaks after clear");
    }

    // ── Interval break overrides ──

    #[test]
    fn numeric_interval_emits_aligned_multiples() {
        let s = continuous(0.5..=12.0).with_interval(2.0);
        let bs = s.breaks(0);
        let nums: Vec<f64> = bs.iter().filter_map(|v| v.as_number()).collect();
        assert_eq!(nums, vec![2.0, 4.0, 6.0, 8.0, 10.0, 12.0]);
    }

    #[test]
    fn numeric_interval_handles_negative_domain() {
        let s = continuous(-5.0..=5.0).with_interval(2.5);
        let bs = s.breaks(0);
        let nums: Vec<f64> = bs.iter().filter_map(|v| v.as_number()).collect();
        assert_eq!(nums, vec![-5.0, -2.5, 0.0, 2.5, 5.0]);
    }

    #[test]
    fn numeric_interval_falls_back_on_discrete() {
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into)).with_interval(1.0);
        let bs = s.breaks(0);
        // NumericInterval is meaningless on Discrete — falls back to
        // the automatic discrete_breaks (full domain).
        assert_eq!(bs.len(), 3);
    }

    #[test]
    fn temporal_interval_emits_calendar_aligned_ticks() {
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 3, 31))
            .with_temporal_interval(TemporalInterval::new(2, CalendarUnit::Week));
        let bs = s.breaks(0);
        // Every tick should be a Date variant aligned to the start of a
        // calendar week (Monday in our convention).
        assert!(!bs.is_empty(), "expected biweekly ticks in the span");
        for v in &bs {
            assert!(matches!(v, Value::Date(_)), "{v:?} is not Date");
        }
    }

    #[test]
    fn temporal_interval_falls_back_on_numeric_scale() {
        // TemporalInterval on a plain numeric scale should silently
        // fall back to the automatic algorithm.
        let s = continuous(0.0..=100.0)
            .with_temporal_interval(TemporalInterval::new(1, CalendarUnit::Week));
        let bs = s.breaks(5);
        assert!(!bs.is_empty(), "fallback should still produce breaks");
        // All breaks should be Value::Number (continuous output).
        assert!(bs.iter().all(|v| matches!(v, Value::Number(_))));
    }

    // ── Minor break overrides ──

    #[test]
    fn explicit_minor_breaks_pin_positions() {
        let s = continuous(0.0..=10.0).with_minor_breaks(vec![
            Value::Number(2.5),
            Value::Number(5.0),
            Value::Number(7.5),
        ]);
        let ms: Vec<f64> = s
            .minor_breaks(5)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert_eq!(ms, vec![2.5, 5.0, 7.5]);
    }

    #[test]
    fn empty_minor_breaks_suppress_minors() {
        let s = continuous(0.0..=10.0).with_minor_breaks(Vec::new());
        assert!(s.minor_breaks(5).is_empty());
    }

    #[test]
    fn explicit_minor_breaks_apply_to_discrete_scales() {
        // The automatic algorithm has nothing to offer a discrete
        // domain, but a pinned list still positions gridlines.
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into))
            .with_minor_breaks(vec![Value::Number(0.5)]);
        let ms: Vec<f64> = s
            .minor_breaks(0)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert_eq!(ms, vec![0.5]);
    }

    #[test]
    fn minor_count_subdivides_each_major_interval() {
        let s = continuous(0.0..=10.0)
            .with_breaks(vec![
                Value::Number(0.0),
                Value::Number(5.0),
                Value::Number(10.0),
            ])
            .with_minor_count(4);
        let ms: Vec<f64> = s
            .minor_breaks(5)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert_eq!(ms, vec![1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 8.0, 9.0]);
    }

    #[test]
    fn minor_count_zero_suppresses_minors() {
        let s = continuous(0.0..=10.0).with_minor_count(0);
        assert!(s.minor_breaks(5).is_empty());
    }

    #[test]
    fn minor_count_overrides_the_transform_default() {
        // Log10 minors are normally the geometric 2..9 per decade.
        let s = continuous(1.0..=100.0)
            .with_transform(TransformKind::Log10)
            .with_minor_count(1);
        let majors: Vec<f64> = s.breaks(5).iter().filter_map(|v| v.as_number()).collect();
        let ms: Vec<f64> = s
            .minor_breaks(5)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert_eq!(ms.len(), majors.len().saturating_sub(1));
    }

    #[test]
    fn minor_interval_skips_positions_carrying_a_major() {
        let s = continuous(0.0..=10.0)
            .with_interval(2.0)
            .with_minor_interval(0.5);
        let ms: Vec<f64> = s
            .minor_breaks(5)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert!(
            ms.iter().all(|m| (m / 2.0).fract() != 0.0),
            "minor landed on a major: {ms:?}"
        );
        assert_eq!(ms.first(), Some(&0.5));
        assert_eq!(ms.len(), 15, "21 half-steps minus 6 majors: {ms:?}");
    }

    #[test]
    fn minor_interval_falls_back_on_discrete() {
        let s = discrete(["a", "b", "c"].into_iter().map(Into::into)).with_minor_interval(0.5);
        assert!(s.minor_breaks(0).is_empty());
    }

    #[test]
    fn minor_temporal_interval_emits_calendar_aligned_dates() {
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 6, 30))
            .with_temporal_interval(TemporalInterval::new(1, CalendarUnit::Month))
            .with_minor_temporal_interval(TemporalInterval::new(1, CalendarUnit::Week));
        let minors = s.minor_breaks(5);
        assert!(!minors.is_empty(), "expected weekly minors in the span");
        assert!(
            minors.iter().all(|v| matches!(v, Value::Date(_))),
            "minors should carry the scale's calendar variant: {minors:?}"
        );
        // Month starts are majors; the weekly minors must skip them.
        let majors: Vec<f64> = s.breaks(5).iter().filter_map(|v| v.as_number()).collect();
        for m in minors.iter().filter_map(|v| v.as_number()) {
            assert!(!majors.contains(&m), "minor {m} coincides with a major");
        }
    }

    #[test]
    fn minor_temporal_interval_falls_back_on_numeric_scale() {
        let s = continuous(0.0..=100.0)
            .with_minor_temporal_interval(TemporalInterval::new(1, CalendarUnit::Week));
        let ms = s.minor_breaks(5);
        assert!(!ms.is_empty(), "fallback should still produce minors");
        assert!(ms.iter().all(|v| matches!(v, Value::Number(_))));
    }

    #[test]
    fn minor_numeric_interval_wraps_temporal_variants() {
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 1, 31))
            .with_minor_interval(2.0);
        let ms = s.minor_breaks(5);
        assert!(!ms.is_empty());
        assert!(ms.iter().all(|v| matches!(v, Value::Date(_))), "{ms:?}");
    }

    #[test]
    fn clear_minor_breaks_reverts_to_auto() {
        let mut s = continuous(0.0..=10.0).with_minor_breaks(Vec::new());
        assert!(s.minor_breaks(5).is_empty());
        s.clear_minor_breaks();
        assert!(
            !s.minor_breaks(5).is_empty(),
            "expected automatic minors after clear"
        );
    }

    #[test]
    fn auto_minors_subdivide_a_pinned_major_interval() {
        // Quarterly majors → monthly minors, one per month that isn't
        // itself a quarter start. Without the pinned interval the auto
        // algorithm sizes minors from the tick target instead.
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31))
            .with_temporal_interval(TemporalInterval::new(3, CalendarUnit::Month));
        let months: Vec<u8> = s
            .minor_breaks(5)
            .iter()
            .filter_map(|v| match v {
                Value::Date(d) => Some(Date::from_days(*d).to_ymd().1),
                _ => None,
            })
            .collect();
        assert_eq!(months, vec![2, 3, 5, 6, 8, 9, 11, 12]);
    }

    #[test]
    fn explicit_minors_win_over_a_pinned_major_interval() {
        let mid = Date::from_ymd(2024, 6, 15);
        let s = temporal(Date::from_ymd(2024, 1, 1)..=Date::from_ymd(2024, 12, 31))
            .with_temporal_interval(TemporalInterval::new(3, CalendarUnit::Month))
            .with_minor_breaks(vec![Value::Date(mid.to_days())]);
        let ms = s.minor_breaks(5);
        assert_eq!(ms.len(), 1);
        assert!(ms[0].key_eq(&Value::Date(mid.to_days())), "{ms:?}");
    }

    #[test]
    fn minor_override_leaves_majors_untouched() {
        let s = continuous(0.0..=10.0).with_minor_count(3);
        let auto = continuous(0.0..=10.0);
        let a: Vec<f64> = s.breaks(5).iter().filter_map(|v| v.as_number()).collect();
        let b: Vec<f64> = auto
            .breaks(5)
            .iter()
            .filter_map(|v| v.as_number())
            .collect();
        assert_eq!(a, b);
    }

    // ── Introspection ──

    #[test]
    fn breaks_spec_accessor_reflects_state() {
        let s = continuous(0.0..=10.0);
        assert!(s.breaks_spec().is_none());
        let s = s.with_interval(2.5);
        assert!(matches!(
            s.breaks_spec(),
            Some(BreaksSpec::NumericInterval(2.5))
        ));
    }

    #[test]
    fn minor_breaks_spec_accessor_reflects_state() {
        let s = continuous(0.0..=10.0);
        assert!(s.minor_breaks_spec().is_none());
        let s = s.with_minor_count(3);
        assert!(matches!(
            s.minor_breaks_spec(),
            Some(MinorBreaksSpec::CountBetween(3))
        ));
    }

    // ── Generation counter ──

    #[test]
    fn override_mutators_bump_generation() {
        let mut s = continuous(0.0..=10.0);
        let g0 = s.generation();
        s.set_breaks(vec![Value::Number(5.0)]);
        assert!(s.generation() > g0);
        let g1 = s.generation();
        s.set_format(|_, _| "X".to_string());
        assert!(s.generation() > g1);
        let g2 = s.generation();
        s.set_interval(1.0);
        assert!(s.generation() > g2);
        let g3 = s.generation();
        s.clear_breaks();
        assert!(s.generation() > g3);
    }

    #[test]
    fn minor_override_mutators_bump_generation() {
        let mut s = continuous(0.0..=10.0);
        let g0 = s.generation();
        s.set_minor_breaks(vec![Value::Number(5.0)]);
        assert!(s.generation() > g0);
        let g1 = s.generation();
        s.set_minor_count(2);
        assert!(s.generation() > g1);
        let g2 = s.generation();
        s.set_minor_interval(0.5);
        assert!(s.generation() > g2);
        let g3 = s.generation();
        s.set_minor_temporal_interval(TemporalInterval::new(1, CalendarUnit::Week));
        assert!(s.generation() > g3);
        let g4 = s.generation();
        s.clear_minor_breaks();
        assert!(s.generation() > g4);
    }

    #[test]
    fn override_chained_builders_do_not_bump_generation() {
        let s = continuous(0.0..=10.0)
            .with_breaks(vec![Value::Number(5.0)])
            .with_format(|_, _| "X".to_string())
            .with_interval(2.0);
        assert_eq!(s.generation(), 0);
    }
}