hephaestus 0.2.0

Backend-agnostic 2D scene renderer for data visualization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
//! `RibbonGeom` — filled band between two curves.
//!
//! Per-mark like [`LineGeom`](super::LineGeom): rows sharing a key value
//! form one band. Within a mark, the geom walks the rows in source order
//! to produce two curves (call them curve A and curve B), then builds a
//! closed contour — forward along curve A, back along curve B — and
//! fills it.
//!
//! Three orientations live in the same struct, selected by which
//! optional channels the user supplies:
//!
//! - **Horizontal band** (band varies along x). Channels `x`, `y`, `y2`.
//!   Curve A is `(x, y)`; curve B is `(x, y2)`. Selected when `y2` is
//!   supplied and `x2` is not.
//! - **Vertical band** (band varies along y). Channels `x`, `y`, `x2`.
//!   Curve A is `(x, y)`; curve B is `(x2, y)`. Selected when `x2` is
//!   supplied and `y2` is not.
//! - **Free band** (both edges arbitrary). Channels `x`, `y`, `x2`, `y2`.
//!   Curve A is `(x, y)`; curve B is `(x2, y2)`. Selected when both
//!   optional channels are supplied. The fill polygon closes curve A's
//!   last vertex to curve B's last vertex (and curve B's first to
//!   curve A's first) with straight segments.
//!
//! At least one of `x2` / `y2` must be supplied — a ribbon needs both
//! edges. To get a band from `(x, y)` to a baseline, supply
//! `y2 = 0.0` (or `x2 = 0.0`) explicitly.
//!
//! Channels consumed:
//!
//! - `"x"` — required; data; numeric.
//! - `"y"` — required; data; numeric.
//! - `"x2"` — optional; data; numeric.
//! - `"y2"` — optional; data; numeric.
//! - `"x_offset"` / `"y_offset"` / `"x2_offset"` / `"y2_offset"` — per-row
//!   absolute pt offset added to the projected vertex. Unsuffixed
//!   addresses curve A, `2`-suffixed addresses curve B. `y_offset` /
//!   `y2_offset` follow the convention "positive is up" (the projected
//!   pixel y is decremented).
//! - `"x_band"` / `"y_band"` / `"x2_band"` / `"y2_band"` — per-row
//!   band-fraction offset folded into the corresponding scale's
//!   `map_with_offset`. No effect on continuous scales (whose band
//!   width is zero). Unsuffixed addresses curve A, `2`-suffixed
//!   addresses curve B.
//! - `"fill"` — band fill color (per-mark, but read at every row when
//!   the channel varies across the mark — see below). Default: none.
//! - `"fill_opacity"` — overrides the alpha of `"fill"` (per-mark or
//!   per-row, same dispatch rule as `"fill"`). Folded in via
//!   `override_alpha`.
//! - `"stroke"` — outline color for curve A (per-mark; first-row-of-mark).
//!   Bound → curve A is stroked; unbound → no outline on curve A.
//! - `"stroke2"` — outline color for curve B (per-mark). Independent of
//!   `"stroke"`; either, both, or neither may be bound.
//! - `"stroke_opacity"` / `"stroke_opacity2"` — override the alpha of
//!   each curve's outline colour (per-mark).
//! - `"linewidth"` — width in pt of curve A's outline (per-mark;
//!   default 1.0 pt). Consulted only when `"stroke"` is bound.
//! - `"linewidth2"` — width in pt of curve B's outline (per-mark;
//!   default 1.0 pt). Consulted only when `"stroke2"` is bound.
//! - `"pick_id"` — per-mark pick id (resolved at the mark's first row).
//!
//! Variance in `"fill"` / `"fill_opacity"` across a mark dispatches to one of
//! two render paths:
//!
//! - Axis-aligned (horizontal / vertical) **and** linear projection —
//!   linear gradient brush along the shared axis with one
//!   [`crate::brush::ColorStop`] per row. The fast path.
//! - Free orientation, **or** any orientation under a non-linear
//!   projection (e.g. polar) — quad-strip mesh between curve A and
//!   curve B with per-vertex colours, so the colour follows the
//!   band's actual sweep rather than a screen-aligned axis. Built via
//!   [`ribbon_band_mesh`](crate::primitives::ribbon_band_mesh).
//!
//! Uniform fill across a mark always renders as a single
//! [`Brush::Solid`] fill. Variance is detected via
//! `channel_varies_across` —
//! the same dispatcher [`LineGeom`](super::LineGeom) uses for its
//! ribbon-mesh outline upgrade.
//!
//! Non-finite rows (NaN in any required positional channel) are dropped
//! silently — the band closes around the remaining vertices, matching
//! [`PolygonGeom`](super::PolygonGeom) semantics. Rows within a mark
//! are drawn in user-supplied order; the geom does not sort.

use crate::brush::Brush;
use crate::color::{Color, ColorSpace};
use crate::geometry::{Affine, Point, Rect};
use crate::path::{FillRule, Path};
use crate::plot::scale::Scale;
use crate::plot::value::DataColumn;
use crate::scene::SceneBuilder;

use super::marks::{build_marks_from_column, MarkSlot};
use super::outline::{draw_curve_outline, resolve_outline_spec, OutlineChannels, OutlineScales};
use super::resolve::{
    channel_color_space, channel_varies_across, override_alpha, pt_to_px, resolve_color_channel,
    resolve_color_channel_or_theme, resolve_number_channel, resolve_number_channel_or,
    resolve_pick_id, resolve_position, ChannelBind,
};
use super::state::{finalize_state, require_x_and_siblings, GeomState, KeysStrategy};
use super::{BuildableGeom, Channel, ExpectedOutput, Geom, GeomBuilder, GeomContext, Keys};

/// Catalog of channels this geom recognises, with their expected scale
/// output type. Outline-related channels (everything driving the
/// per-curve stroke + endpoint-marker dispatch) ship in both an
/// unsuffixed form for curve A and a `2`-suffixed form for curve B, so
/// each boundary can be independently dashed / capped / clipped /
/// marker-stamped.
const CHANNELS: &[(&str, ExpectedOutput)] = &[
    ("x", ExpectedOutput::Numbers),
    ("y", ExpectedOutput::Numbers),
    ("x2", ExpectedOutput::Numbers),
    ("y2", ExpectedOutput::Numbers),
    ("x_offset", ExpectedOutput::Numbers),
    ("y_offset", ExpectedOutput::Numbers),
    ("x2_offset", ExpectedOutput::Numbers),
    ("y2_offset", ExpectedOutput::Numbers),
    ("x_band", ExpectedOutput::Numbers),
    ("y_band", ExpectedOutput::Numbers),
    ("x2_band", ExpectedOutput::Numbers),
    ("y2_band", ExpectedOutput::Numbers),
    ("fill", ExpectedOutput::Colors),
    ("fill_opacity", ExpectedOutput::Numbers),
    ("pick_id", ExpectedOutput::Numbers),
    // Curve A outline.
    ("stroke", ExpectedOutput::Colors),
    ("stroke_opacity", ExpectedOutput::Numbers),
    ("linewidth", ExpectedOutput::Numbers),
    ("linetype", ExpectedOutput::Linetypes),
    ("dash_offset", ExpectedOutput::Numbers),
    ("cap", ExpectedOutput::Strings),
    ("join", ExpectedOutput::Strings),
    ("clip_start_radius", ExpectedOutput::Numbers),
    ("clip_end_radius", ExpectedOutput::Numbers),
    ("start_marker", ExpectedOutput::Strings),
    ("end_marker", ExpectedOutput::Strings),
    ("start_marker_size", ExpectedOutput::Numbers),
    ("end_marker_size", ExpectedOutput::Numbers),
    ("start_marker_fill", ExpectedOutput::Colors),
    ("end_marker_fill", ExpectedOutput::Colors),
    ("start_marker_invert", ExpectedOutput::Any),
    ("end_marker_invert", ExpectedOutput::Any),
    // Curve B outline (mirror of curve A's surface).
    ("stroke2", ExpectedOutput::Colors),
    ("stroke_opacity2", ExpectedOutput::Numbers),
    ("linewidth2", ExpectedOutput::Numbers),
    ("linetype2", ExpectedOutput::Linetypes),
    ("dash_offset2", ExpectedOutput::Numbers),
    ("cap2", ExpectedOutput::Strings),
    ("join2", ExpectedOutput::Strings),
    ("clip_start_radius2", ExpectedOutput::Numbers),
    ("clip_end_radius2", ExpectedOutput::Numbers),
    ("start_marker2", ExpectedOutput::Strings),
    ("end_marker2", ExpectedOutput::Strings),
    ("start_marker_size2", ExpectedOutput::Numbers),
    ("end_marker_size2", ExpectedOutput::Numbers),
    ("start_marker_fill2", ExpectedOutput::Colors),
    ("end_marker_fill2", ExpectedOutput::Colors),
    ("start_marker_invert2", ExpectedOutput::Any),
    ("end_marker_invert2", ExpectedOutput::Any),
];

