quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! `Chart` primitive: sparkline, line, and bar chart visualisations.
//!
//! Three chart kinds serve different data visualisation needs:
//!
//! - [`ChartKind::Sparkline`] — single-row inline chart for embedding
//!   in status bars or table cells. No axes, no labels.
//! - [`ChartKind::Line`] — multi-series line/area chart with optional
//!   axis labels and legend. Set [`Series::fill`] for area charts.
//! - [`ChartKind::Bar`] — vertical bar chart with category labels.
//!   Multiple series **stack** within each x-position.
//! - [`ChartKind::BarGrouped`] — the same data drawn **side by side**
//!   within each x-position instead of stacked.
//!
//! Each [`Series`] carries a `Vec<f64>` of y-values evenly spaced along
//! the x-axis. The y-range auto-derives from data when
//! [`Chart::y_range`] is `None` — for a multi-series stacked bar chart
//! the range is anchored at `0.0` (widened to fit the tallest column
//! total and any negative excursion), so segments stay proportional
//! and a stack never clips.
//!
//! Every backend paints bars from the shared geometry helper
//! [`Chart::bar_column_spans_all`] (or [`Chart::bar_column_spans`] for
//! a single column), which itself derives from
//! [`Chart::effective_y_range`], so stacked and grouped layouts stay
//! identical across TUI, GTK and macOS. [`Chart::column_totals`] is a
//! separate, independently-useful helper (e.g. for labelling a stack's
//! grand total) — it isn't on the geometry path itself.

use crate::event::Rect;
use crate::types::{Color, WidgetId};
use serde::{Deserialize, Serialize};

/// Declarative description of a chart widget.
///
/// # Examples
///
/// ```
/// use quadraui::{Chart, ChartKind, ChartMeasure, Series, WidgetId};
///
/// let chart = Chart {
///     id: WidgetId::new("chart:cpu"),
///     kind: ChartKind::Sparkline,
///     series: vec![Series {
///         label: "cpu %".to_string(),
///         data: vec![10.0, 40.0, 25.0, 60.0],
///         color: None,
///         fill: false,
///     }],
///     x_label: None,
///     y_label: None,
///     y_range: None,
///     x_range: None,
///     show_legend: false,
///     y_ticks: None,
///     x_ticks: None,
///     show_grid: false,
/// };
///
/// let measure = ChartMeasure {
///     width: 40.0,
///     height: 4.0,
///     char_width: 1.0,
///     line_height: 1.0,
/// };
/// let layout = chart.layout(0.0, 0.0, measure);
/// assert!(!layout.data_point_positions.is_empty());
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Chart {
    pub id: WidgetId,
    pub kind: ChartKind,
    pub series: Vec<Series>,
    #[serde(default)]
    pub x_label: Option<String>,
    #[serde(default)]
    pub y_label: Option<String>,
    /// Explicit y-axis range. `None` = auto-derived from data min/max.
    #[serde(default)]
    pub y_range: Option<(f64, f64)>,
    /// Explicit x-axis range, used to compute x-tick *values*.
    /// `None` = ticks are labelled by data index, `0..series.data.len()`.
    /// Data-point x *positions* stay index-evenly-spaced regardless —
    /// this only changes what an x-tick's label reads.
    #[serde(default)]
    pub x_range: Option<(f64, f64)>,
    #[serde(default)]
    pub show_legend: bool,
    /// Number of y-axis tick marks. `None` = auto (5).
    #[serde(default)]
    pub y_ticks: Option<usize>,
    /// Number of x-axis tick marks. `None` = no x-axis tick row at all
    /// (unlike `y_ticks`, this is opt-in, not auto-5 — many charts plot
    /// against a plain index with nothing meaningful to label).
    #[serde(default)]
    pub x_ticks: Option<usize>,
    /// Show horizontal grid lines at y-tick positions.
    #[serde(default)]
    pub show_grid: bool,
}

/// Chart visualisation kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ChartKind {
    /// Single-row inline chart (no axes, no labels).
    Sparkline,
    /// Multi-series line chart with axes. Per-series `fill` enables area fill.
    #[default]
    Line,
    /// Vertical bar chart with category labels.
    ///
    /// Multiple series **stack**: each x-position paints one coloured
    /// segment per series, bottom-up in `series` order, and the bar's
    /// total height is the column sum. A single-series chart is exactly
    /// a plain bar chart — stacking is a no-op there.
    ///
    /// With two or more series and an auto-derived range (no explicit
    /// `y_range`), the floor is anchored at `0.0` specifically so
    /// segment proportions are correct — see [`Chart::effective_y_range`].
    /// An *explicit* `y_range` whose floor isn't `0.0` still skews every
    /// segment's proportion relative to the others, since the geometry
    /// has no way to know which value the caller intends as "empty";
    /// pass `y_range: Some((0.0, …))` if you need one. If the explicit
    /// range excludes `0.0` altogether (e.g. `Some((-10.0, -2.0))`) the
    /// stack's baseline lands on whichever plot edge is nearer zero and
    /// segments are clipped to the range rather than vanishing, but the
    /// proportions on screen are then the caller's to justify.
    Bar,
    /// Vertical bar chart whose series are drawn **side by side**
    /// within each x-position, for comparing magnitudes rather than
    /// composition. Use [`ChartKind::Bar`] to compare totals instead.
    ///
    /// Each slot is split into `series.len()` sub-bars. When a slot is
    /// too narrow to give every series at least one device unit, the
    /// trailing series are clipped — widen the chart or drop a series.
    /// (The TUI backend clips exactly this way; GTK and macOS instead
    /// floor each sub-bar to 1px and let them overlap rather than
    /// dropping data — both are acceptable outcomes for a pathologically
    /// narrow chart, but they render differently from each other.)
    BarGrouped,
}

impl ChartKind {
    /// True for every bar-family kind ([`ChartKind::Bar`],
    /// [`ChartKind::BarGrouped`]).
    pub fn is_bar(self) -> bool {
        matches!(self, ChartKind::Bar | ChartKind::BarGrouped)
    }

    /// True when bar segments accumulate per x-position rather than
    /// sitting side by side.
    pub fn is_stacked_bar(self) -> bool {
        matches!(self, ChartKind::Bar)
    }
}

/// One data series in a chart.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Series {
    pub label: String,
    /// Y-values, evenly spaced along the x-axis.
    pub data: Vec<f64>,
    /// Override colour. `None` = backend picks from a default palette.
    #[serde(default)]
    pub color: Option<Color>,
    /// Fill the area under the line (Line kind only). Ignored for
    /// Sparkline and Bar.
    #[serde(default)]
    pub fill: bool,
}

/// Events a `Chart` emits.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChartEvent {
    /// User clicked the chart body.
    Clicked { id: WidgetId },
    /// User clicked a specific data point.
    DataPointClicked {
        id: WidgetId,
        series_idx: usize,
        data_idx: usize,
    },
    /// User clicked a legend entry.
    LegendClicked { id: WidgetId, series_idx: usize },
}

// ── Layout API ──────────────────────────────────────────────────────────────

/// Backend-supplied measurements for chart layout.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ChartMeasure {
    pub width: f32,
    pub height: f32,
    /// Approximate monospace character width (for axis label sizing).
    pub char_width: f32,
    /// Line height (for axis label rows).
    pub line_height: f32,
}

/// Classification of a hit-test result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChartHit {
    /// Click landed on a specific data point.
    DataPoint(WidgetId, usize, usize),
    /// Click landed on the plot area (no specific point nearby).
    Body(WidgetId),
    /// Click landed on a legend entry (series index).
    Legend(WidgetId, usize),
    /// Click landed outside the chart.
    Empty,
}

/// Fully-resolved chart layout.
#[derive(Debug, Clone, PartialEq)]
pub struct ChartLayout {
    pub bounds: Rect,
    /// The data-plotting region (inside axes/labels).
    pub plot_area: Rect,
    pub legend_bounds: Option<Rect>,
    pub hit_regions: Vec<(Rect, ChartHit)>,
    /// Screen positions of data points: (series_idx, data_idx, x, y).
    /// Apps use these to anchor tooltips and resolve nearest-point from
    /// MouseMoved events.
    pub data_point_positions: Vec<(usize, usize, f32, f32)>,
    /// Y-axis tick positions: (screen_y, data_value).
    pub y_tick_positions: Vec<(f32, f64)>,
    /// X-axis tick positions: (screen_x, data_value).
    pub x_tick_positions: Vec<(f32, f64)>,
}

impl ChartLayout {
    pub fn hit_test(&self, x: f32, y: f32) -> ChartHit {
        for (rect, hit) in &self.hit_regions {
            if x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height {
                return hit.clone();
            }
        }
        ChartHit::Empty
    }

    /// Find the nearest data point to (x, y) within `snap_distance`.
    /// Returns `(series_idx, data_idx)`.
    pub fn nearest_point(&self, x: f32, y: f32, snap_distance: f32) -> Option<(usize, usize)> {
        let mut best: Option<(usize, usize, f32)> = None;
        let snap_sq = snap_distance * snap_distance;
        for &(si, di, px, py) in &self.data_point_positions {
            let dx = x - px;
            let dy = y - py;
            let dist_sq = dx * dx + dy * dy;
            if dist_sq <= snap_sq && (best.is_none() || dist_sq < best.unwrap().2) {
                best = Some((si, di, dist_sq));
            }
        }
        best.map(|(si, di, _)| (si, di))
    }

