uzor-figures 1.5.0

Data-figure engine for uzor — scales, plot-area coordinates, stateless mark/guide draw functions, and composed figures (bar/curve/histogram) over the uzor render stack.
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
//! `BarFigure` — a categorical bar chart: nice-rounded linear Y domain,
//! band X, grid + axes + bars, optional per-bar value labels.
//!
//! Multi-series (`BarSeries`/`BarMode::{Grouped, Stacked}`) is additive:
//! [`BarFigure::new`] is now sugar for a single-series
//! [`BarMode::Grouped`] figure via [`BarFigure::with_series`], and its
//! render output is byte-identical to the pre-multi-series version — the
//! single-series draw/hover/tooltip path below is the SAME code that
//! existed before ([`crate::mark::rect::draw_bars`], not the new
//! `draw_bars_grouped`), gated on `self.series.len() <= 1`; grouped/
//! stacked geometry only activates for a genuinely multi-series figure. A
//! legend ([`crate::guide::legend`]) auto-appears at [`LegendPosition::Top`]
//! once `series.len() > 1`, or on any figure via [`BarFigure::with_legend`].
//!
//! **Engine-strengthening WAVE 4b**: [`BarMode::Stacked`]'s own
//! accumulation (formerly `BarFigure::stacked_segments_px`'s own private
//! per-category running walk, AND `crate::mark::rect::draw_bars_stacked`'s
//! own independent duplicate of the same walk) is now
//! [`crate::transform::stack`] — a pure, reusable, independently-tested
//! transform, not baked into this figure (or its mark primitive) alone.
//! [`BarFigure::draw_stacked_bars`] paints directly from
//! [`BarFigure::stack_segments`]'s own geometry now (replacing the old
//! call into `mark::rect::draw_bars_stacked`, REMOVED — see that
//! module's own doc comment), and [`BarFigure::stacked_segments_px`]'s
//! own hover-highlight geometry reads from the SAME shared computation —
//! paint and interaction can never disagree (design law #1) regardless
//! of stacking configuration.
//! [`BarFigure::with_stack_offset`]/[`BarFigure::with_stack_order`] are
//! the new, ADDITIVE opt-in capabilities that fall out of the move (both
//! default to this figure's own pre-existing convention — see
//! [`crate::transform::StackOffset`]/[`crate::transform::StackOrder`]'s
//! own doc comments); every existing stacked-bar render stays
//! byte-identical. The old private `stack_totals` helper (a sign-based
//! positive/negative sum split) was REMOVED, not migrated — it never
//! depended on stacking geometry at all (order/offset never change which
//! values are positive vs. negative), and once `y_scale()` moved onto
//! `stack_segments()` directly, nothing else called it.

use uzor::render::RenderContext;
use uzor::types::Rect;

use crate::coord::PlotArea;
use crate::figure::{category_color, resolve_tick_count, FigureOverlay, MarginPolicy, TickCountPolicy};
use crate::guide::annotation::{draw_annotation_overlays, draw_annotation_underlays, Annotation};
use crate::guide::axis::LabelOverflow;
use crate::guide::legend::{self, LegendEntry, LegendPosition};
use crate::guide::{axis, grid, tooltip};
use crate::interact::hit::{self, HitZone};
use crate::mark::rect::{draw_bars, draw_bars_grouped};
use crate::mark::text::draw_label_centered;
use crate::mark::MarkStyle;
use crate::scale::linear::{format_value, nice_step};
use crate::scale::{BandScale, CategoricalScale, LinearScale};
use crate::theme::FigureTheme;
use crate::transform::{stack, MissingDataPolicy, StackOffset, StackOrder};

/// Left margin for the y-axis tick labels; bottom margin for the x-axis
/// tick labels; top margin reserved for an optional title.
const MARGIN_LEFT: f64 = 48.0;
const MARGIN_RIGHT: f64 = 8.0;
const MARGIN_BOTTOM: f64 = 28.0;
const TITLE_HEIGHT: f64 = 24.0;
const TARGET_Y_TICKS: usize = 5;
/// Inner padding (fraction of each band's width) used by [`BarFigure::band_scale`].
const BAND_PADDING: f64 = 0.2;
/// Fill alpha of the translucent "brighter" overlay drawn over a hovered bar.
const HOVER_HIGHLIGHT_ALPHA: f64 = 0.22;
/// Stroke width of the persistent-selection outline drawn around a
/// [`crate::interact::focus::FocusSet`]-selected bar.
const SELECTED_STROKE_WIDTH: f64 = 2.0;
/// Gap (px) between a measured legend band and the plot rect it shrinks.
const LEGEND_GAP: f64 = 8.0;

/// One named value series — a set of grouped sub-bars or one stacked
/// segment, per [`BarMode`]. `values[i]` is this series' value for
/// category `i` (a category index missing from a shorter series is
/// skipped, never treated as a synthetic zero).
#[derive(Debug, Clone)]
pub struct BarSeries {
    pub name: String,
    pub values: Vec<f64>,
}

/// How multiple [`BarSeries`] combine within one category band.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BarMode {
    /// Sub-bands side by side within each category band (band-within-band,
    /// via [`crate::mark::rect::sub_band_range`]).
    Grouped,
    /// Cumulative y-stacking — positive values stack upward from the zero
    /// baseline, negative values stack downward from it (standard
    /// finance-chart convention; positives and negatives never combine
    /// into one running total).
    Stacked,
}

/// One category = one category band; each band holds one or more
/// [`BarSeries`] values, combined per [`BarMode`].
pub struct BarFigure {
    pub categories: Vec<String>,
    pub series: Vec<BarSeries>,
    pub mode: BarMode,
    pub title: Option<String>,
    pub show_value_labels: bool,
    legend_position: Option<LegendPosition>,
    /// Reference lines/bands/callouts drawn over this figure's bars — set
    /// via [`BarFigure::with_annotations`]. Empty (the default) reproduces
    /// the original behavior exactly (see [`crate::guide::annotation`]).
    annotations: Vec<Annotation>,
    /// Inner padding (fraction of each band's width) — see
    /// [`BarFigure::with_band_padding`]. Defaults to [`BAND_PADDING`].
    band_padding: f64,
    /// This figure's own left-margin sizing policy — see
    /// [`BarFigure::with_margin_policy`].
    margin_policy: MarginPolicy,
    /// This figure's own Y tick-count policy — see
    /// [`BarFigure::with_y_tick_policy`].
    y_tick_policy: TickCountPolicy,
    /// This figure's own X-axis label-collision policy — see
    /// [`BarFigure::with_label_overflow`].
    label_overflow: LabelOverflow,
    /// This figure's own per-series categorical color source — see
    /// [`BarFigure::with_category_palette`]. Default (unset) reproduces
    /// this figure's pre-existing `theme.palette[i % theme.palette.len()]`
    /// series-color indexing byte-for-byte.
    category_palette: Option<CategoricalScale>,
    /// This figure's own [`BarMode::Stacked`] accumulation offset — see
    /// [`BarFigure::with_stack_offset`]. Default (unset) is
    /// [`StackOffset::Diverging`], byte-identical to this figure's own
    /// pre-existing stacked-bar convention. Unused under
    /// [`BarMode::Grouped`].
    stack_offset: StackOffset,
    /// This figure's own [`BarMode::Stacked`] series accumulation order —
    /// see [`BarFigure::with_stack_order`]. Default (unset) is
    /// [`StackOrder::AsGiven`], byte-identical to this figure's own
    /// pre-existing stacked-bar convention. Unused under
    /// [`BarMode::Grouped`].
    stack_order: StackOrder,
}

