starsight-layer-3 0.3.3

Layer 3: Marks and stats
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
//! Marks: visual elements that read data and render onto a backend.
//!
//! Every mark implements the [`Mark`] trait. Concrete mark types share the same
//! `*Mark` suffix convention. Adding a new chart type means adding a new struct
//! to this file with its own `// ── ItemName ─────` section.
//!
//! Status:
//! - 0.1.0: `Mark` trait, `LineMark`, `PointMark`.
//! - 0.2.0: `BarMark`, `AreaMark`.
//! - 0.3.0+: `HeatmapMark`, `BoxMark`, `ViolinMark`, `PieMark`, `ContourMark`,
//!   `RidgeMark`, `StepMark`, `ErrorBarMark`, `RugMark`.

use crate::statistics::{Bin, BinMethod, BinTransform};
use starsight_layer_1::backends::DrawBackend;
use starsight_layer_1::errors::{Result, StarsightError};
use starsight_layer_1::paths::{LineCap, LineJoin, Path, PathCommand, PathStyle};
use starsight_layer_1::primitives::{Color, Point, Rect};
use starsight_layer_2::coords::{CartesianCoord, Coord, PolarCoord};
use std::collections::HashMap;

/// Downcast a `&dyn Coord` to the concrete `CartesianCoord` required by every
/// 0.2.x-era cartesian mark. New polar marks (`ArcMark`, `RadarMark`, etc.)
/// bypass this and downcast to their own coord type instead.
pub(crate) fn require_cartesian(coord: &dyn Coord) -> Result<&CartesianCoord> {
    coord
        .as_any()
        .downcast_ref::<CartesianCoord>()
        .ok_or_else(|| {
            StarsightError::Config("this mark requires a Cartesian coordinate system".to_string())
        })
}

/// Downcast a `&dyn Coord` to the concrete `PolarCoord`. Mirror of
/// [`require_cartesian`] for polar marks ([`crate::marks::ArcMark`],
/// `RadarMark`, etc.).
pub(crate) fn require_polar(coord: &dyn Coord) -> Result<&PolarCoord> {
    coord.as_any().downcast_ref::<PolarCoord>().ok_or_else(|| {
        StarsightError::Config("this mark requires a polar coordinate system".to_string())
    })
}

// ── Submodule marks (0.3.0+) ─────────────────────────────────────────────────────────────────────
//
// Statistical marks added in 0.3.0 live in their own submodule files to keep
// this top-level file readable. Each submodule re-exports its public type(s)
// up to `marks::` so users can write `starsight::marks::BoxPlotMark` without
// caring that the implementation lives in a sibling file.
pub mod arc;
pub mod bar_polar;
pub mod box_plot;
pub mod candlestick;
pub mod contour;
pub mod errorbar;
pub mod extent;
pub(crate) mod palette;
pub mod pie;
pub mod radar;
pub mod rect_polar;
pub mod rug;
pub mod violin;
pub use arc::ArcMark;
pub use bar_polar::PolarBarMark;
pub use box_plot::{BoxPlotGroup, BoxPlotMark};
pub use candlestick::{CandlestickMark, Ohlc};
pub use contour::{ContourMark, ContourMode};
pub use errorbar::{ErrorBarMark, ErrorBarOrientation};
pub use extent::MarkExtent;
pub use pie::PieMark;
pub use radar::RadarMark;
pub use rect_polar::PolarRectMark;
pub use rug::{AxisDir, RugMark};
pub use violin::{ViolinGroup, ViolinMark, ViolinScale};
// ── DataExtent ───────────────────────────────────────────────────────────────────────────────────

/// Axis-aligned bounding box of a mark's data, in data coordinates.
pub struct DataExtent {
    /// Minimum x value across the mark's data.
    pub x_min: f64,
    /// Maximum x value across the mark's data.
    pub x_max: f64,
    /// Minimum y value across the mark's data.
    pub y_min: f64,
    /// Maximum y value across the mark's data.
    pub y_max: f64,
}

/// Context for bar rendering that enables grouped/stacked modes.
#[derive(Debug, Default)]
pub struct BarRenderContext {
    /// Cumulative baselines for stacked bars: category -> baseline value.
    pub stacked_baselines: HashMap<String, f64>,
    /// Group offsets: `group_name` -> (`group_index`, `total_groups`).
    pub group_offsets: HashMap<String, (i32, i32)>,
    /// Whether this is the first render pass (for computing baselines).
    pub first_pass: bool,
}

// ── LegendGlyph ──────────────────────────────────────────────────────────────────────────────────

/// Visual sample drawn next to a legend entry's label.
///
/// Each [`Mark`] reports the glyph that best represents its appearance via
/// [`Mark::legend_glyph`]. The legend renderer dispatches per variant so
/// [`PointMark`] entries show a filled disk rather than a horizontal line,
/// [`BarMark`] / [`HistogramMark`] entries show a filled rectangle, and
/// [`AreaMark`] entries show a translucent fill — matching what the mark
/// actually draws on the chart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LegendGlyph {
    /// Horizontal stroke. Default for line-shaped marks ([`LineMark`], [`StepMark`]).
    Line,
    /// Filled disk. Used by [`PointMark`].
    Point,
    /// Filled rectangle. Used by [`BarMark`] and [`HistogramMark`].
    Bar,
    /// Filled rectangle with a top stroke. Used by [`AreaMark`].
    Area,
}

// ── Mark ─────────────────────────────────────────────────────────────────────────────────────────

/// Object-safe trait every visual mark implements.
///
/// `render` draws the mark using `coord` to map data values to pixel space and
/// `backend` to issue draw calls. `data_extent` reports the mark's data range so
/// the figure can compute appropriate scales.
pub trait Mark {
    /// Render the mark via the given coordinate system and backend.
    ///
    /// `coord` is `&dyn Coord` so the same trait can dispatch to cartesian and
    /// polar marks. Cartesian marks use the crate-private `require_cartesian`
    /// helper to downcast at the top of their impl; polar marks downcast to
    /// their own coord type.
    ///
    /// # Errors
    /// Returns [`StarsightError`] if the coord type is unsupported by this mark
    /// or if the backend errors on a draw call.
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()>;
    /// Render with bar context for grouped/stacked bar rendering.
    ///
    /// Default implementation forwards to [`render`](Self::render); bar marks
    /// override this to handle group offsets and stacked baselines.
    ///
    /// # Errors
    /// Returns the backend's [`Result`] error if drawing the bar fails.
    #[allow(unused_variables)]
    fn render_bar(
        &self,
        coord: &dyn Coord,
        backend: &mut dyn DrawBackend,
        _context: &BarRenderContext,
    ) -> Result<()> {
        self.render(coord, backend)
    }
    /// Check if this is a bar mark with group/stack info.
    fn as_bar_info(&self) -> Option<(Option<&str>, Option<&str>, Orientation)> {
        None
    }
    /// Get bar data for stacking calculations. Returns (labels, values).
    fn as_bar_data(&self) -> Option<(&[String], &[f64])> {
        None
    }
    /// Bounding box of this mark's data, or `None` if it is empty.
    fn data_extent(&self) -> Option<DataExtent>;
    /// Pixel-space rendered footprint of this mark.
    ///
    /// Used by the legend dodge in layer-5 to find a corner that does not
    /// overlap any mark. The default impl projects [`Self::data_extent`]
    /// through `coord` and returns [`MarkExtent::Bbox`] — exact for marks
    /// whose footprint matches their data bbox (point, bar, heatmap, candle,
    /// pie, donut, rug). Marks where the bbox over-claims coverage
    /// ([`LineMark`] on diagonal data, [`AreaMark`] / contour bands that
    /// fill non-rectangular regions, polar marks whose footprint is annular)
    /// override this to a tighter [`MarkExtent`] variant.
    ///
    /// For non-cartesian coords (e.g. [`PolarCoord`]) the default falls back
    /// to `coord.plot_area()` because projecting only the `(x_min, y_min)` /
    /// `(x_max, y_max)` corners of a polar [`DataExtent`] does not bound the
    /// disk-space footprint. Polar marks should override.
    fn pixel_extent(&self, coord: &dyn Coord) -> MarkExtent {
        if let Some(ext) = self.data_extent()
            && coord.as_any().downcast_ref::<CartesianCoord>().is_some()
        {
            let p1 = coord.data_to_pixel(ext.x_min, ext.y_min);
            let p2 = coord.data_to_pixel(ext.x_max, ext.y_max);
            return MarkExtent::Bbox(Rect::new(
                p1.x.min(p2.x),
                p1.y.min(p2.y),
                p1.x.max(p2.x),
                p1.y.max(p2.y),
            ));
        }
        MarkExtent::Bbox(coord.plot_area())
    }
    /// Returns the color of this mark for legend display.
    fn legend_color(&self) -> Option<Color> {
        None
    }
    /// Returns a label for this mark in the legend.
    fn legend_label(&self) -> Option<&str> {
        None
    }
    /// Returns the glyph the legend should draw for this mark. The default of
    /// [`LegendGlyph::Line`] suits stroked-line marks; concrete marks override
    /// to surface a more honest sample (e.g. [`PointMark`] returns
    /// [`LegendGlyph::Point`], so a scatter legend shows a dot, not a dash).
    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Line
    }
    /// Whether the figure should draw numeric x/y axes around this mark. Most
    /// marks live on a Cartesian axis and want them; angular / decorative
    /// marks like [`PieMark`] override to `false` so the figure suppresses
    /// the axis chrome. The figure honours this only when *every* mark on it
    /// returns `false`; mixed charts keep the axes for the others.
    fn wants_axes(&self) -> bool {
        true
    }

    /// Whether a polar `Figure` should draw the radial-spoke + concentric-
    /// ring grid behind this mark. Quantitative polar marks (`PolarBarMark`
    /// wind roses, `RadarMark` spider charts, `PolarRectMark` polar heatmaps)
    /// keep the default `true` because the grid carries axis context;
    /// decorative wedge marks (`ArcMark` for gauge / nightingale / sunburst,
    /// `PieMark`, `DonutMark`) override to `false` so their wedges don't
    /// render against a distracting full-360 grid. The figure suppresses the
    /// polar grid only when *every* mark returns `false`. Cartesian figures
    /// ignore this method (they use [`Self::wants_axes`] instead). Fix for
    /// Epic L (`starsight-3bp.10.14`).
    fn wants_polar_grid(&self) -> bool {
        true
    }

    /// Whether a `Figure` carrying this mark should default to placing the
    /// legend OUTSIDE the plot area instead of corner-dodging inside.
    ///
    /// Disk-fill marks (`ArcMark`, `PieMark` / `DonutMark`, `RadarMark`,
    /// `PolarBarMark`, `PolarRectMark`) paint over the entire inscribed disk,
    /// so the corner dodge never finds a clear corner — the legend always
    /// overlaps a wedge or polygon edge. They override to `true` so the
    /// figure auto-resolves `LegendPosition::Auto` to
    /// `LegendPosition::Outside(Edge::Right)`, reserving a top-aligned strip
    /// outside the disk. Other marks keep the default `false` and dodge
    /// inside.
    ///
    /// Users override via `Figure::legend_position(...)`. Tracked as Epic L
    /// (`starsight-3bp.10` / L.17).
    fn prefers_outside_legend(&self) -> bool {
        false
    }

    /// Whether this mark needs the axis to inset 5% on both ends so its
    /// data extremes don't visually sit on the plot edge. Default `true`
    /// for point-like marks (`PointMark`, `LineMark`, `AreaMark`,
    /// `ErrorBarMark`, `BoxPlotMark`, `ViolinMark`, `CandlestickMark`,
    /// `StepMark`, `RugMark` — anything where a single value at the extreme
    /// would otherwise touch the axis line).
    ///
    /// Bar-shaped marks (`BarMark`, `HistogramMark`, `HeatmapMark`,
    /// `ContourMark`) override to `false` because their data IS the axis
    /// structure — bars naturally span band edges, heatmap cells tile to
    /// the plot rect, contour bands fill explicit level boundaries.
    ///
    /// `Figure::render_within` aggregates this with `any()` across marks:
    /// the figure pads only when at least one mark wants padding.
    fn wants_axis_padding(&self) -> bool {
        true
    }

    /// Optional colormap legend description for this mark, used by the
    /// figure to auto-attach a colorbar (the layer-5 chrome component).
    /// Marks that map a continuous value range through a colormap
    /// (`HeatmapMark`, `ContourMark` with a colormap) override this to
    /// expose `(colormap, value_min, value_max, label?, log?)`. Other marks
    /// return `None` (the default), so they don't trigger auto-attach.
    fn colormap_legend(&self) -> Option<ColormapLegend> {
        None
    }

    /// Multi-entry legend list for marks that carry one slice / wedge /
    /// bar per category (`PieMark`, `ArcMark` for sunburst). Default
    /// derives a single entry from `legend_color` + `legend_label` +
    /// `legend_glyph` so existing single-color marks (Line, Point, Bar,
    /// etc.) keep working unchanged.
    ///
    /// When this returns multiple entries, the figure renders one legend
    /// row per entry — color swatch + label — so a pie/sunburst gets a
    /// proper "color → category" key off to the side.
    fn legend_entries(&self) -> Vec<(Color, String, LegendGlyph)> {
        if let (Some(c), Some(l)) = (self.legend_color(), self.legend_label())
            && !l.is_empty()
        {
            vec![(c, l.to_string(), self.legend_glyph())]
        } else {
            Vec::new()
        }
    }
}

