ruviz 0.6.0

High-performance 2D plotting library for Rust
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
//! Area and fill between plot implementations
//!
//! Provides area fill, fill_between, and stackplot functionality.
//!
//! # Trait-Based API
//!
//! Area plots implement the core plot traits:
//! - [`PlotConfig`] for `AreaConfig` and `StackPlotConfig`
//! - [`PlotCompute`] for `Area` and `StackedArea` marker structs
//! - [`PlotData`] for `AreaData` and `StackedAreaData`
//! - [`PlotRender`] for `AreaData` and `StackedAreaData`
//!
//! # How the builder draws a stacked area
//!
//! [`Plot::stacked_area`](crate::core::Plot::stacked_area) does **not** add one
//! series holding the whole chart. It adds **one series per named value
//! column** — a [`StackedAreaBand`] each — because a palette slot, a legend
//! entry and a `.color()` are per-series things and a stack whose bands cannot
//! be told apart in the legend says nothing. [`stacked_area_bands`] performs
//! that split; [`StackedAreaData`] remains the whole-chart shape for callers
//! driving [`PlotCompute`] and [`PlotRender`] directly.

use crate::core::Result;
use crate::plots::traits::{
    ComputedSeries, ComputedStyle, LegendKey, PlotArea, PlotCompute, PlotConfig, PlotData,
    PlotPrimitive, PlotRender, draw_primitives,
};
use crate::render::skia::SkiaRenderer;
use crate::render::{Color, LineStyle, Theme};

/// Configuration for area plot
#[derive(Debug, Clone)]
pub struct AreaConfig {
    /// Fill color
    pub color: Option<Color>,
    /// Fill alpha
    pub alpha: f32,
    /// Line color (None for no line)
    pub line_color: Option<Color>,
    /// Line width
    pub line_width: f32,
    /// Baseline value (default 0.0)
    pub baseline: f64,
    /// Interpolation between points
    pub interpolation: AreaInterpolation,
}

/// Interpolation method for area fill
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AreaInterpolation {
    /// Linear interpolation between points
    #[default]
    Linear,
    /// Step function (constant until next point)
    Step,
    /// Smooth spline interpolation
    Smooth,
}

impl Default for AreaConfig {
    fn default() -> Self {
        Self {
            color: None,
            alpha: 0.5,
            line_color: None,
            line_width: 1.5,
            baseline: 0.0,
            interpolation: AreaInterpolation::Linear,
        }
    }
}

impl AreaConfig {
    /// Create new config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set fill color
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// Set fill alpha
    pub fn alpha(mut self, alpha: f32) -> Self {
        self.alpha = alpha.clamp(0.0, 1.0);
        self
    }

    /// Set line color
    pub fn line_color(mut self, color: Color) -> Self {
        self.line_color = Some(color);
        self
    }

    /// Set line width
    pub fn line_width(mut self, width: f32) -> Self {
        self.line_width = width.max(0.0);
        self
    }

    /// Set baseline
    pub fn baseline(mut self, baseline: f64) -> Self {
        self.baseline = baseline;
        self
    }

    /// Set interpolation
    pub fn interpolation(mut self, interp: AreaInterpolation) -> Self {
        self.interpolation = interp;
        self
    }
}

/// Generate polygon vertices for area fill (fill to baseline)
///
/// # Arguments
/// * `x` - X coordinates
/// * `y` - Y coordinates
/// * `baseline` - Y value for baseline
///
/// # Returns
/// Polygon vertices as (x, y) pairs
pub fn area_polygon(x: &[f64], y: &[f64], baseline: f64) -> Vec<(f64, f64)> {
    if x.is_empty() || y.is_empty() {
        return vec![];
    }

    let n = x.len().min(y.len());
    let mut polygon = Vec::with_capacity(n * 2 + 2);

    // Top edge (data points)
    for i in 0..n {
        polygon.push((x[i], y[i]));
    }

    // Bottom edge (baseline, reversed)
    polygon.push((x[n - 1], baseline));
    polygon.push((x[0], baseline));

    polygon
}