/// Which optional channels supply curve B, and therefore how the
/// band relates to the panel axes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Orientation {
    /// Band sweeps along x; curve A is `(x, y)`, curve B is `(x, y2)`.
    Horizontal,
    /// Band sweeps along y; curve A is `(x, y)`, curve B is `(x2, y)`.
    Vertical,
    /// Both edges independent; curve A is `(x, y)`, curve B is
    /// `(x2, y2)`. No shared axis.
    Free,
}

/// A vectorised filled-band geom.
///
/// See the module-level docs for the channel set and the
/// horizontal-vs-vertical orientation rule.
pub struct RibbonGeom {
    pub(crate) state: GeomState,
    /// Cached mark layout — rebuilt at the start of each `draw` /
    /// `rebuild_diff_against_previous`.
    pub(crate) marks: Vec<MarkSlot>,
    /// Selected from the channel set at `build_from` time.
    pub(crate) orientation: Orientation,
}

crate::impl_geom_inherents_grouped!(RibbonGeom);

impl RibbonGeom {
    /// Build the mark layout from the current keys column.
    pub(crate) fn build_marks(&self) -> Vec<MarkSlot> {
        super::marks::build_marks(&self.state.keys)
    }
}

// ─── BuildableGeom impl ──────────────────────────────────────────────────────

impl BuildableGeom for RibbonGeom {
    fn build_from(builder: GeomBuilder<Self>) -> Self {
        let (keys_opt, channels) = builder.into_parts();
        let n = require_x_and_siblings(&channels, &["y"], "RibbonGeom");

        let has_x2 = channels.contains_key("x2");
        let has_y2 = channels.contains_key("y2");
        let orientation = match (has_x2, has_y2) {
            (false, false) => panic!(
                "RibbonGeom::build: needs at least one of \"x2\" or \"y2\" \
                 (use a constant baseline, e.g. y2 = 0.0, for an area-to-axis ribbon)"
            ),
            (true, false) => Orientation::Vertical,
            (false, true) => Orientation::Horizontal,
            (true, true) => Orientation::Free,
        };

        let state = finalize_state(
            keys_opt,
            channels,
            n,
            KeysStrategy::OneMark,
            CHANNELS,
            "RibbonGeom",
        );
        RibbonGeom {
            state,
            marks: Vec::new(),
            orientation,
        }
    }
}

// ─── Draw-time channel/scale bundle ──────────────────────────────────────────

/// Channel + scale references and orientation handed to
/// [`draw_one_ribbon_mark`] for one draw call. Bundles curve-A/-B
/// outline handles (already aggregated by [`OutlineChannels`] /
/// [`OutlineScales`]) with the fill, fill-opacity, and pick-id channels and
/// the x/x2/y/y2 positional inputs.
#[derive(Clone, Copy)]
struct RibbonDrawCtx<'a> {
    orientation: Orientation,
    x_col: &'a DataColumn,
    y_col: &'a DataColumn,
    x_scale: Option<&'a Scale>,
    y_scale: Option<&'a Scale>,
    x2: ChannelBind<'a>,
    y2: ChannelBind<'a>,
    x_offset: ChannelBind<'a>,
    y_offset: ChannelBind<'a>,
    x2_offset: ChannelBind<'a>,
    y2_offset: ChannelBind<'a>,
    x_band: ChannelBind<'a>,
    y_band: ChannelBind<'a>,
    x2_band: ChannelBind<'a>,
    y2_band: ChannelBind<'a>,
    fill: ChannelBind<'a>,
    fill_opacity: ChannelBind<'a>,
    pick_id: ChannelBind<'a>,
    outline_a_ch: OutlineChannels<'a>,
    outline_b_ch: OutlineChannels<'a>,
    outline_a_scales: OutlineScales<'a>,
    outline_b_scales: OutlineScales<'a>,
}

impl<'a> RibbonDrawCtx<'a> {
    /// Resolve x/y columns + scales and look up every per-mark channel
    /// by name. Returns `None` when `x` or `y` is missing or
    /// non-positional.
    fn build(
        channels: &'a std::collections::HashMap<String, Channel>,
        ctx: &'a GeomContext<'a>,
        orientation: Orientation,
    ) -> Option<Self> {
        let (x_col, x_scale) = match channels.get("x")? {
            Channel::Data(c) => (c, ctx.scale_for("x")),
            Channel::RawData(c) => (c, None),
            _ => return None,
        };
        let (y_col, y_scale) = match channels.get("y")? {
            Channel::Data(c) => (c, ctx.scale_for("y")),
            Channel::RawData(c) => (c, None),
            _ => return None,
        };
        let b = |name: &str| ChannelBind::from_ctx(channels, ctx, name);
        Some(Self {
            orientation,
            x_col,
            y_col,
            x_scale,
            y_scale,
            x2: b("x2"),
            y2: b("y2"),
            x_offset: b("x_offset"),
            y_offset: b("y_offset"),
            x2_offset: b("x2_offset"),
            y2_offset: b("y2_offset"),
            x_band: b("x_band"),
            y_band: b("y_band"),
            x2_band: b("x2_band"),
            y2_band: b("y2_band"),
            fill: b("fill"),
            fill_opacity: b("fill_opacity"),
            pick_id: b("pick_id"),
            outline_a_ch: OutlineChannels::from_map(channels, ""),
            outline_b_ch: OutlineChannels::from_map(channels, "2"),
            outline_a_scales: OutlineScales::from_ctx(ctx, ""),
            outline_b_scales: OutlineScales::from_ctx(ctx, "2"),
        })
    }
}

// ─── Geom impl ───────────────────────────────────────────────────────────────

impl Geom for RibbonGeom {
    fn state(&self) -> &GeomState {
        &self.state
    }

    fn state_mut(&mut self) -> &mut GeomState {
        &mut self.state
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn kind(&self) -> Option<&'static str> {
        Some("ribbon")
    }

    fn mark_count(&self) -> usize {
        if self.marks.is_empty() && !self.is_empty() {
            return self.build_marks().len();
        }
        self.marks.len()
    }

    fn invalidate_caches(&mut self) {
        self.marks.clear();
    }

    fn rebuild_diff_against_previous(&mut self) {
        if !self.state.dirty {
            return;
        }
        let next_marks = self.build_marks();
        let prev_marks = match &self.state.prev_keys {
            Keys::Explicit(col) if !col.is_empty() => build_marks_from_column(col),
            _ => Vec::new(),
        };
        let first_rows =
            |ms: &[MarkSlot]| -> Vec<usize> { ms.iter().map(|m| m.first_row).collect() };
        self.state.rebuild_grouped_diff(
            &first_rows(&prev_marks),
            &first_rows(&next_marks),
            "RibbonGeom",
        );
        self.marks = next_marks;
    }

    fn draw(&self, scene: &mut dyn SceneBuilder, ctx: &GeomContext<'_>) {
        let panel = ctx.panel_rect;
        let panel_w = panel.x1 - panel.x0;
        let panel_h = panel.y1 - panel.y0;
        if panel_w <= 0.0 || panel_h <= 0.0 {
            return;
        }

        let owned_marks;
        let marks: &[MarkSlot] = if self.marks.is_empty() && !self.is_empty() {
            owned_marks = self.build_marks();
            &owned_marks
        } else {
            &self.marks
        };
        if marks.is_empty() {
            return;
        }

        let dc = match RibbonDrawCtx::build(&self.state.channels, ctx, self.orientation) {
            Some(dc) => dc,
            None => return,
        };

        for mark in marks.iter() {
            draw_one_ribbon_mark(scene, ctx, panel, dc, mark);
        }
    }
}