// ── ColormapLegend ───────────────────────────────────────────────────────────────────────────────

/// Information a mark exposes when it wants the figure to render a
/// colorbar/scale-to-colormap legend on its behalf.
///
/// Returned by [`Mark::colormap_legend`]. Layer-5 inspects every mark on
/// the figure; when at least one returns `Some` and the figure has not
/// opted out via `Figure::colorbar(false)`, a vertical colorbar strip is
/// attached on the right side of the plot area.
#[derive(Clone, Debug)]
pub struct ColormapLegend {
    /// Colormap used to render the mark's continuous value field.
    pub colormap: starsight_layer_1::colormap::Colormap,
    /// Lowest value the mark renders.
    pub value_min: f64,
    /// Highest value the mark renders.
    pub value_max: f64,
    /// Legend label (often the same as the mark's `label`). When `None`,
    /// the colorbar reads as a bare value scale.
    pub label: Option<String>,
    /// Hint that the value range is log-distributed; the colorbar will
    /// place ticks accordingly.
    pub log_scale: bool,
}

// ── LineMark ─────────────────────────────────────────────────────────────────────────────────────

/// Connected line series with optional NaN gaps.
#[derive(Debug, Clone)]
pub struct LineMark {
    /// X data values.
    pub x: Vec<f64>,
    /// Y data values (must be the same length as `x`).
    pub y: Vec<f64>,
    /// Line color.
    pub color: Color,
    /// Stroke width in pixels.
    pub width: f32,
    /// Legend label.
    pub label: Option<String>,
}

impl LineMark {
    /// New line series from x and y data with default color and width.
    #[must_use]
    pub fn new(x: Vec<f64>, y: Vec<f64>) -> Self {
        Self {
            x,
            y,
            color: Color::BLUE,
            width: 2.0,
            label: None,
        }
    }

    /// Builder: set line color.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.color = c;
        self
    }

    /// Builder: set legend label.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Builder: set stroke width in pixels.
    #[must_use]
    pub fn width(mut self, w: f32) -> Self {
        self.width = w;
        self
    }
}

impl Mark for LineMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        let mut commands = Vec::new();
        let mut need_move = true;

        for (x, y) in self.x.iter().zip(&self.y) {
            if x.is_nan() || y.is_nan() {
                need_move = true;
                continue;
            }
            let p = coord.data_to_pixel(*x, *y);
            if need_move {
                commands.push(PathCommand::MoveTo(p));
                need_move = false;
            } else {
                commands.push(PathCommand::LineTo(p));
            }
        }

        if commands.is_empty() {
            return Ok(());
        }

        let path = Path { commands };
        let style = PathStyle {
            stroke_color: self.color,
            stroke_width: self.width,
            fill_color: None,
            line_cap: LineCap::Round,
            line_join: LineJoin::Round,
            ..PathStyle::default()
        };
        backend.draw_path(&path, &style)
    }

    fn data_extent(&self) -> Option<DataExtent> {
        extent_from_xy(&self.x, &self.y)
    }

    fn pixel_extent(&self, coord: &dyn Coord) -> MarkExtent {
        let Some(cart) = coord.as_any().downcast_ref::<CartesianCoord>() else {
            return MarkExtent::Bbox(coord.plot_area());
        };
        let mut segments = Vec::with_capacity(self.x.len().saturating_sub(1));
        let mut prev: Option<Point> = None;
        for (xv, yv) in self.x.iter().zip(&self.y) {
            if xv.is_nan() || yv.is_nan() {
                prev = None;
                continue;
            }
            let p = cart.data_to_pixel(*xv, *yv);
            if let Some(prev_p) = prev {
                segments.push((prev_p, p));
            }
            prev = Some(p);
        }
        if segments.is_empty() {
            MarkExtent::Bbox(cart.plot_area)
        } else {
            MarkExtent::Segments(segments)
        }
    }

    fn legend_color(&self) -> Option<Color> {
        Some(self.color)
    }

    fn legend_label(&self) -> Option<&str> {
        self.label.as_deref()
    }
}

// ── PointMark ────────────────────────────────────────────────────────────────────────────────────

/// Scatter plot of individual points.
///
/// `colors` and `radii` are parallel to `x`/`y` and follow the same broadcast rule:
/// `None` → default; `Some(vec)` of length 1 → broadcast; length matching the data
/// → per-point. Length-mismatched vectors fall through to defaults rather than panic.
#[derive(Debug, Clone)]
pub struct PointMark {
    /// X data values.
    pub x: Vec<f64>,
    /// Y data values (must be the same length as `x`).
    pub y: Vec<f64>,
    /// Per-point fill colors. See broadcast rule on the struct doc.
    pub colors: Option<Vec<Color>>,
    /// Per-point radii in pixels. See broadcast rule on the struct doc.
    pub radii: Option<Vec<f32>>,
    /// Legend label.
    pub label: Option<String>,
    /// Mark-wide alpha multiplier in `[0, 1]`. Applied uniformly to every point
    /// at draw time via the path's opacity attribute. Default 1.0.
    pub alpha: f32,
}

impl PointMark {
    /// New scatter from x and y data with default color and radius.
    #[must_use]
    pub fn new(x: Vec<f64>, y: Vec<f64>) -> Self {
        Self {
            x,
            y,
            colors: Some(vec![Color::BLUE]),
            radii: Some(vec![4.0]),
            label: None,
            alpha: 1.0,
        }
    }