/// Generate polygon vertices for fill_between
///
/// # Arguments
/// * `x` - X coordinates
/// * `y1` - Lower Y boundary
/// * `y2` - Upper Y boundary
///
/// # Returns
/// Polygon vertices as (x, y) pairs
pub fn fill_between_polygon(x: &[f64], y1: &[f64], y2: &[f64]) -> Vec<(f64, f64)> {
    if x.is_empty() || y1.is_empty() || y2.is_empty() {
        return vec![];
    }

    let n = x.len().min(y1.len()).min(y2.len());
    let mut polygon = Vec::with_capacity(n * 2);

    // Upper boundary (y2)
    for i in 0..n {
        polygon.push((x[i], y2[i]));
    }

    // Lower boundary (y1, reversed)
    for i in (0..n).rev() {
        polygon.push((x[i], y1[i]));
    }

    polygon
}

/// Generate polygon vertices for fill_between with condition
///
/// Only fills where condition is true
///
/// # Arguments
/// * `x` - X coordinates
/// * `y1` - Lower Y boundary
/// * `y2` - Upper Y boundary
/// * `where_mask` - Boolean mask for which points to include
///
/// # Returns
/// Vec of polygon segments (each segment is a separate filled region)
pub fn fill_between_where(
    x: &[f64],
    y1: &[f64],
    y2: &[f64],
    where_mask: &[bool],
) -> Vec<Vec<(f64, f64)>> {
    if x.is_empty() || y1.is_empty() || y2.is_empty() || where_mask.is_empty() {
        return vec![];
    }

    let n = x.len().min(y1.len()).min(y2.len()).min(where_mask.len());
    let mut segments = Vec::new();
    let mut current_segment: Option<(usize, usize)> = None;

    for (i, &mask_val) in where_mask.iter().enumerate().take(n) {
        if mask_val {
            match current_segment {
                None => current_segment = Some((i, i)),
                Some((start, _)) => current_segment = Some((start, i)),
            }
        } else if let Some((start, end)) = current_segment {
            // End of segment
            let segment_x: Vec<f64> = x[start..=end].to_vec();
            let segment_y1: Vec<f64> = y1[start..=end].to_vec();
            let segment_y2: Vec<f64> = y2[start..=end].to_vec();
            segments.push(fill_between_polygon(&segment_x, &segment_y1, &segment_y2));
            current_segment = None;
        }
    }

    // Handle final segment
    if let Some((start, end)) = current_segment {
        let segment_x: Vec<f64> = x[start..=end].to_vec();
        let segment_y1: Vec<f64> = y1[start..=end].to_vec();
        let segment_y2: Vec<f64> = y2[start..=end].to_vec();
        segments.push(fill_between_polygon(&segment_x, &segment_y1, &segment_y2));
    }

    segments
}

/// Configuration for stacked area plot
#[derive(Debug, Clone)]
pub struct StackPlotConfig {
    /// Colors for each series (None for auto-colors)
    pub colors: Option<Vec<Color>>,
    /// Alpha for fill
    pub alpha: f32,
    /// Labels for each series
    pub labels: Vec<String>,
    /// Baseline mode
    pub baseline: StackBaseline,
    /// Show lines between areas
    pub show_lines: bool,
    /// Line color
    pub line_color: Color,
    /// Line width
    pub line_width: f32,
}

/// Baseline mode for stack plot
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StackBaseline {
    /// Zero baseline (standard stacked area)
    #[default]
    Zero,
    /// Symmetric around zero (streamgraph style)
    Symmetric,
    /// Wiggle minimized (ThemeRiver style)
    Wiggle,
}

impl Default for StackPlotConfig {
    fn default() -> Self {
        Self {
            colors: None,
            alpha: 0.8,
            labels: vec![],
            baseline: StackBaseline::Zero,
            show_lines: false,
            line_color: Color::from_rgb(255, 255, 255),
            line_width: 0.5,
        }
    }
}