/// Render a single ribbon mark — fill contour, optional gradient brush,
/// optional per-vertex mesh, plus per-curve outlines. Each mark is
/// independent; the caller iterates.
fn draw_one_ribbon_mark(
    scene: &mut dyn SceneBuilder,
    ctx: &GeomContext<'_>,
    panel: Rect,
    dc: RibbonDrawCtx<'_>,
    mark: &MarkSlot,
) {
    let RibbonDrawCtx {
        orientation,
        x_col,
        y_col,
        x_scale,
        y_scale,
        x2: ChannelBind {
            ch: x2_ch,
            scale: x2_scale_bound,
        },
        y2: ChannelBind {
            ch: y2_ch,
            scale: y2_scale_bound,
        },
        x_offset:
            ChannelBind {
                ch: x_offset_ch,
                scale: x_offset_scale,
            },
        y_offset:
            ChannelBind {
                ch: y_offset_ch,
                scale: y_offset_scale,
            },
        x2_offset:
            ChannelBind {
                ch: x2_offset_ch,
                scale: x2_offset_scale,
            },
        y2_offset:
            ChannelBind {
                ch: y2_offset_ch,
                scale: y2_offset_scale,
            },
        x_band: ChannelBind {
            ch: x_band_ch,
            scale: x_band_scale,
        },
        y_band: ChannelBind {
            ch: y_band_ch,
            scale: y_band_scale,
        },
        x2_band:
            ChannelBind {
                ch: x2_band_ch,
                scale: x2_band_scale,
            },
        y2_band:
            ChannelBind {
                ch: y2_band_ch,
                scale: y2_band_scale,
            },
        fill,
        fill_opacity,
        pick_id:
            ChannelBind {
                ch: pick_id_ch,
                scale: pick_id_scale,
            },
        outline_a_ch,
        outline_b_ch,
        outline_a_scales,
        outline_b_scales,
    } = dc;

    let i0 = mark.first_row;

    // Per-mark fill colour at first row, at the per-mark fill
    // opacity. Used for both the uniform `Brush::Solid` path and as
    // a fallback colour when building gradient stops if a row's
    // own fill is unresolved.
    let mark_fill = override_alpha(
        resolve_color_channel_or_theme(
            fill.ch,
            fill.scale,
            i0,
            ctx.theme.geom.ribbon.fill.as_ref(),
            &ctx.theme.palette,
        ),
        resolve_number_channel(fill_opacity.ch, fill_opacity.scale, i0),
    );
    let pick = resolve_pick_id(pick_id_ch, pick_id_scale, i0);
    let outline_a_spec = resolve_outline_spec(
        ctx,
        (&ctx.theme.geom.ribbon).into(),
        &outline_a_ch,
        &outline_a_scales,
        ChannelBind::default(),
        i0,
        pick,
    );
    let outline_b_spec = resolve_outline_spec(
        ctx,
        (&ctx.theme.geom.ribbon).into(),
        &outline_b_ch,
        &outline_b_scales,
        ChannelBind::default(),
        i0,
        pick,
    );

    // If nothing to draw (no fill, no stroke on either curve)
    // skip the whole mark.
    if mark_fill.is_none() && outline_a_spec.is_none() && outline_b_spec.is_none() {
        return;
    }

    // ── Build the two curves vertex-by-vertex. ──
    //
    // For each row we project two channel-space points to panel
    // pixels: curve-A vertex from the unprimed `(x, y)` pair, and
    // curve-B vertex from `(x2_or_x, y2_or_y)` based on which
    // optional channels were supplied. Under non-linear
    // projections (polar, future ternary) we densify each edge
    // between consecutive rows via `interpolate_segment_with_t`
    // on whichever curve has the higher chord error, then resample
    // the *other* curve at the same channel-space `t` values so
    // `curve_a_pts.len() == curve_b_pts.len()` — required by the
    // mesh dispatch and harmless to the path dispatch.
    //
    // `vertex_origins` carries a per-vertex bracketing-row /
    // interior-t tag so per-vertex colours can be lerped between
    // the bracketing rows for the mesh path.
    let is_linear = ctx.projection.is_linear();
    let mut samples_a: Vec<crate::plot::projection::InteriorSample> = Vec::new();
    let mut samples_b: Vec<crate::plot::projection::InteriorSample> = Vec::new();
    let mut merged_t: Vec<f64> = Vec::new();

    let mut curve_a_pts: Vec<Point> = Vec::with_capacity(mark.rows.len());
    let mut curve_b_pts: Vec<Point> = Vec::with_capacity(mark.rows.len());
    let mut row_for_vertex: Vec<usize> = Vec::with_capacity(mark.rows.len());
    let mut vertex_origins: Vec<VertexOrigin> = Vec::with_capacity(mark.rows.len());
    let mut prev_real: Option<(usize, [f64; 2], [f64; 2])> = None;
    // First real row's (a_ch, b_ch); used after the loop to densify
    // the start cap (curve B's first → curve A's first in data space).
    let mut first_real: Option<([f64; 2], [f64; 2])> = None;

    for &i in &mark.rows {
        let x_band = resolve_number_channel_or(x_band_ch, x_band_scale, i, 0.0);
        let y_band = resolve_number_channel_or(y_band_ch, y_band_scale, i, 0.0);
        let x2_band = resolve_number_channel_or(x2_band_ch, x2_band_scale, i, 0.0);
        let y2_band = resolve_number_channel_or(y2_band_ch, y2_band_scale, i, 0.0);
        let x_frac = resolve_position(x_col.get(i), x_scale, x_band);
        let y_frac = resolve_position(y_col.get(i), y_scale, y_band);
        if !x_frac.is_finite() || !y_frac.is_finite() {
            continue;
        }
        let (b_x_frac, b_y_frac) = match resolve_b_row(
            orientation,
            x2_ch,
            y2_ch,
            x2_scale_bound,
            y2_scale_bound,
            i,
            x_frac,
            y_frac,
            x2_band,
            y2_band,
        ) {
            Some(b) => b,
            None => continue,
        };

        let a_ch = [x_frac, y_frac];
        let b_ch = [b_x_frac, b_y_frac];

        if !is_linear {
            if let Some((prev_row, prev_a, prev_b)) = prev_real {
                samples_a.clear();
                samples_b.clear();
                ctx.projection
                    .interpolate_segment_with_t(panel, &prev_a, &a_ch, &mut samples_a);
                ctx.projection
                    .interpolate_segment_with_t(panel, &prev_b, &b_ch, &mut samples_b);
                merged_t.clear();
                merged_t.extend(samples_a.iter().map(|s| s.t));
                merged_t.extend(samples_b.iter().map(|s| s.t));
                merged_t.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
                merged_t.dedup_by(|x, y| (*x - *y).abs() < 1e-9);
                for &t in &merged_t {
                    let a_lerp = [
                        (1.0 - t) * prev_a[0] + t * a_ch[0],
                        (1.0 - t) * prev_a[1] + t * a_ch[1],
                    ];
                    let b_lerp = [
                        (1.0 - t) * prev_b[0] + t * b_ch[0],
                        (1.0 - t) * prev_b[1] + t * b_ch[1],
                    ];
                    let (apx, apy) = ctx.projection.project_to_panel_px(panel, &a_lerp);
                    let (bpx, bpy) = ctx.projection.project_to_panel_px(panel, &b_lerp);
                    curve_a_pts.push(Point::new(apx, apy));
                    curve_b_pts.push(Point::new(bpx, bpy));
                    vertex_origins.push(VertexOrigin {
                        prev_row,
                        next_row: i,
                        t,
                    });
                }
            }
        }

        let (mut apx, mut apy) = ctx.projection.project_to_panel_px(panel, &a_ch);
        let (mut bpx, mut bpy) = ctx.projection.project_to_panel_px(panel, &b_ch);
        if let Some(off) = resolve_number_channel(x_offset_ch, x_offset_scale, i) {
            apx += pt_to_px(off, ctx.dpi);
        }
        if let Some(off) = resolve_number_channel(y_offset_ch, y_offset_scale, i) {
            apy -= pt_to_px(off, ctx.dpi);
        }
        if let Some(off) = resolve_number_channel(x2_offset_ch, x2_offset_scale, i) {
            bpx += pt_to_px(off, ctx.dpi);
        }
        if let Some(off) = resolve_number_channel(y2_offset_ch, y2_offset_scale, i) {
            bpy -= pt_to_px(off, ctx.dpi);
        }
        curve_a_pts.push(Point::new(apx, apy));
        curve_b_pts.push(Point::new(bpx, bpy));
        row_for_vertex.push(i);
        vertex_origins.push(VertexOrigin {
            prev_row: i,
            next_row: i,
            t: 1.0,
        });
        if first_real.is_none() {
            first_real = Some((a_ch, b_ch));
        }
        prev_real = Some((i, a_ch, b_ch));
    }

    if row_for_vertex.len() < 2 {
        // A degenerate single-row band has no area.
        return;
    }
    debug_assert_eq!(curve_a_pts.len(), curve_b_pts.len());
    debug_assert_eq!(curve_a_pts.len(), vertex_origins.len());

    // Densify the two terminal caps under non-linear projections.
    // The start cap connects curve B's first vertex back to curve A's
    // first vertex in data space; the end cap connects curve A's last
    // vertex to curve B's last vertex. Under Cartesian, both calls
    // return zero interior samples and the contour shape is unchanged.
    // Under polar with a non-radial cap (Free orientation with
    // distinct theta on the two endpoints) the cap acquires the same
    // geodesic curvature as the per-curve densification.
    //
    // Cap densification touches only the closed-contour path (the
    // solid and gradient fill paths plus future per-curve outline
    // strokes). The mesh path (varying fill) keeps straight cap
    // chords — the mesh's quad topology doesn't naturally accommodate
    // cap-arc triangles, and forcing it would require a fan
    // triangulation that complicates `ribbon_band_mesh`.
    let mut start_cap_samples: Vec<crate::plot::projection::InteriorSample> = Vec::new();
    let mut end_cap_samples: Vec<crate::plot::projection::InteriorSample> = Vec::new();
    if !is_linear {
        if let (Some((first_a, first_b)), Some((_, last_a, last_b))) = (first_real, prev_real) {
            ctx.projection.interpolate_segment_with_t(
                panel,
                &last_a,
                &last_b,
                &mut end_cap_samples,
            );
            ctx.projection.interpolate_segment_with_t(
                panel,
                &first_b,
                &first_a,
                &mut start_cap_samples,
            );
        }
    }

    // Build the closed fill contour: forward along curve A, end cap
    // samples, reversed curve B, start cap samples, then close.
    let mut path = Path::new();
    path.move_to(curve_a_pts[0]);
    for p in &curve_a_pts[1..] {
        path.line_to(*p);
    }
    for s in &end_cap_samples {
        path.line_to(Point::new(s.px, s.py));
    }
    for p in curve_b_pts.iter().rev() {
        path.line_to(*p);
    }
    for s in &start_cap_samples {
        path.line_to(Point::new(s.px, s.py));
    }
    path.close_path();

    // ── Fill dispatch (variance-detect). ──
    //
    // Solid fill (or no variation) — single `Brush::Solid` over
    // the closed contour path. Variation under axis-aligned +
    // linear projection — linear gradient brush along the shared
    // axis (the fast path). Variation under Free orientation or
    // any non-linear projection — quad-strip mesh between the
    // two curves with per-vertex colours, so the gradient
    // follows the band's actual sweep instead of a screen-aligned
    // axis.
    if let Some(mark_color) = mark_fill {
        let varies = channel_varies_across(fill.ch, fill.scale, &row_for_vertex)
            || channel_varies_across(fill_opacity.ch, fill_opacity.scale, &row_for_vertex);
        let axis_aligned = matches!(orientation, Orientation::Horizontal | Orientation::Vertical);
        let use_mesh = varies && (!axis_aligned || !is_linear);

        let row_fill = RowFill::new(fill, fill_opacity, mark_color);
        if use_mesh {
            let (colors_a, colors_b) = build_per_vertex_colors(&vertex_origins, &row_fill);
            let mut mesh = crate::primitives::ribbon_band_mesh(
                &curve_a_pts,
                &curve_b_pts,
                &colors_a,
                &colors_b,
            );
            if !mesh.vertices.is_empty() && curve_a_pts.len() >= 2 {
                // Cap-fan + clip combo. The fan adds
                // triangles in outward-bulging cap crescents
                // (where the strip's straight chord falls
                // short of the data-space arc); the clip
                // carves any inward-bulging cap overshoot
                // off the strip's straight chord. Both
                // directions land at the densified arc
                // boundary symmetrically.
                let last = curve_a_pts.len() - 1;
                let start_neighbor = Point::new(
                    (curve_a_pts[1].x + curve_b_pts[1].x) * 0.5,
                    (curve_a_pts[1].y + curve_b_pts[1].y) * 0.5,
                );
                let end_neighbor = Point::new(
                    (curve_a_pts[last - 1].x + curve_b_pts[last - 1].x) * 0.5,
                    (curve_a_pts[last - 1].y + curve_b_pts[last - 1].y) * 0.5,
                );
                append_cap_fan_to_mesh(
                    &mut mesh,
                    curve_a_pts[0],
                    curve_b_pts[0],
                    start_neighbor,
                    &start_cap_samples,
                    colors_a[0],
                    CapDirection::Start,
                );
                append_cap_fan_to_mesh(
                    &mut mesh,
                    curve_a_pts[last],
                    curve_b_pts[last],
                    end_neighbor,
                    &end_cap_samples,
                    *colors_a.last().unwrap(),
                    CapDirection::End,
                );
                scene.push_layer(
                    crate::blend::BlendMode::NORMAL,
                    1.0,
                    Affine::IDENTITY,
                    &path,
                );
                scene.draw_mesh(&mesh, Affine::IDENTITY, pick);
                scene.pop_layer();
            }
        } else {
            let brush = if varies {
                build_gradient_brush(orientation, &curve_a_pts, &vertex_origins, &row_fill)
                    .map(Brush::Gradient)
                    .unwrap_or_else(|| Brush::Solid(mark_color))
            } else {
                Brush::Solid(mark_color)
            };
            scene.fill(
                FillRule::NonZero,
                Affine::IDENTITY,
                &brush,
                None,
                &path,
                pick,
            );
        }
    }

    // ── Per-curve outlines. ──
    //
    // Each curve emits its own full LineGeom-style outline if
    // its stroke channel is bound: dashed pattern, endpoint
    // markers, endpoint clipping all flow through the same
    // helper that LineGeom / BSplineGeom use.
    if let Some(ref spec) = outline_a_spec {
        draw_curve_outline(
            scene,
            ctx.shapes,
            ctx.dpi,
            ctx.theme.geom.marker_outline_pt,
            &curve_a_pts,
            spec,
        );
    }
    if let Some(ref spec) = outline_b_spec {
        draw_curve_outline(
            scene,
            ctx.shapes,
            ctx.dpi,
            ctx.theme.geom.marker_outline_pt,
            &curve_b_pts,
            spec,
        );
    }
}