    /// Builder: broadcast a single color to every point.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.colors = Some(vec![c]);
        self
    }

    /// Builder: set per-point colors. Length 1 broadcasts; length matching data
    /// gives per-point colors. Used by bubble scatters where each point's color
    /// encodes a continuous variable through a colormap.
    #[must_use]
    pub fn colors(mut self, cs: Vec<Color>) -> Self {
        self.colors = Some(cs);
        self
    }

    /// Builder: broadcast a single radius (pixels) to every point.
    #[must_use]
    pub fn radius(mut self, r: f32) -> Self {
        self.radii = Some(vec![r]);
        self
    }

    /// Builder: set per-point radii (pixels). Length 1 broadcasts; length matching
    /// data gives per-point sizes. Used by bubble scatters.
    #[must_use]
    pub fn radii(mut self, rs: Vec<f32>) -> Self {
        self.radii = Some(rs);
        self
    }

    /// Builder: set the mark-wide alpha multiplier (clamped to `[0, 1]`).
    #[must_use]
    pub fn alpha(mut self, a: f32) -> Self {
        self.alpha = a.clamp(0.0, 1.0);
        self
    }

    /// Builder: set legend label.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Per-point color lookup. Same broadcast rule as `BarMark` — `None`/mismatched
    /// fall back to BLUE; length 1 broadcasts; length matching data is per-point.
    fn color_at(&self, i: usize) -> Color {
        match self.colors.as_deref() {
            None => Color::BLUE,
            Some([c]) => *c,
            Some(cs) if cs.len() == self.x.len() => cs[i],
            Some(cs) => cs.first().copied().unwrap_or(Color::BLUE),
        }
    }

    /// Per-point radius lookup. Default 4.0 px when unset/mismatched.
    fn radius_at(&self, i: usize) -> f32 {
        match self.radii.as_deref() {
            None => 4.0,
            Some([r]) => *r,
            Some(rs) if rs.len() == self.x.len() => rs[i],
            Some(rs) => rs.first().copied().unwrap_or(4.0),
        }
    }
}

impl Mark for PointMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        // Per-point colors/radii mean we can't share a single Path across all
        // points the way the original implementation did. Group consecutive points
        // by (color, radius) so each unique combination still maps to one draw_path
        // call — common bubble-scatter cases (a few size buckets) emit at most a
        // dozen draws, single-color/single-radius cases collapse back to one draw.
        let mut current_key: Option<(Color, u32)> = None;
        let mut commands: Vec<PathCommand> = Vec::new();

        let flush = |backend: &mut dyn DrawBackend,
                     commands: &mut Vec<PathCommand>,
                     key: Option<(Color, u32)>,
                     alpha: f32|
         -> Result<()> {
            if commands.is_empty() {
                return Ok(());
            }
            if let Some((color, _)) = key {
                let path = Path {
                    commands: std::mem::take(commands),
                };
                let style = PathStyle {
                    stroke_color: color,
                    stroke_width: 0.0,
                    fill_color: Some(color),
                    opacity: alpha,
                    ..PathStyle::default()
                };
                backend.draw_path(&path, &style)?;
            }
            Ok(())
        };

        for (i, (x, y)) in self.x.iter().zip(&self.y).enumerate() {
            if x.is_nan() || y.is_nan() {
                continue;
            }
            let color = self.color_at(i);
            let radius = self.radius_at(i);
            // Bucket by radius via its bit representation so f32 NaN is not a key
            // (already filtered above) and equal radii hash equal.
            let key = (color, radius.to_bits());
            if current_key != Some(key) {
                flush(backend, &mut commands, current_key, self.alpha)?;
                current_key = Some(key);
            }
            let center = coord.data_to_pixel(*x, *y);
            push_circle(&mut commands, center, radius);
        }
        flush(backend, &mut commands, current_key, self.alpha)?;

        Ok(())
    }

    fn data_extent(&self) -> Option<DataExtent> {
        extent_from_xy(&self.x, &self.y)
    }

    fn legend_color(&self) -> Option<Color> {
        Some(
            self.colors
                .as_deref()
                .and_then(|cs| cs.first().copied())
                .unwrap_or(Color::BLUE),
        )
    }

    fn legend_label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Point
    }
}

// ── BarMark ──────────────────────────────────────────────────────────────────────────────────────
/// Bar chart for individual values.
///
/// `colors` and `bases` are parallel arrays to `y`. They follow the same broadcast
/// rule everywhere they're used:
///
/// - `None` → use the default for every bar (blue / 0.0).
/// - `Some(vec)` with `len == 1` → broadcast the single value across all bars.
/// - `Some(vec)` with `len == y.len()` → per-bar value at index `i`.
/// - Anything else → falls through to the default; render is robust, no panic.
#[derive(Debug, Clone)]
pub struct BarMark {
    /// X category labels.
    pub x: Vec<String>,
    /// Y data height (the value rendered as the bar's extent above its base).
    pub y: Vec<f64>,
    /// Per-bar fill colors (see broadcast rules on the struct doc).
    pub colors: Option<Vec<Color>>,
    /// Define the width of each bar as a fraction of the band.
    pub width: Option<f32>,
    /// Set bar origin axis.
    pub orientation: Orientation,
    /// Group name for grouped bars (dodged within band).
    pub group: Option<String>,
    /// Stack name for stacked bars (accumulated baseline).
    pub stack: Option<String>,
    /// Per-bar base values (see broadcast rules on the struct doc). When unset, all
    /// bars start at 0; when set, each bar floats at its own base — used by waterfall
    /// charts where bar `i` sits on the running total of bars `0..i`.
    pub bases: Option<Vec<f64>>,
    /// Legend label.
    pub label: Option<String>,
    /// Draw thin gray connector lines between consecutive bars at `bases[i] + y[i]`.
    /// Only honored for `Orientation::Vertical`. Used by waterfall charts.
    pub connectors: bool,
}
/// Bar/box mark orientation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Orientation {
    /// Bars rise vertically along the y-axis (categories on x).
    #[default]
    Vertical,
    /// Bars extend horizontally along the x-axis (categories on y).
    Horizontal,
}
impl BarMark {
    /// New bar chart from x and y data with default color and bar width.
    #[must_use]
    pub fn new(x: Vec<String>, y: Vec<f64>) -> Self {
        Self {
            x,
            y,
            colors: Some(vec![Color::BLUE]),
            width: Some(0.8),
            orientation: Orientation::Vertical,
            group: None,
            stack: None,
            bases: None,
            label: None,
            connectors: false,
        }
    }

    /// Builder: switch the bars to a horizontal orientation.
    #[must_use]
    pub fn horizontal(mut self) -> Self {
        self.orientation = Orientation::Horizontal;
        self
    }

    /// Builder: set group name for grouped bars (bars are dodged within each band).
    #[must_use]
    pub fn group(mut self, name: impl Into<String>) -> Self {
        self.group = Some(name.into());
        self
    }

    /// Builder: set stack name for stacked bars (bars are accumulated).
    #[must_use]
    pub fn stack(mut self, name: impl Into<String>) -> Self {
        self.stack = Some(name.into());
        self
    }

    /// Builder: broadcast a single base value to every bar (where bars start).
    #[must_use]
    pub fn base(mut self, b: f64) -> Self {
        self.bases = Some(vec![b]);
        self
    }

    /// Builder: set per-bar base values (length should match `y` for per-bar bases;
    /// length 1 broadcasts). Used by waterfall charts.
    #[must_use]
    pub fn bases(mut self, bs: Vec<f64>) -> Self {
        self.bases = Some(bs);
        self
    }

