wbi-rs 0.1.11

A Rust library + CLI to fetch, store, visualize, and summarize World Bank indicator data.
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
//! Visualization utilities: render multi-series charts to **SVG** or **PNG**.
//!
//! - Distinct series colors (Microsoft Office palette)
//! - Locale-aware tick labels (`30,000` vs `30.000`), whole numbers
//! - Legend placement: `Inside`, `Right`, `Top`, `Bottom` (non-overlapping for external legends)
//! - Plot kinds: `Line`, `Scatter`, `LinePoints`, `Area`, `StackedArea`, `GroupedBar`, `Loess`
//! - Custom chart title and legend handling for long labels

pub mod legend;
pub mod loess;
pub mod text;
pub mod types;
pub mod util;

// Re-export types for public API
pub use types::{DEFAULT_LEGEND_MODE, LegendMode, PlotKind};

// Re-export style modules (transitional)
pub use crate::viz_style as style;

// Add near existing imports:
use crate::viz_plotters_adapter::{fill_style, line_style, rgb_color};
use crate::viz_style;
use crate::viz_style::{MarkerShape, SeriesStyle};

use crate::models::DataPoint;
use anyhow::{Result, anyhow};
use num_format::ToFormattedString;

use plotters::backend::DrawingBackend;
use plotters::coord::Shift;
use plotters::prelude::*;
use plotters::series::AreaSeries;

use plotters::style::FontFamily;

use plotters_bitmap::BitMapBackend;
use plotters_svg::SVGBackend;

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::Once;

use legend::{draw_legend_panel, estimate_top_bottom_legend_height_px};
use util::{
    choose_axis_scale, compute_left_label_area_px, derive_axis_unit, is_percentage_like,
    map_locale, office_color,
};

/// One-time registration for a fallback "sans-serif" font when using the `ab_glyph` text path.
/// Required because `ab_glyph` doesn't discover OS fonts.
static INIT_FONTS: Once = Once::new();

fn ensure_fonts_registered() {
    // Safe to call many times; only runs once.
    INIT_FONTS.call_once(|| {
        // Updated path for new module location: from `src/viz/mod.rs` → project root → `assets/DejaVuSans.ttf`
        let _ = plotters::style::register_font(
            "sans-serif",
            plotters::style::FontStyle::Normal,
            include_bytes!("../../assets/DejaVuSans.ttf"),
        );
    });
}

/// Convenience: plot with default locale (`"en"`) and default legend (`Bottom`) as a line chart.
pub fn plot_lines<P: AsRef<Path>>(
    points: &[DataPoint],
    out_path: P,
    width: u32,
    height: u32,
) -> Result<()> {
    plot_chart(
        points,
        out_path,
        width,
        height,
        "en",
        DEFAULT_LEGEND_MODE,
        "World Bank Indicator(s)",
        PlotKind::Line,
        0.3,  // default LOESS span
        None, // no country styles
    )
}

/// Convenience: plot with chosen locale and default legend (`Bottom`) as a line chart.
pub fn plot_lines_locale<P: AsRef<Path>>(
    points: &[DataPoint],
    out_path: P,
    width: u32,
    height: u32,
    locale_tag: &str,
) -> Result<()> {
    plot_chart(
        points,
        out_path,
        width,
        height,
        locale_tag,
        DEFAULT_LEGEND_MODE,
        "World Bank Indicator(s)",
        PlotKind::Line,
        0.3,
        None, // no country styles
    )
}

/// Convenience: plot with chosen locale and legend (default title) as a line chart.
pub fn plot_lines_locale_with_legend<P: AsRef<Path>>(
    points: &[DataPoint],
    out_path: P,
    width: u32,
    height: u32,
    locale_tag: &str,
    legend: LegendMode,
) -> Result<()> {
    plot_chart(
        points,
        out_path,
        width,
        height,
        locale_tag,
        legend,
        "World Bank Indicator(s)",
        PlotKind::Line,
        0.3,
        None, // no country styles
    )
}