impl StackPlotConfig {
    /// Create new config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set colors
    pub fn colors(mut self, colors: Vec<Color>) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Set alpha
    pub fn alpha(mut self, alpha: f32) -> Self {
        self.alpha = alpha.clamp(0.0, 1.0);
        self
    }

    /// Set labels
    pub fn labels(mut self, labels: Vec<String>) -> Self {
        self.labels = labels;
        self
    }

    /// Set baseline mode
    pub fn baseline(mut self, baseline: StackBaseline) -> Self {
        self.baseline = baseline;
        self
    }

    /// Show separator lines
    pub fn lines(mut self, show: bool) -> Self {
        self.show_lines = show;
        self
    }
}

// Implement PlotConfig marker trait
impl PlotConfig for AreaConfig {}
impl PlotConfig for StackPlotConfig {}

/// Marker struct for Area plot type
pub struct Area;

/// Marker struct for StackedArea plot type
pub struct StackedArea;

/// Compute stacked area data
///
/// # Arguments
/// * `x` - Shared X coordinates
/// * `ys` - Multiple Y series to stack
/// * `baseline` - Baseline mode
///
/// # Returns
/// Vec of (lower_bound, upper_bound) for each series
pub fn compute_stack(
    x: &[f64],
    ys: &[Vec<f64>],
    baseline: StackBaseline,
) -> Vec<(Vec<f64>, Vec<f64>)> {
    if x.is_empty() || ys.is_empty() {
        return vec![];
    }

    let n = x.len();
    let num_series = ys.len();

    // Compute cumulative sums
    let mut cumulative: Vec<Vec<f64>> = vec![vec![0.0; n]; num_series + 1];

    for (i, y) in ys.iter().enumerate() {
        for j in 0..n.min(y.len()) {
            cumulative[i + 1][j] = cumulative[i][j] + y[j];
        }
    }

    // Apply baseline transformation
    let offset: Vec<f64> = match baseline {
        StackBaseline::Zero => vec![0.0; n],
        StackBaseline::Symmetric => {
            // Center around zero
            let total = &cumulative[num_series];
            total.iter().map(|t| -t / 2.0).collect()
        }
        StackBaseline::Wiggle => {
            // Minimize wiggle (ThemeRiver algorithm)
            // For simplicity, use symmetric for now
            let total = &cumulative[num_series];
            total.iter().map(|t| -t / 2.0).collect()
        }
    };

    // Build result
    let mut result = Vec::with_capacity(num_series);
    for i in 0..num_series {
        let lower: Vec<f64> = cumulative[i]
            .iter()
            .zip(offset.iter())
            .map(|(c, o)| c + o)
            .collect();
        let upper: Vec<f64> = cumulative[i + 1]
            .iter()
            .zip(offset.iter())
            .map(|(c, o)| c + o)
            .collect();
        result.push((lower, upper));
    }

    result
}

// ============================================================================
// Trait-Based API
// ============================================================================

/// Computed area data
#[derive(Debug, Clone)]
pub struct AreaData {
    /// Polygon vertices for the filled area
    pub polygon: Vec<(f64, f64)>,
    /// X coordinates
    pub x: Vec<f64>,
    /// Y coordinates
    pub y: Vec<f64>,
    /// Data bounds
    pub bounds: ((f64, f64), (f64, f64)),
    /// Configuration used
    pub(crate) config: AreaConfig,
}

/// Input for area plot computation
pub struct AreaInput<'a> {
    /// X coordinates
    pub x: &'a [f64],
    /// Y coordinates
    pub y: &'a [f64],
}

impl<'a> AreaInput<'a> {
    /// Create new area input
    pub fn new(x: &'a [f64], y: &'a [f64]) -> Self {
        Self { x, y }
    }
}

impl PlotCompute for Area {
    type Input<'a> = AreaInput<'a>;
    type Config = AreaConfig;
    type Output = AreaData;