/// Build a linear gradient brush along the band's shared axis from the
/// per-row vertex positions on curve A. Returns `None` if the gradient
/// would be degenerate (fewer than two stops with distinct offsets, or
/// zero shared-axis span).
///
/// Stops carry the per-row resolved fill (at the per-row fill opacity)
/// at offsets proportional to each vertex's projected position along
/// the shared axis. Densified interior points (added between rows under
/// polar projection) are skipped — only the real per-row vertices
/// contribute stops, since interior points have no row identity.
fn build_gradient_brush(
    orientation: Orientation,
    curve_a_pts: &[Point],
    vertex_origins: &[VertexOrigin],
    fill: &RowFill<'_>,
) -> Option<crate::brush::Gradient> {
    // Free orientation has no single axis for a linear gradient to run
    // along; the caller routes that case through the mesh path.
    if matches!(orientation, Orientation::Free) {
        return None;
    }

    // Only real per-row vertices carry a fill value, and `VertexOrigin`
    // marks them by `prev_row == next_row`. Densified interior vertices
    // bracket two rows and contribute no stop — the gradient already
    // covers them, since a brush is evaluated at each point's projected
    // position rather than per vertex.
    let real: Vec<(usize, Point)> = vertex_origins
        .iter()
        .zip(curve_a_pts)
        .filter(|(o, _)| o.prev_row == o.next_row)
        .map(|(o, p)| (o.prev_row, *p))
        .collect();
    let n = real.len();
    if n < 2 {
        return None;
    }

    // Shared-axis range in panel pixels. Under polar this isn't strictly
    // an axis, but the gradient is still anchored screen-aligned by the
    // band's pixel-space extent along the corresponding axis.
    let pick_coord = |p: &Point| match orientation {
        Orientation::Horizontal => p.x,
        Orientation::Vertical => p.y,
        Orientation::Free => 0.0,
    };
    let coords: Vec<f64> = real.iter().map(|(_, p)| pick_coord(p)).collect();
    let min_c = coords.iter().cloned().fold(f64::INFINITY, f64::min);
    let max_c = coords.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let span = max_c - min_c;
    if !span.is_finite() || span.abs() < f64::EPSILON {
        return None;
    }

    let (start, end) = match orientation {
        Orientation::Horizontal => {
            let mid_y = (real[0].1.y + real[n - 1].1.y) * 0.5;
            (Point::new(min_c, mid_y), Point::new(max_c, mid_y))
        }
        Orientation::Vertical => {
            let mid_x = (real[0].1.x + real[n - 1].1.x) * 0.5;
            (Point::new(mid_x, min_c), Point::new(mid_x, max_c))
        }
        Orientation::Free => return None,
    };

    // Build one stop per real vertex, sorted by gradient offset so peniko
    // sees a strictly-monotonic sequence. Projected coords don't follow
    // row order under cartesian (y axis is flipped) or under non-linear
    // projections in general — sort before deduping.
    let mut pairs: Vec<(f64, Color)> = Vec::with_capacity(n);
    for (k, &(i, _)) in real.iter().enumerate() {
        let offset = ((coords[k] - min_c) / span).clamp(0.0, 1.0);
        pairs.push((offset, fill.at(i)));
    }
    pairs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));

    let mut stops: Vec<crate::brush::ColorStop> = Vec::with_capacity(pairs.len());
    let mut last_offset = f64::NEG_INFINITY;
    for (offset, color) in pairs {
        if offset <= last_offset {
            continue;
        }
        stops.push(crate::brush::ColorStop {
            offset: offset as f32,
            color: color.into(),
        });
        last_offset = offset;
    }
    if stops.len() < 2 {
        return None;
    }
    Some(crate::brush::Gradient::new_linear(start, end).with_stops(stops.as_slice()))
}