/// Convenience: plot with chosen locale, legend, and custom title as a line chart.
pub fn plot_lines_locale_with_legend_title<P: AsRef<Path>>(
    points: &[DataPoint],
    out_path: P,
    width: u32,
    height: u32,
    locale_tag: &str,
    legend: LegendMode,
    title: &str,
) -> Result<()> {
    plot_chart(
        points,
        out_path,
        width,
        height,
        locale_tag,
        legend,
        title,
        PlotKind::Line,
        0.3,
        None, // no country styles
    )
}

/// Fully-configurable entry point: choose locale, legend placement, custom title, plot kind, and LOESS span.
#[allow(clippy::too_many_arguments)]
pub fn plot_chart<P: AsRef<Path>>(
    points: &[DataPoint],
    out_path: P,
    width: u32,
    height: u32,
    locale_tag: &str,
    legend: LegendMode,
    title: &str,
    kind: PlotKind,
    loess_span: f64, // fraction of neighbors (0,1], used only for PlotKind::Loess
    country_styles: Option<bool>, // None when feature disabled, Some(bool) when enabled
) -> Result<()> {
    if points.is_empty() {
        return Err(anyhow!("no data to plot"));
    }
    ensure_fonts_registered();
    let out_path = out_path.as_ref();
    let path_string = out_path.to_string_lossy().into_owned();

    let years: Vec<i32> = points.iter().map(|p| p.year).filter(|y| *y != 0).collect();
    let (mut min_year, mut max_year) = (
        *years
            .iter()
            .min()
            .ok_or_else(|| anyhow!("no valid years"))?,
        *years
            .iter()
            .max()
            .ok_or_else(|| anyhow!("no valid years"))?,
    );
    if min_year == max_year {
        min_year -= 1;
        max_year += 1;
    }

    let values: Vec<f64> = points.iter().filter_map(|p| p.value).collect();
    if values.is_empty() {
        return Err(anyhow!("no numeric values to plot"));
    }
    let (mut min_val, mut max_val) = (
        values.iter().cloned().fold(f64::INFINITY, f64::min),
        values.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
    );
    if (max_val - min_val).abs() < f64::EPSILON {
        min_val -= 1.0;
        max_val += 1.0;
    }

    let (_num_locale, _dec_sep) = map_locale(locale_tag);

    if out_path.extension().and_then(|s| s.to_str()) == Some("svg") {
        let root = SVGBackend::new(path_string.as_str(), (width, height)).into_drawing_area();
        draw_chart(
            root,
            points,
            min_year,
            max_year,
            min_val,
            max_val,
            locale_tag,
            legend,
            title,
            kind,
            loess_span,
            country_styles,
        )?;
    } else {
        let root = BitMapBackend::new(path_string.as_str(), (width, height)).into_drawing_area();
        draw_chart(
            root,
            points,
            min_year,
            max_year,
            min_val,
            max_val,
            locale_tag,
            legend,
            title,
            kind,
            loess_span,
            country_styles,
        )?;
    }
    Ok(())
}