    /// Convert a screen x-coordinate to a data-space x index (fractional).
    pub fn screen_to_data_x(&self, screen_x: f32, data_len: usize) -> f64 {
        if data_len <= 1 || self.plot_area.width <= 0.0 {
            return 0.0;
        }
        let frac = ((screen_x - self.plot_area.x) / self.plot_area.width).clamp(0.0, 1.0);
        frac as f64 * (data_len - 1) as f64
    }

    /// Convert a data-space x index to a screen x-coordinate.
    pub fn data_to_screen_x(&self, data_x: f64, data_len: usize) -> f32 {
        if data_len <= 1 {
            return self.plot_area.x;
        }
        let frac = (data_x / (data_len - 1) as f64).clamp(0.0, 1.0) as f32;
        self.plot_area.x + frac * self.plot_area.width
    }
}

impl Chart {
    /// Resolve the effective y-range from explicit range or data min/max.
    ///
    /// For a stacked bar chart ([`ChartKind::Bar`]) with more than one
    /// series, the range is anchored so that segment proportions are
    /// correct: the floor is `min(0.0, ...)` and the ceiling is
    /// `max(0.0, ...)` over every *partial sum* reached while
    /// accumulating each column (not just each column's final total),
    /// so a stack can never clip and its segments' relative proportions
    /// stay correct. Using raw individual values as the floor here would
    /// under-draw the first series in every column by a constant
    /// offset whenever the smallest single value anywhere is `> 0`.
    ///
    /// A single-series `Bar` chart has nothing to compose against, so
    /// it keeps the plain min/max-of-data behaviour every other chart
    /// kind uses — single-series output is unaffected by stacking.
    pub fn effective_y_range(&self) -> (f64, f64) {
        if let Some(range) = self.y_range {
            return range;
        }
        if self.kind.is_stacked_bar() && self.series.len() > 1 {
            let mut min = 0.0_f64;
            let mut max = 0.0_f64;
            for data_idx in 0..self.max_data_len() {
                let mut cum = 0.0;
                for s in &self.series {
                    cum += s.data.get(data_idx).copied().unwrap_or(0.0);
                    if cum < min {
                        min = cum;
                    }
                    if cum > max {
                        max = cum;
                    }
                }
            }
            return if (max - min).abs() < f64::EPSILON {
                (min - 1.0, max + 1.0)
            } else {
                (min, max)
            };
        }
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for s in &self.series {
            for &v in &s.data {
                if v < min {
                    min = v;
                }
                if v > max {
                    max = v;
                }
            }
        }
        if min > max {
            (0.0, 1.0)
        } else if (max - min).abs() < f64::EPSILON {
            (min - 1.0, max + 1.0)
        } else {
            (min, max)
        }
    }

    /// Maximum data length across all series.
    pub fn max_data_len(&self) -> usize {
        self.series.iter().map(|s| s.data.len()).max().unwrap_or(0)
    }

    /// Sum of every series' value at each x-position, i.e. the height a
    /// stacked bar reaches. Series shorter than [`Chart::max_data_len`]
    /// contribute `0.0` for the missing positions.
    pub fn column_totals(&self) -> Vec<f64> {
        (0..self.max_data_len())
            .map(|i| {
                self.series
                    .iter()
                    .map(|s| s.data.get(i).copied().unwrap_or(0.0))
                    .sum()
            })
            .collect()
    }

    /// Vertical extent of every bar segment in the `data_idx` column,
    /// as `(series_idx, bottom, top)` fractions of the plot height
    /// measured **up from the plot floor**, in bottom-to-top paint
    /// order. This is the one source of truth every backend's bar
    /// painter and [`Chart::layout`] share.
    ///
    /// - [`ChartKind::Bar`] with two or more series — spans accumulate:
    ///   each segment covers the gap between the running total before
    ///   and after that series, so an all-zero series occupies an empty
    ///   span and does **not** shift the series above it. A negative
    ///   value walks the stack back *down*, and its segment is returned
    ///   bottom-first (`bottom <= top` always holds).
    /// - [`ChartKind::Bar`] with a single series, and
    ///   [`ChartKind::BarGrouped`] — every span starts at the plot
    ///   floor. Grouped callers lay the series out side by side
    ///   horizontally; a single-series stack has nothing to compose
    ///   against, so it stays a plain bar chart.
    ///
    /// Returns one entry per series (zero-height for missing data), so
    /// callers can index by series without re-checking lengths. Empty
    /// for non-bar kinds.
    ///
    /// This resolves [`Chart::effective_y_range`] on every call, which
    /// for a stacked chart is itself an O(series × columns) scan. Paint
    /// loops that walk every column should call
    /// [`Chart::bar_column_spans_all`] instead, which resolves the range
    /// once for the whole chart.
    pub fn bar_column_spans(&self, data_idx: usize) -> Vec<(usize, f64, f64)> {
        if !self.kind.is_bar() {
            return Vec::new();
        }
        self.bar_column_spans_in(data_idx, self.effective_y_range())
    }

    /// [`Chart::bar_column_spans`] for every column, outer index =
    /// column, resolving the y-range once instead of once per column.
    ///
    /// Backends paint whole charts, so this is the form their paint
    /// loops want: it turns the bar pass from O(columns² × series) into
    /// O(columns × series). Empty for non-bar kinds.
    pub fn bar_column_spans_all(&self) -> Vec<Vec<(usize, f64, f64)>> {
        if !self.kind.is_bar() {
            return Vec::new();
        }
        let y_range = self.effective_y_range();
        (0..self.max_data_len())
            .map(|di| self.bar_column_spans_in(di, y_range))
            .collect()
    }

    /// Shared body of [`Chart::bar_column_spans`] and
    /// [`Chart::bar_column_spans_all`], with the y-range already
    /// resolved by the caller.
    fn bar_column_spans_in(
        &self,
        data_idx: usize,
        (y_min, y_max): (f64, f64),
    ) -> Vec<(usize, f64, f64)> {
        let range = y_max - y_min;
        let norm = |v: f64| {
            if range > 0.0 {
                ((v - y_min) / range).clamp(0.0, 1.0)
            } else {
                0.5
            }
        };

        let mut spans = Vec::with_capacity(self.series.len());
        // Gated on `series.len() > 1` to match [`Chart::effective_y_range`]'s
        // zero-anchoring exactly. A *single*-series `Bar` keeps the plain
        // min/max-of-data range, so `norm(0.0)` there is not the plot floor —
        // for all-negative data (`[-5, -3, -1]` → range `(-5, -1)`) it clamps
        // to `1.0` and every bar would collapse to zero height. Single-series
        // bars take the `else` branch and keep the plain rendering.
        if self.kind.is_stacked_bar() && self.series.len() > 1 {
            // Each segment spans the gap between two consecutive cumulative
            // levels, both mapped through `norm`. Deriving `bottom` from the
            // *previous cumulative value* rather than carrying the previous
            // `top` forward means a segment stays visible even when zero
            // falls outside the range entirely (an explicit all-negative
            // `y_range` used to collapse the whole stack to zero height), and
            // `min`/`max` keeps `bottom <= top` when a negative value walks
            // the stack back down.
            let mut cum = 0.0;
            for (si, s) in self.series.iter().enumerate() {
                let next = cum + s.data.get(data_idx).copied().unwrap_or(0.0);
                let (a, b) = (norm(cum), norm(next));
                spans.push((si, a.min(b), a.max(b)));
                cum = next;
            }
        } else {
            for (si, s) in self.series.iter().enumerate() {
                let top = s.data.get(data_idx).map(|&v| norm(v)).unwrap_or(0.0);
                spans.push((si, 0.0, top));
            }
        }
        spans
    }