/// Bracketing-row identity for a single emitted curve vertex. Real
/// vertices set `prev_row == next_row`; densified interior vertices
/// carry the two bracketing row indices and the `t ∈ (0, 1)` fraction
/// of the segment between them.
#[derive(Clone, Copy, Debug)]
struct VertexOrigin {
    prev_row: usize,
    next_row: usize,
    /// Channel-space fraction within the bracketing segment. `1.0` for
    /// real vertices (and ignored, since `prev_row == next_row`).
    t: f64,
}

/// Resolve curve B's `(x, y)` panel-fraction for one row. Returns
/// `None` when either coordinate is non-finite (the row is dropped).
/// Falls back to the corresponding curve-A coordinate for the channel
/// that wasn't supplied in axis-aligned modes. The `x2_band` / `y2_band`
/// arguments fold band-fraction offsets into the curve-B scales (no
/// effect on continuous scales).
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_b_row(
    orientation: Orientation,
    x2_ch: Option<&Channel>,
    y2_ch: Option<&Channel>,
    x2_scale_bound: Option<&crate::plot::scale::Scale>,
    y2_scale_bound: Option<&crate::plot::scale::Scale>,
    row: usize,
    x_frac: f64,
    y_frac: f64,
    x2_band: f64,
    y2_band: f64,
) -> Option<(f64, f64)> {
    let b_x = match orientation {
        Orientation::Horizontal => x_frac,
        Orientation::Vertical | Orientation::Free => {
            resolve_optional_position(x2_ch, x2_scale_bound, row, x2_band)?
        }
    };
    let b_y = match orientation {
        Orientation::Vertical => y_frac,
        Orientation::Horizontal | Orientation::Free => {
            resolve_optional_position(y2_ch, y2_scale_bound, row, y2_band)?
        }
    };
    Some((b_x, b_y))
}

/// Which terminal of the band a cap fan attaches to. Determines the
/// order in which the cap samples are walked around the pivot so the
/// fan winds consistently — start-cap samples come from
/// `interpolate_segment_with_t(B's-first → A's-first)` and need to be
/// reversed; end-cap samples come from `A's-last → B's-last` and walk
/// the fan directly.
#[derive(Clone, Copy, Debug)]
pub(crate) enum CapDirection {
    Start,
    End,
}

/// Append a fan triangulation that fills the crescent between the
/// strip's straight cap chord (pivot ↔ other) and the densified
/// data-space cap arc.
///
/// The pivot vertex (one of the curve endpoints at the cap) is the
/// fan apex; the ring walks from the pivot along the cap arc to
/// `other` (the matching endpoint on the opposite curve). All cap-fan
/// vertices take `cap_color` — the band's per-vertex colour at that
/// end of the strip — so the fan blends seamlessly into the strip's
/// first / last quad.
///
/// `neighbor` is the strip's pair adjacent to the cap (the second pair
/// for a `Start` cap, the second-to-last pair for an `End` cap),
/// supplied as the midpoint of its A and B vertices. It defines the
/// strip's sweep direction at the cap so the fan can detect when the
/// cap arc bulges into the strip's interior — in that case the fan is
/// skipped to avoid double-filling the strip with overlapping
/// triangles. Under the more common outward-bulge geometry (e.g.
/// caps at constant outer radius under polar) the fan adds the
/// missing crescent without overlap.
///
/// No-op when there are no interior cap samples (linear projection,
/// or a cap whose endpoints coincide in data space).
pub(crate) fn append_cap_fan_to_mesh(
    mesh: &mut crate::mesh::Mesh,
    pivot: Point,
    other: Point,
    neighbor: Point,
    cap_samples: &[crate::plot::projection::InteriorSample],
    cap_color: Color,
    direction: CapDirection,
) {
    if cap_samples.is_empty() {
        return;
    }
    let chord_mid = Point::new((pivot.x + other.x) * 0.5, (pivot.y + other.y) * 0.5);
    // Strip's sweep direction at the cap (from cap midpoint toward
    // the next-or-previous pair midpoint).
    let sweep_x = neighbor.x - chord_mid.x;
    let sweep_y = neighbor.y - chord_mid.y;
    // Average cap-sample offset from the chord midpoint.
    let mut bulge_x = 0.0;
    let mut bulge_y = 0.0;
    for s in cap_samples {
        bulge_x += s.px - chord_mid.x;
        bulge_y += s.py - chord_mid.y;
    }
    let inv_n = 1.0 / cap_samples.len() as f64;
    bulge_x *= inv_n;
    bulge_y *= inv_n;
    // Positive dot product → cap bulges in the same direction the
    // strip sweeps, i.e. into the strip's interior. Adding fan
    // triangles there would double-fill area the strip already
    // covers; skip the fan and accept the strip's straight chord as
    // a slight overshoot of the data-space arc.
    if bulge_x * sweep_x + bulge_y * sweep_y > 0.0 {
        return;
    }
    let base = mesh.vertices.len() as u32;
    mesh.vertices.push(pivot);
    mesh.colors.push(cap_color);
    let cap_arc_iter: Vec<Point> = match direction {
        CapDirection::Start => cap_samples
            .iter()
            .rev()
            .map(|s| Point::new(s.px, s.py))
            .chain(std::iter::once(other))
            .collect(),
        CapDirection::End => cap_samples
            .iter()
            .map(|s| Point::new(s.px, s.py))
            .chain(std::iter::once(other))
            .collect(),
    };
    for p in &cap_arc_iter {
        mesh.vertices.push(*p);
        mesh.colors.push(cap_color);
    }
    for i in 0..cap_arc_iter.len() - 1 {
        mesh.indices.push(base);
        mesh.indices.push(base + 1 + i as u32);
        mesh.indices.push(base + 2 + i as u32);
    }
}

fn resolve_optional_position(
    ch: Option<&Channel>,
    scale_bound: Option<&crate::plot::scale::Scale>,
    row: usize,
    band: f64,
) -> Option<f64> {
    let value = match ch? {
        Channel::Constant(v) | Channel::RawConstant(v) => v.clone(),
        Channel::Data(col) | Channel::RawData(col) => col.get(row),
    };
    let scale = match ch? {
        Channel::RawConstant(_) | Channel::RawData(_) => None,
        _ => scale_bound,
    };
    let f = resolve_position(value, scale, band);
    if f.is_finite() {
        Some(f)
    } else {
        None
    }
}

/// Per-row fill resolver for the band interior, shared by every path
/// that paints a ribbon from per-row fills.
///
/// A row's colour is its `"fill"` channel at its `"fill_opacity"`,
/// falling back to the mark's colour when either is unbound. Blends
/// between two rows walk the fill scale's own colour space, so a
/// densified vertex sits on the ramp the scale defines.
#[derive(Clone, Copy)]
pub(crate) struct RowFill<'a> {
    fill: ChannelBind<'a>,
    fill_opacity: ChannelBind<'a>,
    fallback: Color,
    space: ColorSpace,
}

impl<'a> RowFill<'a> {
    /// Bundle the two fill channels with the mark's fallback colour.
    pub(crate) fn new(
        fill: ChannelBind<'a>,
        fill_opacity: ChannelBind<'a>,
        fallback: Color,
    ) -> Self {
        RowFill {
            fill,
            fill_opacity,
            fallback,
            space: channel_color_space(fill.scale),
        }
    }

    /// The colour one source row paints.
    pub(crate) fn at(&self, row: usize) -> Color {
        override_alpha(
            resolve_color_channel(self.fill.ch, self.fill.scale, row),
            resolve_number_channel(self.fill_opacity.ch, self.fill_opacity.scale, row),
        )
        .unwrap_or(self.fallback)
    }

    /// The colour a point `t` of the way from `row_a` to `row_b` paints.
    pub(crate) fn between(&self, row_a: usize, row_b: usize, t: f64) -> Color {
        crate::color::lerp_color(self.at(row_a), self.at(row_b), t, self.space)
    }
}