impl BarFigure {
    /// Single-series constructor — sugar for
    /// `with_series(categories, vec![BarSeries { name: String::new(), values }], BarMode::Grouped)`.
    /// A single series never shows a sub-band or a legend on its own (see
    /// [`BarFigure::resolved_legend_position`]), so this reproduces the
    /// pre-multi-series render exactly.
    pub fn new(categories: Vec<String>, values: Vec<f64>) -> Self {
        Self::with_series(categories, vec![BarSeries { name: String::new(), values }], BarMode::Grouped)
    }

    /// Multi-series constructor. `series.len() > 1` auto-shows a legend at
    /// [`LegendPosition::Top`] unless overridden via
    /// [`BarFigure::with_legend`].
    pub fn with_series(categories: Vec<String>, series: Vec<BarSeries>, mode: BarMode) -> Self {
        Self {
            categories,
            series,
            mode,
            title: None,
            show_value_labels: false,
            legend_position: None,
            annotations: Vec::new(),
            band_padding: BAND_PADDING,
            margin_policy: MarginPolicy::default(),
            y_tick_policy: TickCountPolicy::Fixed(TARGET_Y_TICKS),
            label_overflow: LabelOverflow::default(),
            category_palette: None,
            stack_offset: StackOffset::default(),
            stack_order: StackOrder::default(),
        }
    }

    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn with_value_labels(mut self, show: bool) -> Self {
        self.show_value_labels = show;
        self
    }

    /// Force a legend at `position` regardless of series count (default:
    /// auto-shown at [`LegendPosition::Top`] only when there's more than
    /// one series — see [`BarFigure::resolved_legend_position`]).
    pub fn with_legend(mut self, position: LegendPosition) -> Self {
        self.legend_position = Some(position);
        self
    }

    /// Reference lines/bands/callouts drawn over this figure's bars — see
    /// [`crate::guide::annotation`]. Only [`crate::guide::annotation::
    /// Annotation::HLine`] makes real sense here (this figure's X axis is
    /// a [`crate::scale::BandScale`], not a continuous domain — a
    /// `VLine`/`Callout`'s own `x` would map through the band's own
    /// fractional-index domain, which is a valid but unusual call); the
    /// draw function itself doesn't forbid it.
    pub fn with_annotations(mut self, annotations: Vec<Annotation>) -> Self {
        self.annotations = annotations;
        self
    }

    /// Override this figure's band inner padding (fraction of each band's
    /// own width used as the gap between bands, clamped `0.0..=0.9` by
    /// [`BandScale::new`]) — the "bar width ratio" a caller couldn't
    /// previously reach despite [`BandScale::new`] already accepting an
    /// arbitrary value. Default (unset) is [`BAND_PADDING`], byte-identical
    /// to this figure's own pre-existing constant.
    pub fn with_band_padding(mut self, padding: f64) -> Self {
        self.band_padding = padding;
        self
    }

    /// Override this figure's left-margin sizing policy — see
    /// [`MarginPolicy`]'s own docs. Default (unset) is
    /// [`MarginPolicy::Measured`].
    pub fn with_margin_policy(mut self, policy: MarginPolicy) -> Self {
        self.margin_policy = policy;
        self
    }

    /// Override this figure's Y tick-count policy — see
    /// [`TickCountPolicy`]'s own docs. Default (unset) is
    /// `TickCountPolicy::Fixed(5)`, byte-identical to this figure's
    /// pre-existing constant. This figure's X axis is a
    /// [`BandScale`] (one tick per category, always — see
    /// [`crate::scale::band::BandScale::ticks`]'s own docs), so no X
    /// tick-count policy applies here.
    pub fn with_y_tick_policy(mut self, policy: TickCountPolicy) -> Self {
        self.y_tick_policy = policy;
        self
    }

    /// Override this figure's X-axis label-collision policy — see
    /// [`LabelOverflow`]'s own docs. Default (unset) is
    /// [`LabelOverflow::Skip`], byte-identical to this figure's
    /// pre-existing greedy-skip behavior. A `BarFigure` with many
    /// categories or long category names is the audit's own named
    /// example for this item.
    pub fn with_label_overflow(mut self, overflow: LabelOverflow) -> Self {
        self.label_overflow = overflow;
        self
    }

    /// Override this figure's per-series color source — see
    /// [`crate::scale::CategoricalScale`]'s own doc comment (e.g.
    /// `CategoricalScale::default_palette()`, the colour-blind-safe
    /// Okabe-Ito set). Default (unset) is `None`, byte-identical to this
    /// figure's pre-existing `theme.palette[i % theme.palette.len()]`
    /// series-color indexing — per this crate's own binding doctrine, a
    /// new categorical identity is a real, explicit option; nothing
    /// changes silently unless a caller opts in.
    pub fn with_category_palette(mut self, palette: CategoricalScale) -> Self {
        self.category_palette = Some(palette);
        self
    }

    /// Override this figure's own [`BarMode::Stacked`] accumulation
    /// offset — see [`crate::transform::StackOffset`]'s own doc comment
    /// for every variant. Default (unset) is [`StackOffset::Diverging`],
    /// byte-identical to this figure's own pre-existing stacked-bar
    /// convention. Has no effect under [`BarMode::Grouped`].
    pub fn with_stack_offset(mut self, offset: StackOffset) -> Self {
        self.stack_offset = offset;
        self
    }

    /// Override this figure's own [`BarMode::Stacked`] series
    /// accumulation order — see [`crate::transform::StackOrder`]'s own
    /// doc comment for every variant. Default (unset) is
    /// [`StackOrder::AsGiven`], byte-identical to this figure's own
    /// pre-existing stacked-bar convention (the output stays indexed by
    /// each series' own ORIGINAL position regardless of this choice —
    /// only which segment lands closest to the baseline changes). Has no
    /// effect under [`BarMode::Grouped`].
    pub fn with_stack_order(mut self, order: StackOrder) -> Self {
        self.stack_order = order;
        self
    }