    /// Builder: broadcast a single color to every bar.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.colors = Some(vec![c]);
        self
    }

    /// Builder: set per-bar colors (length should match `y` for per-bar colors;
    /// length 1 broadcasts). Used by waterfall charts and any other chart where
    /// individual bars carry semantic color (e.g. above/below threshold).
    #[must_use]
    pub fn colors(mut self, cs: Vec<Color>) -> Self {
        self.colors = Some(cs);
        self
    }

    /// Builder: set bar width as a fraction of the band (0.0..1.0).
    #[must_use]
    pub fn width(mut self, r: f32) -> Self {
        self.width = Some(r);
        self
    }

    /// Builder: set legend label.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Builder: enable thin gray connector lines between consecutive bars (at
    /// `bases[i] + y[i]`). Only honored for vertical orientation. Used by waterfalls.
    #[must_use]
    pub fn connectors(mut self, on: bool) -> Self {
        self.connectors = on;
        self
    }

    /// Per-bar color lookup: `colors[i]` if set and lengths align, else broadcast
    /// the first element, else fall back to BLUE. Robust against length mismatches.
    fn color_at(&self, i: usize) -> Color {
        match self.colors.as_deref() {
            None => Color::BLUE,
            Some([c]) => *c,
            Some(cs) if cs.len() == self.y.len() => cs[i],
            // length mismatch (and not 1) — fall back rather than panic
            Some(cs) => cs.first().copied().unwrap_or(Color::BLUE),
        }
    }

    /// Per-bar base lookup with the same broadcast rules as colors. 0.0 default.
    fn base_at(&self, i: usize) -> f64 {
        match self.bases.as_deref() {
            None => 0.0,
            Some([b]) => *b,
            Some(bs) if bs.len() == self.y.len() => bs[i],
            Some(bs) => bs.first().copied().unwrap_or(0.0),
        }
    }
}
impl Mark for BarMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        // Keep the original index alongside each valid bar so per-bar bases/colors
        // line up with self.y even when some entries are filtered out as NaN/empty.
        let valid: Vec<(usize, &str, f64)> = self
            .x
            .iter()
            .zip(&self.y)
            .enumerate()
            .filter(|(_, (x, y))| !x.is_empty() && !y.is_nan())
            .map(|(i, (x, y))| (i, x.as_str(), *y))
            .collect();

        let n = valid.len();
        if n == 0 {
            return Ok(());
        }

        let area = coord.plot_area;
        let width_fraction = self.width.unwrap_or(0.8);

        match self.orientation {
            Orientation::Vertical => {
                // Route bar band-center positions through `scale.map(i + 0.5)`
                // so bar centers stay aligned with the grid line midpoints
                // (`Axis::category` uses LinearScale with domain 0..n; the
                // `+ 0.5` puts the center on the band middle). Math stays in
                // f64 until the single cast to pixel space — fixes the
                // 1–2 px drift visible at the bollinger 90-bar volume panel
                // where two f32 chains diverged by one ULP per step.
                let band_width = area.width() / n as f32;
                let bar_width = band_width * width_fraction;
                let n_f64 = n as f64;

                for (i, (orig_i, _label, value)) in valid.iter().enumerate() {
                    let x_center = area.left + ((i as f64 + 0.5) / n_f64) as f32 * area.width();
                    let x_left = x_center - bar_width / 2.0;
                    let x_right = x_center + bar_width / 2.0;

                    let base = self.base_at(*orig_i);
                    let y_top =
                        area.bottom - coord.y_axis.scale.map(base + *value) as f32 * area.height();
                    let y_bottom =
                        area.bottom - coord.y_axis.scale.map(base) as f32 * area.height();
                    let rect_top = y_top.min(y_bottom);
                    let rect_bottom = y_top.max(y_bottom);

                    let rect = Rect::new(x_left, rect_top, x_right, rect_bottom);
                    backend.fill_rect(rect, self.color_at(*orig_i))?;
                }
            }
            Orientation::Horizontal => {
                let band_height = area.height() / n as f32;
                let bar_height = band_height * width_fraction;
                let n_f64 = n as f64;

                for (i, (orig_i, _label, value)) in valid.iter().enumerate() {
                    let y_center = area.top + ((i as f64 + 0.5) / n_f64) as f32 * area.height();
                    let y_top = y_center - bar_height / 2.0;
                    let y_bottom = y_center + bar_height / 2.0;

                    let base = self.base_at(*orig_i);
                    let x_left = area.left + coord.x_axis.scale.map(base) as f32 * area.width();
                    let x_right =
                        area.left + coord.x_axis.scale.map(base + *value) as f32 * area.width();
                    let rect_left = x_left.min(x_right);
                    let rect_right = x_left.max(x_right);

                    let rect = Rect::new(rect_left, y_top, rect_right, y_bottom);
                    backend.fill_rect(rect, self.color_at(*orig_i))?;
                }
            }
        }

        Ok(())
    }

    // Bar rendering is symmetric between vertical and horizontal orientations;
    // splitting helpers here would duplicate ~30 lines of parameter setup.
    #[allow(clippy::too_many_lines)]
    fn render_bar(
        &self,
        coord: &dyn Coord,
        backend: &mut dyn DrawBackend,
        context: &BarRenderContext,
    ) -> Result<()> {
        let coord = require_cartesian(coord)?;
        let valid: Vec<(usize, &str, f64)> = self
            .x
            .iter()
            .zip(&self.y)
            .enumerate()
            .filter(|(_, (x, y))| !x.is_empty() && !y.is_nan())
            .map(|(i, (x, y))| (i, x.as_str(), *y))
            .collect();

        let n = valid.len();
        if n == 0 {
            return Ok(());
        }

        let area = coord.plot_area;
        let width_fraction = self.width.unwrap_or(0.8);

        // Connector geometry: collected during the bar pass for vertical orientation
        // when self.connectors is on. Each entry is (x_left, x_right, y_running_total_pixel).
        let mut connector_geom: Vec<(f32, f32, f32)> = if self.connectors {
            Vec::with_capacity(n)
        } else {
            Vec::new()
        };

        match self.orientation {
            Orientation::Vertical => {
                let band_width = area.width() / n as f32;
                let total_groups = context
                    .group_offsets
                    .values()
                    .map(|(_, t)| *t)
                    .max()
                    .unwrap_or(1);
                let group_gap = 0.15;
                let bar_width = if total_groups > 1 {
                    band_width * width_fraction * (1.0 - group_gap) / total_groups as f32
                } else {
                    band_width * width_fraction
                };

                let n_f64 = n as f64;
                for (i, (orig_i, label, value)) in valid.iter().enumerate() {
                    // Same f64-mediated band-center math as the simple
                    // BarMark::render path above.
                    let base_x_center =
                        area.left + ((i as f64 + 0.5) / n_f64) as f32 * area.width();
                    let x_offset = if let Some(group_name) = &self.group {
                        if let Some(&(idx, total)) = context.group_offsets.get(group_name) {
                            let sub_band = band_width * (1.0 - group_gap) / total as f32;
                            (idx as f32 - (total - 1) as f32 / 2.0) * sub_band
                        } else {
                            0.0
                        }
                    } else {
                        0.0
                    };
                    let x_center = base_x_center + x_offset;
                    let x_left = x_center - bar_width / 2.0;
                    let x_right = x_center + bar_width / 2.0;

                    // Stacked > per-bar base > 0.0. Stacked bars float at the running
                    // height for that category; per-bar bases let waterfalls sit at
                    // their running totals.
                    let (y_bottom_val, y_top_val) = if self.stack.is_some() {
                        let baseline = *context.stacked_baselines.get(*label).unwrap_or(&0.0);
                        (baseline, baseline + value)
                    } else {
                        let base = self.base_at(*orig_i);
                        (base, base + value)
                    };

                    let y_top =
                        area.bottom - coord.y_axis.scale.map(y_top_val) as f32 * area.height();
                    let y_bottom =
                        area.bottom - coord.y_axis.scale.map(y_bottom_val) as f32 * area.height();

                    let rect_top = y_top.min(y_bottom);
                    let rect_bottom = y_top.max(y_bottom);

                    let rect = Rect::new(x_left, rect_top, x_right, rect_bottom);
                    backend.fill_rect(rect, self.color_at(*orig_i))?;

                    if self.connectors {
                        // y_top is the pixel-y of (base + value), the running total —
                        // exactly where the connector to the next bar should sit.
                        connector_geom.push((x_left, x_right, y_top));
                    }
                }

                // Connector pass: thin gray segments from bar i's right edge to bar
                // i+1's left edge, both at bar i's running-total y. Vertical only.
                if self.connectors && connector_geom.len() >= 2 {
                    let connector_color = Color::new(0x88, 0x88, 0x88);
                    let style = PathStyle {
                        stroke_color: connector_color,
                        stroke_width: 1.0,
                        fill_color: None,
                        ..PathStyle::default()
                    };
                    for pair in connector_geom.windows(2) {
                        let (_, x_right_i, y_running) = pair[0];
                        let (x_left_next, _, _) = pair[1];
                        let path = Path {
                            commands: vec![
                                PathCommand::MoveTo(Point::new(x_right_i, y_running)),
                                PathCommand::LineTo(Point::new(x_left_next, y_running)),
                            ],
                        };
                        backend.draw_path(&path, &style)?;
                    }
                }
            }
            Orientation::Horizontal => {
                let band_height = area.height() / n as f32;
                let total_groups = context
                    .group_offsets
                    .values()
                    .map(|(_, t)| *t)
                    .max()
                    .unwrap_or(1);
                let group_gap = 0.15;
                let bar_height = if total_groups > 1 {
                    band_height * width_fraction * (1.0 - group_gap) / total_groups as f32
                } else {
                    band_height * width_fraction
                };

                let n_f64 = n as f64;
                for (i, (orig_i, label, value)) in valid.iter().enumerate() {
                    // Same f64-mediated band-center math as the simple
                    // BarMark::render path above.
                    let base_y_center =
                        area.top + ((i as f64 + 0.5) / n_f64) as f32 * area.height();
                    let y_offset = if let Some(group_name) = &self.group {
                        if let Some(&(idx, total)) = context.group_offsets.get(group_name) {
                            let sub_band = band_height * (1.0 - group_gap) / total as f32;
                            (idx as f32 - (total - 1) as f32 / 2.0) * sub_band
                        } else {
                            0.0
                        }
                    } else {
                        0.0
                    };
                    let y_center = base_y_center + y_offset;
                    let y_top = y_center - bar_height / 2.0;
                    let y_bottom = y_center + bar_height / 2.0;

                    let (x_left_val, x_right_val) = if self.stack.is_some() {
                        let baseline = *context.stacked_baselines.get(*label).unwrap_or(&0.0);
                        (baseline, baseline + value)
                    } else {
                        let base = self.base_at(*orig_i);
                        (base, base + value)
                    };
                    let x_left =
                        area.left + coord.x_axis.scale.map(x_left_val) as f32 * area.width();
                    let x_right =
                        area.left + coord.x_axis.scale.map(x_right_val) as f32 * area.width();
                    let rect_left = x_left.min(x_right);
                    let rect_right = x_left.max(x_right);

                    let rect = Rect::new(rect_left, y_top, rect_right, y_bottom);
                    backend.fill_rect(rect, self.color_at(*orig_i))?;
                }
                // Horizontal connectors are out of scope at 0.3.0 — would need a
                // second pass keyed on x rather than y. Spec only calls for vertical.
            }
        }

        Ok(())
    }

    fn as_bar_info(&self) -> Option<(Option<&str>, Option<&str>, Orientation)> {
        Some((
            self.group.as_deref(),
            self.stack.as_deref(),
            self.orientation,
        ))
    }

    fn as_bar_data(&self) -> Option<(&[String], &[f64])> {
        Some((&self.x, &self.y))
    }

    fn data_extent(&self) -> Option<DataExtent> {
        let valid_y: Vec<f64> = self.y.iter().copied().filter(|v| !v.is_nan()).collect();
        if valid_y.is_empty() {
            return None;
        }
        let v_min = valid_y
            .iter()
            .copied()
            .fold(f64::INFINITY, f64::min)
            .min(0.0);
        let v_max = valid_y
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
            .max(0.0);
        let n = self.x.len() as f64;
        // Orientation determines which axis carries values vs categories. Reporting
        // category count as x for horizontal bars caused Wilkinson tick selection
        // to extend the value range way past actual data, so bars only filled ~70%
        // of the plot area.
        Some(match self.orientation {
            Orientation::Vertical => DataExtent {
                x_min: 0.0,
                x_max: n,
                y_min: v_min,
                y_max: v_max,
            },
            Orientation::Horizontal => DataExtent {
                x_min: v_min,
                x_max: v_max,
                y_min: 0.0,
                y_max: n,
            },
        })
    }

    fn legend_color(&self) -> Option<Color> {
        // Broadcast first color (or BLUE fallback). We always return Some so that
        // bar marks reliably render a legend swatch even when colors aren't set.
        Some(
            self.colors
                .as_deref()
                .and_then(|cs| cs.first().copied())
                .unwrap_or(Color::BLUE),
        )
    }

    fn legend_label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Bar
    }

    fn wants_axis_padding(&self) -> bool {
        // Bars span band edges by design — their data IS the axis structure,
        // so 5% inset would just push bars away from the axis line and
        // create awkward gaps.
        false
    }
}