    /// Compute layout and hit regions.
    ///
    /// Backends call this with their native measurements. The returned
    /// [`ChartLayout`] is consumed by both paint and hit_test — one
    /// source of truth.
    pub fn layout(&self, origin_x: f32, origin_y: f32, measure: ChartMeasure) -> ChartLayout {
        let bounds = Rect::new(origin_x, origin_y, measure.width, measure.height);

        match self.kind {
            ChartKind::Sparkline => {
                let hit_regions = vec![(bounds, ChartHit::Body(self.id))];
                let mut data_point_positions = Vec::new();
                if let Some(s) = self.series.first() {
                    let (y_min, y_max) = self.effective_y_range();
                    let range = y_max - y_min;
                    let pw = measure.width;
                    let n = s.data.len();
                    let start = n.saturating_sub(pw as usize);
                    for (i, &val) in s.data[start..].iter().enumerate() {
                        let norm = if range > 0.0 {
                            ((val - y_min) / range).clamp(0.0, 1.0)
                        } else {
                            0.5
                        };
                        let sx = origin_x + i as f32;
                        let sy = origin_y + (1.0 - norm as f32) * measure.height;
                        data_point_positions.push((0, start + i, sx, sy));
                    }
                }
                ChartLayout {
                    bounds,
                    plot_area: bounds,
                    legend_bounds: None,
                    hit_regions,
                    data_point_positions,
                    y_tick_positions: Vec::new(),
                    x_tick_positions: Vec::new(),
                }
            }
            ChartKind::Line | ChartKind::Bar | ChartKind::BarGrouped => {
                let (y_min, y_max) = self.effective_y_range();
                let range = y_max - y_min;
                let y_tick_count = self.y_ticks.unwrap_or(5);
                // `None` means "no x ticks" (unlike `y_ticks`, which
                // defaults to 5) — an opt-in axis row, not an always-on
                // one, since a caller with no meaningful x-axis value
                // (e.g. a plain index) shouldn't have to explicitly turn
                // ticks off.
                let x_tick_count = self.x_ticks.unwrap_or(0);
                let x_ticks_height = if x_tick_count > 0 {
                    measure.line_height
                } else {
                    0.0
                };
                let x_label_height = if self.x_label.is_some() {
                    measure.line_height
                } else {
                    0.0
                };
                let legend_height = if self.show_legend && !self.series.is_empty() {
                    measure.line_height
                } else {
                    0.0
                };
                // Independent of `y_label_width` (it only subtracts the
                // x-ticks row, x-label row and legend row), so it's safe
                // to compute ahead of the gutter to know whether ticks
                // will actually be painted into it.
                let plot_h_avail =
                    (measure.height - x_ticks_height - x_label_height - legend_height).max(0.0);

                // Size the gutter from the labels that will actually be
                // painted — the interior tick values, not just the
                // endpoints. `format_tick_value` emits a decimal
                // place for any non-integral value, so an interior tick
                // like `14.4` between endpoints `0` and `18` is routinely
                // longer than either end.
                let y_label_width = if y_tick_count > 0 || self.y_label.is_some() {
                    let mut max_label_len = if y_tick_count > 0 && plot_h_avail > 0.0 && range > 0.0
                    {
                        (0..=y_tick_count)
                            .map(|i| {
                                let frac = i as f64 / y_tick_count as f64;
                                format_tick_value(y_min + frac * range).len()
                            })
                            .max()
                            .unwrap_or(0)
                    } else {
                        format_tick_value(y_max)
                            .len()
                            .max(format_tick_value(y_min).len())
                    };
                    if let Some(label) = &self.y_label {
                        max_label_len = max_label_len.max(label.len());
                    }
                    measure.char_width * (max_label_len as f32 + 1.0)
                } else {
                    0.0
                };

                let plot_x = origin_x + y_label_width;
                let plot_y = origin_y + legend_height;
                let plot_w = (measure.width - y_label_width).max(0.0);
                let plot_h = plot_h_avail;
                let plot_area = Rect::new(plot_x, plot_y, plot_w, plot_h);

                let legend_bounds = if legend_height > 0.0 {
                    Some(Rect::new(plot_x, origin_y, plot_w, legend_height))
                } else {
                    None
                };

                let mut hit_regions = Vec::new();
                if let Some(lb) = legend_bounds {
                    let entry_w = if self.series.is_empty() {
                        0.0
                    } else {
                        (plot_w / self.series.len() as f32).max(1.0)
                    };
                    for (i, _) in self.series.iter().enumerate() {
                        let ex = lb.x + entry_w * i as f32;
                        let ew = if i + 1 == self.series.len() {
                            lb.x + lb.width - ex
                        } else {
                            entry_w
                        };
                        hit_regions.push((
                            Rect::new(ex, lb.y, ew, lb.height),
                            ChartHit::Legend(self.id, i),
                        ));
                    }
                }
                hit_regions.push((plot_area, ChartHit::Body(self.id)));

                let mut data_point_positions = Vec::new();
                if self.kind.is_bar() {
                    // Bars own a slot, not a point: anchor each segment
                    // at its own rectangle so `nearest_point` resolves
                    // to the (series, index) under the cursor — which is
                    // what a stacked-segment tooltip needs.
                    let n = self.max_data_len();
                    let slot_w = if n == 0 { 0.0 } else { plot_w / n as f32 };
                    let series_count = self.series.len().max(1) as f32;
                    let stacked = self.kind.is_stacked_bar();
                    for (di, column) in self.bar_column_spans_all().into_iter().enumerate() {
                        for (si, bottom, top) in column {
                            let (sx, sy) = if stacked {
                                let mid = (bottom + top) / 2.0;
                                (
                                    plot_x + slot_w * (di as f32 + 0.5),
                                    plot_y + plot_h - mid as f32 * plot_h,
                                )
                            } else {
                                let sub_w = slot_w / series_count;
                                (
                                    plot_x + slot_w * di as f32 + sub_w * (si as f32 + 0.5),
                                    plot_y + plot_h - top as f32 * plot_h,
                                )
                            };
                            data_point_positions.push((si, di, sx, sy));
                        }
                    }
                } else {
                    for (si, s) in self.series.iter().enumerate() {
                        let n = s.data.len();
                        for (di, &val) in s.data.iter().enumerate() {
                            let norm = if range > 0.0 {
                                ((val - y_min) / range).clamp(0.0, 1.0)
                            } else {
                                0.5
                            };
                            let sx = if n <= 1 {
                                plot_x
                            } else {
                                plot_x + (di as f32 / (n - 1) as f32) * plot_w
                            };
                            let sy = plot_y + plot_h - norm as f32 * plot_h;
                            data_point_positions.push((si, di, sx, sy));
                        }
                    }
                }

                let mut y_tick_positions = Vec::new();
                if y_tick_count > 0 && plot_h > 0.0 && range > 0.0 {
                    for i in 0..=y_tick_count {
                        let frac = i as f64 / y_tick_count as f64;
                        let val = y_min + frac * range;
                        let sy = plot_y + plot_h - frac as f32 * plot_h;
                        y_tick_positions.push((sy, val));
                    }
                }

                // Honour an explicit `x_range` for tick *values*
                // (data-point x positions stay index-evenly-spaced —
                // this only changes what a tick's label reads). Without
                // one, ticks fall back to the pre-#975 behaviour of
                // labelling by data index.
                let data_len = self.max_data_len();
                let mut x_tick_positions = Vec::new();
                if x_tick_count > 0 && plot_w > 0.0 && data_len > 1 {
                    let (x_min, x_max) = self.x_range.unwrap_or((0.0, (data_len - 1) as f64));
                    let x_span = x_max - x_min;
                    for i in 0..=x_tick_count {
                        let frac = i as f64 / x_tick_count as f64;
                        let val = x_min + frac * x_span;
                        let sx = plot_x + frac as f32 * plot_w;
                        x_tick_positions.push((sx, val));
                    }
                }

                ChartLayout {
                    bounds,
                    plot_area,
                    legend_bounds,
                    hit_regions,
                    data_point_positions,
                    y_tick_positions,
                    x_tick_positions,
                }
            }
        }
    }
}

/// Format a tick value for axis labels. Uses integer format when the
/// value has no fractional part, otherwise one decimal place.
pub fn format_tick_value(v: f64) -> String {
    if (v - v.round()).abs() < 0.01 {
        format!("{}", v as i64)
    } else {
        format!("{:.1}", v)
    }
}

// ── PaintSurface paint ────
//
// `paint` below is the shared implementation for painting all chart kinds,
// written against [`crate::paint_surface::PaintSurface`] instead of any
// one backend's drawing API.
//
// Behavioural changes from the three separate backend implementations:
//
//   - **The clip.** `paint` always brackets its body in
//     `surface_push_clip(layout.bounds)` / `surface_pop_clip()`, ensuring
//     overlays (legend/crosshair/hover-marker) can't bleed past the chart's
//     bounds on any backend.
//   - **Area fill (`Series::fill`) is dropped.** `PaintSurface` has no
//     polygon-fill verb (only axis-aligned `surface_fill_rect`), so there
//     is no way to reproduce an arbitrary under-the-line fill. `Series::fill`
//     no longer paints an area on any pixel backend. TUI's own `tui::chart`
//     keeps its own fill rendering.
//   - **The sparkline's data cadence.** Data points stretch evenly across
//     the plot's full width, not windowed to the most recent `plot_area.width`
//     points. A hovered sparkline point's marker still reads its position from
//     `layout.data_point_positions` (matching the windowed cadence), so a data
//     point outside the window can show a hover marker slightly off the
//     re-stretched line.
//   - **The crosshair.** A solid line with per-series value labels,
//     approximating the 50%-alpha tint with `blend` against `theme.background`.
//   - **Axis lines.** The plot's left/bottom axis lines always stroke
//     for `ChartKind::Line` and `Bar`/`BarGrouped`.
//   - **The grid line color.** Uses `theme.separator` at full opacity
//     (the theme's own semantic "chrome line" color).
//   - **The hover marker.** A filled square approximation (since `PaintSurface`
//     has no circle verb), sized to match the GTK/Windows circle footprint
//     (radius 5 / radius 8 rings → 10×10 / 16×16 squares). The outer ring's
//     halo is CPU-blended against the live `theme.background`, not a
//     hardcoded default.
//
// `SERIES_COLORS` is an alias for the crate's one definition,
// `theme::CHART_SERIES`, and `series_color` resolves through
// [`Theme::chart_series`] — so this module and `tui::chart` can't drift
// apart on the values or the length.
//
// `#[allow(dead_code)]`: only *called* once a real pixel backend is
// compiled in, exercised by each backend's own `Backend::draw_chart` call
// site plus this module's own `RecordingSurface` tests.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
mod native_surface_paint {
    use super::{Chart, ChartKind, ChartLayout};
    use crate::paint_surface::PaintSurface;
    use crate::theme::Theme;
    use crate::types::Color;
    use crate::Rect;