/// Build per-vertex colours for both curve sides of the mesh path.
/// Real vertices take the per-row resolved fill; densified interior
/// vertices lerp between the two bracketing rows' colours along `t`.
/// Both sides share the same colour at the same vertex index — the
/// ribbon has one fill per vertex pair.
fn build_per_vertex_colors(
    vertex_origins: &[VertexOrigin],
    fill: &RowFill<'_>,
) -> (Vec<Color>, Vec<Color>) {
    let mut colors: Vec<Color> = Vec::with_capacity(vertex_origins.len());
    for origin in vertex_origins {
        let c = if origin.prev_row == origin.next_row {
            fill.at(origin.prev_row)
        } else {
            fill.between(origin.prev_row, origin.next_row, origin.t)
        };
        colors.push(c);
    }
    // Both curve sides share the same per-row fill in the ribbon model;
    // clone once rather than re-resolving.
    let colors_b = colors.clone();
    (colors, colors_b)
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color::Color;
    use crate::geometry::Rect;
    use crate::plot::geom::{DirectScaleResolver, Raw};
    use crate::plot::value::Value;
    use crate::scene::recording::{Op, RecordingScene};

    fn shapes() -> crate::shape::ShapeRegistry {
        crate::shape::ShapeRegistry::with_builtins()
    }

    fn ctx<'a>(
        panel: Rect,
        registry: &'a crate::shape::ShapeRegistry,
        scales: &'a DirectScaleResolver<'a>,
    ) -> GeomContext<'a> {
        GeomContext::new(panel, 96.0, registry, scales)
    }

    fn red() -> Color {
        Color::new([1.0, 0.0, 0.0, 1.0])
    }

    fn blue() -> Color {
        Color::new([0.0, 0.0, 1.0, 1.0])
    }

    /// Alpha of every fill and stroke a drawn ribbon emitted.
    fn painted_alphas(g: &mut RibbonGeom) -> (Vec<f32>, Vec<f32>) {
        g.rebuild_diff_against_previous();
        let panel = Rect::new(0.0, 0.0, 200.0, 200.0);
        let registry = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(&mut scene, &ctx(panel, &registry, &scales));
        let (mut fills, mut strokes) = (Vec::new(), Vec::new());
        for op in &scene.ops {
            match op {
                Op::Fill {
                    brush: crate::brush::Brush::Solid(c),
                    ..
                } => fills.push(c.components[3]),
                Op::Stroke {
                    brush: crate::brush::Brush::Solid(c),
                    ..
                } => strokes.push(c.components[3]),
                _ => {}
            }
        }
        (fills, strokes)
    }

    #[test]
    fn fill_opacity_and_per_curve_stroke_opacity_act_independently() {
        let mut g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.8_f64, 0.7, 0.9]))
            .set("y2", Raw(vec![0.2_f64, 0.3, 0.1]))
            .set("fill", red())
            .set("fill_opacity", 0.3_f64)
            .set("stroke", blue())
            .set("stroke_opacity", 0.6_f64)
            .set("stroke2", blue())
            .set("stroke_opacity2", 0.9_f64)
            .build();
        let (fills, mut strokes) = painted_alphas(&mut g);
        assert!(
            fills.iter().all(|a| (a - 0.3).abs() < 1e-6),
            "band fill alphas {fills:?}"
        );
        strokes.sort_by(f32::total_cmp);
        strokes.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
        assert_eq!(strokes.len(), 2, "one alpha per outline: {strokes:?}");
        assert!((strokes[0] - 0.6).abs() < 1e-6, "curve A {:?}", strokes[0]);
        assert!((strokes[1] - 0.9).abs() < 1e-6, "curve B {:?}", strokes[1]);
    }

    // ── build() ──

    #[test]
    fn no_keys_synthesises_single_mark() {
        let g = RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0, 1.0])
            .set("y2", 0.0_f64)
            .build();
        assert_eq!(g.len(), 3);
        assert_eq!(g.mark_count(), 1);
    }

    #[test]
    fn explicit_keys_define_marks() {
        let g = RibbonGeom::builder()
            .keys(vec!["A", "A", "A", "B", "B", "B"])
            .set("x", vec![0.0_f64, 1.0, 2.0, 0.0, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0, 1.0, 0.5, 1.5, 0.5])
            .set("y2", 0.0_f64)
            .build();
        assert_eq!(g.mark_count(), 2);
    }

    #[test]
    fn explicit_y2_selects_horizontal() {
        let g = RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0, 1.0])
            .set("y2", vec![0.2_f64, 0.4, 0.3])
            .build();
        assert_eq!(g.orientation, Orientation::Horizontal);
    }

    #[test]
    fn x2_selects_vertical_mode() {
        let g = RibbonGeom::builder()
            .set("x", vec![0.0_f64, 0.5, 1.0])
            .set("y", vec![0.0_f64, 0.5, 1.0])
            .set("x2", vec![0.2_f64, 0.7, 1.2])
            .build();
        assert_eq!(g.orientation, Orientation::Vertical);
    }

    #[test]
    fn both_x2_and_y2_selects_free() {
        let g = RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0])
            .set("y", vec![0.0_f64, 1.0])
            .set("x2", vec![0.2_f64, 0.8])
            .set("y2", vec![0.2_f64, 0.8])
            .build();
        assert_eq!(g.orientation, Orientation::Free);
    }

    #[test]
    #[should_panic(expected = "needs at least one")]
    fn no_curve_b_channel_panics() {
        RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0])
            .set("y", vec![0.0_f64, 1.0])
            .build();
    }

    #[test]
    #[should_panic(expected = "missing required channel")]
    fn missing_x_panics() {
        RibbonGeom::builder().set("y", vec![0.0_f64, 1.0]).build();
    }

    #[test]
    #[should_panic(expected = "missing required channel")]
    fn missing_y_panics() {
        RibbonGeom::builder().set("x", vec![0.0_f64, 1.0]).build();
    }

    #[test]
    #[should_panic(expected = "does not match")]
    fn length_mismatch_panics() {
        RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0])
            .build();
    }

    // ── Drawing ──

    fn draw_and_record(mut g: RibbonGeom) -> RecordingScene {
        g.rebuild_diff_against_previous();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        scene
    }

    #[test]
    fn constant_fill_uses_solid_brush() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("fill", red())
            .build();
        let scene = draw_and_record(g);
        let solid_fills = scene
            .ops
            .iter()
            .filter(|op| {
                matches!(
                    op,
                    Op::Fill {
                        brush: Brush::Solid(_),
                        ..
                    }
                )
            })
            .count();
        let gradient_fills = scene
            .ops
            .iter()
            .filter(|op| {
                matches!(
                    op,
                    Op::Fill {
                        brush: Brush::Gradient(_),
                        ..
                    }
                )
            })
            .count();
        assert_eq!(solid_fills, 1);
        assert_eq!(gradient_fills, 0);
    }

    #[test]
    fn varying_fill_uses_gradient_brush_horizontal() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("fill", vec![red(), blue(), red()])
            .build();
        let scene = draw_and_record(g);
        for op in &scene.ops {
            if let Op::Fill {
                brush: Brush::Gradient(g),
                ..
            } = op
            {
                // Linear horizontal gradient: start and end share a y.
                if let crate::brush::GradientKind::Linear(crate::brush::LinearGradientPosition {
                    start,
                    end,
                }) = g.kind
                {
                    assert!((start.y - end.y).abs() < f64::EPSILON);
                    assert!(start.x < end.x);
                } else {
                    panic!("expected linear gradient");
                }
                assert!(g.stops.len() >= 2);
                return;
            }
        }
        panic!("no gradient fill emitted");
    }

    #[test]
    fn varying_fill_uses_gradient_brush_vertical() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("x2", Raw(vec![0.3_f64, 0.3, 0.3]))
            .set("fill", vec![red(), blue(), red()])
            .build();
        let scene = draw_and_record(g);
        for op in &scene.ops {
            if let Op::Fill {
                brush: Brush::Gradient(g),
                ..
            } = op
            {
                // Linear vertical gradient: start and end share an x.
                if let crate::brush::GradientKind::Linear(crate::brush::LinearGradientPosition {
                    start,
                    end,
                }) = g.kind
                {
                    assert!((start.x - end.x).abs() < f64::EPSILON);
                    assert!(start.y < end.y);
                } else {
                    panic!("expected linear gradient");
                }
                return;
            }
        }
        panic!("no gradient fill emitted");
    }

    #[test]
    fn stroke_only_curve_a() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("stroke", red())
            .set("linewidth", 2.0_f64)
            .build();
        let scene = draw_and_record(g);
        let strokes: Vec<&Op> = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .collect();
        assert_eq!(strokes.len(), 1);
    }

    #[test]
    fn stroke_only_curve_b() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("stroke2", blue())
            .set("linewidth2", 2.0_f64)
            .build();
        let scene = draw_and_record(g);
        let strokes: Vec<&Op> = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .collect();
        assert_eq!(strokes.len(), 1);
    }

    #[test]
    fn curve_b_independent_linetype_dashes() {
        // Curve A solid, curve B dashed → two stroke ops, the curve-B
        // one carrying a non-empty dash pattern.
        use crate::plot::value::LinetypeStep;
        use std::sync::Arc;
        let dashed: Arc<[LinetypeStep]> =
            Arc::from(vec![LinetypeStep::Dash(4.0), LinetypeStep::Gap(2.0)]);
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(vec![0.2_f64, 0.3, 0.2]))
            .set("stroke", red())
            .set("stroke2", blue())
            .set("linewidth", 2.0_f64)
            .set("linewidth2", 2.0_f64)
            .set("linetype2", Value::Linetype(dashed))
            .build();
        let scene = draw_and_record(g);
        let strokes: Vec<&Op> = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .collect();
        assert_eq!(strokes.len(), 2);
        // Locate the strokes by brush color and check dash status.
        let mut found_solid_red = false;
        let mut found_dashed_blue = false;
        for op in &strokes {
            if let Op::Stroke {
                brush: Brush::Solid(c),
                stroke,
                ..
            } = op
            {
                let is_dashed = !stroke.dash_pattern.is_empty();
                let is_red = c.components[0] > 0.99 && c.components[2] < 0.01;
                let is_blue = c.components[0] < 0.01 && c.components[2] > 0.99;
                if is_red && !is_dashed {
                    found_solid_red = true;
                }
                if is_blue && is_dashed {
                    found_dashed_blue = true;
                }
            }
        }
        assert!(found_solid_red, "expected solid red stroke on curve A");
        assert!(found_dashed_blue, "expected dashed blue stroke on curve B");
    }

    #[test]
    fn clip_start_radius2_clips_curve_b_only() {
        // Curve A unclipped, curve B with clip_start_radius2 = 5pt.
        // Both curves should be stroked, but curve B's first vertex is
        // pushed forward along the curve by the clip.
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(vec![0.2_f64, 0.3, 0.2]))
            .set("stroke", red())
            .set("stroke2", blue())
            .set("linewidth", 2.0_f64)
            .set("linewidth2", 2.0_f64)
            .set("clip_start_radius2", 5.0_f64)
            .build();
        let scene = draw_and_record(g);
        // Both strokes still emit.
        let strokes_count = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .count();
        assert_eq!(strokes_count, 2);
        // Curve B's path should start near (but not at) curve A's start
        // x-coordinate, since the clip trims the first vertex off
        // (the original curve B's first vertex is at x ≈ 10, and
        // clip_start_radius2 = 5pt ≈ 6.67px at 96 dpi pushes it forward).
        let mut curve_a_first_x = None;
        let mut curve_b_first_x = None;
        for op in &scene.ops {
            if let Op::Stroke {
                brush: Brush::Solid(c),
                path,
                ..
            } = op
            {
                let first_x = path
                    .elements()
                    .iter()
                    .find_map(|el| match el {
                        crate::path::PathEl::MoveTo(p) => Some(p.x),
                        _ => None,
                    })
                    .unwrap();
                let is_red = c.components[0] > 0.99 && c.components[2] < 0.01;
                let is_blue = c.components[0] < 0.01 && c.components[2] > 0.99;
                if is_red {
                    curve_a_first_x = Some(first_x);
                } else if is_blue {
                    curve_b_first_x = Some(first_x);
                }
            }
        }
        let a_x = curve_a_first_x.expect("curve A stroke missing");
        let b_x = curve_b_first_x.expect("curve B stroke missing");
        // Curve A starts at the unclipped first vertex; curve B starts
        // *past* it because of the clip.
        assert!(
            b_x > a_x + 1.0,
            "curve B should be clipped forward of curve A's first vertex (a_x={a_x}, b_x={b_x})"
        );
    }

    #[test]
    fn curve_b_independent_endpoint_markers() {
        // Curve A unmarked, curve B with start + end markers.
        // Expect the curve-B markers to emit additional ops above the
        // two stroke ops (one per curve).
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(vec![0.2_f64, 0.3, 0.2]))
            .set("stroke", red())
            .set("stroke2", blue())
            .set("linewidth", 2.0_f64)
            .set("linewidth2", 2.0_f64)
            .set("start_marker2", "circle")
            .set("end_marker2", "circle")
            .build();
        let scene = draw_and_record(g);
        let strokes = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .count();
        let fills = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Fill { .. }))
            .count();
        assert_eq!(strokes, 2, "expected two curve strokes");
        // Two markers (start + end) on curve B; built-in "circle" shape
        // emits one Op::Fill per marker. Curve A has no markers.
        assert_eq!(fills, 2, "expected one fill per curve-B marker");
    }

    #[test]
    fn stroke_both_curves() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(vec![0.2_f64, 0.3, 0.2]))
            .set("stroke", red())
            .set("stroke2", blue())
            .set("linewidth", 2.0_f64)
            .set("linewidth2", 2.0_f64)
            .build();
        let scene = draw_and_record(g);
        let strokes: Vec<&Op> = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Stroke { .. }))
            .collect();
        assert_eq!(strokes.len(), 2);
    }

    #[test]
    fn no_fill_no_stroke_emits_nothing() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .build();
        let scene = draw_and_record(g);
        assert!(scene.ops.is_empty());
    }

    #[test]
    fn nonfinite_row_dropped() {
        // A 4-row mark with one NaN row → remaining 3 vertices form
        // a valid closed band.
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.4, 0.7, 0.9]))
            .set("y", Raw(vec![0.5_f64, f64::NAN, 0.8, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("fill", red())
            .build();
        let scene = draw_and_record(g);
        let fills = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Fill { .. }))
            .count();
        assert_eq!(fills, 1);
    }

    #[test]
    fn closed_contour_has_one_close() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("y2", Raw(0.2_f64))
            .set("fill", red())
            .build();
        let scene = draw_and_record(g);
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                let closes = path
                    .elements()
                    .iter()
                    .filter(|el| matches!(el, crate::path::PathEl::ClosePath))
                    .count();
                assert_eq!(closes, 1);
                return;
            }
        }
        panic!("no fill emitted");
    }

    #[test]
    fn fill_path_walks_a_forward_then_b_reversed() {
        // 3-row horizontal band with explicit y2 well below y. The fill
        // path should visit the three (x, y) vertices left-to-right then
        // the three (x, y2) vertices right-to-left.
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.8_f64, 0.8, 0.8]))
            .set("y2", Raw(vec![0.2_f64, 0.2, 0.2]))
            .set("fill", red())
            .build();
        let scene = draw_and_record(g);
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                // First element is MoveTo at curve-A start. Last LineTo
                // before close is curve-B end (=row 0 in reversed order).
                let elements: Vec<_> = path.elements().iter().collect();
                if let crate::path::PathEl::MoveTo(start) = &elements[0] {
                    // y=0.8 on a 100×100 panel under default cartesian
                    // projection projects to y_px = panel.y1 - 0.8 * h =
                    // 100 - 80 = 20.
                    assert!((start.y - 20.0).abs() < 1.0);
                    assert!((start.x - 10.0).abs() < 1.0);
                } else {
                    panic!("first element not MoveTo");
                }
                return;
            }
        }
        panic!("no fill emitted");
    }

    #[test]
    fn declared_channels_alphabetical() {
        let g = RibbonGeom::builder()
            .set("x", vec![0.0_f64, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0, 1.0])
            .set("y2", 0.0_f64)
            .set("fill", red())
            .build();
        let names: Vec<&str> = g.declared_channels().iter().map(|d| d.name).collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
    }

    #[test]
    fn diff_marks_enter_on_first_draw() {
        let mut g = RibbonGeom::builder()
            .keys(vec!["A", "A", "A", "B", "B", "B"])
            .set("x", vec![0.0_f64, 1.0, 2.0, 0.0, 1.0, 2.0])
            .set("y", vec![1.0_f64, 2.0, 1.0, 0.5, 1.5, 0.5])
            .set("y2", 0.0_f64)
            .build();
        g.rebuild_diff_against_previous();
        assert_eq!(g.state.enter.len(), 2);
        assert_eq!(g.state.exit.len(), 0);
    }

    #[test]
    fn polar_band_densifies_edges() {
        use crate::plot::projection::Projection;
        let polar = Projection::polar();
        let mut g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.8_f64, 0.8, 0.8]))
            .set("y2", Raw(vec![0.4_f64, 0.4, 0.4]))
            .set("fill", red())
            .build();
        g.rebuild_diff_against_previous();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        let panel = Rect::new(0.0, 0.0, 200.0, 200.0);
        let ctx = GeomContext::with_projection(panel, 96.0, &shapes, &scales, &polar);
        g.draw(&mut scene, &ctx);

        // Under polar densification, each of the two angular edges
        // (curve A along outer radius, curve B along inner radius) gets
        // additional interior samples inserted by `interpolate_segment`.
        // Without densification a 3-row band would produce 6 line-to
        // elements (3 forward on A + 3 reversed on B); with curved arcs
        // we expect significantly more.
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                let line_count = path
                    .elements()
                    .iter()
                    .filter(|el| matches!(el, crate::path::PathEl::LineTo(_)))
                    .count();
                assert!(
                    line_count > 6,
                    "expected densified line count > 6, got {line_count}"
                );
                return;
            }
        }
        panic!("no fill emitted");
    }

    #[test]
    fn polar_band_caps_are_densified() {
        // Free orientation under polar with curve A and curve B sitting at
        // distinct theta values at both ends → the start and end caps span
        // a non-trivial polar arc and should be densified.
        use crate::plot::projection::Projection;
        let polar = Projection::polar();
        let mut g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.8_f64, 0.8, 0.8]))
            .set("x2", Raw(vec![0.2_f64, 0.5, 0.8]))
            .set("y2", Raw(vec![0.4_f64, 0.4, 0.4]))
            .set("fill", red())
            .build();
        g.rebuild_diff_against_previous();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        let panel = Rect::new(0.0, 0.0, 200.0, 200.0);
        let ctx = GeomContext::with_projection(panel, 96.0, &shapes, &scales, &polar);
        g.draw(&mut scene, &ctx);

        // Without cap densification a 3-row Free band under polar produces:
        //   1 MoveTo
        // + 2 LineTo on curve A (rows 1, 2 — row 0 is MoveTo)
        // + N_polar interior LineTos for the row-to-row densification on A
        // + 3 LineTo on reversed curve B
        // + N_polar interior LineTos for the row-to-row densification on B
        // + 1 ClosePath
        //
        // With cap densification both caps add interior LineTos as well. We
        // check the path contains the two cap arcs by looking for the
        // densified samples that don't fall on a straight line between
        // their bracketing curve endpoints.
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                let lines: Vec<crate::geometry::Point> = path
                    .elements()
                    .iter()
                    .filter_map(|el| match el {
                        crate::path::PathEl::LineTo(p) => Some(*p),
                        _ => None,
                    })
                    .collect();
                let move_to = path
                    .elements()
                    .iter()
                    .find_map(|el| match el {
                        crate::path::PathEl::MoveTo(p) => Some(*p),
                        _ => None,
                    })
                    .expect("expected a MoveTo");
                let mut all_pts = vec![move_to];
                all_pts.extend(lines.iter().copied());

                // Identify the cap region: the polygon walks
                // curve A forward → end cap samples → reversed curve B →
                // start cap samples → close. The reversed curve B's first
                // point is the end of curve B at row 2 = (x=0.8, y2=0.4)
                // in polar coords; reversed curve B's last point is at row
                // 0 = (x=0.2, y2=0.4). The start cap samples lie between
                // (x=0.2, y2=0.4) and (x=0.1, y=0.8) in data space.
                //
                // Simpler proof of densification: count line segments. A
                // 3-row Free band's bare polygon (no row densification, no
                // cap densification) has 6 line segments (3 on A forward,
                // 3 on reversed B). Polar row densification adds some; cap
                // densification adds more. Assert that the total exceeds
                // what row densification alone could produce.
                //
                // Compare against the same band run WITHOUT cap
                // densification (the previous behaviour) by counting the
                // segments that land outside the straight chords from
                // curve_a[last] → curve_b[last] and curve_b[0] →
                // curve_a[0]. If any such "off-chord" point exists, cap
                // densification fired.
                let total_lines = lines.len();
                assert!(
                    total_lines > 6,
                    "expected densified polygon, got {total_lines} line segments"
                );

                // Stronger check: under the same cap setup with Cartesian
                // (no densification at all) the polygon has exactly 6
                // LineTos (no row, no cap densification). Under polar with
                // row-only densification we'd expect roughly the same plus
                // row-densification samples — strictly more than 6, but
                // still finite. The cap arc here spans theta from
                // ≈ 0.2 turns to ≈ 0.1 turns and from ≈ 0.9 turns to
                // ≈ 0.8 turns at constant radius, well within the
                // `MAX_THETA_STEP_RAD = π/120` threshold for sample
                // insertion. So we should see at LEAST a couple of
                // off-chord points.

                // Walk all line-to points; identify those that lie on the
                // straight chord between curve A's last and curve B's
                // last (the end cap region) or curve B's first and curve
                // A's first (the start cap region) — anything OFF those
                // straight chords is a cap arc sample, proving cap
                // densification fired.
                //
                // We don't have direct access to the curve endpoints here,
                // but we know the polygon visits curve A's first (at
                // MoveTo), so the polygon's sample stream is
                // self-describing. Walking the recorded points and
                // looking for any non-collinear triples close to the
                // expected cap regions is enough.
                let collinear_eps = 0.5_f64; // 0.5 px slack
                let mut cap_arc_count = 0usize;
                for w in all_pts.windows(3) {
                    let (a, b, c) = (w[0], w[1], w[2]);
                    // Signed area of triangle abc: if non-zero, b is off
                    // the chord between a and c.
                    let area2 = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
                    if area2.abs() > collinear_eps {
                        cap_arc_count += 1;
                    }
                }
                assert!(
                    cap_arc_count > 0,
                    "expected at least one off-chord (curved) interior sample, got {cap_arc_count}"
                );
                return;
            }
        }
        panic!("no fill emitted");
    }

    #[test]
    fn free_orientation_solid_fill_emits_path() {
        // Both x2 and y2 supplied with constant fill — still goes
        // through the closed-contour path fill, not the mesh.
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("x2", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y2", Raw(vec![0.2_f64, 0.4, 0.2]))
            .set("fill", red())
            .build();
        assert_eq!(g.orientation, Orientation::Free);
        let scene = draw_and_record(g);
        let fills = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Fill { .. }))
            .count();
        let meshes = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::DrawMesh { .. }))
            .count();
        assert_eq!(fills, 1);
        assert_eq!(meshes, 0);
    }

    #[test]
    fn free_orientation_varying_fill_uses_mesh() {
        let g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5]))
            .set("x2", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y2", Raw(vec![0.2_f64, 0.4, 0.2]))
            .set("fill", vec![red(), blue(), red()])
            .build();
        let scene = draw_and_record(g);
        let mesh_op = scene.ops.iter().find_map(|op| match op {
            Op::DrawMesh { mesh, .. } => Some(mesh),
            _ => None,
        });
        let mesh = mesh_op.expect("expected mesh draw for Free + varying fill");
        // Three rows → 2 quads → 4 triangles → 12 indices.
        assert_eq!(mesh.triangle_count(), 4);
        // Quad-pair canonical index pattern reaches the backend.
        assert_eq!(&mesh.indices[0..6], &[0, 1, 2, 0, 2, 3]);
    }

    #[test]
    fn axis_aligned_varying_fill_under_polar_uses_mesh() {
        use crate::plot::projection::Projection;
        let polar = Projection::polar();
        let mut g = RibbonGeom::builder()
            .set("x", Raw(vec![0.1_f64, 0.5, 0.9]))
            .set("y", Raw(vec![0.8_f64, 0.8, 0.8]))
            .set("y2", Raw(vec![0.4_f64, 0.4, 0.4]))
            .set("fill", vec![red(), blue(), red()])
            .build();
        g.rebuild_diff_against_previous();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        let panel = Rect::new(0.0, 0.0, 200.0, 200.0);
        let ctx = GeomContext::with_projection(panel, 96.0, &shapes, &scales, &polar);
        g.draw(&mut scene, &ctx);
        let meshes = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::DrawMesh { .. }))
            .count();
        let gradient_fills = scene
            .ops
            .iter()
            .filter(|op| {
                matches!(
                    op,
                    Op::Fill {
                        brush: Brush::Gradient(_),
                        ..
                    }
                )
            })
            .count();
        assert_eq!(
            meshes, 1,
            "expected mesh dispatch under polar + varying fill"
        );
        assert_eq!(
            gradient_fills, 0,
            "gradient brush should not run under non-linear projection"
        );
    }

    #[test]
    fn pick_id_per_mark_resolves_from_first_row() {
        let g = RibbonGeom::builder()
            .keys(vec!["A", "A", "A", "B", "B", "B"])
            .set("x", Raw(vec![0.1_f64, 0.3, 0.5, 0.6, 0.7, 0.9]))
            .set("y", Raw(vec![0.5_f64, 0.7, 0.5, 0.4, 0.6, 0.4]))
            .set("y2", Raw(0.2_f64))
            .set("fill", red())
            .set("pick_id", vec![1001_i64, 0, 0, 2002, 0, 0])
            .build();
        let scene = draw_and_record(g);
        let picks: Vec<u32> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Fill {
                    pick_id: crate::pick::PickId::Id(n),
                    ..
                } => Some(*n),
                _ => None,
            })
            .collect();
        assert_eq!(picks, vec![1001, 2002]);
    }
}