    fn compute(input: Self::Input<'_>, config: &Self::Config) -> Result<Self::Output> {
        if input.x.is_empty() || input.y.is_empty() {
            return Err(crate::core::PlottingError::EmptyDataSet);
        }

        let polygon = area_polygon(input.x, input.y, config.baseline);

        let x_min = input.x.iter().cloned().fold(f64::INFINITY, f64::min);
        let x_max = input.x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let y_min = input
            .y
            .iter()
            .cloned()
            .fold(f64::INFINITY, f64::min)
            .min(config.baseline);
        let y_max = input
            .y
            .iter()
            .cloned()
            .fold(f64::NEG_INFINITY, f64::max)
            .max(config.baseline);

        Ok(AreaData {
            polygon,
            x: input.x.to_vec(),
            y: input.y.to_vec(),
            bounds: ((x_min, x_max), (y_min, y_max)),
            config: config.clone(),
        })
    }
}

impl PlotData for AreaData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        self.bounds
    }

    fn is_empty(&self) -> bool {
        self.polygon.is_empty()
    }
}

impl PlotRender for AreaData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        _theme: &Theme,
        color: Color,
    ) -> Result<()> {
        if self.polygon.is_empty() {
            return Ok(());
        }

        let config = &self.config;
        let fill_color = config.color.unwrap_or(color).with_alpha(config.alpha);

        // Convert polygon to screen coordinates
        let screen_polygon: Vec<(f32, f32)> = self
            .polygon
            .iter()
            .map(|(x, y)| area.data_to_screen(*x, *y))
            .collect();

        // Draw filled area
        renderer.draw_filled_polygon(&screen_polygon, fill_color)?;

        // Draw top line if configured
        if let Some(line_color) = config.line_color {
            let n = self.x.len();
            let line_points: Vec<(f32, f32)> = (0..n)
                .map(|i| area.data_to_screen(self.x[i], self.y[i]))
                .collect();
            renderer.draw_polyline(
                &line_points,
                line_color,
                config.line_width,
                LineStyle::Solid,
            )?;
        }

        Ok(())
    }
}

/// Computed stacked area data
#[derive(Debug, Clone)]
pub struct StackedAreaData {
    /// Stack bounds for each series (lower, upper)
    pub stacks: Vec<(Vec<f64>, Vec<f64>)>,
    /// X coordinates
    pub x: Vec<f64>,
    /// Data bounds
    pub bounds: ((f64, f64), (f64, f64)),
    /// Configuration used
    pub(crate) config: StackPlotConfig,
}

/// Input for stacked area plot computation
pub struct StackedAreaInput<'a> {
    /// X coordinates
    pub x: &'a [f64],
    /// Y series to stack
    pub ys: &'a [Vec<f64>],
}

impl<'a> StackedAreaInput<'a> {
    /// Create new stacked area input
    pub fn new(x: &'a [f64], ys: &'a [Vec<f64>]) -> Self {
        Self { x, ys }
    }
}

impl PlotCompute for StackedArea {
    type Input<'a> = StackedAreaInput<'a>;
    type Config = StackPlotConfig;
    type Output = StackedAreaData;

    fn compute(input: Self::Input<'_>, config: &Self::Config) -> Result<Self::Output> {
        if input.x.is_empty() || input.ys.is_empty() {
            return Err(crate::core::PlottingError::EmptyDataSet);
        }

        let stacks = compute_stack(input.x, input.ys, config.baseline);

        if stacks.is_empty() {
            return Err(crate::core::PlottingError::EmptyDataSet);
        }

        // Compute bounds
        let x_min = input.x.iter().cloned().fold(f64::INFINITY, f64::min);
        let x_max = input.x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);

        let mut y_min = f64::INFINITY;
        let mut y_max = f64::NEG_INFINITY;
        for (lower, upper) in &stacks {
            y_min = y_min.min(lower.iter().cloned().fold(f64::INFINITY, f64::min));
            y_max = y_max.max(upper.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
        }

        Ok(StackedAreaData {
            stacks,
            x: input.x.to_vec(),
            bounds: ((x_min, x_max), (y_min, y_max)),
            config: config.clone(),
        })
    }
}