// ── AreaMark ─────────────────────────────────────────────────────────────────────────────────────
/// Area chart for stacked values
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct AreaMark {
    /// X data values.
    x: Vec<f64>,
    /// Y data values (must be the same length as `x`)
    y: Vec<f64>,
    baseline: AreaBaseline,
    /// Area fill color
    fill: Color,
    /// Area opacity, 1 to 0
    opacity: f32,
}
/// Where the area mark's lower edge sits.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum AreaBaseline {
    /// Fill between the data and y = 0.
    #[default]
    Zero,
    /// Fill between the data and a fixed y value.
    Fixed(f64),
}
impl AreaMark {
    /// New area chart from x and y data with default color and full opacity.
    #[must_use]
    pub fn new(x: Vec<f64>, y: Vec<f64>) -> Self {
        Self {
            x,
            y,
            baseline: AreaBaseline::Zero,
            fill: Color::RED,
            opacity: 1.,
        }
    }

    /// Builder: set area color.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.fill = c;
        self
    }

    /// Builder: set area opacity 1 to 0.
    #[must_use]
    pub fn opacity(mut self, o: f32) -> Self {
        self.opacity = o;
        self
    }

    /// Builder: set baseline for area fill (default is Zero, i.e., y=0).
    #[must_use]
    pub fn baseline(mut self, b: f64) -> Self {
        self.baseline = AreaBaseline::Fixed(b);
        self
    }
}

fn render_segment(
    coord: &CartesianCoord,
    backend: &mut dyn DrawBackend,
    points: &[(f64, f64)],
    baseline_y: f64,
    fill: Color,
    opacity: f32,
) -> Result<()> {
    let mut commands = Vec::new();

    if let Some((first_x, first_y)) = points.first() {
        commands.push(PathCommand::MoveTo(coord.data_to_pixel(*first_x, *first_y)));
    }

    for (x, y) in points.iter().skip(1) {
        commands.push(PathCommand::LineTo(coord.data_to_pixel(*x, *y)));
    }

    if let Some((last_x, _)) = points.last() {
        commands.push(PathCommand::LineTo(
            coord.data_to_pixel(*last_x, baseline_y),
        ));
    }
    if let Some((first_x, _)) = points.first() {
        commands.push(PathCommand::LineTo(
            coord.data_to_pixel(*first_x, baseline_y),
        ));
    }
    commands.push(PathCommand::Close);

    let path = Path { commands };
    let style = PathStyle {
        fill_color: Some(fill),
        opacity,
        ..PathStyle::default()
    };
    backend.draw_path(&path, &style)
}

impl Mark for AreaMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        let baseline_y = match self.baseline {
            AreaBaseline::Zero => 0.0,
            AreaBaseline::Fixed(y) => y,
        };

        let n = self.x.len().min(self.y.len());
        let mut segment_start: Option<usize> = None;
        let mut segment_points: Vec<(f64, f64)> = Vec::new();

        for i in 0..n {
            let xi = self.x[i];
            let yi = self.y[i];

            if xi.is_nan() || yi.is_nan() {
                if let Some(_start) = segment_start {
                    if segment_points.len() >= 2 {
                        render_segment(
                            coord,
                            backend,
                            &segment_points,
                            baseline_y,
                            self.fill,
                            self.opacity,
                        )?;
                    }
                    segment_points.clear();
                    segment_start = None;
                }
                continue;
            }

            if segment_start.is_none() {
                segment_start = Some(i);
            }
            segment_points.push((xi, yi));
        }

        if segment_start.is_some() && segment_points.len() >= 2 {
            render_segment(
                coord,
                backend,
                &segment_points,
                baseline_y,
                self.fill,
                self.opacity,
            )?;
        }

        Ok(())
    }

    fn data_extent(&self) -> Option<DataExtent> {
        let baseline_y = match self.baseline {
            AreaBaseline::Zero => 0.0,
            AreaBaseline::Fixed(y) => y,
        };
        let y_min = self
            .y
            .iter()
            .copied()
            .fold(f64::INFINITY, f64::min)
            .min(baseline_y);
        let y_max = self
            .y
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
            .max(baseline_y);
        Some(DataExtent {
            x_min: self.x.iter().copied().fold(f64::INFINITY, f64::min),
            x_max: self.x.iter().copied().fold(f64::NEG_INFINITY, f64::max),
            y_min,
            y_max,
        })
    }

    fn pixel_extent(&self, coord: &dyn Coord) -> MarkExtent {
        let Some(cart) = coord.as_any().downcast_ref::<CartesianCoord>() else {
            return MarkExtent::Bbox(coord.plot_area());
        };
        let baseline_y = match self.baseline {
            AreaBaseline::Zero => 0.0,
            AreaBaseline::Fixed(y) => y,
        };
        // Match render_segment's polygon shape: data points top, then back
        // along the baseline. NaN gaps split into separate polygons.
        let mut polygons: Vec<Vec<Point>> = Vec::new();
        let mut current: Vec<Point> = Vec::new();
        let mut current_first_x: Option<f64> = None;
        let mut current_last_x: Option<f64> = None;
        let n = self.x.len().min(self.y.len());
        for i in 0..n {
            let xi = self.x[i];
            let yi = self.y[i];
            if xi.is_nan() || yi.is_nan() {
                if current.len() >= 2
                    && let (Some(fx), Some(lx)) = (current_first_x, current_last_x)
                {
                    current.push(cart.data_to_pixel(lx, baseline_y));
                    current.push(cart.data_to_pixel(fx, baseline_y));
                    polygons.push(std::mem::take(&mut current));
                }
                current.clear();
                current_first_x = None;
                current_last_x = None;
                continue;
            }
            if current.is_empty() {
                current_first_x = Some(xi);
            }
            current.push(cart.data_to_pixel(xi, yi));
            current_last_x = Some(xi);
        }
        if current.len() >= 2
            && let (Some(fx), Some(lx)) = (current_first_x, current_last_x)
        {
            current.push(cart.data_to_pixel(lx, baseline_y));
            current.push(cart.data_to_pixel(fx, baseline_y));
            polygons.push(current);
        }
        if polygons.is_empty() {
            MarkExtent::Bbox(cart.plot_area)
        } else {
            MarkExtent::Polygons(polygons)
        }
    }

    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Area
    }
}

// ── HeatmapMark ──────────────────────────────────────────────────────────────────────────────────

use starsight_layer_1::colormap::Colormap;

/// How heatmap cell values map to the `[0, 1]` colormap input.
///
/// The default `Linear` is what most heatmaps want (`(v - vmin) / (vmax - vmin)`).
/// `Log` applies `log10` to value and bounds with a small epsilon, useful when the
/// data spans several decades — without it, the brightest cells saturate the
/// colormap and dim cells collapse into the floor color.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum HeatmapColorScale {
    /// Linear: `t = (v - vmin) / (vmax - vmin)`.
    #[default]
    Linear,
    /// Log10: `t = (log10(v') - log10(vmin')) / (log10(vmax') - log10(vmin'))`,
    /// where `v' = max(v, eps)` to keep `log10` finite. Negative cells clip to `eps`.
    Log,
}

/// Heatmap: a 2D grid of values mapped to colors via a colormap.
#[derive(Debug, Clone)]
pub struct HeatmapMark {
    /// 2D grid of values (row = y, col = x).
    pub data: Vec<Vec<f64>>,
    /// Colormap for mapping values to colors.
    pub colormap: Colormap,
    /// How values map to the `[0, 1]` colormap input. Default linear.
    pub color_scale: HeatmapColorScale,
    /// Optional label for legend.
    pub label: Option<String>,
}

impl HeatmapMark {
    /// Create a new heatmap from a 2D grid of values.
    #[must_use]
    pub fn new(data: Vec<Vec<f64>>) -> Self {
        Self {
            data,
            colormap: Colormap::default(),
            color_scale: HeatmapColorScale::Linear,
            label: None,
        }
    }

    /// Set the colormap for mapping values to colors.
    #[must_use]
    pub fn colormap(mut self, colormap: Colormap) -> Self {
        self.colormap = colormap;
        self
    }

    /// Set the value-to-`[0, 1]` mapping mode (linear or log).
    #[must_use]
    pub fn color_scale(mut self, scale: HeatmapColorScale) -> Self {
        self.color_scale = scale;
        self
    }

    /// Convenience: switch to log-scale color mapping.
    #[must_use]
    pub fn log_scale(self) -> Self {
        self.color_scale(HeatmapColorScale::Log)
    }

    /// Set the legend label.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    fn value_range(&self) -> (f64, f64) {
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for row in &self.data {
            for &v in row {
                if !v.is_nan() {
                    min = min.min(v);
                    max = max.max(v);
                }
            }
        }
        (min, max)
    }
}