    /// The crate's one series palette, accessible here under this module's
    /// historical name for the backend rasteriser tests that import it as
    /// a `const` — a `const` can't call [`Theme::chart_series`], which is
    /// what all *painting* goes through.
    pub(crate) const SERIES_COLORS: [Color; 6] = crate::theme::CHART_SERIES;

    fn series_color(chart: &Chart, idx: usize, theme: &Theme) -> Color {
        let palette = theme.chart_series();
        chart
            .series
            .get(idx)
            .and_then(|s| s.color)
            .unwrap_or(palette[idx % palette.len()])
    }

    /// Stroke a polyline through `points` as `points.len() - 1` separate
    /// segments, since `PaintSurface::surface_draw_line` only draws one
    /// segment at a time.
    fn stroke_polyline(
        surface: &mut dyn PaintSurface,
        points: &[(f32, f32)],
        color: Color,
        stroke_width: f32,
    ) {
        for pair in points.windows(2) {
            let (from, to) = (pair[0], pair[1]);
            surface.surface_draw_line(
                crate::Point::new(from.0, from.1),
                crate::Point::new(to.0, to.1),
                color,
                stroke_width,
            );
        }
    }

    /// Paint a [`Chart`] (already resolved into `layout`) onto `surface`.
    /// See this module's doc for the divergences resolved while
    /// unifying three per-backend copies into this one.
    ///
    /// `layout` must be the same [`ChartLayout`] the caller uses for
    /// hit-testing/hover resolution — mirrors `primitives::form::paint`'s
    /// contract of reading geometry only from the caller-supplied
    /// layout, never recomputing it.
    pub(crate) fn paint(
        chart: &Chart,
        layout: &ChartLayout,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    ) {
        let b = layout.bounds;
        if b.width <= 0.0 || b.height <= 0.0 {
            return;
        }

        // Clip to the chart's own rect — see this
        // module's doc for why Windows didn't have this before.
        surface.surface_push_clip(b);

        match chart.kind {
            ChartKind::Sparkline => paint_sparkline(surface, layout, chart, theme),
            ChartKind::Line => paint_line(surface, layout, chart, theme),
            ChartKind::Bar | ChartKind::BarGrouped => paint_bar(surface, layout, chart, theme),
        }

        if let Some(data_x) = crosshair_x {
            paint_crosshair(surface, layout, chart, theme, data_x);
        }
        if let Some((si, di)) = hovered_point {
            paint_hover_marker(surface, layout, si, di, chart, theme);
        }

        surface.surface_pop_clip();
    }

    fn paint_sparkline(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
    ) {
        let pa = layout.plot_area;
        surface.surface_fill_rect(pa, theme.background);

        let Some(s) = chart.series.first() else {
            return;
        };
        if s.data.is_empty() || pa.width <= 0.0 || pa.height <= 0.0 {
            return;
        }
        let (y_min, y_max) = chart.effective_y_range();
        let range = y_max - y_min;
        let color = series_color(chart, 0, theme);
        let n = s.data.len();
        let points: Vec<(f32, f32)> = s
            .data
            .iter()
            .enumerate()
            .map(|(i, &val)| {
                let norm = if range > 0.0 {
                    ((val - y_min) / range).clamp(0.0, 1.0)
                } else {
                    0.5
                };
                let sx = pa.x
                    + if n <= 1 {
                        0.0
                    } else {
                        (i as f32 / (n - 1) as f32) * pa.width
                    };
                let sy = pa.y + pa.height - norm as f32 * pa.height;
                (sx, sy)
            })
            .collect();
        stroke_polyline(surface, &points, color, 1.5);
    }

    fn paint_line(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
    ) {
        let pa = layout.plot_area;
        surface.surface_fill_rect(pa, theme.background);
        if pa.width <= 0.0 || pa.height <= 0.0 {
            return;
        }

        // Axes.
        surface.surface_draw_line(
            crate::Point::new(pa.x, pa.y),
            crate::Point::new(pa.x, pa.y + pa.height),
            theme.muted_fg,
            1.0,
        );
        surface.surface_draw_line(
            crate::Point::new(pa.x, pa.y + pa.height),
            crate::Point::new(pa.x + pa.width, pa.y + pa.height),
            theme.muted_fg,
            1.0,
        );

        for (si, s) in chart.series.iter().enumerate() {
            if s.data.is_empty() {
                continue;
            }
            let color = series_color(chart, si, theme);
            let points: Vec<(f32, f32)> = layout
                .data_point_positions
                .iter()
                .filter_map(|&(pt_si, _, x, y)| if pt_si == si { Some((x, y)) } else { None })
                .collect();
            stroke_polyline(surface, &points, color, 2.0);
        }

        paint_legend(surface, layout, chart, theme);
        paint_axis_labels(surface, layout, chart, theme);
    }

    fn paint_bar(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
    ) {
        let pa = layout.plot_area;
        surface.surface_fill_rect(pa, theme.background);
        if pa.width <= 0.0 || pa.height <= 0.0 {
            return;
        }

        let n = chart.max_data_len();
        if n > 0 {
            let slot_w = pa.width / n as f32;
            let gap = (slot_w * 0.15).max(1.0);
            let bar_w = (slot_w - gap).max(1.0);
            let stacked = chart.kind.is_stacked_bar();
            let series_count = chart.series.len().max(1) as f32;
            let baseline = pa.y + pa.height;

            for (i, column) in chart.bar_column_spans_all().into_iter().enumerate() {
                let slot_x = pa.x + i as f32 * slot_w + gap / 2.0;
                for (si, bottom, top) in column {
                    let (bx, seg_w) = if stacked {
                        (slot_x, bar_w)
                    } else {
                        let sub_w = (bar_w / series_count).max(1.0);
                        (slot_x + si as f32 * sub_w, sub_w)
                    };
                    let seg_h = (top - bottom) as f32 * pa.height;
                    if seg_h <= 0.0 {
                        continue;
                    }
                    let by = baseline - top as f32 * pa.height;
                    surface.surface_fill_rect(
                        Rect::new(bx, by, seg_w, seg_h),
                        series_color(chart, si, theme),
                    );
                }
            }

            surface.surface_draw_line(
                crate::Point::new(pa.x, baseline),
                crate::Point::new(pa.x + pa.width, baseline),
                theme.muted_fg,
                1.0,
            );
        }

        paint_legend(surface, layout, chart, theme);
        paint_axis_labels(surface, layout, chart, theme);
    }

    fn paint_legend(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
    ) {
        let Some(lb) = layout.legend_bounds else {
            return;
        };
        surface.surface_fill_rect(lb, theme.background);

        let mut cx = lb.x + 2.0;
        for (i, s) in chart.series.iter().enumerate() {
            let color = series_color(chart, i, theme);
            let swatch = lb.height * 0.6;
            let sy = lb.y + (lb.height - swatch) / 2.0;
            surface.surface_fill_rect(Rect::new(cx, sy, swatch, swatch), color);
            cx += swatch + 4.0;

            let (tw, th) = surface.surface_measure_text(&s.label);
            surface.surface_draw_text_run(
                Rect::new(cx, lb.y, tw, th.max(lb.height)),
                &s.label,
                theme.foreground,
            );
            cx += tw + 12.0;
        }
    }