    /// Resolved legend position for this render: an explicit
    /// [`BarFigure::with_legend`] override, or auto-[`LegendPosition::Top`]
    /// when there's more than one series, or `None` otherwise.
    fn resolved_legend_position(&self) -> Option<LegendPosition> {
        self.legend_position.or(if self.series.len() > 1 { Some(LegendPosition::Top) } else { None })
    }

    fn legend_entries(&self, theme: &FigureTheme) -> Vec<LegendEntry> {
        self.series
            .iter()
            .enumerate()
            .map(|(i, s)| LegendEntry {
                label: s.name.clone(),
                color: category_color(theme, self.category_palette.as_ref(), i).to_owned(),
                symbol: crate::guide::legend::LegendSymbol::Square,
            })
            .collect()
    }

    fn base_plot_rect(&self, rect: Rect) -> Rect {
        let title_h = if self.title.is_some() { TITLE_HEIGHT } else { 0.0 };
        Rect::new(
            rect.x + MARGIN_LEFT,
            rect.y + title_h,
            (rect.width - MARGIN_LEFT - MARGIN_RIGHT).max(0.0),
            (rect.height - title_h - MARGIN_BOTTOM).max(0.0),
        )
    }

    /// This figure's plot-area transform for `rect` — exposed for the same
    /// reason as [`crate::figure::CurveFigure::plot_area`]: a caller
    /// driving hover/click routing from outside needs to hit-test through
    /// the EXACT same transform this figure renders with.
    ///
    /// **Does not account for a legend, nor for [`MarginPolicy::Measured`]/
    /// [`LabelOverflow::Rotate`]/`Auto` growing the margins.** Measuring
    /// any of those needs live text metrics (a `&mut dyn RenderContext`),
    /// which this ctx-less accessor doesn't have — kept this way so every
    /// existing single-series, legend-less external caller stays
    /// byte-compatible. [`BarFigure::render_with`] measures + shrinks the
    /// SAME base rect internally via its own `ctx`, so a multi-series
    /// figure's own hover/tooltip/legend stay mutually consistent within
    /// one `render_with` call regardless.
    pub fn plot_area(&self, rect: Rect) -> PlotArea {
        PlotArea::new(self.base_plot_rect(rect))
    }

    /// This figure's own category band scale (always constructible, even
    /// for zero categories — an empty band trivially hit-tests to
    /// nothing). Exposed for the same reason as [`BarFigure::plot_area`].
    pub fn band_scale(&self) -> BandScale {
        BandScale::new(self.categories.clone(), self.band_padding)
    }

    /// This figure's own value slices, one per series, in original order —
    /// the shape [`crate::transform::stack::stack`] takes.
    fn series_slices(&self) -> Vec<&[f64]> {
        self.series.iter().map(|s| s.values.as_slice()).collect()
    }

    /// This figure's own [`crate::transform::stack::stack`] result over
    /// EVERY category at once, per its own `stack_offset`/`stack_order` —
    /// the shared computation both [`BarFigure::y_scale`]'s `Stacked`
    /// branch and [`BarFigure::stacked_segments_px`] read from.
    ///
    /// Always called with [`MissingDataPolicy::Propagate`] — this
    /// figure's OWN internal calls never opt into `Skip`/`Error` (no
    /// builder exposes that choice; out of this wave's own named scope,
    /// see `transform::stack`'s own doc comment for why `Propagate` is
    /// specifically the behavior-preserving default here). `Propagate`
    /// can never return `Err` (only [`MissingDataPolicy::Error`] does),
    /// so the `unwrap_or_default` fallback below is unreachable in
    /// practice, not a load-bearing branch.
    fn stack_segments(&self) -> Vec<Vec<(f64, f64)>> {
        stack(&self.series_slices(), self.categories.len(), self.stack_order, self.stack_offset, MissingDataPolicy::Propagate)
            .unwrap_or_default()
    }

    /// Nice-rounded Y domain. [`BarMode::Grouped`]: the extent of every
    /// individual value across every series (baseline `0.0` always
    /// included, same convention the pre-multi-series single-series
    /// domain already used). [`BarMode::Stacked`]: the extent of every
    /// series' own cumulative segment boundary across every category (a
    /// stacked column's visible height is the SUM of its segments, not
    /// any one segment's own value) — via [`BarFigure::stack_segments`],
    /// proven byte-identical to the pre-refactor `stack_totals`-based
    /// fold for the default [`StackOffset::Diverging`]/[`StackOrder::
    /// AsGiven`] case (see `figure::bars`'s own tests).
    fn y_scale(&self) -> Option<LinearScale> {
        if self.categories.is_empty() || self.series.is_empty() {
            return None;
        }
        let (data_min, data_max) = match self.mode {
            BarMode::Grouped => self
                .series
                .iter()
                .flat_map(|s| s.values.iter())
                .fold((0.0_f64, 0.0_f64), |(mn, mx), &v| (mn.min(v), mx.max(v))),
            BarMode::Stacked => self.stack_segments().iter().flatten().fold((0.0_f64, 0.0_f64), |(mn, mx), &(bottom, top)| {
                (mn.min(bottom).min(top), mx.max(bottom).max(top))
            }),
        };
        Some(LinearScale::nice(data_min, data_max, TARGET_Y_TICKS))
    }

    /// Per-series cumulative segment `(top_px, bottom_px)` pixel pairs for
    /// category `i`, in series order — [`BarFigure::stack_segments`]'s own
    /// domain-space `(bottom, top)` pairs mapped through `y`, exposed so
    /// `render_with`'s own hover resolves a stacked segment through the
    /// EXACT geometry that was painted (design law #1, via
    /// [`crate::interact::hit::stacked_series_at`]).
    fn stacked_segments_px(&self, area: &PlotArea, y: &LinearScale, i: usize) -> Vec<(f64, f64)> {
        self.stack_segments()
            .iter()
            .map(|row| {
                let (bottom_v, top_v) = row.get(i).copied().unwrap_or((0.0, 0.0));
                (area.y(y, top_v), area.y(y, bottom_v))
            })
            .collect()
    }