// This is the main chart drawing function - copied from original viz.rs
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn draw_chart<DB>(
    root: DrawingArea<DB, Shift>,
    points: &[DataPoint],
    min_year: i32,
    max_year: i32,
    min_val: f64,
    max_val: f64,
    locale_tag: &str,
    legend: LegendMode,
    title: &str,
    kind: PlotKind,
    loess_span: f64,
    country_styles: Option<bool>,
) -> Result<()>
where
    DB: DrawingBackend,
    <DB as DrawingBackend>::ErrorType: 'static,
{
    // ----------------------------
    // 0) Common constants
    // ----------------------------
    const MARGIN: i32 = 16; // matches .margin(16) below
    let x_min = min_year as f64;
    let x_max = max_year as f64;

    // Axis scaling for large magnitudes (thousands/millions/billions/…)
    // Derive a unit from the indicator metadata/name, then decide scaling.
    // Percent-like units are NOT scaled; currencies/counts can be scaled to thousands/millions/…
    let base_unit = derive_axis_unit(points); // e.g., "current US$" or "annual %"
    let max_abs = min_val.abs().max(max_val.abs());

    let (yscale, scale_word) = if let Some(ref unit) = base_unit {
        if is_percentage_like(unit) {
            (1.0, "") // do not scale percentages
        } else {
            choose_axis_scale(max_abs) // e.g., (1e6, "millions")
        }
    } else {
        // Mixed indicators or no unit => fall back to generic scaling
        choose_axis_scale(max_abs)
    };

    // This is the final Y-axis title
    let y_axis_title = match (base_unit.as_deref(), scale_word) {
        (Some(u), "") => u.to_string(),         // e.g., "annual %"
        (Some(u), sw) => format!("{u} ({sw})"), // e.g., "current US$ (millions)"
        (None, "") => "Value".to_string(),
        (None, sw) => format!("Value ({sw})"),
    };

    // X/Y tick formatters with locale support
    let (num_locale, dec_sep) = map_locale(locale_tag);
    let x_label_fmt = |x: &f64| (x.round() as i32).to_string();
    let y_label_fmt_scaled = |v: &f64| {
        let a = v.abs();
        let prec = if a >= 100.0 {
            0
        } else if a >= 10.0 {
            1
        } else {
            2
        };
        
        // Use locale-aware formatting
        if prec == 0 {
            // Integer formatting with locale-aware thousands separators
            let int_val = v.round() as i64;
            int_val.to_formatted_string(num_locale)
        } else {
            // Float formatting with locale-aware decimal separator
            let s = format!("{:.*}", prec, *v);
            if let Some((int_part, frac_part)) = s.split_once('.') {
                let sign = if int_part.starts_with('-') { "-" } else { "" };
                let digits = int_part.trim_start_matches('-');
                let int_num: i64 = digits.parse().unwrap_or(0);
                let grouped = int_num.to_formatted_string(num_locale);
                format!("{}{}{}{}", sign, grouped, dec_sep, frac_part)
            } else {
                // No decimal part, just format as integer
                let int_val = v.round() as i64;
                int_val.to_formatted_string(num_locale)
            }
        }
    };
    let x_label_count = ((max_year - min_year + 1) as usize).min(12);
    let y_label_count = 10usize;

    // ----------------------------
    // 1) Build name maps & groups
    // ----------------------------
    let mut indicator_name_by_id: HashMap<String, String> = HashMap::new();
    let mut country_name_by_iso3: HashMap<String, String> = HashMap::new();
    for p in points {
        indicator_name_by_id
            .entry(p.indicator_id.clone())
            .or_insert_with(|| p.indicator_name.clone());
        country_name_by_iso3
            .entry(p.country_iso3.clone())
            .or_insert_with(|| p.country_name.clone());
    }

    // Group as (ISO3, indicator_id) -> Vec<(year, value)>
    let mut groups: BTreeMap<(String, String), Vec<(i32, f64)>> = BTreeMap::new();
    for p in points {
        if let (y, Some(v)) = (p.year, p.value)
            && y != 0
        {
            groups
                .entry((p.country_iso3.clone(), p.indicator_id.clone()))
                .or_default()
                .push((y, v));
        }
    }
    for ((_country, _indicator), series) in groups.iter_mut() {
        series.sort_by_key(|(y, _)| *y);
    }

    // Sorted list by *country name* then *indicator name*
    let mut series_list: Vec<(String, String, String, String, Vec<(i32, f64)>)> = Vec::new();
    for ((iso3, indicator_id), series) in groups.iter() {
        let country_label = country_name_by_iso3
            .get(iso3)
            .cloned()
            .unwrap_or_else(|| iso3.clone());
        let indicator_label = indicator_name_by_id
            .get(indicator_id)
            .cloned()
            .unwrap_or_else(|| indicator_id.clone());
        series_list.push((
            iso3.clone(),
            indicator_id.clone(),
            country_label,
            indicator_label,
            series.clone(),
        ));
    }
    series_list.sort_by(|a, b| a.2.cmp(&b.2).then(a.3.cmp(&b.3)));

    // Shorter legend labels when possible:
    // - one indicator across many countries → label = country name only
    // - one country across many indicators → label = indicator name only
    // - both vary → "Country — Indicator"
    let unique_indicators: BTreeSet<&str> =
        points.iter().map(|p| p.indicator_id.as_str()).collect();
    let unique_countries: BTreeSet<&str> = points.iter().map(|p| p.country_iso3.as_str()).collect();
    let one_indicator = unique_indicators.len() == 1;
    let one_country = unique_countries.len() == 1;

    let make_label = |country_label: &str, indicator_label: &str| -> String {
        if one_indicator && !one_country {
            country_label.to_string()
        } else if one_country && !one_indicator {
            indicator_label.to_string()
        } else {
            format!("{}{}", country_label, indicator_label)
        }
    };

    // ----------------------------
    // 2) Compute dynamic gutters before splitting
    // ----------------------------
    // Left label area depends on *scaled* Y range & tick font size (12)
    let left_label_width_px =
        compute_left_label_area_px(min_val / yscale, max_val / yscale, y_label_count, 12);
    // X-axis text column starts at margin + left label area
    let axis_x_start_px: i32 = MARGIN + left_label_width_px as i32;

    // Legend height for Top/Bottom: pre-measure how much vertical space we need.
    // Build the list of final legend texts in drawing order (matches series_list).
    let legend_texts: Vec<String> = series_list
        .iter()
        .map(|(_iso3, _ind, country_label, indicator_label, _s)| {
            make_label(country_label, indicator_label)
        })
        .collect();

    let (root_w_u32, root_h_u32) = root.dim_in_pixel();
    let root_w = root_w_u32 as i32;
    let root_h = root_h_u32 as i32;

    // Title is generally omitted (best practice). We pass "" later.
    let _has_title = false;
    let _title_font_px: u32 = 16;
    let _font_px: u32 = 14;

    // Estimator to avoid missing-symbol issues:
    let legend_needed_h = if matches!(legend, LegendMode::Top | LegendMode::Bottom) {
        estimate_top_bottom_legend_height_px(
            &legend_texts,
            axis_x_start_px,
            root_w,
            /* has_title: */ false, // we render without a legend title by default
            /* title_font_px: */ 16,
            /* font_px: */ 14,
        )
    } else {
        0
    };

    // ----------------------------
    // 3) Split drawing areas
    // ----------------------------
    let (plot_area, legend_area_opt): (DrawingArea<DB, Shift>, Option<DrawingArea<DB, Shift>>) =
        match legend {
            LegendMode::Right => {
                let (plot, legend) = root.split_horizontally((85).percent_width());
                (plot, Some(legend))
            }
            LegendMode::Top => {
                let h = legend_needed_h.max(40);
                let (legend, plot) = root.split_vertically(h);
                (plot, Some(legend))
            }
            LegendMode::Bottom => {
                let h = legend_needed_h.max(40);
                // keep at least 40px for plot area
                let (plot, legend) = root.split_vertically((root_h - h).max(40));
                (plot, Some(legend))
            }
            LegendMode::Inside => (root, None),
        };

    plot_area
        .fill(&WHITE)
        .map_err(|e| anyhow::anyhow!("{:?}", e))?;
    if let Some(ref legend_area) = legend_area_opt {
        legend_area
            .fill(&WHITE)
            .map_err(|e| anyhow::anyhow!("{:?}", e))?;
    }

    // ----------------------------
    // 4) Build chart (scaled Y range)
    // ----------------------------
    let mut chart = ChartBuilder::on(&plot_area)
        .margin(MARGIN as u32)
        .caption(
            {
                let t = title.trim();
                if t.is_empty() || t == "World Bank Indicator(s)" {
                    // derive from indicator names
                    let names: BTreeSet<&str> =
                        points.iter().map(|p| p.indicator_name.as_str()).collect();
                    if names.is_empty() {
                        "World Bank Series".to_string()
                    } else if names.len() == 1 {
                        names.iter().next().unwrap().to_string()
                    } else if names.len() <= 3 {
                        names.into_iter().collect::<Vec<_>>().join(", ")
                    } else {
                        let first = names.iter().next().unwrap();
                        let more = names.len() - 1;
                        format!("{first} + {more} more")
                    }
                } else {
                    t.to_string()
                }
            },
            (FontFamily::SansSerif, 24),
        )
        .set_label_area_size(LabelAreaPosition::Left, left_label_width_px)
        .set_label_area_size(LabelAreaPosition::Bottom, 56)
        .build_cartesian_2d(x_min..x_max, (min_val / yscale)..(max_val / yscale))
        .map_err(|e| anyhow::anyhow!("{:?}", e))?;

    chart
        .configure_mesh()
        .x_desc("Year")
        .y_desc(y_axis_title)
        .x_labels(x_label_count)
        .y_labels(y_label_count)
        .x_label_formatter(&x_label_fmt)
        .y_label_formatter(&y_label_fmt_scaled)
        .label_style((FontFamily::SansSerif, 12))
        .axis_desc_style((FontFamily::SansSerif, 16))
        .draw()
        .map_err(|e| anyhow::anyhow!("{:?}", e))?;

    // ----------------------------
    // 5) Draw series & collect legend items
    // ----------------------------
    let mut legend_items: Vec<(String, SeriesStyle)> = Vec::new();
    let inside_mode = matches!(legend, LegendMode::Inside);

    // Create a flag for easier handling
    let use_country_styles = country_styles.unwrap_or(false);

    // Helper for legend labels
    let make_label_for_legend = |country_label: &str, indicator_label: &str| -> String {
        // Always use the standard labeling logic - country styles should only affect visual styling, not labels
        make_label(country_label, indicator_label)
    };

    // De-duplicate legend labels when using country styles
    let mut seen_legend_labels: BTreeSet<String> = BTreeSet::new();

    match kind {
        PlotKind::Line
        | PlotKind::Scatter
        | PlotKind::LinePoints
        | PlotKind::Area
        | PlotKind::Loess => {
            for (idx, (iso3, indicator_id, country_label, indicator_label, series)) in
                series_list.iter().enumerate()
            {
                let legend_label = make_label_for_legend(country_label, indicator_label);
                let color = office_color(idx);

                // Build style (viz_style) for markers/legend; fallback to color-only defaults
                let style = if use_country_styles {
                    viz_style::SeriesStyle::for_series(iso3, indicator_id)
                } else {
                    SeriesStyle {
                        country: iso3.clone(),
                        indicator: indicator_id.clone(),
                        hsl: viz_style::Hsl {
                            h_deg: 0.0,
                            s: 0.0,
                            l: 0.0,
                        },
                        rgb: viz_style::Rgb8 {
                            r: color.0,
                            g: color.1,
                            b: color.2,
                        },
                        hex: String::new(),
                        marker: MarkerShape::Circle,
                        line_dash: viz_style::LineDash::Solid,
                        marker_size: 6,
                        line_width: 2,
                    }
                };

                // Convert to f64 X and **scale Y**
                let series_f: Vec<(f64, f64)> = series
                    .iter()
                    .map(|(x, y)| (*x as f64, *y / yscale))
                    .collect();

                match kind {
                    PlotKind::Line | PlotKind::Loess => {
                        let pts: Vec<(f64, f64)> = if matches!(kind, PlotKind::Loess) {
                            // Smooth on original values, then scale the result for plotting
                            let xs: Vec<f64> = series.iter().map(|(x, _)| *x as f64).collect();
                            let ys: Vec<f64> = series.iter().map(|(_, y)| *y).collect();
                            let yhat = loess::loess_series(&xs, &ys, loess_span);
                            xs.into_iter()
                                .zip(yhat.into_iter().map(|v| v / yscale))
                                .collect()
                        } else {
                            series_f.clone()
                        };
                        let final_label = if matches!(kind, PlotKind::Loess) {
                            format!("{legend_label} (LOESS)")
                        } else {
                            legend_label.clone()
                        };

                        let elem = chart.draw_series(std::iter::once(PathElement::new(
                            pts,
                            line_style(&style),
                        )))?;
                        if inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            let text = final_label.clone();
                            let style_clone = style.clone();
                            let color = rgb_color(&style);
                            elem.label(text.clone()).legend(move |(x, y)| {
                                EmptyElement::at((x, y))
                                    + PathElement::new(
                                        vec![(x - 14, y), (x + 14, y)],
                                        line_style(&style_clone),
                                    )
                                    + Circle::new((x, y), 4, color.filled())
                                    + Text::new(text.clone(), (x + 20, y), ("sans-serif", 14))
                            });
                        }
                        if !inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            legend_items.push((final_label, style.clone()));
                        }
                    }
                    PlotKind::Scatter => {
                        // Markers only - use circles for now, but proper shapes in legend
                        chart.draw_series(series_f.iter().map(|(x, y)| {
                            Circle::new((*x, *y), style.marker_size as i32, fill_style(&style))
                        }))?;

                        if inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            let text = legend_label.clone();
                            let color = rgb_color(&style);
                            let empty =
                                chart.draw_series(std::iter::empty::<Circle<(f64, f64), i32>>())?;
                            empty.label(text.clone()).legend(move |(x, y)| {
                                EmptyElement::at((x, y))
                                    + Circle::new((x + 8, y), 4, color.filled())
                                    + Text::new(text.clone(), (x + 20, y), ("sans-serif", 14))
                            });
                        }
                        if !inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            legend_items.push((legend_label.clone(), style.clone()));
                        }
                    }
                    PlotKind::LinePoints => {
                        // Draw the line
                        let pts: Vec<(f64, f64)> = series_f.clone();
                        chart.draw_series(std::iter::once(PathElement::new(
                            pts,
                            line_style(&style),
                        )))?;
                        // Overlay markers - use circles for now, but in legend show proper marker
                        chart.draw_series(series_f.iter().map(|(x, y)| {
                            Circle::new((*x, *y), style.marker_size as i32, fill_style(&style))
                        }))?;

                        if inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            let text = legend_label.clone();
                            let style_clone = style.clone();
                            let color = rgb_color(&style);
                            let empty =
                                chart.draw_series(std::iter::empty::<Circle<(f64, f64), i32>>())?;
                            empty.label(text.clone()).legend(move |(x, y)| {
                                EmptyElement::at((x, y))
                                    + PathElement::new(
                                        vec![(x - 14, y), (x + 14, y)],
                                        line_style(&style_clone),
                                    )
                                    + Circle::new((x, y), 4, color.filled())
                                    + Text::new(text.clone(), (x + 20, y), ("sans-serif", 14))
                            });
                        }
                        if !inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            legend_items.push((legend_label.clone(), style.clone()));
                        }
                    }
                    PlotKind::Area => {
                        let area_pts: Vec<(f64, f64)> = series_f;
                        let elem = chart.draw_series(AreaSeries::new(
                            area_pts,
                            0.0,
                            fill_style(&style),
                        ))?;
                        if inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            let text = legend_label.clone();
                            let color = rgb_color(&style);
                            elem.label(text.clone()).legend(move |(x, y)| {
                                EmptyElement::at((x, y))
                                    + Circle::new((x + 8, y), 4, color.filled())
                                    + Text::new(text.clone(), (x + 20, y), ("sans-serif", 14))
                            });
                        }
                        if !inside_mode && seen_legend_labels.insert(legend_label.clone()) {
                            legend_items.push((legend_label, style));
                        }
                    }
                    _ => {}
                }
            }
        }
        PlotKind::StackedArea => {
            let years_all: Vec<i32> = (min_year..=max_year).collect();
            let mut cum: Vec<f64> = vec![0.0; years_all.len()];

            for (idx, (iso3, indicator_id, country_label, indicator_label, series)) in
                series_list.iter().enumerate()
            {
                let color = office_color(idx);
                let legend_label = make_label(country_label, indicator_label);

                // Map series to full year grid, missing -> 0.0
                let mut vals: Vec<f64> = vec![0.0; years_all.len()];
                for (y, v) in series.iter() {
                    if *y >= min_year && *y <= max_year {
                        vals[(*y - min_year) as usize] = (*v).max(0.0);
                    }
                }
                // Build upper curve by adding to cumulative
                let mut upper: Vec<(f64, f64)> = Vec::with_capacity(vals.len());
                let mut lower: Vec<(f64, f64)> = Vec::with_capacity(vals.len());
                for (i, v) in vals.iter().enumerate() {
                    let x = (min_year + i as i32) as f64;
                    lower.push((x, cum[i]));
                    cum[i] += *v;
                    upper.push((x, cum[i]));
                }
                // polygon: lower (forward) + upper (reverse), scaled
                let mut poly: Vec<(f64, f64)> = Vec::with_capacity(upper.len() * 2);
                poly.extend(lower.iter().map(|(x, y)| (*x, *y / yscale)));
                poly.extend(upper.iter().rev().map(|(x, y)| (*x, *y / yscale)));

                let fill = color.clone().mix(0.30).filled();
                let border = color.clone().stroke_width(1);
                chart
                    .draw_series(std::iter::once(Polygon::new(poly, fill)))
                    .map_err(|e| anyhow::anyhow!("{:?}", e))?;
                chart
                    .draw_series(std::iter::once(PathElement::new(
                        upper
                            .iter()
                            .map(|(x, y)| (*x, *y / yscale))
                            .collect::<Vec<_>>(),
                        border,
                    )))
                    .map_err(|e| anyhow::anyhow!("{:?}", e))?;

                legend_items.push((
                    legend_label,
                    SeriesStyle {
                        country: iso3.clone(),
                        indicator: indicator_id.clone(),
                        hsl: viz_style::Hsl {
                            h_deg: 0.0,
                            s: 0.0,
                            l: 0.0,
                        },
                        rgb: viz_style::Rgb8 {
                            r: color.0,
                            g: color.1,
                            b: color.2,
                        },
                        hex: String::new(),
                        marker: MarkerShape::Circle,
                        line_dash: viz_style::LineDash::Solid,
                        marker_size: 6,
                        line_width: 2,
                    },
                ));
            }
        }
        PlotKind::GroupedBar => {
            let n_series = series_list.len().max(1);
            let group_width = 0.8f64;
            let bar_w = group_width / n_series as f64;

            for (idx, (iso3, indicator_id, country_label, indicator_label, series)) in
                series_list.iter().enumerate()
            {
                let color = office_color(idx);
                let legend_label = make_label(country_label, indicator_label);

                for (y, v) in series.iter() {
                    let x_center = *y as f64;
                    let x0 = x_center - group_width / 2.0 + idx as f64 * bar_w;
                    let x1 = x0 + bar_w;
                    let y0 = 0.0f64.min(*v) / yscale;
                    let y1 = 0.0f64.max(*v) / yscale;
                    let rect = Rectangle::new([(x0, y0), (x1, y1)], color.clone().filled());
                    chart
                        .draw_series(std::iter::once(rect))
                        .map_err(|e| anyhow::anyhow!("{:?}", e))?;
                }

                legend_items.push((
                    legend_label,
                    SeriesStyle {
                        country: iso3.clone(),
                        indicator: indicator_id.clone(),
                        hsl: viz_style::Hsl {
                            h_deg: 0.0,
                            s: 0.0,
                            l: 0.0,
                        },
                        rgb: viz_style::Rgb8 {
                            r: color.0,
                            g: color.1,
                            b: color.2,
                        },
                        hex: String::new(),
                        marker: MarkerShape::Circle,
                        line_dash: viz_style::LineDash::Solid,
                        marker_size: 6,
                        line_width: 2,
                    },
                ));
            }
        }
    }

    // ----------------------------
    // 6) Legend rendering
    // ----------------------------
    if inside_mode {
        chart
            .configure_series_labels()
            .border_style(BLACK)
            .position(SeriesLabelPosition::UpperLeft)
            .background_style(WHITE.mix(0.85))
            .label_font((FontFamily::SansSerif, 14))
            .draw()
            .map_err(|e| anyhow::anyhow!("{:?}", e))?;
    } else if let Some(ref legend_area) = legend_area_opt {
        // Best practice: no explicit "Legend" title
        // Convert SeriesStyle to RGBAColor for the legend panel
        let legend_items_rgb: Vec<(String, RGBAColor)> = legend_items
            .iter()
            .map(|(label, style)| (label.clone(), rgb_color(style)))
            .collect();
        draw_legend_panel(legend_area, &legend_items_rgb, "", legend, axis_x_start_px)?;
    }

    // ----------------------------
    // 7) Present
    // ----------------------------
    plot_area
        .present()
        .map_err(|e| anyhow::anyhow!("{:?}", e))?;
    if let Some(ref legend_area) = legend_area_opt {
        legend_area
            .present()
            .map_err(|e| anyhow::anyhow!("{:?}", e))?;
    }
    Ok(())
}