impl PlotData for StackedAreaData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        self.bounds
    }

    fn is_empty(&self) -> bool {
        self.stacks.is_empty()
    }
}

impl PlotRender for StackedAreaData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        _color: Color,
    ) -> Result<()> {
        if self.stacks.is_empty() {
            return Ok(());
        }

        let config = &self.config;

        for (i, (lower, upper)) in self.stacks.iter().enumerate() {
            let polygon = fill_between_polygon(&self.x, lower, upper);

            let fill_color = config
                .colors
                .as_ref()
                .and_then(|c| c.get(i).copied())
                .unwrap_or_else(|| theme.get_color(i))
                .with_alpha(config.alpha);

            // Convert to screen coordinates
            let screen_polygon: Vec<(f32, f32)> = polygon
                .iter()
                .map(|(x, y)| area.data_to_screen(*x, *y))
                .collect();

            renderer.draw_filled_polygon(&screen_polygon, fill_color)?;

            // Draw separator line if configured
            if config.show_lines && i < self.stacks.len() - 1 {
                let upper_line: Vec<(f32, f32)> = self
                    .x
                    .iter()
                    .zip(upper.iter())
                    .map(|(x, y)| area.data_to_screen(*x, *y))
                    .collect();
                renderer.draw_polyline(
                    &upper_line,
                    config.line_color,
                    config.line_width,
                    LineStyle::Solid,
                )?;
            }
        }

        Ok(())
    }
}

// ============================================================================
// One band at a time: what the `Plot` builder actually adds
// ============================================================================

/// The filled region one *named* value column of a stacked area chart covers.
///
/// A stacked area chart is N of these, added to the plot as N ordinary series:
/// the palette slot, the legend entry, the `.color()` override and the
/// `.label()` are all per-series things, so a chart that needs N of each is N
/// series. Nothing about the render path is multi-series.
///
/// `lower` is the running total of the bands underneath and `upper` includes
/// this one, so the union of the bands' [`PlotData::data_bounds`] is the
/// cumulative extent of the stack — there is no separate whole-chart bounds
/// arm that could disagree with the geometry.
#[derive(Debug, Clone)]
pub struct StackedAreaBand {
    /// Shared x positions.
    pub x: Vec<f64>,
    /// Running total under this band, per sample.
    pub lower: Vec<f64>,
    /// Running total including this band, per sample.
    pub upper: Vec<f64>,
    /// Fill opacity from the chart config; composes with the series alpha.
    pub(crate) alpha: f32,
    /// Whether to stroke this band's top edge as a separator. False on the
    /// topmost band, whose top edge is the silhouette of the chart rather than
    /// a boundary between two bands.
    pub(crate) show_line: bool,
    /// Separator colour.
    pub(crate) line_color: Color,
    /// Separator width in **points**, so it is DPI-invariant.
    pub(crate) line_width: f32,
}

/// One [`StackedAreaBand`] per named value column.
///
/// `names` and `values` are parallel: `values[i]` is the column named
/// `names[i]`, sampled at the same `x` as every other column.
pub fn stacked_area_bands(
    x: &[f64],
    names: &[String],
    ys: &[Vec<f64>],
    config: &StackPlotConfig,
) -> Vec<(String, StackedAreaBand)> {
    let stacks = compute_stack(x, ys, config.baseline);
    let last = stacks.len().saturating_sub(1);

    stacks
        .into_iter()
        .enumerate()
        .map(|(index, (lower, upper))| {
            (
                names.get(index).cloned().unwrap_or_default(),
                StackedAreaBand {
                    x: x.to_vec(),
                    lower,
                    upper,
                    alpha: config.alpha,
                    show_line: config.show_lines && index < last,
                    line_color: config.line_color,
                    line_width: config.line_width,
                },
            )
        })
        .collect()
}

impl PlotData for StackedAreaBand {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        let mut x_min = f64::INFINITY;
        let mut x_max = f64::NEG_INFINITY;
        for &value in &self.x {
            if value.is_finite() {
                x_min = x_min.min(value);
                x_max = x_max.max(value);
            }
        }