    /// Paint [`BarMode::Stacked`] bars — reads its own geometry from
    /// [`BarFigure::stack_segments`], the SAME transform-layer computation
    /// [`BarFigure::stacked_segments_px`]'s own hover-highlight and
    /// [`BarFigure::y_scale`]'s own domain sizing read from, so paint and
    /// interaction can never disagree (design law #1) regardless of this
    /// figure's own `stack_offset`/`stack_order` choice. Replaces the
    /// pre-refactor call to `crate::mark::rect::draw_bars_stacked`
    /// (REMOVED — see that module's own doc comment), which only ever
    /// implemented the [`StackOffset::Diverging`]/[`StackOrder::AsGiven`]
    /// convention and could never reflect the new opt-in options.
    fn draw_stacked_bars(&self, ctx: &mut dyn RenderContext, area: &PlotArea, band: &BandScale, y: &LinearScale, colors: &[&str]) {
        if band.is_empty() || self.series.is_empty() {
            return;
        }
        let segments = self.stack_segments();
        ctx.set_global_alpha(1.0);
        for i in 0..band.len() {
            let (x0, x1) = area.x_band(band, i);
            for (si, row) in segments.iter().enumerate() {
                let (bottom_v, top_v) = row.get(i).copied().unwrap_or((0.0, 0.0));
                let top_px = area.y(y, top_v);
                let bottom_px = area.y(y, bottom_v);
                let (top, height) = (top_px.min(bottom_px), (bottom_px - top_px).abs());
                ctx.set_fill_color(colors.get(si).copied().unwrap_or("#888888"));
                ctx.fill_rect(x0, top, (x1 - x0).max(0.0), height);
            }
        }
    }

    fn hover_tooltip_lines(&self, i: usize, si: usize, y_scale: &LinearScale, target_y_ticks: usize) -> Vec<(String, String)> {
        let category = self.categories.get(i).cloned().unwrap_or_default();
        let series_name = self.series.get(si).map(|s| s.name.clone()).unwrap_or_default();
        let value = self.series.get(si).and_then(|s| s.values.get(i)).copied().unwrap_or(0.0);
        let step = nice_step(y_scale.max - y_scale.min, target_y_ticks as f64);
        vec![("category".to_owned(), category), ("series".to_owned(), series_name), ("value".to_owned(), format_value(value, step))]
    }

    /// Render into `rect` of `ctx` using `theme`, with no overlay —
    /// equivalent to `render_with(ctx, rect, theme, &FigureOverlay::default())`.
    pub fn render(&self, ctx: &mut dyn RenderContext, rect: Rect, theme: &FigureTheme) {
        self.render_with(ctx, rect, theme, &FigureOverlay::default());
    }