impl Mark for HeatmapMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        if self.data.is_empty() || self.data[0].is_empty() {
            return Ok(());
        }

        let (data_min, data_max) = self.value_range();
        let range = if (data_max - data_min).abs() < f64::EPSILON {
            1.0
        } else {
            data_max - data_min
        };

        // Log-scale prep: pre-compute the log10 bounds and a small epsilon to keep
        // log10 finite when data hits zero or goes negative. eps scales with vmax so
        // the floor is a few decades below the top regardless of the data's units.
        let (log_min, log_range, log_eps) = match self.color_scale {
            HeatmapColorScale::Log => {
                let eps = (data_max.abs() * 1e-12).max(f64::MIN_POSITIVE);
                let lmin = data_min.max(eps).log10();
                let lmax = data_max.max(eps).log10();
                let lrange = if (lmax - lmin).abs() < f64::EPSILON {
                    1.0
                } else {
                    lmax - lmin
                };
                (lmin, lrange, eps)
            }
            HeatmapColorScale::Linear => (0.0, 1.0, 0.0),
        };

        let n_rows = self.data.len();
        let n_cols = self.data[0].len();

        let left = coord.plot_area.left;
        let top = coord.plot_area.top;
        let w = coord.plot_area.width();
        let h = coord.plot_area.height();

        for (row_idx, row) in self.data.iter().enumerate() {
            for (col_idx, &value) in row.iter().enumerate() {
                if value.is_nan() {
                    continue;
                }

                let normalized = match self.color_scale {
                    HeatmapColorScale::Linear => (value - data_min) / range,
                    HeatmapColorScale::Log => (value.max(log_eps).log10() - log_min) / log_range,
                };
                let color = self.colormap.sample(normalized);

                // Integer-snapped boundaries: cell N's right == cell N+1's left exactly,
                // so adjacent cells share a pixel edge and anti-aliasing can't leak through.
                let x0 = (left + w * (col_idx as f32 / n_cols as f32)).round();
                let x1 = (left + w * ((col_idx + 1) as f32 / n_cols as f32)).round();
                let y0 = (top + h * (row_idx as f32 / n_rows as f32)).round();
                let y1 = (top + h * ((row_idx + 1) as f32 / n_rows as f32)).round();
                backend.fill_rect(Rect::new(x0, y0, x1, y1), color)?;
            }
        }

        Ok(())
    }

    fn data_extent(&self) -> Option<DataExtent> {
        if self.data.is_empty() || self.data[0].is_empty() {
            return None;
        }
        let n_cols = self.data[0].len();
        Some(DataExtent {
            x_min: 0.0,
            x_max: n_cols as f64,
            y_min: 0.0,
            y_max: self.data.len() as f64,
        })
    }

    fn legend_color(&self) -> Option<Color> {
        Some(self.colormap.sample(0.5))
    }

    fn legend_label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Bar
    }

    fn colormap_legend(&self) -> Option<ColormapLegend> {
        let (vmin, vmax) = self.value_range();
        if !vmin.is_finite() || !vmax.is_finite() || vmax <= vmin {
            return None;
        }
        Some(ColormapLegend {
            colormap: self.colormap,
            value_min: vmin,
            value_max: vmax,
            label: self.label.clone(),
            log_scale: matches!(self.color_scale, HeatmapColorScale::Log),
        })
    }

    fn wants_axis_padding(&self) -> bool {
        // Heatmap cells tile the plot rect — padding would create empty
        // gutters between the data cells and the axes.
        false
    }
}

// ── ContourMark ──────────────────────────────────────────────────────────────────────────────────
// TODO(0.4.0): pub struct ContourMark { z: Vec<Vec<f64>>, levels: Vec<f64>, ... }

// ── RidgeMark ────────────────────────────────────────────────────────────────────────────────────
// TODO(0.5.0): pub struct RidgeMark { densities: Vec<Vec<f64>>, offset: f64 }

// ── StepMark ─────────────────────────────────────────────────────────────────────────────────────
/// Step chart: constant between points with vertical/horizontal transitions.
#[derive(Debug, Clone)]
pub struct StepMark {
    /// X data values.
    pub x: Vec<f64>,
    /// Y data values.
    pub y: Vec<f64>,
    /// Step position: when the vertical transition happens.
    pub where_: StepPosition,
    /// Line color.
    pub color: Color,
    /// Stroke width in pixels.
    pub width: f32,
}

/// Where the vertical step transition happens relative to data points.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum StepPosition {
    #[default]
    /// Vertical transition happens *before* the data point (`curveStepBefore`).
    Pre,
    /// Vertical transition at midpoint between points (`curveStep`).
    Mid,
    /// Vertical transition happens *after* the data point (`curveStepAfter`).
    Post,
}

impl StepMark {
    /// New step chart from x and y data with default color.
    #[must_use]
    pub fn new(x: Vec<f64>, y: Vec<f64>) -> Self {
        Self {
            x,
            y,
            where_: StepPosition::default(),
            color: Color::BLUE,
            width: 2.0,
        }
    }

    /// Builder: set step position.
    #[must_use]
    pub fn position(mut self, p: StepPosition) -> Self {
        self.where_ = p;
        self
    }

    /// Builder: set line color.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.color = c;
        self
    }

    /// Builder: set stroke width in pixels.
    #[must_use]
    pub fn width(mut self, w: f32) -> Self {
        self.width = w;
        self
    }
}

impl Mark for StepMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        let mut commands = Vec::new();
        let mut need_move = true;

        let n = self.x.len().min(self.y.len());
        if n < 2 {
            return Ok(());
        }

        // Collect valid points (skip NaN)
        let valid: Vec<(f64, f64)> = (0..n)
            .filter_map(|i| {
                let x = self.x[i];
                let y = self.y[i];
                if x.is_nan() || y.is_nan() {
                    None
                } else {
                    Some((x, y))
                }
            })
            .collect();

        if valid.len() < 2 {
            return Ok(());
        }

        for i in 0..valid.len() {
            let (x, y) = valid[i];
            let curr = coord.data_to_pixel(x, y);

            if need_move {
                commands.push(PathCommand::MoveTo(curr));
                need_move = false;
                continue;
            }

            let (prev_x, prev_y) = valid[i - 1];
            let prev = coord.data_to_pixel(prev_x, prev_y);

            match self.where_ {
                StepPosition::Pre => {
                    commands.push(PathCommand::LineTo(Point::new(curr.x, prev.y)));
                    commands.push(PathCommand::LineTo(curr));
                }
                StepPosition::Post => {
                    commands.push(PathCommand::LineTo(Point::new(prev.x, curr.y)));
                    commands.push(PathCommand::LineTo(curr));
                }
                StepPosition::Mid => {
                    let mid_x = f32::midpoint(prev.x, curr.x);
                    commands.push(PathCommand::LineTo(Point::new(mid_x, prev.y)));
                    commands.push(PathCommand::LineTo(Point::new(mid_x, curr.y)));
                    commands.push(PathCommand::LineTo(curr));
                }
            }
        }

        let path = Path { commands };
        let style = PathStyle {
            stroke_color: self.color,
            stroke_width: self.width,
            fill_color: None,
            line_cap: LineCap::Round,
            line_join: LineJoin::Round,
            ..PathStyle::default()
        };
        backend.draw_path(&path, &style)
    }

    fn data_extent(&self) -> Option<DataExtent> {
        extent_from_xy(&self.x, &self.y)
    }

    fn pixel_extent(&self, coord: &dyn Coord) -> MarkExtent {
        let Some(cart) = coord.as_any().downcast_ref::<CartesianCoord>() else {
            return MarkExtent::Bbox(coord.plot_area());
        };
        // Reproduce the rendered L-leg path as discrete segments so the
        // legend dodge sees the real footprint, not the diagonal between
        // consecutive data points.
        let valid: Vec<(f64, f64)> = self
            .x
            .iter()
            .zip(&self.y)
            .filter_map(|(x, y)| (!x.is_nan() && !y.is_nan()).then_some((*x, *y)))
            .collect();
        if valid.len() < 2 {
            return MarkExtent::Bbox(cart.plot_area);
        }
        let mut segments = Vec::with_capacity(valid.len() * 2);
        let pts: Vec<Point> = valid
            .iter()
            .map(|(x, y)| cart.data_to_pixel(*x, *y))
            .collect();
        for i in 1..pts.len() {
            let prev = pts[i - 1];
            let curr = pts[i];
            match self.where_ {
                StepPosition::Pre => {
                    segments.push((prev, Point::new(curr.x, prev.y)));
                    segments.push((Point::new(curr.x, prev.y), curr));
                }
                StepPosition::Post => {
                    segments.push((prev, Point::new(prev.x, curr.y)));
                    segments.push((Point::new(prev.x, curr.y), curr));
                }
                StepPosition::Mid => {
                    let mid_x = f32::midpoint(prev.x, curr.x);
                    segments.push((prev, Point::new(mid_x, prev.y)));
                    segments.push((Point::new(mid_x, prev.y), Point::new(mid_x, curr.y)));
                    segments.push((Point::new(mid_x, curr.y), curr));
                }
            }
        }
        MarkExtent::Segments(segments)
    }
}

// ── HistogramMark ───────────────────────────────────────────────────────────────────────

/// Histogram: bar chart with bins computed from data.
#[derive(Debug, Clone)]
pub struct HistogramMark {
    /// Raw data values.
    pub data: Vec<f64>,
    /// Binning method.
    pub method: BinMethod,
    /// Bar color.
    pub color: Color,
}

impl HistogramMark {
    /// New histogram from raw data.
    #[must_use]
    pub fn new(data: Vec<f64>) -> Self {
        Self {
            data,
            method: BinMethod::default(),
            color: Color::from_hex(0x4C_72B0),
        }
    }