    fn paint_axis_labels(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
    ) {
        let pa = layout.plot_area;

        for &(sy, val) in &layout.y_tick_positions {
            let label = super::format_tick_value(val);
            let (tw, th) = surface.surface_measure_text(&label);
            surface.surface_draw_text_run(
                Rect::new(pa.x - tw - 4.0, sy - th / 2.0, tw, th),
                &label,
                theme.muted_fg,
            );

            if chart.show_grid && sy > pa.y && sy < pa.y + pa.height {
                surface.surface_draw_line(
                    crate::Point::new(pa.x, sy),
                    crate::Point::new(pa.x + pa.width, sy),
                    theme.separator,
                    0.5,
                );
            }
        }

        // X-axis ticks: centred under each tick's screen x but
        // clamped to stay inside the chart's own bounds — a tick at
        // `frac == 1.0` sits exactly on the bounds' right edge, and a
        // naive centred label there would always spill past it. A
        // label that still collides with the previous (already-clamped)
        // one is dropped rather than painted overlapping. `layout` only
        // ever populates `x_tick_positions` when `chart.x_ticks` is
        // `Some(n > 0)` (see `Chart::layout`), which is exactly the
        // condition that reserved this row's height, so the two stay in
        // sync without re-deriving it here.
        let bounds = layout.bounds;
        let x_ticks_height = if !layout.x_tick_positions.is_empty() {
            surface.surface_line_height()
        } else {
            0.0
        };
        let mut prev_label_end: Option<f32> = None;
        for &(sx, val) in &layout.x_tick_positions {
            let label = super::format_tick_value(val);
            let (tw, th) = surface.surface_measure_text(&label);
            if tw > bounds.width {
                continue;
            }
            let max_x = bounds.x + bounds.width - tw;
            let lx = (sx - tw / 2.0).clamp(bounds.x, max_x);
            if let Some(prev_end) = prev_label_end {
                if lx < prev_end + 4.0 {
                    continue;
                }
            }
            surface.surface_draw_text_run(
                Rect::new(lx, pa.y + pa.height, tw, th),
                &label,
                theme.muted_fg,
            );
            prev_label_end = Some(lx + tw);
        }

        if let Some(label) = &chart.x_label {
            let (tw, th) = surface.surface_measure_text(label);
            let cx = pa.x + (pa.width - tw) / 2.0;
            let cy = pa.y + pa.height + x_ticks_height;
            surface.surface_draw_text_run(Rect::new(cx, cy, tw, th), label, theme.foreground);
        }

        if let Some(label) = &chart.y_label {
            let (tw, th) = surface.surface_measure_text(label);
            surface.surface_draw_text_run(
                Rect::new(layout.bounds.x, pa.y, tw, th),
                label,
                theme.foreground,
            );
        }
    }

    fn paint_crosshair(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        chart: &Chart,
        theme: &Theme,
        data_x: f64,
    ) {
        let data_len = chart.max_data_len();
        let screen_x = layout.data_to_screen_x(data_x, data_len);
        let pa = layout.plot_area;
        if screen_x <= pa.x || screen_x >= pa.x + pa.width {
            return;
        }

        let line_color = theme.background.blend(theme.muted_fg, 0.5);
        surface.surface_draw_line(
            crate::Point::new(screen_x, pa.y),
            crate::Point::new(screen_x, pa.y + pa.height),
            line_color,
            1.0,
        );

        let (y_min, y_max) = chart.effective_y_range();
        let range = y_max - y_min;
        for (si, s) in chart.series.iter().enumerate() {
            if s.data.is_empty() {
                continue;
            }
            let idx = data_x.round() as usize;
            let Some(&val) = s.data.get(idx) else {
                continue;
            };
            let label = super::format_tick_value(val);
            let color = series_color(chart, si, theme);
            let norm = if range > 0.0 {
                ((val - y_min) / range).clamp(0.0, 1.0)
            } else {
                0.5
            };
            let sy = pa.y + pa.height - norm as f32 * pa.height;
            let (tw, th) = surface.surface_measure_text(&label);
            surface.surface_draw_text_run(
                Rect::new(screen_x + 4.0, sy - 8.0, tw, th),
                &label,
                color,
            );
        }
    }

    fn paint_hover_marker(
        surface: &mut dyn PaintSurface,
        layout: &ChartLayout,
        series_idx: usize,
        data_idx: usize,
        chart: &Chart,
        theme: &Theme,
    ) {
        let Some(&(_, _, sx, sy)) = layout
            .data_point_positions
            .iter()
            .find(|&&(si, di, _, _)| si == series_idx && di == data_idx)
        else {
            return;
        };
        let color = series_color(chart, series_idx, theme);
        let inner = 5.0_f32;
        surface.surface_fill_rect(
            Rect::new(sx - inner, sy - inner, inner * 2.0, inner * 2.0),
            color,
        );
        let outer_color = theme.background.blend(color, 0.3);
        let outer = 8.0_f32;
        surface.surface_fill_rect(
            Rect::new(sx - outer, sy - outer, outer * 2.0, outer * 2.0),
            outer_color,
        );
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::chart::Series;
        use crate::types::WidgetId;
        use crate::Image;

        /// Records every drawing verb `paint` issues, so a paint
        /// assertion can run on any host — no Cairo, Core Graphics or
        /// Direct2D needed. Mirrors `primitives::find_replace`'s own
        /// `RecordingSurface`: the pixel backends' real
        /// `ImageSurface`/`BitmapSurface`/`HeadlessSurface` driver tests
        /// still cover "the verb reached real pixels"; this covers "the
        /// shared painter emits the right verb at all", on every leg of
        /// the quality gate that enables gtk, win, or macos.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            lines: Vec<(crate::Point, crate::Point, Color, f32)>,
            texts: Vec<(Rect, String, Color)>,
            clip_pushes: Vec<Rect>,
            clip_pops: usize,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(200.0, 100.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 14.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// Test-only recorder — `paint` never calls this verb
            /// (see this module's own doc for why no primitive here has been
            /// migrated onto it yet); this exists only so `RecordingSurface`
            /// satisfies the trait. Records into the same `fills` list as
            /// `surface_fill_rect` (radius dropped) — no test asserts on it
            /// today.
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, _rect: Rect, _color: Color, _stroke_width: f32) {}
            fn surface_stroke_rounded_rect(
                &mut self,
                _rect: Rect,
                _radius: f32,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.texts.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                from: crate::Point,
                to: crate::Point,
                color: Color,
                stroke_width: f32,
            ) {
                self.lines.push((from, to, color, stroke_width));
            }
            fn surface_push_clip(&mut self, rect: Rect) {
                self.clip_pushes.push(rect);
            }
            fn surface_pop_clip(&mut self) {
                self.clip_pops += 1;
            }
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn line_chart(data: Vec<f64>) -> Chart {
            Chart {
                id: WidgetId::new("chart"),
                kind: ChartKind::Line,
                series: vec![Series {
                    label: "a".into(),
                    data,
                    color: None,
                    fill: false,
                }],
                x_label: None,
                y_label: None,
                y_range: None,
                x_range: None,
                show_legend: false,
                y_ticks: Some(0),
                x_ticks: Some(0),
                show_grid: false,
            }
        }

        fn layout_for(chart: &Chart) -> ChartLayout {
            chart.layout(
                0.0,
                0.0,
                crate::primitives::chart::ChartMeasure {
                    width: 100.0,
                    height: 50.0,
                    char_width: 8.0,
                    line_height: 16.0,
                },
            )
        }

        /// Regression: every pixel backend must clip a chart's paint to its
        /// own bounds.
        #[test]
        fn paint_clips_to_the_charts_own_bounds() {
            let chart = line_chart(vec![1.0, 2.0, 3.0]);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            assert_eq!(
                surface.clip_pushes,
                vec![layout.bounds],
                "paint must push exactly one clip, at the chart's own bounds"
            );
            assert_eq!(
                surface.clip_pops, 1,
                "every surface_push_clip must be balanced by surface_pop_clip"
            );
        }

        #[test]
        fn zero_size_chart_paints_nothing_and_never_clips() {
            let chart = line_chart(vec![1.0, 2.0]);
            let layout = ChartLayout {
                bounds: Rect::new(0.0, 0.0, 0.0, 0.0),
                plot_area: Rect::new(0.0, 0.0, 0.0, 0.0),
                legend_bounds: None,
                hit_regions: Vec::new(),
                data_point_positions: Vec::new(),
                y_tick_positions: Vec::new(),
                x_tick_positions: Vec::new(),
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            assert!(surface.clip_pushes.is_empty());
            assert_eq!(surface.clip_pops, 0);
            assert!(surface.fills.is_empty());
        }

        fn line_chart_with_x_ticks(
            data: Vec<f64>,
            x_range: Option<(f64, f64)>,
            x_ticks: usize,
        ) -> Chart {
            Chart {
                id: WidgetId::new("chart"),
                kind: ChartKind::Line,
                series: vec![Series {
                    label: "a".into(),
                    data,
                    color: None,
                    fill: false,
                }],
                x_label: None,
                y_label: None,
                y_range: None,
                x_range,
                show_legend: false,
                y_ticks: Some(0),
                x_ticks: Some(x_ticks),
                show_grid: false,
            }
        }

        /// Pixel backends (GTK/win/macOS) share this `paint_axis_labels`, so
        /// a fix here covers all three at once.
        #[test]
        fn x_axis_ticks_paint_text_runs_with_their_values() {
            let chart = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0], None, 1);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            let labels: Vec<&str> = surface.texts.iter().map(|(_, t, _)| t.as_str()).collect();
            assert!(
                labels.contains(&"0") && labels.contains(&"2"),
                "expected x-tick labels for data indices 0 and 2, got {labels:?}"
            );
        }