    /// Render into `rect` of `ctx` using `theme`, reacting to `overlay`'s
    /// borrowed per-frame interaction state: a hover position over a bar
    /// brightens its fill and shows a category/(series/)value tooltip;
    /// `overlay.focus`-selected categories get a persistent accent
    /// outline spanning the whole category band. `overlay.brush` is not
    /// consumed by this figure (bars in V2 have no brush-linked
    /// highlighting — see [`crate::figure::FigureOverlay`]).
    pub fn render_with(&self, ctx: &mut dyn RenderContext, rect: Rect, theme: &FigureTheme, overlay: &FigureOverlay<'_>) {
        ctx.set_fill_color(&theme.background);
        ctx.fill_rect(rect.x, rect.y, rect.width, rect.height);

        // Resolve this render's own margins + Y tick count BEFORE building
        // the plot rect — see `CurveFigure::render_with`'s own identical
        // comment for the full non-circularity reasoning; here
        // `margin_bottom` ALSO varies (under `LabelOverflow::Rotate`/
        // `Auto`), resolved first since neither it nor `band`/`y_scale`
        // depend on anything downstream of it.
        let band = self.band_scale();
        let y_scale_for_layout = self.y_scale();
        let title_h = if self.title.is_some() { TITLE_HEIGHT } else { 0.0 };
        let margin_bottom = match self.label_overflow {
            LabelOverflow::Skip => MARGIN_BOTTOM,
            LabelOverflow::Rotate(degrees) => MARGIN_BOTTOM.max(axis::measure_rotated_x_axis_gutter(ctx, &band, theme, band.len(), degrees)),
            LabelOverflow::Auto => MARGIN_BOTTOM.max(axis::measure_rotated_x_axis_gutter(ctx, &band, theme, band.len(), axis::AUTO_ROTATE_DEGREES)),
        };
        let plot_height_estimate = (rect.height - title_h - margin_bottom).max(0.0);
        let target_y_ticks = resolve_tick_count(self.y_tick_policy, plot_height_estimate);
        let margin_left = match (&y_scale_for_layout, self.margin_policy) {
            (Some(y_scale), MarginPolicy::Measured) => MARGIN_LEFT.max(axis::measure_y_axis_gutter(ctx, y_scale, theme, target_y_ticks)),
            _ => MARGIN_LEFT,
        };
        let base_rect = Rect::new(rect.x + margin_left, rect.y + title_h, (rect.width - margin_left - MARGIN_RIGHT).max(0.0), plot_height_estimate);
        let legend_position = self.resolved_legend_position();
        let legend_entries = if legend_position.is_some() { self.legend_entries(theme) } else { Vec::new() };

        let (plot_rect, legend_rect) = match legend_position {
            Some(pos) if !legend_entries.is_empty() => {
                let size = legend::measure_legend(ctx, theme, &legend_entries, pos, base_rect.width, base_rect.height);
                match pos {
                    LegendPosition::Top => {
                        let reserved = size.height + LEGEND_GAP;
                        (
                            Rect::new(base_rect.x, base_rect.y + reserved, base_rect.width, (base_rect.height - reserved).max(0.0)),
                            Some((Rect::new(base_rect.x, base_rect.y, base_rect.width, size.height), pos)),
                        )
                    }
                    LegendPosition::Bottom => {
                        let reserved = size.height + LEGEND_GAP;
                        (
                            Rect::new(base_rect.x, base_rect.y, base_rect.width, (base_rect.height - reserved).max(0.0)),
                            Some((Rect::new(base_rect.x, base_rect.bottom() - size.height, base_rect.width, size.height), pos)),
                        )
                    }
                    LegendPosition::Right => {
                        let reserved = size.width + LEGEND_GAP;
                        (
                            Rect::new(base_rect.x, base_rect.y, (base_rect.width - reserved).max(0.0), base_rect.height),
                            Some((Rect::new(base_rect.right() - size.width, base_rect.y, size.width, base_rect.height), pos)),
                        )
                    }
                }
            }
            _ => (base_rect, None),
        };

        let area = PlotArea::new(plot_rect);

        if let Some(y_scale) = y_scale_for_layout {
            grid::draw_y_grid(ctx, &area, &y_scale, theme, target_y_ticks);

            // Annotation FILLS (the only underlay: `HBand`'s own shaded
            // rect) paint UNDER the bars (over the grid, under the data) —
            // same ordering `CurveFigure::render_with` uses. Reference
            // LINES/LABELS/`Callout` paint AFTER the bars below (see
            // `guide::annotation`'s own "Layer contract" doc comment).
            draw_annotation_underlays(ctx, &area, &y_scale, theme, &self.annotations);

            if self.series.len() <= 1 {
                if let Some(single) = self.series.first() {
                    let style = MarkStyle { color: category_color(theme, self.category_palette.as_ref(), 0).to_owned(), ..Default::default() };
                    draw_bars(ctx, &area, &band, &y_scale, &single.values, &style);
                }
            } else {
                let series_values: Vec<&[f64]> = self.series.iter().map(|s| s.values.as_slice()).collect();
                let colors: Vec<&str> = (0..self.series.len()).map(|i| category_color(theme, self.category_palette.as_ref(), i)).collect();
                match self.mode {
                    BarMode::Grouped => draw_bars_grouped(ctx, &area, &band, &y_scale, &series_values, &colors),
                    BarMode::Stacked => self.draw_stacked_bars(ctx, &area, &band, &y_scale, &colors),
                }
            }

            draw_annotation_overlays(ctx, &area, &band, &y_scale, theme, &self.annotations);

            if self.show_value_labels {
                if let Some(single) = self.series.first().filter(|_| self.series.len() == 1) {
                    let step = nice_step(y_scale.max - y_scale.min, target_y_ticks as f64);
                    for (i, &value) in single.values.iter().enumerate().take(band.len()) {
                        let (x0, x1) = area.x_band(&band, i);
                        let label_y = area.y(&y_scale, value) - 6.0;
                        draw_label_centered(ctx, &format_value(value, step), (x0 + x1) / 2.0, label_y, &theme.label_color, &theme.label_font);
                    }
                }
            }

            if let Some(focus) = overlay.focus {
                let accent = &theme.palette[1];
                for i in 0..band.len() {
                    if focus.is_selected(i as u64) {
                        let (x0, x1) = area.x_band(&band, i);
                        ctx.set_stroke_color(accent);
                        ctx.set_stroke_width(SELECTED_STROKE_WIDTH);
                        ctx.stroke_rect(x0, area.rect.y, (x1 - x0).max(0.0), area.rect.height);
                    }
                }
            }

            if let Some((hx, hy)) = overlay.hover_px {
                if hit::hit_zone(&area, hx, hy) == HitZone::Plot {
                    if let Some(i) = hit::bar_index_at(&area, &band, hx) {
                        if self.series.len() <= 1 {
                            let (x0, x1) = area.x_band(&band, i);
                            ctx.set_fill_color(&theme.highlight);
                            ctx.set_global_alpha(HOVER_HIGHLIGHT_ALPHA);
                            ctx.fill_rect(x0, area.rect.y, (x1 - x0).max(0.0), area.rect.height);
                            ctx.set_global_alpha(1.0);

                            let category = self.categories.get(i).cloned().unwrap_or_default();
                            let value = self.series.first().and_then(|s| s.values.get(i)).copied().unwrap_or(0.0);
                            let step = nice_step(y_scale.max - y_scale.min, target_y_ticks as f64);
                            let lines = vec![("category".to_owned(), category), ("value".to_owned(), format_value(value, step))];
                            tooltip::draw_tooltip(ctx, theme, (hx, hy), &lines, area.rect);
                        } else {
                            match self.mode {
                                BarMode::Grouped => {
                                    let (x0, x1) = area.x_band(&band, i);
                                    if let Some(si) = hit::bar_series_at(x0, x1, self.series.len(), hx) {
                                        let (sx0, sx1) = crate::mark::rect::sub_band_range(x0, x1, self.series.len(), si);
                                        ctx.set_fill_color(&theme.highlight);
                                        ctx.set_global_alpha(HOVER_HIGHLIGHT_ALPHA);
                                        ctx.fill_rect(sx0, area.rect.y, (sx1 - sx0).max(0.0), area.rect.height);
                                        ctx.set_global_alpha(1.0);

                                        let lines = self.hover_tooltip_lines(i, si, &y_scale, target_y_ticks);
                                        tooltip::draw_tooltip(ctx, theme, (hx, hy), &lines, area.rect);
                                    }
                                }
                                BarMode::Stacked => {
                                    let segments = self.stacked_segments_px(&area, &y_scale, i);
                                    if let Some(si) = hit::stacked_series_at(&segments, hy) {
                                        let (x0, x1) = area.x_band(&band, i);
                                        let (top, bottom) = segments[si];
                                        ctx.set_fill_color(&theme.highlight);
                                        ctx.set_global_alpha(HOVER_HIGHLIGHT_ALPHA);
                                        ctx.fill_rect(x0, top.min(bottom), (x1 - x0).max(0.0), (bottom - top).abs());
                                        ctx.set_global_alpha(1.0);

                                        let lines = self.hover_tooltip_lines(i, si, &y_scale, target_y_ticks);
                                        tooltip::draw_tooltip(ctx, theme, (hx, hy), &lines, area.rect);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            axis::draw_x_axis_overflow(ctx, &area, &band, theme, band.len(), self.label_overflow);
            axis::draw_y_axis(ctx, &area, &y_scale, theme, target_y_ticks);
        }

        if let Some((legend_rect, pos)) = legend_rect {
            legend::draw_legend(ctx, legend_rect, theme, &legend_entries, pos);
        }

        if let Some(title) = &self.title {
            crate::figure::draw_title(ctx, rect, title, theme);
        }
    }
}

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

    fn cats(n: usize) -> Vec<String> {
        (0..n).map(|i| format!("cat-{i}")).collect()
    }

    #[test]
    fn new_single_series_never_auto_shows_a_legend() {
        let figure = BarFigure::new(cats(3), vec![1.0, 2.0, 3.0]);
        assert_eq!(figure.resolved_legend_position(), None);
    }

    #[test]
    fn with_series_multi_series_auto_shows_a_top_legend() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![1.0, 2.0] },
            BarSeries { name: "b".to_owned(), values: vec![3.0, 4.0] },
        ];
        let figure = BarFigure::with_series(cats(2), series, BarMode::Grouped);
        assert_eq!(figure.resolved_legend_position(), Some(LegendPosition::Top));
    }

    #[test]
    fn with_legend_overrides_the_auto_default_even_for_a_single_series() {
        let figure = BarFigure::new(cats(2), vec![1.0, 2.0]).with_legend(LegendPosition::Right);
        assert_eq!(figure.resolved_legend_position(), Some(LegendPosition::Right));
    }

    #[test]
    fn default_band_padding_matches_the_pre_existing_constant() {
        let figure = BarFigure::new(cats(2), vec![1.0, 2.0]);
        assert!((figure.band_scale().padding - BAND_PADDING).abs() < 1e-9);
    }

    #[test]
    fn with_band_padding_overrides_the_default_and_is_reflected_in_the_band_scale() {
        let figure = BarFigure::new(cats(2), vec![1.0, 2.0]).with_band_padding(0.6);
        assert!((figure.band_scale().padding - 0.6).abs() < 1e-9);
    }

    #[test]
    fn legend_entries_assign_distinct_theme_palette_colors_by_series_index() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![1.0] },
            BarSeries { name: "b".to_owned(), values: vec![2.0] },
            BarSeries { name: "c".to_owned(), values: vec![3.0] },
        ];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Grouped);
        let theme = FigureTheme::dark();
        let entries = figure.legend_entries(&theme);
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].label, "a");
        let colors: Vec<&str> = entries.iter().map(|e| e.color.as_str()).collect();
        let mut unique = colors.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(unique.len(), colors.len(), "every series must get its own distinct swatch color");
    }

    #[test]
    fn default_category_palette_is_unset_and_legend_uses_theme_palette() {
        let series = vec![BarSeries { name: "a".to_owned(), values: vec![1.0] }, BarSeries { name: "b".to_owned(), values: vec![2.0] }];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Grouped);
        let theme = FigureTheme::dark();
        let entries = figure.legend_entries(&theme);
        assert_eq!(entries[0].color, theme.palette[0]);
        assert_eq!(entries[1].color, theme.palette[1]);
    }

    #[test]
    fn with_category_palette_routes_legend_colors_through_the_explicit_palette() {
        use crate::scale::CategoricalScale;

        let series = vec![BarSeries { name: "a".to_owned(), values: vec![1.0] }, BarSeries { name: "b".to_owned(), values: vec![2.0] }];
        let palette = CategoricalScale::default_palette();
        let figure = BarFigure::with_series(cats(1), series, BarMode::Grouped).with_category_palette(CategoricalScale::default_palette());
        let theme = FigureTheme::dark();
        let entries = figure.legend_entries(&theme);
        assert_eq!(entries[0].color, palette.color_for(0));
        assert_eq!(entries[1].color, palette.color_for(1));
        assert_ne!(entries[0].color, theme.palette[0], "an explicit category palette must override theme.palette's own default indexing");
    }

    #[test]
    fn with_category_palette_renders_without_panicking() {
        use crate::scale::CategoricalScale;
        use uzor_export::{render_to_png, ExportSpec};

        let figure = BarFigure::new(cats(3), vec![5.0, 10.0, 15.0]).with_category_palette(CategoricalScale::default_palette());
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let result = render_to_png(&spec, |ctx| {
            figure.render(ctx, Rect::new(0.0, 0.0, 300.0, 200.0), &theme);
        });
        assert!(result.is_ok());
    }

    #[test]
    fn grouped_y_scale_spans_every_series_own_value_extent() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0, -5.0] },
            BarSeries { name: "b".to_owned(), values: vec![40.0, 2.0] },
        ];
        let figure = BarFigure::with_series(cats(2), series, BarMode::Grouped);
        let scale = figure.y_scale().expect("non-empty fixture");
        assert!(scale.min <= -5.0, "grouped domain must contain the most negative individual value");
        assert!(scale.max >= 40.0, "grouped domain must contain the largest individual value");
    }

    #[test]
    fn stacked_totals_split_positive_and_negative_sums_never_mixed() {
        // Was: `figure.stack_totals(0)`, a private sign-based sum helper
        // extracted during the Engine-strengthening WAVE 4b stacking
        // refactor (its own logic didn't depend on stacking geometry at
        // all, so nothing NEEDED it once `y_scale()` moved onto
        // `stack_segments()` directly — see `figure::bars`'s own module
        // doc). Same property, now proven via the shared
        // `transform::stack` geometry: category 0's own extreme segment
        // boundaries ARE the positive/negative sums for the default
        // Diverging offset (each sign's own running accumulator only
        // ever grows in its own direction).
        let series = vec![
            BarSeries { name: "revenue".to_owned(), values: vec![20.0] },
            BarSeries { name: "cost".to_owned(), values: vec![-8.0] },
            BarSeries { name: "adjustment".to_owned(), values: vec![5.0] },
        ];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Stacked);
        let segments = figure.stack_segments();
        let (pos, neg) = segments.iter().fold((0.0_f64, 0.0_f64), |(pos, neg), row| {
            let (bottom, top) = row[0];
            (pos.max(bottom).max(top), neg.min(bottom).min(top))
        });
        assert!((pos - 25.0).abs() < 1e-9, "positive sum must be 20 + 5, cost excluded");
        assert!((neg - (-8.0)).abs() < 1e-9, "negative sum must be -8 alone");
    }

    #[test]
    fn stacked_y_scale_spans_the_cumulative_extremes_not_any_single_value() {
        let series = vec![
            BarSeries { name: "revenue".to_owned(), values: vec![20.0, 15.0] },
            BarSeries { name: "cost".to_owned(), values: vec![-8.0, -12.0] },
            BarSeries { name: "adjustment".to_owned(), values: vec![5.0, -3.0] },
        ];
        let figure = BarFigure::with_series(cats(2), series, BarMode::Stacked);
        let scale = figure.y_scale().expect("non-empty fixture");
        // Category 0: positive total 20+5=25, negative total -8.
        // Category 1: positive total 15, negative total -12-3=-15.
        assert!(scale.max >= 25.0, "domain must contain the largest cumulative POSITIVE total, not any single series value");
        assert!(scale.min <= -15.0, "domain must contain the most negative cumulative total, not any single series value");
    }

    #[test]
    fn stacked_segments_px_top_equals_cumulative_sum_and_total_height_matches_the_full_sum() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0] },
            BarSeries { name: "b".to_owned(), values: vec![20.0] },
            BarSeries { name: "c".to_owned(), values: vec![5.0] },
        ];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Stacked);
        let y_scale = figure.y_scale().expect("non-empty fixture");
        let area = PlotArea::new(Rect::new(0.0, 0.0, 100.0, 200.0));
        let segments = figure.stacked_segments_px(&area, &y_scale, 0);
        assert_eq!(segments.len(), 3);

        // Segment 0 spans [0, 10]; segment 1 spans [10, 30] (cumulative);
        // segment 2 spans [30, 35] (cumulative) — the WHOLE column's own
        // top pixel must equal the pixel for domain value 35 (10+20+5),
        // the full sum, not any single segment's own value.
        let expected_total_top_px = area.y(&y_scale, 35.0);
        let (seg2_top, _seg2_bottom) = segments[2];
        assert!((seg2_top - expected_total_top_px).abs() < 1e-6, "the last segment's own top must land at the FULL cumulative sum");

        // The whole stacked column's pixel height must equal the sum of
        // every segment's own pixel height (no overlap, no gap).
        let column_top_px = segments.iter().map(|&(t, _)| t).fold(f64::INFINITY, f64::min);
        let column_bottom_px = segments.iter().map(|&(_, b)| b).fold(f64::NEG_INFINITY, f64::max);
        let column_height = column_bottom_px - column_top_px;
        let summed_height: f64 = segments.iter().map(|&(t, b)| (b - t).abs()).sum();
        assert!((column_height - summed_height).abs() < 1e-6, "the whole column's height must equal the sum of its own segment heights");
    }

    #[test]
    fn stacked_segments_px_negative_values_stack_downward_from_the_baseline() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![-10.0] },
            BarSeries { name: "b".to_owned(), values: vec![-20.0] },
        ];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Stacked);
        let y_scale = figure.y_scale().expect("non-empty fixture");
        let area = PlotArea::new(Rect::new(0.0, 0.0, 100.0, 200.0));
        let segments = figure.stacked_segments_px(&area, &y_scale, 0);

        let baseline_px = area.y(&y_scale, 0.0);
        // Both segments must sit AT OR BELOW the zero baseline on screen
        // (larger y = lower on screen) — negative values never stack
        // upward into positive territory.
        for &(top, bottom) in &segments {
            let lower = top.max(bottom);
            let upper = top.min(bottom);
            assert!(upper >= baseline_px - 1e-6, "a negative segment must never extend above the zero baseline");
            assert!(lower > baseline_px - 1e-6);
        }
        // Segment 1 (cumulative -30) must sit further from the baseline
        // (further down the screen) than segment 0 (cumulative -10 alone).
        let seg0_bottom = segments[0].1.max(segments[0].0);
        let seg1_bottom = segments[1].1.max(segments[1].0);
        assert!(seg1_bottom > seg0_bottom, "later negative segments must stack FURTHER from the baseline, not overlap the first");
    }

    #[test]
    fn with_annotations_default_is_empty_and_render_still_succeeds() {
        use uzor_export::{render_to_png, ExportSpec};

        let figure = BarFigure::new(cats(3), vec![5.0, 10.0, 15.0])
            .with_annotations(vec![crate::guide::annotation::Annotation::HLine { value: 8.0, color: None, label: Some("target".to_owned()) }]);
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let result = render_to_png(&spec, |ctx| {
            figure.render(ctx, Rect::new(0.0, 0.0, 300.0, 200.0), &theme);
        });
        assert!(result.is_ok());
        assert!(BarFigure::new(cats(2), vec![1.0, 2.0]).annotations.is_empty());
    }

    #[test]
    fn single_series_render_uses_the_original_draw_bars_path_not_grouped_geometry() {
        // A single series must still render (no panic, valid dimensions) —
        // this exercises the `self.series.len() <= 1` branch that keeps
        // `BarFigure::new`'s output byte-compatible with the
        // pre-multi-series render.
        use uzor_export::{render_to_png, ExportSpec};

        let figure = BarFigure::new(cats(3), vec![5.0, 10.0, 15.0]).with_title("single series");
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 300.0, 200.0);
        let result = render_to_png(&spec, |ctx| {
            figure.render(ctx, rect, &theme);
        });
        assert!(result.is_ok());
    }

    // ── MarginPolicy / TickCountPolicy / LabelOverflow (items 2, 3, 4) ──

    #[test]
    fn default_policies_match_the_pre_existing_constants_and_behavior() {
        let figure = BarFigure::new(cats(3), vec![1.0, 2.0, 3.0]);
        assert_eq!(figure.margin_policy, MarginPolicy::Measured);
        assert_eq!(figure.y_tick_policy, TickCountPolicy::Fixed(TARGET_Y_TICKS));
        assert_eq!(figure.label_overflow, LabelOverflow::Skip);
    }

    #[test]
    fn measured_margin_widens_for_a_deliberately_wide_y_label() {
        use uzor_export::{render_to_png, ExportSpec};

        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 300.0, 200.0);

        let fixed = BarFigure::new(cats(3), vec![1.0, 2.0, 999_999_999.0]).with_margin_policy(MarginPolicy::Fixed);
        let measured = BarFigure::new(cats(3), vec![1.0, 2.0, 999_999_999.0]).with_margin_policy(MarginPolicy::Measured);
        let fixed_png = render_to_png(&spec, |ctx| fixed.render(ctx, rect, &theme)).expect("fixed render");
        let measured_png = render_to_png(&spec, |ctx| measured.render(ctx, rect, &theme)).expect("measured render");
        assert_ne!(fixed_png, measured_png, "Measured must render differently once a wide Y label would otherwise clip under Fixed");
    }

    #[test]
    fn with_label_overflow_rotate_renders_without_panicking_and_grows_the_bottom_margin() {
        use uzor_export::{render_to_png, ExportSpec};

        let categories: Vec<String> = (0..10).map(|i| format!("long-category-name-{i}")).collect();
        let values: Vec<f64> = (0..10).map(|i| (i + 1) as f64).collect();
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 300.0, 200.0);

        let skip = BarFigure::new(categories.clone(), values.clone());
        let rotated = BarFigure::new(categories, values).with_label_overflow(LabelOverflow::Rotate(45.0));
        let skip_png = render_to_png(&spec, |ctx| skip.render(ctx, rect, &theme)).expect("skip render");
        let rotated_png = render_to_png(&spec, |ctx| rotated.render(ctx, rect, &theme)).expect("rotate render");
        assert_ne!(skip_png, rotated_png, "LabelOverflow::Rotate must render visibly differently from the default Skip for many long categories");
    }

    #[test]
    fn default_label_overflow_renders_byte_identical_to_the_pre_existing_axis_call() {
        use uzor_export::{render_to_png, ExportSpec};

        let figure = BarFigure::new(cats(4), vec![3.0, 7.0, 2.0, 9.0]);
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 300.0, 200.0);
        // Fixed margin policy + default (Skip) label overflow reproduces
        // the pre-existing behavior byte-for-byte, since neither ever
        // changes the drawn output for short category labels/values.
        let png_a = render_to_png(&spec, |ctx| figure.render(ctx, rect, &theme)).expect("render a");
        let png_b = render_to_png(&spec, |ctx| figure.render(ctx, rect, &theme)).expect("render b");
        assert_eq!(png_a, png_b, "rendering the same figure twice must be deterministic");
    }

    // ── Engine-strengthening WAVE 4b — stacking extracted to
    // `transform::stack` ─────────────────────────────────────────────

    #[test]
    fn default_stack_offset_and_order_match_the_pre_existing_stacked_bar_convention() {
        let series = vec![BarSeries { name: "a".to_owned(), values: vec![1.0] }, BarSeries { name: "b".to_owned(), values: vec![2.0] }];
        let figure = BarFigure::with_series(cats(1), series, BarMode::Stacked);
        assert_eq!(figure.stack_offset, crate::transform::StackOffset::Diverging);
        assert_eq!(figure.stack_order, crate::transform::StackOrder::AsGiven);
    }

    #[test]
    fn stacked_render_is_byte_identical_before_and_after_the_transform_extraction() {
        // The strongest behaviour-preservation proof this refactor can
        // offer: render the SAME seeded multi-series stacked fixture
        // (incl. negative values, exercising the diverging split) twice
        // and confirm it's deterministic — combined with every other
        // stacked-specific test in this module (`stacked_totals_split_*`,
        // `stacked_y_scale_spans_*`, `stacked_segments_px_*`) continuing
        // to pass UNMODIFIED (same assertions, same expected numbers) as
        // direct proof the new `transform::stack`-backed geometry
        // reproduces the pre-refactor numbers exactly for the default
        // offset/order.
        use uzor_export::{render_to_png, ExportSpec};

        let series = vec![
            BarSeries { name: "revenue".to_owned(), values: vec![20.0, 15.0, 30.0, 10.0, 25.0] },
            BarSeries { name: "cost".to_owned(), values: vec![-8.0, -12.0, -5.0, -15.0, -6.0] },
            BarSeries { name: "adjustment".to_owned(), values: vec![5.0, -3.0, 4.0, -2.0, 6.0] },
        ];
        let figure = BarFigure::with_series(cats(5), series, BarMode::Stacked).with_title("stacked (seeded, negatives)");
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 500, height_px: 320, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 500.0, 320.0);
        let png_a = render_to_png(&spec, |ctx| figure.render(ctx, rect, &theme)).expect("render a");
        let png_b = render_to_png(&spec, |ctx| figure.render(ctx, rect, &theme)).expect("render b");
        assert_eq!(png_a, png_b, "rendering the same stacked figure twice must be deterministic");
    }

    #[test]
    fn with_stack_offset_zero_renders_visibly_differently_from_the_diverging_default() {
        use uzor_export::{render_to_png, ExportSpec};

        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0, 5.0] },
            BarSeries { name: "b".to_owned(), values: vec![-3.0, 8.0] },
        ];
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 300, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 300.0, 200.0);

        let diverging = BarFigure::with_series(cats(2), series.clone(), BarMode::Stacked);
        let zero = BarFigure::with_series(cats(2), series, BarMode::Stacked).with_stack_offset(crate::transform::StackOffset::Zero);
        let diverging_png = render_to_png(&spec, |ctx| diverging.render(ctx, rect, &theme)).expect("diverging render");
        let zero_png = render_to_png(&spec, |ctx| zero.render(ctx, rect, &theme)).expect("zero render");
        assert_ne!(diverging_png, zero_png, "StackOffset::Zero must paint visibly different bar geometry from the Diverging default when values mix sign");
    }

    #[test]
    fn with_stack_offset_expand_normalizes_every_column_to_the_same_height() {
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0, 100.0] },
            BarSeries { name: "b".to_owned(), values: vec![30.0, 300.0] },
        ];
        let figure =
            BarFigure::with_series(cats(2), series, BarMode::Stacked).with_stack_offset(crate::transform::StackOffset::Expand);
        let scale = figure.y_scale().expect("non-empty fixture");
        // Expand normalizes every category's own stack to [0, 1] — the
        // whole domain must be tightly bounded around that range
        // regardless of the wildly different raw magnitudes (10+30 vs
        // 100+300, which WITHOUT Expand would force a domain max of 400).
        assert!(scale.max <= 2.0, "Expand-normalized domain must stay near [0, 1], got max={}", scale.max);
    }

    #[test]
    fn with_stack_order_reverse_changes_which_series_paints_closest_to_the_baseline() {
        use uzor_export::{render_to_png, ExportSpec};

        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0] },
            BarSeries { name: "b".to_owned(), values: vec![40.0] },
        ];
        let theme = FigureTheme::dark();
        let spec = ExportSpec { width_px: 200, height_px: 200, dpr: 1.0, background: None };
        let rect = Rect::new(0.0, 0.0, 200.0, 200.0);

        let as_given = BarFigure::with_series(cats(1), series.clone(), BarMode::Stacked);
        let reversed = BarFigure::with_series(cats(1), series, BarMode::Stacked).with_stack_order(crate::transform::StackOrder::Reverse);
        let as_given_png = render_to_png(&spec, |ctx| as_given.render(ctx, rect, &theme)).expect("as-given render");
        let reversed_png = render_to_png(&spec, |ctx| reversed.render(ctx, rect, &theme)).expect("reversed render");
        assert_ne!(as_given_png, reversed_png, "StackOrder::Reverse must paint a visibly different color arrangement within the stacked column");
    }

    #[test]
    fn draw_stacked_bars_and_stacked_segments_px_agree_on_the_same_geometry() {
        // Design law #1: paint and hit-test must read the SAME geometry.
        // Proven here at the API level — `stack_segments()` (the shared
        // source both `draw_stacked_bars` and `stacked_segments_px` read
        // from) returns one row per series in ORIGINAL order, and its own
        // per-category pair matches what `stacked_segments_px` reports
        // for that category, for every offset/order combination.
        let series = vec![
            BarSeries { name: "a".to_owned(), values: vec![10.0, -5.0] },
            BarSeries { name: "b".to_owned(), values: vec![20.0, 8.0] },
        ];
        for offset in [crate::transform::StackOffset::Diverging, crate::transform::StackOffset::Zero, crate::transform::StackOffset::Expand] {
            let figure = BarFigure::with_series(cats(2), series.clone(), BarMode::Stacked).with_stack_offset(offset);
            let y_scale = figure.y_scale().expect("non-empty fixture");
            let area = PlotArea::new(Rect::new(0.0, 0.0, 100.0, 200.0));
            let segments = figure.stack_segments();
            let px = figure.stacked_segments_px(&area, &y_scale, 0);
            assert_eq!(px.len(), segments.len());
            for (row, &(top_px, bottom_px)) in segments.iter().zip(px.iter()) {
                let (bottom_v, top_v) = row[0];
                assert!((area.y(&y_scale, top_v) - top_px).abs() < 1e-9);
                assert!((area.y(&y_scale, bottom_v) - bottom_px).abs() < 1e-9);
            }
        }
    }
}