    /// Builder: set binning method.
    #[must_use]
    pub fn method(mut self, m: BinMethod) -> Self {
        self.method = m;
        self
    }

    /// Builder: set bar color.
    #[must_use]
    pub fn color(mut self, c: Color) -> Self {
        self.color = c;
        self
    }
}

impl Mark for HistogramMark {
    fn render(&self, coord: &dyn Coord, backend: &mut dyn DrawBackend) -> Result<()> {
        let coord = require_cartesian(coord)?;
        let transform = BinTransform::new(self.method);
        let bins: Vec<Bin> = transform.compute(&self.data);

        let area = coord.plot_area;
        let n = bins.len();
        let band_width = area.width() / n as f32;
        let bar_width = band_width;

        let y_max = bins.iter().map(|b| b.count as f64).fold(0.0f64, f64::max);

        for (i, bin) in bins.iter().enumerate() {
            let x_center = area.left + (i as f32 + 0.5) * band_width;
            let x_left = x_center - bar_width / 2.0;
            let x_right = x_center + bar_width / 2.0;

            let height_ratio = if y_max > 0.0 {
                (bin.count as f64 / y_max) as f32
            } else {
                0.0
            };
            let bar_height = height_ratio * area.height();

            let y_top = area.bottom - bar_height;
            let y_bottom = area.bottom;

            let rect = Rect::new(x_left, y_top, x_right, y_bottom);
            backend.fill_rect(rect, self.color)?;
        }

        Ok(())
    }

    fn data_extent(&self) -> Option<DataExtent> {
        let data: Vec<f64> = self.data.iter().copied().filter(|v| !v.is_nan()).collect();
        if data.is_empty() {
            return None;
        }
        let transform = BinTransform::new(self.method);
        let bins = transform.compute(&data);
        let count_max = bins.iter().map(|b| b.count).max().unwrap_or(0) as f64;
        Some(DataExtent {
            x_min: bins.first().map_or(0.0, |b| b.left),
            x_max: bins.last().map_or(1.0, |b| b.right),
            y_min: 0.0,
            y_max: count_max,
        })
    }

    fn legend_glyph(&self) -> LegendGlyph {
        LegendGlyph::Bar
    }

    fn wants_axis_padding(&self) -> bool {
        // Histogram bins tile the x-axis range — padding would push the
        // first/last bin off the data extents.
        false
    }
}

// ── helpers ──────────────────────────────────────────────────────────────────────────────────────

/// Approximate a circle with four cubic Bézier arcs (magic constant `4/3 * (√2 - 1)`).
fn push_circle(cmds: &mut Vec<PathCommand>, c: Point, r: f32) {
    const K: f32 = 0.552_284_8;
    let kr = K * r;

    cmds.push(PathCommand::MoveTo(Point::new(c.x + r, c.y)));
    cmds.push(PathCommand::CubicTo(
        Point::new(c.x + r, c.y + kr),
        Point::new(c.x + kr, c.y + r),
        Point::new(c.x, c.y + r),
    ));
    cmds.push(PathCommand::CubicTo(
        Point::new(c.x - kr, c.y + r),
        Point::new(c.x - r, c.y + kr),
        Point::new(c.x - r, c.y),
    ));
    cmds.push(PathCommand::CubicTo(
        Point::new(c.x - r, c.y - kr),
        Point::new(c.x - kr, c.y - r),
        Point::new(c.x, c.y - r),
    ));
    cmds.push(PathCommand::CubicTo(
        Point::new(c.x + kr, c.y - r),
        Point::new(c.x + r, c.y - kr),
        Point::new(c.x + r, c.y),
    ));
    cmds.push(PathCommand::Close);
}