        let mut y_min = f64::INFINITY;
        let mut y_max = f64::NEG_INFINITY;
        for &value in self.lower.iter().chain(self.upper.iter()) {
            if value.is_finite() {
                y_min = y_min.min(value);
                y_max = y_max.max(value);
            }
        }

        if !x_min.is_finite() || !y_min.is_finite() {
            return ((0.0, 1.0), (0.0, 1.0));
        }
        ((x_min, x_max), (y_min, y_max))
    }

    fn is_empty(&self) -> bool {
        self.x.is_empty() || self.upper.is_empty()
    }
}

impl ComputedSeries for StackedAreaBand {
    fn kind(&self) -> &'static str {
        "stacked_area"
    }

    fn point_count(&self) -> usize {
        self.x.len()
    }

    /// A filled patch — a line swatch would claim the band is a curve.
    fn legend_key(&self) -> LegendKey {
        LegendKey::Patch
    }

    /// One filled band, plus its separator when it has one above it.
    fn primitives(&self, area: &PlotArea, style: &ComputedStyle) -> Vec<PlotPrimitive> {
        let fill = style.tinted(style.color.with_alpha(self.alpha));

        // A vertex the axes cannot place is not part of the shape, and the
        // shape closes over the vertices that remain — the polygon rule.
        let points = area.project_points(fill_between_polygon(&self.x, &self.lower, &self.upper));
        let mut primitives = Vec::new();
        if points.len() >= 3 {
            primitives.push(PlotPrimitive::Polygon {
                points,
                fill: Some(fill),
                edge: None,
            });
        }

        if self.show_line {
            // `.line_width(..)` on the chain overrides the config's own, so the
            // separator obeys the same width knob every other stroke does.
            let width_px = style.stroke_px(self.line_width);
            let color = style.tinted(self.line_color);
            // A separator is a *line*, so it breaks at a gap rather than being
            // drawn across one.
            for run in area.project_subpaths(self.x.iter().copied().zip(self.upper.iter().copied()))
            {
                for pair in run.windows(2) {
                    primitives.push(PlotPrimitive::Line {
                        from: pair[0],
                        to: pair[1],
                        color,
                        width_px,
                        style: LineStyle::Solid,
                    });
                }
            }
        }

        primitives
    }
}