        /// An explicit `x_range` drives tick *values*, not the data index.
        #[test]
        fn x_axis_tick_values_honour_x_range() {
            let chart = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0], Some((100.0, 300.0)), 1);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            let labels: Vec<&str> = surface.texts.iter().map(|(_, t, _)| t.as_str()).collect();
            assert!(
                labels.contains(&"100") && labels.contains(&"300"),
                "expected x_range-derived labels, got {labels:?}"
            );
            assert!(
                !labels.contains(&"0") && !labels.contains(&"2"),
                "index-based labels should not appear once x_range is set: {labels:?}"
            );
        }

        #[test]
        fn line_series_paints_with_its_resolved_color() {
            let chart = line_chart(vec![1.0, 4.0, 2.0]);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            assert!(
                surface
                    .lines
                    .iter()
                    .any(|&(_, _, c, _)| c == SERIES_COLORS[0]),
                "expected at least one line segment in the series' resolved colour, got {:?}",
                surface.lines,
            );
        }

        /// Builds an n-series line chart where no series sets its own
        /// `color`, so every one of them falls through to the theme
        /// palette.
        fn uncoloured_multi_series_chart(n: usize) -> Chart {
            Chart {
                id: WidgetId::new("chart"),
                kind: ChartKind::Line,
                series: (0..n)
                    .map(|i| Series {
                        label: format!("s{i}"),
                        data: vec![1.0, 4.0, 2.0],
                        color: None,
                        fill: false,
                    })
                    .collect(),
                x_label: None,
                y_label: None,
                y_range: None,
                x_range: None,
                show_legend: false,
                y_ticks: Some(0),
                x_ticks: Some(0),
                show_grid: false,
            }
        }

        /// A series with no explicit `color` resolves through
        /// [`Theme::chart_series`], and more series than the palette has
        /// entries cycles back through it (`idx % 6`) rather than
        /// panicking or inventing an off-palette colour.
        #[test]
        fn uncoloured_series_cycle_through_the_themes_chart_series_palette() {
            let chart = uncoloured_multi_series_chart(8);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let palette = theme.chart_series();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            // `surface.lines` also carries chrome (axes, grid) painted
            // in theme colours that aren't series colours, so assert on
            // palette coverage rather than on every recorded line.
            let painted: Vec<Color> = surface.lines.iter().map(|&(_, _, c, _)| c).collect();
            assert!(
                !painted.is_empty(),
                "fixture painted no line segments at all"
            );
            for expected in &palette {
                assert!(
                    painted.contains(expected),
                    "8 uncoloured series should cover all 6 palette entries; {expected:?} never appeared in {painted:?}",
                );
            }
        }

        /// A `Series` that *does* set its own `color` keeps it — the
        /// theme palette is only the fallback for series that don't
        #[test]
        fn explicit_series_color_wins_over_the_theme_palette() {
            let mut chart = uncoloured_multi_series_chart(1);
            let custom = Color::rgb(1, 2, 3);
            assert!(
                !Theme::default().chart_series().contains(&custom),
                "test fixture invalid: custom colour must not be in the palette"
            );
            chart.series[0].color = Some(custom);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, None, None);

            assert!(
                surface.lines.iter().any(|&(_, _, c, _)| c == custom),
                "expected the line to paint with the series' own colour, got {:?}",
                surface.lines,
            );
            assert!(
                surface
                    .lines
                    .iter()
                    .all(|&(_, _, c, _)| c != theme.chart_series()[0]),
                "palette entry 0 must not be used once the series sets its own colour, got {:?}",
                surface.lines,
            );
        }

        #[test]
        fn hover_marker_paints_two_nested_fills_at_the_data_point() {
            let chart = line_chart(vec![1.0, 4.0, 2.0]);
            let layout = layout_for(&chart);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, Some((0, 1)), None);

            let (_, _, sx, sy) = layout.data_point_positions[1];
            // Filter to small, marker-sized fills (<= the 16x16 outer
            // ring) centred on the data point — excludes the much
            // larger plot-area background fill, which also covers this
            // point.
            let fills_at_point = surface
                .fills
                .iter()
                .filter(|(r, _)| {
                    r.width <= 16.0
                        && r.height <= 16.0
                        && r.x <= sx
                        && sx <= r.x + r.width
                        && r.y <= sy
                        && sy <= r.y + r.height
                })
                .count();
            assert_eq!(
                fills_at_point, 2,
                "hover marker should paint two nested fills (inner + outer ring) centred on the data point"
            );
        }

        /// Regression: the hover marker's outer-ring halo must blend against
        /// the *live* `theme.background` passed into `paint`, not a hardcoded
        /// default. Uses a theme whose background differs sharply from
        /// `Theme::default()`'s dark palette to verify the blend tracks the
        /// live theme.
        #[test]
        fn hover_marker_outer_ring_blends_against_the_live_theme_background() {
            let chart = line_chart(vec![1.0, 4.0, 2.0]);
            let layout = layout_for(&chart);
            let light_background = Color::rgb(240, 240, 240);
            let theme = Theme {
                background: light_background,
                ..Theme::default()
            };
            let mut surface = RecordingSurface::default();

            paint(&chart, &layout, &mut surface, &theme, Some((0, 1)), None);

            let (_, _, sx, sy) = layout.data_point_positions[1];
            let series_color = SERIES_COLORS[0];
            let expected_outer = light_background.blend(series_color, 0.3);
            let wrong_outer_from_default_theme =
                Theme::default().background.blend(series_color, 0.3);
            assert_ne!(
                expected_outer, wrong_outer_from_default_theme,
                "test fixture invalid: light and default-theme backgrounds must blend to different colours"
            );

            let outer_ring_fill = surface
                .fills
                .iter()
                .filter(|(r, _)| {
                    r.width <= 16.0
                        && r.height <= 16.0
                        && r.width > 10.0
                        && r.x <= sx
                        && sx <= r.x + r.width
                        && r.y <= sy
                        && sy <= r.y + r.height
                })
                .map(|(_, c)| *c)
                .next();
            assert_eq!(
                outer_ring_fill,
                Some(expected_outer),
                "outer ring should blend the series colour against the live theme's background, not Theme::default()'s"
            );
        }
    }
}