/// Compute the axis-aligned bounding box of paired x/y data, skipping NaN entries.
fn extent_from_xy(x: &[f64], y: &[f64]) -> Option<DataExtent> {
    let mut x_min = f64::INFINITY;
    let mut x_max = f64::NEG_INFINITY;
    let mut y_min = f64::INFINITY;
    let mut y_max = f64::NEG_INFINITY;
    let mut any = false;

    for (&xv, &yv) in x.iter().zip(y) {
        if xv.is_nan() || yv.is_nan() {
            continue;
        }
        x_min = x_min.min(xv);
        x_max = x_max.max(xv);
        y_min = y_min.min(yv);
        y_max = y_max.max(yv);
        any = true;
    }

    if any {
        Some(DataExtent {
            x_min,
            x_max,
            y_min,
            y_max,
        })
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use starsight_layer_1::backends::vectors::SvgBackend;
    use starsight_layer_2::axes::Axis;
    use starsight_layer_2::scales::LinearScale;

    fn coord_for(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> CartesianCoord {
        CartesianCoord {
            x_axis: Axis {
                scale: Box::new(LinearScale {
                    domain_min: x_min,
                    domain_max: x_max,
                }),
                label: None,
                tick_positions: vec![],
                tick_labels: vec![],
            },
            y_axis: Axis {
                scale: Box::new(LinearScale {
                    domain_min: y_min,
                    domain_max: y_max,
                }),
                label: None,
                tick_positions: vec![],
                tick_labels: vec![],
            },
            plot_area: Rect::new(0.0, 0.0, 100.0, 100.0),
        }
    }

    #[test]
    fn line_mark_new() {
        let mark = LineMark::new(vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]);
        assert_eq!(mark.x.len(), 3);
        assert_eq!(mark.y.len(), 3);
    }

    #[test]
    fn line_mark_data_extent() {
        let mark = LineMark::new(vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]);
        let extent = mark.data_extent();
        assert!(extent.is_some());
        let e = extent.unwrap();
        assert_eq!(e.x_min, 1.0);
        assert_eq!(e.x_max, 3.0);
    }

    #[test]
    fn line_mark_data_extent_empty() {
        let mark = LineMark::new(vec![], vec![]);
        let extent = mark.data_extent();
        assert!(extent.is_none());
    }

    #[test]
    fn line_mark_nan_gaps() {
        let mark = LineMark::new(vec![1.0, 2.0, f64::NAN, 4.0], vec![1.0, 2.0, 3.0, 4.0]);
        let extent = mark.data_extent();
        assert!(extent.is_some());
    }

    #[test]
    fn line_mark_builders() {
        let m = LineMark::new(vec![0.0], vec![0.0])
            .color(Color::RED)
            .width(3.0)
            .label("series");
        assert_eq!(m.color, Color::RED);
        assert_eq!(m.width, 3.0);
        assert_eq!(m.label.as_deref(), Some("series"));
        assert_eq!(m.legend_color(), Some(Color::RED));
        assert_eq!(m.legend_label(), Some("series"));
    }

    #[test]
    fn line_mark_render_all_nan_returns_ok() {
        let mark = LineMark::new(vec![f64::NAN], vec![f64::NAN]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn line_mark_render_with_data() {
        let mark = LineMark::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0]);
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn point_mark_new() {
        let mark = PointMark::new(vec![1.0, 2.0], vec![3.0, 4.0]);
        assert_eq!(mark.x.len(), 2);
    }

    #[test]
    fn point_mark_data_extent() {
        let mark = PointMark::new(vec![1.0, 2.0], vec![3.0, 4.0]);
        let extent = mark.data_extent();
        assert!(extent.is_some());
    }

    #[test]
    fn point_mark_builders() {
        let m = PointMark::new(vec![0.0], vec![0.0])
            .color(Color::GREEN)
            .radius(8.0)
            .label("dots");
        assert_eq!(m.colors, Some(vec![Color::GREEN]));
        assert_eq!(m.radii, Some(vec![8.0]));
        assert_eq!(m.legend_color(), Some(Color::GREEN));
        assert_eq!(m.legend_label(), Some("dots"));
    }

    #[test]
    fn point_mark_per_point_colors_and_radii() {
        let m = PointMark::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0])
            .colors(vec![Color::RED, Color::GREEN, Color::BLUE])
            .radii(vec![3.0, 5.0, 7.0])
            .alpha(0.5);
        assert_eq!(m.colors.as_ref().map(Vec::len), Some(3));
        assert_eq!(m.radii.as_ref().map(Vec::len), Some(3));
        assert!((m.alpha - 0.5).abs() < 1e-6);
        // legend_color picks the first color
        assert_eq!(m.legend_color(), Some(Color::RED));
    }

    #[test]
    fn point_mark_render_all_nan_returns_ok() {
        let mark = PointMark::new(vec![f64::NAN], vec![f64::NAN]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn point_mark_render_with_data() {
        let mark = PointMark::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 2.0]);
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn area_mark_new() {
        let mark = AreaMark::new(vec![1.0, 2.0], vec![3.0, 4.0]);
        assert_eq!(mark.x.len(), 2);
    }

    #[test]
    fn area_mark_data_extent() {
        let mark = AreaMark::new(vec![1.0, 2.0], vec![3.0, 4.0]);
        let extent = mark.data_extent();
        assert!(extent.is_some());
    }

    #[test]
    fn area_mark_builders() {
        let m = AreaMark::new(vec![0.0], vec![0.0])
            .color(Color::GREEN)
            .opacity(0.5)
            .baseline(10.0);
        assert_eq!(m.fill, Color::GREEN);
        assert_eq!(m.opacity, 0.5);
        assert!(matches!(m.baseline, AreaBaseline::Fixed(_)));
    }

    #[test]
    fn step_mark_new() {
        let mark = StepMark::new(vec![1.0, 2.0], vec![3.0, 4.0]);
        assert_eq!(mark.x.len(), 2);
    }

    #[test]
    fn step_mark_builders() {
        let m = StepMark::new(vec![0.0], vec![0.0])
            .color(Color::RED)
            .width(5.0)
            .position(StepPosition::Mid);
        assert_eq!(m.color, Color::RED);
        assert_eq!(m.width, 5.0);
        assert_eq!(m.where_, StepPosition::Mid);
    }

    #[test]
    fn step_mark_render_short_returns_ok() {
        let mark = StepMark::new(vec![1.0], vec![1.0]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn step_mark_render_all_nan_returns_ok() {
        let mark = StepMark::new(vec![f64::NAN, f64::NAN], vec![f64::NAN, f64::NAN]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn histogram_mark_new() {
        let mark = HistogramMark::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        assert_eq!(mark.data.len(), 5);
    }

    #[test]
    fn histogram_mark_builders() {
        let m = HistogramMark::new(vec![1.0, 2.0])
            .color(Color::RED)
            .method(BinMethod::default());
        assert_eq!(m.color, Color::RED);
    }

    #[test]
    fn histogram_mark_render_empty_returns_ok() {
        let mark = HistogramMark::new(vec![]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn histogram_mark_render_with_data() {
        let mark = HistogramMark::new((0..50).map(f64::from).collect());
        let coord = coord_for(0.0, 50.0, 0.0, 10.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn histogram_mark_data_extent_empty_is_none() {
        let mark = HistogramMark::new(vec![]);
        assert!(mark.data_extent().is_none());
    }

    #[test]
    fn histogram_mark_data_extent_only_nan_is_none() {
        let mark = HistogramMark::new(vec![f64::NAN]);
        assert!(mark.data_extent().is_none());
    }

    #[test]
    fn data_extent_new() {
        let extent = DataExtent {
            x_min: 0.0,
            x_max: 10.0,
            y_min: 0.0,
            y_max: 10.0,
        };
        assert_eq!(extent.x_min, 0.0);
    }

    // ── BarMark ────────────────────────────────────────────────────────────────────────────────

    #[test]
    fn bar_mark_builders() {
        let m = BarMark::new(vec!["a".to_string()], vec![1.0])
            .color(Color::RED)
            .width(0.5)
            .group("g")
            .stack("s")
            .base(2.0)
            .label("series");
        assert_eq!(m.colors, Some(vec![Color::RED]));
        assert_eq!(m.width, Some(0.5));
        assert_eq!(m.group.as_deref(), Some("g"));
        assert_eq!(m.stack.as_deref(), Some("s"));
        assert_eq!(m.bases, Some(vec![2.0]));
        assert!(!m.connectors);
        assert_eq!(m.legend_label(), Some("series"));
        assert_eq!(m.legend_color(), Some(Color::RED));
    }

    #[test]
    fn bar_mark_per_bar_bases_and_colors() {
        let m = BarMark::new(
            vec!["a".to_string(), "b".to_string(), "c".to_string()],
            vec![1.0, -2.0, 3.0],
        )
        .bases(vec![0.0, 1.0, -1.0])
        .colors(vec![Color::RED, Color::GREEN, Color::BLUE])
        .connectors(true);
        assert_eq!(m.bases.as_ref().map(Vec::len), Some(3));
        assert_eq!(m.colors.as_ref().map(Vec::len), Some(3));
        assert!(m.connectors);
        // legend_color picks the first color
        assert_eq!(m.legend_color(), Some(Color::RED));
    }

    #[test]
    fn bar_mark_render_bar_vertical_with_connectors() {
        let mark = BarMark::new(
            vec!["a".to_string(), "b".to_string(), "c".to_string()],
            vec![1.0, -0.5, 1.5],
        )
        .bases(vec![0.0, 1.0, 0.5])
        .connectors(true);
        let coord = coord_for(0.0, 3.0, -1.0, 3.0);
        let mut backend = SvgBackend::new(120, 120);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_horizontal() {
        let m = BarMark::new(vec!["a".to_string()], vec![1.0]).horizontal();
        assert_eq!(m.orientation, Orientation::Horizontal);
    }

    #[test]
    fn bar_mark_render_vertical_simple() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0]);
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn bar_mark_render_horizontal_simple() {
        let mark =
            BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0]).horizontal();
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn bar_mark_render_empty_returns_ok() {
        let mark = BarMark::new(vec![], vec![]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_empty_returns_ok() {
        let mark = BarMark::new(vec![], vec![]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_vertical_grouped() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0]).group("g");
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        let mut ctx = BarRenderContext::default();
        ctx.group_offsets.insert("g".into(), (0, 2));
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_vertical_grouped_offset_missing() {
        // Group set on the mark but the context has no entry for that group
        // exercises the `else` branch where x_offset falls back to 0.0.
        let mark = BarMark::new(vec!["a".to_string()], vec![1.0]).group("missing");
        let coord = coord_for(0.0, 1.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_vertical_stacked() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0]).stack("s");
        let coord = coord_for(0.0, 2.0, 0.0, 4.0);
        let mut backend = SvgBackend::new(100, 100);
        let mut ctx = BarRenderContext::default();
        ctx.stacked_baselines.insert("a".into(), 1.0);
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_vertical_with_base() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0]).base(0.5);
        let coord = coord_for(0.0, 2.0, 0.0, 4.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_horizontal_grouped() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0])
            .horizontal()
            .group("g");
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        let mut ctx = BarRenderContext::default();
        ctx.group_offsets.insert("g".into(), (0, 2));
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_horizontal_grouped_offset_missing() {
        let mark = BarMark::new(vec!["a".to_string()], vec![1.0])
            .horizontal()
            .group("missing");
        let coord = coord_for(0.0, 2.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_horizontal_stacked() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0])
            .horizontal()
            .stack("s");
        let coord = coord_for(0.0, 4.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        let mut ctx = BarRenderContext::default();
        ctx.stacked_baselines.insert("a".into(), 1.0);
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_render_bar_horizontal_with_base() {
        let mark = BarMark::new(vec!["a".to_string(), "b".to_string()], vec![1.0, 2.0])
            .horizontal()
            .base(0.5);
        let coord = coord_for(0.0, 4.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn bar_mark_data_extent_horizontal() {
        let m = BarMark::new(vec!["a".into(), "b".into()], vec![1.0, 2.0]).horizontal();
        let e = m.data_extent().unwrap();
        assert_eq!(e.x_min, 0.0);
        assert_eq!(e.x_max, 2.0);
        assert_eq!(e.y_min, 0.0);
        assert_eq!(e.y_max, 2.0);
    }

    #[test]
    fn bar_mark_data_extent_empty() {
        let m = BarMark::new(vec![], vec![]);
        assert!(m.data_extent().is_none());
    }

    #[test]
    fn bar_mark_as_bar_info_and_data() {
        let m = BarMark::new(vec!["a".into()], vec![1.0])
            .group("g")
            .stack("s");
        let info = m.as_bar_info().unwrap();
        assert_eq!(info.0, Some("g"));
        assert_eq!(info.1, Some("s"));
        let data = m.as_bar_data().unwrap();
        assert_eq!(data.0.len(), 1);
        assert_eq!(data.1.len(), 1);
    }

    // ── HeatmapMark ────────────────────────────────────────────────────────────────────────────

    #[test]
    fn heatmap_mark_builders() {
        let m = HeatmapMark::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]])
            .colormap(starsight_layer_1::colormap::PLASMA)
            .label("h");
        assert_eq!(m.label.as_deref(), Some("h"));
        assert_eq!(m.legend_label(), Some("h"));
    }

    #[test]
    fn heatmap_mark_render_empty_returns_ok() {
        let mark = HeatmapMark::new(vec![]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn heatmap_mark_render_inner_empty_row_returns_ok() {
        let mark = HeatmapMark::new(vec![vec![]]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn heatmap_mark_render_constant_values() {
        // All same value, so range collapses to zero (uses fallback `1.0`)
        let mark = HeatmapMark::new(vec![vec![5.0, 5.0], vec![5.0, 5.0]]);
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn heatmap_mark_render_skips_nan() {
        let mark = HeatmapMark::new(vec![vec![1.0, f64::NAN], vec![2.0, 3.0]]);
        let coord = coord_for(0.0, 2.0, 0.0, 2.0);
        let mut backend = SvgBackend::new(100, 100);
        mark.render(&coord, &mut backend).unwrap();
    }

    #[test]
    fn heatmap_mark_data_extent_empty() {
        let m = HeatmapMark::new(vec![]);
        assert!(m.data_extent().is_none());
        let m2 = HeatmapMark::new(vec![vec![]]);
        assert!(m2.data_extent().is_none());
    }

    #[test]
    fn heatmap_mark_legend_color() {
        let m = HeatmapMark::new(vec![vec![1.0]]);
        assert!(m.legend_color().is_some());
    }

    // ── Mark trait default impls ──────────────────────────────────────────────────────────────

    #[test]
    fn mark_default_render_bar_falls_back_to_render() {
        let mark = LineMark::new(vec![0.0, 1.0], vec![0.0, 1.0]);
        let coord = coord_for(0.0, 1.0, 0.0, 1.0);
        let mut backend = SvgBackend::new(100, 100);
        let ctx = BarRenderContext::default();
        // LineMark doesn't override render_bar, so default impl forwards to render
        mark.render_bar(&coord, &mut backend, &ctx).unwrap();
    }

    #[test]
    fn mark_default_legend_returns_none() {
        let mark = StepMark::new(vec![0.0, 1.0], vec![0.0, 1.0]);
        assert!(mark.legend_color().is_none());
        assert!(mark.legend_label().is_none());
    }

    #[test]
    fn mark_default_as_bar_info_is_none() {
        let mark = LineMark::new(vec![0.0], vec![0.0]);
        assert!(mark.as_bar_info().is_none());
        assert!(mark.as_bar_data().is_none());
    }
}