impl PlotRender for StackedAreaBand {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        _theme: &Theme,
        color: Color,
    ) -> Result<()> {
        let style = ComputedStyle::opaque(renderer.render_scale(), color);
        draw_primitives(renderer, &self.primitives(area, &style))
    }

    fn render_styled(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        _theme: &Theme,
        color: Color,
        alpha: f32,
        _line_width: Option<f32>,
    ) -> Result<()> {
        let style = ComputedStyle {
            scale: renderer.render_scale(),
            color,
            alpha,
            line_width: None,
        };
        draw_primitives(renderer, &self.primitives(area, &style))
    }
}

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

    #[test]
    fn test_area_polygon() {
        let x = vec![0.0, 1.0, 2.0];
        let y = vec![1.0, 2.0, 1.0];
        let polygon = area_polygon(&x, &y, 0.0);

        // Should have 5 points: 3 data + 2 baseline
        assert_eq!(polygon.len(), 5);
        assert_eq!(polygon[0], (0.0, 1.0));
        assert_eq!(polygon[3], (2.0, 0.0));
        assert_eq!(polygon[4], (0.0, 0.0));
    }

    #[test]
    fn test_fill_between_polygon() {
        let x = vec![0.0, 1.0, 2.0];
        let y1 = vec![0.0, 0.0, 0.0];
        let y2 = vec![1.0, 2.0, 1.0];
        let polygon = fill_between_polygon(&x, &y1, &y2);

        // Should have 6 points: 3 upper + 3 lower
        assert_eq!(polygon.len(), 6);
    }

    #[test]
    fn test_fill_between_where() {
        let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
        let y1 = vec![0.0; 5];
        let y2 = vec![1.0; 5];
        let mask = vec![true, true, false, true, true];

        let segments = fill_between_where(&x, &y1, &y2, &mask);
        assert_eq!(segments.len(), 2); // Two segments due to false in middle
    }

    #[test]
    fn test_compute_stack_zero() {
        let x = vec![0.0, 1.0, 2.0];
        let ys = vec![vec![1.0, 2.0, 1.0], vec![2.0, 1.0, 2.0]];

        let stack = compute_stack(&x, &ys, StackBaseline::Zero);
        assert_eq!(stack.len(), 2);

        // First series: 0 to y[0]
        assert!((stack[0].0[0] - 0.0).abs() < 1e-10);
        assert!((stack[0].1[0] - 1.0).abs() < 1e-10);

        // Second series: y[0] to y[0]+y[1]
        assert!((stack[1].0[0] - 1.0).abs() < 1e-10);
        assert!((stack[1].1[0] - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_compute_stack_symmetric() {
        let x = vec![0.0, 1.0];
        let ys = vec![vec![2.0, 2.0]];

        let stack = compute_stack(&x, &ys, StackBaseline::Symmetric);
        assert_eq!(stack.len(), 1);

        // Should be centered around 0
        assert!((stack[0].0[0] - (-1.0)).abs() < 1e-10);
        assert!((stack[0].1[0] - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_area_config_implements_plot_config() {
        fn assert_plot_config<T: PlotConfig>() {}
        assert_plot_config::<AreaConfig>();
    }

    #[test]
    fn test_stack_plot_config_implements_plot_config() {
        fn assert_plot_config<T: PlotConfig>() {}
        assert_plot_config::<StackPlotConfig>();
    }

    #[test]
    fn test_area_plot_compute_trait() {
        use crate::plots::traits::PlotCompute;

        let x = vec![0.0, 1.0, 2.0];
        let y = vec![1.0, 2.0, 1.0];
        let config = AreaConfig::default();
        let input = AreaInput::new(&x, &y);
        let result = Area::compute(input, &config);

        assert!(result.is_ok());
        let area_data = result.unwrap();
        assert!(!area_data.polygon.is_empty());
    }

    #[test]
    fn test_area_plot_compute_empty() {
        use crate::plots::traits::PlotCompute;

        let x: Vec<f64> = vec![];
        let y: Vec<f64> = vec![];
        let config = AreaConfig::default();
        let input = AreaInput::new(&x, &y);
        let result = Area::compute(input, &config);

        assert!(result.is_err());
    }

    #[test]
    fn test_area_plot_data_trait() {
        use crate::plots::traits::{PlotCompute, PlotData};

        let x = vec![0.0, 1.0, 2.0];
        let y = vec![1.0, 2.0, 1.0];
        let config = AreaConfig::default();
        let input = AreaInput::new(&x, &y);
        let area_data = Area::compute(input, &config).unwrap();

        // Test data_bounds
        let ((x_min, x_max), (y_min, y_max)) = area_data.data_bounds();
        assert!((x_min - 0.0).abs() < 1e-10);
        assert!((x_max - 2.0).abs() < 1e-10);
        assert!(y_min <= y_max);

        // Test is_empty
        assert!(!area_data.is_empty());
    }

    #[test]
    fn test_stacked_area_plot_compute_trait() {
        use crate::plots::traits::PlotCompute;

        let x = vec![0.0, 1.0, 2.0];
        let ys = vec![vec![1.0, 2.0, 1.0], vec![2.0, 1.0, 2.0]];
        let config = StackPlotConfig::default();
        let input = StackedAreaInput::new(&x, &ys);
        let result = StackedArea::compute(input, &config);

        assert!(result.is_ok());
        let stack_data = result.unwrap();
        assert_eq!(stack_data.stacks.len(), 2);
    }

    #[test]
    fn test_stacked_area_plot_data_trait() {
        use crate::plots::traits::{PlotCompute, PlotData};

        let x = vec![0.0, 1.0, 2.0];
        let ys = vec![vec![1.0, 2.0, 1.0], vec![2.0, 1.0, 2.0]];
        let config = StackPlotConfig::default();
        let input = StackedAreaInput::new(&x, &ys);
        let stack_data = StackedArea::compute(input, &config).unwrap();

        // Test data_bounds
        let ((x_min, x_max), (y_min, y_max)) = stack_data.data_bounds();
        assert!((x_min - 0.0).abs() < 1e-10);
        assert!((x_max - 2.0).abs() < 1e-10);
        assert!(y_min <= y_max);

        // Test is_empty
        assert!(!stack_data.is_empty());
    }

    // ===== The per-band split the `Plot` builder adds =====

    fn stack_input() -> (Vec<f64>, Vec<String>, Vec<Vec<f64>>) {
        (
            vec![0.0, 1.0, 2.0],
            vec!["a".to_string(), "b".to_string()],
            vec![vec![1.0, 2.0, 1.0], vec![2.0, 1.0, 2.0]],
        )
    }

    #[test]
    fn a_stacked_area_splits_into_one_band_per_named_column() {
        let (x, names, ys) = stack_input();
        let bands = stacked_area_bands(&x, &names, &ys, &StackPlotConfig::default());

        assert_eq!(bands.len(), 2, "one series per named value column");
        assert_eq!(bands[0].0, "a");
        assert_eq!(bands[1].0, "b");
        assert_eq!(bands[0].1.lower, vec![0.0, 0.0, 0.0]);
        assert_eq!(bands[0].1.upper, vec![1.0, 2.0, 1.0]);
        assert_eq!(bands[1].1.lower, vec![1.0, 2.0, 1.0]);
        assert_eq!(bands[1].1.upper, vec![3.0, 3.0, 3.0]);
    }

    #[test]
    fn bands_report_cumulative_bounds() {
        let (x, names, ys) = stack_input();
        let bands = stacked_area_bands(&x, &names, &ys, &StackPlotConfig::default());

        assert_eq!(bands[0].1.data_bounds(), ((0.0, 2.0), (0.0, 2.0)));
        assert_eq!(bands[1].1.data_bounds(), ((0.0, 2.0), (1.0, 3.0)));

        // The union is what the axis has to show, and it matches the
        // whole-chart compute exactly.
        let top = bands
            .iter()
            .map(|(_, b)| b.data_bounds().1.1)
            .fold(f64::NEG_INFINITY, f64::max);
        let whole =
            StackedArea::compute(StackedAreaInput::new(&x, &ys), &StackPlotConfig::default())
                .unwrap();
        assert_eq!(top, whole.data_bounds().1.1);
    }

    #[test]
    fn only_the_bands_underneath_carry_a_separator() {
        // The top band's upper edge is the silhouette of the chart, not a
        // boundary between two bands, so stroking it would draw an outline the
        // reader has to interpret as a series.
        let (x, names, ys) = stack_input();
        let config = StackPlotConfig::default().lines(true);
        let bands = stacked_area_bands(&x, &names, &ys, &config);

        assert!(bands[0].1.show_line);
        assert!(!bands[1].1.show_line);
    }

    #[test]
    fn a_band_draws_one_filled_polygon() {
        let (x, names, ys) = stack_input();
        let bands = stacked_area_bands(&x, &names, &ys, &StackPlotConfig::default());
        let band = &bands[0].1;
        let ((x_min, x_max), (y_min, y_max)) = band.data_bounds();
        let area = PlotArea::new(0.0, 0.0, 200.0, 100.0, x_min, x_max, y_min, y_max);
        let style = ComputedStyle::opaque(
            crate::core::units::RenderScale::new(96.0),
            Color::from_rgb(10, 20, 30),
        );

        let primitives = band.primitives(&area, &style);
        assert_eq!(primitives.len(), 1);
        assert!(matches!(
            &primitives[0],
            PlotPrimitive::Polygon {
                points,
                fill: Some(_),
                edge: None,
            } if points.len() == 6
        ));
    }
}