#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(unused_imports)]
pub(crate) use native_surface_paint::{paint, SERIES_COLORS};

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

    fn sparkline_chart(data: Vec<f64>) -> Chart {
        Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Sparkline,
            series: vec![Series {
                label: String::new(),
                data,
                color: None,
                fill: false,
            }],
            x_label: None,
            y_label: None,
            y_range: None,
            x_range: None,
            show_legend: false,
            y_ticks: None,
            x_ticks: None,
            show_grid: false,
        }
    }

    fn line_chart(data: Vec<f64>) -> Chart {
        Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Line,
            series: vec![Series {
                label: "Series A".into(),
                data,
                color: None,
                fill: false,
            }],
            x_label: Some("Time".into()),
            y_label: Some("Value".into()),
            y_range: None,
            x_range: None,
            show_legend: true,
            y_ticks: None,
            x_ticks: None,
            show_grid: false,
        }
    }

    #[test]
    fn sparkline_layout_fills_bounds() {
        let chart = sparkline_chart(vec![1.0, 2.0, 3.0]);
        let m = ChartMeasure {
            width: 20.0,
            height: 1.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        assert_eq!(layout.plot_area, layout.bounds);
        assert!(layout.legend_bounds.is_none());
    }

    #[test]
    fn sparkline_hit_test_body() {
        let chart = sparkline_chart(vec![1.0, 2.0]);
        let m = ChartMeasure {
            width: 10.0,
            height: 1.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        assert_eq!(
            layout.hit_test(5.0, 0.5),
            ChartHit::Body(WidgetId::new("chart"))
        );
        assert_eq!(layout.hit_test(15.0, 0.5), ChartHit::Empty);
    }

    #[test]
    fn line_layout_subtracts_axes_and_legend() {
        let chart = line_chart(vec![1.0, 2.0, 3.0]);
        let m = ChartMeasure {
            width: 40.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        assert!(layout.plot_area.x > 0.0, "y-label shifts plot right");
        assert!(
            layout.plot_area.height < 20.0,
            "x-label + legend reduce height"
        );
        assert!(layout.legend_bounds.is_some());
    }

    // ── Y-axis gutter sizing ─────────────────────────────────────────────

    /// A `Line` chart with an explicit y-range/tick-count and no legend or
    /// x-label, for exercising gutter sizing in isolation.
    fn line_chart_with_ticks(y_range: (f64, f64), y_ticks: usize) -> Chart {
        Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Line,
            series: vec![Series {
                label: "S".into(),
                data: vec![1.0, 2.0],
                color: None,
                fill: false,
            }],
            x_label: None,
            y_label: None,
            y_range: Some(y_range),
            x_range: None,
            show_legend: false,
            y_ticks: Some(y_ticks),
            x_ticks: None,
            show_grid: false,
        }
    }

    #[test]
    fn y_gutter_sizes_from_interior_tick_labels_not_just_endpoints() {
        // 0..18 over 5 ticks: the interior ticks format as "3.6", "7.2",
        // "10.8", "14.4" — 4 characters, longer than either endpoint
        // ("0"/"18", 1-2 chars). Pre-fix the gutter was sized from the
        // endpoints alone and the interior labels spilled outside the
        // chart's own bounds.
        let chart = line_chart_with_ticks((0.0, 18.0), 5);
        let m = ChartMeasure {
            width: 40.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let bounds_x = 2.0;
        let layout = chart.layout(bounds_x, 0.0, m);
        assert!(
            layout.plot_area.x - bounds_x >= 5.0,
            "gutter should reserve the 4-char interior label + 1 padding: \
             plot_area.x={}, bounds.x={bounds_x}",
            layout.plot_area.x
        );
    }

    #[test]
    fn y_label_longer_than_tick_labels_widens_the_gutter() {
        // A `y_label` longer than the widest tick label must not be
        // silently truncated: the gutter has to widen to fit it too.
        let mut chart = line_chart_with_ticks((0.0, 18.0), 5);
        let long_label = "Merges per bucket"; // 18 chars vs. "14.4"'s 4.
        chart.y_label = Some(long_label.into());
        let m = ChartMeasure {
            width: 60.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        let expected_min = long_label.len() as f32 + 1.0;
        assert!(
            layout.plot_area.x >= expected_min,
            "gutter should widen to fit the y_label in full: \
             plot_area.x={}, expected >= {expected_min}",
            layout.plot_area.x
        );
    }

    // ── X-axis ticks ─────────────────────────────────────────────────────

    /// A `Line` chart with x-ticks enabled and no y-gutter, for exercising
    /// x-tick geometry and value resolution in isolation.
    fn line_chart_with_x_ticks(
        data: Vec<f64>,
        x_range: Option<(f64, f64)>,
        x_ticks: usize,
    ) -> Chart {
        Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Line,
            series: vec![Series {
                label: "S".into(),
                data,
                color: None,
                fill: false,
            }],
            x_label: None,
            y_label: None,
            y_range: None,
            x_range,
            show_legend: false,
            y_ticks: Some(0),
            x_ticks: Some(x_ticks),
            show_grid: false,
        }
    }

    #[test]
    fn x_ticks_default_to_data_index_when_x_range_is_none() {
        let chart = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0, 4.0, 5.0], None, 2);
        let m = ChartMeasure {
            width: 30.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        let values: Vec<f64> = layout.x_tick_positions.iter().map(|&(_, v)| v).collect();
        // 3 ticks (fracs 0, 0.5, 1) over 5 points (index range 0..4).
        assert_eq!(values, vec![0.0, 2.0, 4.0]);
    }

    #[test]
    fn x_ticks_use_x_range_when_set() {
        let chart = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0], Some((100.0, 300.0)), 1);
        let m = ChartMeasure {
            width: 30.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        let values: Vec<f64> = layout.x_tick_positions.iter().map(|&(_, v)| v).collect();
        assert_eq!(
            values,
            vec![100.0, 300.0],
            "x_range must drive tick values instead of the data index"
        );
    }

    #[test]
    fn x_ticks_are_empty_when_x_ticks_field_is_none() {
        // `x_ticks: None` means no x-tick row at all (unlike `y_ticks`,
        // which defaults to 5).
        let mut chart = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0], None, 0);
        chart.x_ticks = None;
        let m = ChartMeasure {
            width: 30.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        assert!(layout.x_tick_positions.is_empty());
    }

    #[test]
    fn x_ticks_reserve_a_plot_height_row_when_enabled() {
        let with_ticks = line_chart_with_x_ticks(vec![1.0, 2.0, 3.0], None, 2);
        let mut without_ticks = with_ticks.clone();
        without_ticks.x_ticks = None;
        let m = ChartMeasure {
            width: 30.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout_with = with_ticks.layout(0.0, 0.0, m);
        let layout_without = without_ticks.layout(0.0, 0.0, m);
        assert_eq!(
            layout_without.plot_area.height - layout_with.plot_area.height,
            m.line_height,
            "enabling x_ticks should shrink the plot by exactly one tick row"
        );
    }

    #[test]
    fn line_legend_hit_test() {
        let mut chart = line_chart(vec![1.0, 2.0]);
        chart.series.push(Series {
            label: "Series B".into(),
            data: vec![3.0, 4.0],
            color: None,
            fill: false,
        });
        let m = ChartMeasure {
            width: 40.0,
            height: 20.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        let lb = layout.legend_bounds.unwrap();
        let mid_x = lb.x + lb.width / 4.0;
        assert_eq!(
            layout.hit_test(mid_x, lb.y + 0.5),
            ChartHit::Legend(WidgetId::new("chart"), 0)
        );
        let mid_x2 = lb.x + lb.width * 3.0 / 4.0;
        assert_eq!(
            layout.hit_test(mid_x2, lb.y + 0.5),
            ChartHit::Legend(WidgetId::new("chart"), 1)
        );
    }

    #[test]
    fn effective_y_range_auto() {
        let chart = sparkline_chart(vec![2.0, 5.0, 3.0]);
        assert_eq!(chart.effective_y_range(), (2.0, 5.0));
    }

    #[test]
    fn effective_y_range_explicit() {
        let mut chart = sparkline_chart(vec![2.0, 5.0]);
        chart.y_range = Some((0.0, 10.0));
        assert_eq!(chart.effective_y_range(), (0.0, 10.0));
    }

    #[test]
    fn effective_y_range_empty() {
        let chart = sparkline_chart(vec![]);
        assert_eq!(chart.effective_y_range(), (0.0, 1.0));
    }

    #[test]
    fn effective_y_range_flat() {
        let chart = sparkline_chart(vec![5.0, 5.0, 5.0]);
        let (lo, hi) = chart.effective_y_range();
        assert!(lo < 5.0 && hi > 5.0);
    }

    // ── Multi-series bars ───────────────────────────────────────────────

    fn bar_chart(kind: ChartKind, data: Vec<Vec<f64>>) -> Chart {
        Chart {
            id: WidgetId::new("chart"),
            kind,
            series: data
                .into_iter()
                .enumerate()
                .map(|(i, d)| Series {
                    label: format!("S{i}"),
                    data: d,
                    color: None,
                    fill: false,
                })
                .collect(),
            x_label: None,
            y_label: None,
            y_range: None,
            x_range: None,
            show_legend: false,
            y_ticks: None,
            x_ticks: None,
            show_grid: false,
        }
    }

    #[test]
    fn stacked_bar_y_ceiling_is_max_column_total() {
        let chart = bar_chart(
            ChartKind::Bar,
            vec![vec![1.0, 5.0], vec![2.0, 1.0], vec![3.0, 0.0]],
        );
        // Column totals are 6 and 6; the max single value is 5.
        assert_eq!(chart.column_totals(), vec![6.0, 6.0]);
        assert_eq!(chart.effective_y_range(), (0.0, 6.0));
    }

    #[test]
    fn grouped_bar_y_ceiling_is_max_single_value() {
        let chart = bar_chart(
            ChartKind::BarGrouped,
            vec![vec![1.0, 5.0], vec![2.0, 1.0], vec![3.0, 0.0]],
        );
        assert_eq!(chart.effective_y_range(), (0.0, 5.0));
    }

    #[test]
    fn single_series_bar_y_range_is_unchanged_by_stacking() {
        // One series' column totals are the data itself, so the auto-range
        // doesn't move.
        let chart = bar_chart(ChartKind::Bar, vec![vec![2.0, 5.0, 3.0]]);
        assert_eq!(chart.effective_y_range(), (2.0, 5.0));
    }

    #[test]
    fn stacked_bar_floor_anchors_at_zero_when_min_value_is_nonzero() {
        // Two series, one point each, neither containing a literal 0.0
        // anywhere. The auto-derived floor must still be 0.0 (not 5.0, the
        // smallest raw value in the chart) or the segments render
        // out-of-proportion to their true values.
        let chart = bar_chart(ChartKind::Bar, vec![vec![10.0], vec![5.0]]);
        assert_eq!(chart.effective_y_range(), (0.0, 15.0));

        let spans = chart.bar_column_spans(0);
        // A = 10 of 15 total → 2/3 of the stack; B = 5 of 15 → 1/3.
        // Pre-fix this rendered as an exact 50/50 split instead.
        assert!((spans[0].1 - 0.0).abs() < 1e-9);
        assert!((spans[0].2 - 2.0 / 3.0).abs() < 1e-9, "A span: {spans:?}");
        assert!((spans[1].1 - 2.0 / 3.0).abs() < 1e-9);
        assert!((spans[1].2 - 1.0).abs() < 1e-9, "B span: {spans:?}");
    }

    #[test]
    fn stacked_bar_floor_tracks_negative_partial_sums_not_just_totals() {
        // A column total alone can hide a dip below zero mid-stack:
        // 10 + (-15) + 20 sums to 15, but the running sum touches -5
        // partway through. The floor must cover that dip.
        let chart = bar_chart(ChartKind::Bar, vec![vec![10.0], vec![-15.0], vec![20.0]]);
        assert_eq!(chart.effective_y_range(), (-5.0, 15.0));
    }

    #[test]
    fn bar_column_spans_baseline_tracks_a_nonzero_explicit_floor() {
        // With an explicit y_range whose floor isn't 0.0, the stack's
        // baseline (where the bottom segment starts) must track
        // wherever zero maps to under that range, not the plot's
        // literal bottom edge.
        let mut chart = bar_chart(ChartKind::Bar, vec![vec![10.0], vec![10.0]]);
        chart.y_range = Some((-10.0, 30.0));
        let spans = chart.bar_column_spans(0);
        // norm(0.0) = (0 - -10) / 40 = 0.25.
        assert!((spans[0].1 - 0.25).abs() < 1e-9, "spans: {spans:?}");
    }

    #[test]
    fn single_series_bar_spans_rise_from_the_plot_floor_for_negative_data() {
        // A single-series chart keeps the plain min/max auto-range, where
        // 0.0 sits outside the data. Here the range is (-5, -1), so `norm(0.0)`
        // clamps to 1.0 and every bar would collapse to zero height.
        let chart = bar_chart(ChartKind::Bar, vec![vec![-5.0, -3.0, -1.0]]);
        assert_eq!(chart.effective_y_range(), (-5.0, -1.0));
        for (di, expected_top) in [0.0, 0.5, 1.0].into_iter().enumerate() {
            let spans = chart.bar_column_spans(di);
            assert_eq!(spans.len(), 1);
            assert!((spans[0].1 - 0.0).abs() < 1e-9, "col {di}: {spans:?}");
            assert!(
                (spans[0].2 - expected_top).abs() < 1e-9,
                "col {di}: {spans:?}"
            );
        }
    }

    #[test]
    fn single_series_bar_spans_are_unshifted_for_mixed_sign_data() {
        // Same root cause, milder symptom: with range (-2, 3) the old
        // `norm(0.0)` baseline of 0.4 made the tallest bar span
        // 40%–100% instead of the full plot height.
        let chart = bar_chart(ChartKind::Bar, vec![vec![-2.0, 3.0]]);
        assert_eq!(chart.effective_y_range(), (-2.0, 3.0));
        assert_eq!(chart.bar_column_spans(0), vec![(0, 0.0, 0.0)]);
        assert_eq!(chart.bar_column_spans(1), vec![(0, 0.0, 1.0)]);
    }

    #[test]
    fn stacked_spans_stay_visible_when_an_explicit_range_excludes_zero() {
        // Zero is above the whole range, so the stack's baseline clamps to the
        // plot ceiling and the segments hang below it. Deriving each segment from
        // consecutive cumulative levels keeps them visible.
        let mut chart = bar_chart(ChartKind::Bar, vec![vec![-3.0], vec![-4.0]]);
        chart.y_range = Some((-10.0, -2.0));
        let spans = chart.bar_column_spans(0);
        // -3 maps to 0.875 and -7 to 0.375 over the 8-unit range.
        assert!((spans[0].1 - 0.875).abs() < 1e-9, "spans: {spans:?}");
        assert!((spans[0].2 - 1.0).abs() < 1e-9, "spans: {spans:?}");
        assert!((spans[1].1 - 0.375).abs() < 1e-9, "spans: {spans:?}");
        assert!((spans[1].2 - 0.875).abs() < 1e-9, "spans: {spans:?}");
        assert!(spans.iter().all(|(_, b, t)| t > b), "spans: {spans:?}");
    }

    #[test]
    fn stacked_span_of_a_negative_series_walks_the_stack_back_down() {
        // 10 then -15 then +20 over the auto range (-5, 15): the middle
        // series' segment spans downward from 10 to -5 and is still
        // returned bottom-first.
        let chart = bar_chart(ChartKind::Bar, vec![vec![10.0], vec![-15.0], vec![20.0]]);
        assert_eq!(chart.effective_y_range(), (-5.0, 15.0));
        let spans = chart.bar_column_spans(0);
        assert_eq!(
            spans,
            vec![(0, 0.25, 0.75), (1, 0.0, 0.75), (2, 0.0, 1.0)],
            "spans: {spans:?}"
        );
    }

    #[test]
    fn stacked_spans_accumulate_bottom_up() {
        let mut chart = bar_chart(ChartKind::Bar, vec![vec![1.0], vec![1.0], vec![1.0]]);
        chart.y_range = Some((0.0, 3.0));
        let spans = chart.bar_column_spans(0);
        assert_eq!(spans.len(), 3);
        assert!((spans[0].1 - 0.0).abs() < 1e-9 && (spans[0].2 - 1.0 / 3.0).abs() < 1e-9);
        assert!((spans[1].1 - 1.0 / 3.0).abs() < 1e-9 && (spans[1].2 - 2.0 / 3.0).abs() < 1e-9);
        assert!((spans[2].1 - 2.0 / 3.0).abs() < 1e-9 && (spans[2].2 - 1.0).abs() < 1e-9);
    }

    #[test]
    fn stacked_all_zero_series_does_not_shift_the_others() {
        let mut with_zeros = bar_chart(
            ChartKind::Bar,
            vec![vec![1.0], vec![0.0], vec![1.0], vec![0.0]],
        );
        with_zeros.y_range = Some((0.0, 2.0));
        let spans = with_zeros.bar_column_spans(0);
        // The zero series occupies an empty span at the boundary…
        assert_eq!((spans[1].1, spans[1].2), (0.5, 0.5));
        assert_eq!((spans[3].1, spans[3].2), (1.0, 1.0));
        // …and the series above it keeps the span it would have had.
        assert_eq!((spans[0].1, spans[0].2), (0.0, 0.5));
        assert_eq!((spans[2].1, spans[2].2), (0.5, 1.0));
    }

    #[test]
    fn grouped_spans_all_start_at_the_floor() {
        let mut chart = bar_chart(ChartKind::BarGrouped, vec![vec![1.0], vec![2.0], vec![4.0]]);
        chart.y_range = Some((0.0, 4.0));
        let spans = chart.bar_column_spans(0);
        assert_eq!(spans, vec![(0, 0.0, 0.25), (1, 0.0, 0.5), (2, 0.0, 1.0)]);
    }

    #[test]
    fn bar_column_spans_empty_for_non_bar_kinds() {
        let chart = sparkline_chart(vec![1.0, 2.0]);
        assert!(chart.bar_column_spans(0).is_empty());
        assert!(chart.bar_column_spans_all().is_empty());
    }

    #[test]
    fn bar_column_spans_all_matches_the_per_column_helper() {
        // The bulk form exists only to resolve the y-range once for the
        // whole chart; it must agree with the single-column form column
        // for column, for both bar kinds.
        for kind in [ChartKind::Bar, ChartKind::BarGrouped] {
            let chart = bar_chart(kind, vec![vec![1.0, 5.0, -2.0], vec![2.0, 0.0, 3.0]]);
            let all = chart.bar_column_spans_all();
            assert_eq!(all.len(), chart.max_data_len(), "{kind:?}");
            for (di, column) in all.iter().enumerate() {
                assert_eq!(*column, chart.bar_column_spans(di), "{kind:?} col {di}");
            }
        }
    }

    #[test]
    fn stacked_bar_nearest_point_resolves_series_and_index() {
        let mut chart = bar_chart(
            ChartKind::Bar,
            vec![vec![1.0, 1.0], vec![1.0, 1.0], vec![1.0, 1.0]],
        );
        chart.y_range = Some((0.0, 3.0));
        let m = ChartMeasure {
            width: 30.0,
            height: 30.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        // One anchor per (series, column), not one per column.
        assert_eq!(layout.data_point_positions.len(), 6);

        let pa = layout.plot_area;
        let slot_w = pa.width / 2.0;
        // Second column, top third of the stack → series 2, index 1.
        let x = pa.x + slot_w * 1.5;
        let y = pa.y + pa.height / 6.0;
        assert_eq!(layout.nearest_point(x, y, slot_w), Some((2, 1)));
        // Bottom third of the first column → series 0, index 0.
        let y_bottom = pa.y + pa.height * 5.0 / 6.0;
        assert_eq!(
            layout.nearest_point(pa.x + slot_w * 0.5, y_bottom, slot_w),
            Some((0, 0))
        );
    }

    #[test]
    fn grouped_bar_anchors_sit_side_by_side() {
        let mut chart = bar_chart(ChartKind::BarGrouped, vec![vec![1.0], vec![2.0], vec![3.0]]);
        chart.y_range = Some((0.0, 3.0));
        let m = ChartMeasure {
            width: 30.0,
            height: 30.0,
            char_width: 1.0,
            line_height: 1.0,
        };
        let layout = chart.layout(0.0, 0.0, m);
        let xs: Vec<f32> = layout.data_point_positions.iter().map(|p| p.2).collect();
        assert_eq!(xs.len(), 3);
        assert!(xs[0] < xs[1] && xs[1] < xs[2], "sub-bars advance: {xs:?}");
        // Taller value → higher anchor (smaller screen y).
        let ys: Vec<f32> = layout.data_point_positions.iter().map(|p| p.3).collect();
        assert!(ys[0] > ys[1] && ys[1] > ys[2], "bar tops rise: {ys:?}");
    }

    #[test]
    fn bar_kind_predicates() {
        assert!(ChartKind::Bar.is_bar() && ChartKind::Bar.is_stacked_bar());
        assert!(ChartKind::BarGrouped.is_bar() && !ChartKind::BarGrouped.is_stacked_bar());
        assert!(!ChartKind::Line.is_bar() && !ChartKind::Sparkline.is_bar());
    }

    #[test]
    fn bar_grouped_round_trips_through_serde() {
        let json = serde_json::to_string(&ChartKind::BarGrouped).unwrap();
        assert_eq!(json, "\"BarGrouped\"");
        let back: ChartKind = serde_json::from_str(&json).unwrap();
        assert_eq!(back, ChartKind::BarGrouped);
        let old: ChartKind = serde_json::from_str("\"Bar\"").unwrap();
        assert_eq!(old, ChartKind::Bar);
    }
}