envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! Rendering functions for the Chart component.
//!
//! Extracted from the main chart module to keep file sizes manageable.
//! Contains renderers for bar charts and shared-axis charts (line, area, scatter),
//! as well as legend, axis labels, and threshold line rendering.

use ratatui::prelude::*;
use ratatui::widgets::{
    Axis as RatatuiAxis, Bar, BarChart, BarGroup, Chart as RatatuiChart, Dataset, GraphType,
    Paragraph,
};

use super::format::smart_format;
use super::{BarMode, ChartKind, ChartState};
use crate::theme::Theme;

/// Renders the legend showing series labels and colors.
pub(super) fn render_legend(state: &ChartState, frame: &mut Frame, area: Rect) {
    let total_entries = state.series.len() + state.thresholds.len() + state.vertical_lines.len();
    let mut entry_index = 0;

    let mut spans: Vec<Span> = state
        .series
        .iter()
        .enumerate()
        .flat_map(|(i, s)| {
            let marker = if i == state.active_series {
                ""
            } else {
                ""
            };
            entry_index += 1;
            let separator = if entry_index < total_entries {
                "  "
            } else {
                ""
            };
            vec![Span::styled(
                format!("{} {}{}", marker, s.label(), separator),
                Style::default().fg(s.color()),
            )]
        })
        .collect();

    for threshold in &state.thresholds {
        entry_index += 1;
        let separator = if entry_index < total_entries {
            "  "
        } else {
            ""
        };
        spans.push(Span::styled(
            format!("── {}{}", threshold.label, separator),
            Style::default().fg(threshold.color),
        ));
    }

    for vline in &state.vertical_lines {
        entry_index += 1;
        let separator = if entry_index < total_entries {
            "  "
        } else {
            ""
        };
        spans.push(Span::styled(
            format!("{}{}", vline.label, separator),
            Style::default().fg(vline.color),
        ));
    }

    let line = Line::from(spans);
    let paragraph = Paragraph::new(line).alignment(Alignment::Center);
    frame.render_widget(paragraph, area);
}

/// Renders a bar chart supporting Single, Grouped, and Stacked modes.
pub(super) fn render_bar_chart(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
    horizontal: bool,
    _focused: bool,
    disabled: bool,
) {
    if state.series.is_empty() {
        return;
    }

    match state.bar_mode {
        BarMode::Single => {
            render_bar_chart_single(state, frame, area, theme, horizontal, disabled);
        }
        BarMode::Grouped => {
            render_bar_chart_grouped(state, frame, area, theme, horizontal, disabled);
        }
        BarMode::Stacked => {
            render_bar_chart_stacked(state, frame, area, theme, horizontal, disabled);
        }
    }
}

/// Renders a bar chart in Single mode: only the active series is shown.
fn render_bar_chart_single(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
    horizontal: bool,
    disabled: bool,
) {
    let series = &state.series[state.active_series];
    if series.is_empty() {
        return;
    }
    let style = if disabled {
        theme.disabled_style()
    } else {
        Style::default().fg(series.color())
    };
    let bars: Vec<Bar> = series
        .values()
        .iter()
        .enumerate()
        .map(|(i, &v)| {
            let label = category_label(state, i);
            Bar::default()
                .value(v.max(0.0) as u64)
                .label(Line::from(label))
                .style(style)
        })
        .collect();
    let bar_width = auto_bar_width(area, bars.len(), 1, horizontal, state.bar_width);
    let group = BarGroup::default().bars(&bars);
    let mut bar_chart = BarChart::default()
        .data(group)
        .bar_width(bar_width)
        .bar_gap(state.bar_gap)
        .bar_style(style);
    if horizontal {
        bar_chart = bar_chart.direction(Direction::Horizontal);
    }
    frame.render_widget(bar_chart, area);
}

/// Renders a bar chart in Grouped mode: all series side-by-side at each position.
fn render_bar_chart_grouped(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
    horizontal: bool,
    disabled: bool,
) {
    let num_series = state.series.len();
    let num_positions = state
        .series
        .iter()
        .map(|s| s.values().len())
        .max()
        .unwrap_or(0);
    if num_positions == 0 {
        return;
    }
    let bar_width = auto_bar_width(area, num_positions, num_series, horizontal, state.bar_width);
    let groups: Vec<BarGroup> = (0..num_positions)
        .map(|pos| {
            let label = category_label(state, pos);
            let bars: Vec<Bar> = state
                .series
                .iter()
                .map(|s| {
                    let value = s.values().get(pos).copied().unwrap_or(0.0).max(0.0) as u64;
                    let style = if disabled {
                        theme.disabled_style()
                    } else {
                        Style::default().fg(s.color())
                    };
                    Bar::default().value(value).style(style)
                })
                .collect();
            BarGroup::default().label(Line::from(label)).bars(&bars)
        })
        .collect();
    let mut bar_chart = BarChart::default()
        .bar_width(bar_width)
        .bar_gap(state.bar_gap)
        .group_gap(state.bar_gap.saturating_add(1));
    for group in &groups {
        bar_chart = bar_chart.data(group.clone());
    }
    if horizontal {
        bar_chart = bar_chart.direction(Direction::Horizontal);
    }
    frame.render_widget(bar_chart, area);
}

/// Renders a bar chart in Stacked mode: series values stacked vertically.
fn render_bar_chart_stacked(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
    horizontal: bool,
    disabled: bool,
) {
    let np = state
        .series
        .iter()
        .map(|s| s.values().len())
        .max()
        .unwrap_or(0);
    if np == 0 {
        return;
    }
    let bar_width = auto_bar_width(area, np, 1, horizontal, state.bar_width);
    let bars: Vec<Bar> = (0..np)
        .map(|pos| {
            let label = category_label(state, pos);
            let total: f64 = state
                .series
                .iter()
                .map(|s| s.values().get(pos).copied().unwrap_or(0.0).max(0.0))
                .sum();
            let color = if disabled {
                theme
                    .disabled_style()
                    .fg
                    .unwrap_or(ratatui::style::Color::DarkGray)
            } else {
                state
                    .series
                    .iter()
                    .find(|s| s.values().get(pos).copied().unwrap_or(0.0) > 0.0)
                    .unwrap_or(&state.series[0])
                    .color()
            };
            Bar::default()
                .value(total as u64)
                .label(Line::from(label))
                .style(Style::default().fg(color))
        })
        .collect();
    let group = BarGroup::default().bars(&bars);
    let mut bar_chart = BarChart::default()
        .data(group)
        .bar_width(bar_width)
        .bar_gap(state.bar_gap);
    if horizontal {
        bar_chart = bar_chart.direction(Direction::Horizontal);
    }
    frame.render_widget(bar_chart, area);
    if !disabled && state.series.len() > 1 {
        render_stacked_segments(state, frame, area, np, bar_width, horizontal);
    }
}

fn render_stacked_segments(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    np: usize,
    bar_width: u16,
    horizontal: bool,
) {
    let max_total: f64 = (0..np)
        .map(|p| {
            state
                .series
                .iter()
                .map(|s| s.values().get(p).copied().unwrap_or(0.0).max(0.0))
                .sum::<f64>()
        })
        .reduce(f64::max)
        .unwrap_or(1.0)
        .max(1.0);
    let buf = frame.buffer_mut();
    for pos in 0..np {
        let total: f64 = state
            .series
            .iter()
            .map(|s| s.values().get(pos).copied().unwrap_or(0.0).max(0.0))
            .sum();
        if total <= 0.0 {
            continue;
        }
        if horizontal {
            paint_h_stack(state, buf, area, pos, bar_width, total, max_total);
        } else {
            paint_v_stack(state, buf, area, pos, bar_width, total, max_total);
        }
    }
}

fn paint_v_stack(
    state: &ChartState,
    buf: &mut Buffer,
    area: Rect,
    pos: usize,
    bw: u16,
    total: f64,
    max_total: f64,
) {
    let step = bw + state.bar_gap;
    let xs = area.x + (pos as u16) * step;
    let xe = (xs + bw).min(area.right());
    if xs >= area.right() {
        return;
    }
    let uh = area.height.saturating_sub(1);
    let bh = ((total / max_total) * (uh as f64)).round() as u16;
    let bb = area.bottom().saturating_sub(1);
    let mut filled: u16 = 0;
    for s in &state.series {
        let v = s.values().get(pos).copied().unwrap_or(0.0).max(0.0);
        if v <= 0.0 {
            continue;
        }
        let seg = ((v / total) * bh as f64).round().max(1.0) as u16;
        let seg = seg.min(bh.saturating_sub(filled));
        if seg == 0 {
            continue;
        }
        let top = bb.saturating_sub(filled + seg - 1);
        let bot = bb.saturating_sub(filled);
        for y in top..=bot {
            for x in xs..xe {
                if let Some(cell) = buf.cell_mut(Position::new(x, y)) {
                    cell.set_fg(s.color());
                }
            }
        }
        filled += seg;
    }
}

fn paint_h_stack(
    state: &ChartState,
    buf: &mut Buffer,
    area: Rect,
    pos: usize,
    bw: u16,
    total: f64,
    max_total: f64,
) {
    let step = bw + state.bar_gap;
    let ys = area.y + (pos as u16) * step;
    let ye = (ys + bw).min(area.bottom());
    if ys >= area.bottom() {
        return;
    }
    let bl = ((total / max_total) * (area.width.saturating_sub(1) as f64)).round() as u16;
    let mut filled: u16 = 0;
    for s in &state.series {
        let v = s.values().get(pos).copied().unwrap_or(0.0).max(0.0);
        if v <= 0.0 {
            continue;
        }
        let seg = ((v / total) * bl as f64).round().max(1.0) as u16;
        let seg = seg.min(bl.saturating_sub(filled));
        if seg == 0 {
            continue;
        }
        let left = area.x + filled;
        let right = left + seg;
        for y in ys..ye {
            for x in left..right {
                if let Some(cell) = buf.cell_mut(Position::new(x, y)) {
                    cell.set_fg(s.color());
                }
            }
        }
        filled += seg;
    }
}

fn category_label(state: &ChartState, pos: usize) -> String {
    if pos < state.categories().len() {
        state.categories()[pos].clone()
    } else {
        format!("{}", pos + 1)
    }
}

fn auto_bar_width(area: Rect, np: usize, bpp: usize, horizontal: bool, hint: u16) -> u16 {
    if np == 0 || bpp == 0 {
        return hint.max(1);
    }
    let avail = if horizontal {
        area.height as usize
    } else {
        area.width as usize
    };
    let total_bars = np * bpp;
    let gaps = np.saturating_sub(1);
    let usable = avail.saturating_sub(gaps);
    let auto_w = (usable / total_bars).max(1) as u16;
    let max_w = if horizontal {
        area.height.max(1)
    } else {
        area.width.max(1)
    };
    auto_w.max(hint).min(max_w)
}

/// Renders a line, area, or scatter chart using ratatui's Chart widget with shared axes.
///
/// This is used for `ChartKind::Line`, `ChartKind::Area`, and `ChartKind::Scatter`,
/// and renders all series overlaid on shared X and Y axes. Uses LTTB downsampling
/// for large datasets and applies scale transforms for logarithmic axes.
pub(super) fn render_shared_axis_chart(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    theme: &Theme,
    _focused: bool,
    disabled: bool,
) {
    if state.series.is_empty() && state.thresholds.is_empty() && state.vertical_lines.is_empty() {
        return;
    }

    let effective_min = state.effective_min();
    let effective_max = state.effective_max();

    // Compute X-axis bounds across all series.
    // For series with explicit x_values, use those min/max values.
    // For series with implicit indices, use 0..len-1.
    let (min_x_data, max_x_data) = {
        let mut overall_min = f64::INFINITY;
        let mut overall_max = f64::NEG_INFINITY;
        for s in &state.series {
            if let Some(x_vals) = s.x_values() {
                if let Some(&x_min) = x_vals.iter().reduce(|a, b| if a < b { a } else { b }) {
                    overall_min = overall_min.min(x_min);
                }
                if let Some(&x_max) = x_vals.iter().reduce(|a, b| if a > b { a } else { b }) {
                    overall_max = overall_max.max(x_max);
                }
            } else {
                let len = s.values().len();
                if len > 0 {
                    overall_min = overall_min.min(0.0);
                    overall_max = overall_max.max((len - 1) as f64);
                }
            }
        }
        if overall_min.is_infinite() {
            (0.0, 1.0)
        } else {
            (overall_min, overall_max.max(overall_min + 1.0))
        }
    };
    let max_x = max_x_data;

    // Compute effective max points based on render area width
    let effective_max_points = (area.width as usize * 2).min(state.max_display_points);

    let graph_type = match state.kind {
        ChartKind::Scatter => GraphType::Scatter,
        _ => GraphType::Line,
    };

    let is_log = state.y_scale.is_logarithmic();

    // Build data vectors with LTTB downsampling and scale transforms
    let series_data: Vec<Vec<(f64, f64)>> = state
        .series
        .iter()
        .map(|s| {
            // Convert to (x, y) pairs, using explicit x_values if available
            let points: Vec<(f64, f64)> = if let Some(x_vals) = s.x_values() {
                x_vals
                    .iter()
                    .zip(s.values())
                    .map(|(&x, &y)| (x, y))
                    .collect()
            } else {
                s.values()
                    .iter()
                    .enumerate()
                    .map(|(i, &v)| (i as f64, v))
                    .collect()
            };

            // Apply LTTB downsampling
            let downsampled = if points.len() > effective_max_points {
                super::downsample::lttb(&points, effective_max_points)
            } else {
                points
            };

            // Apply scale transform to Y values
            if is_log {
                downsampled
                    .into_iter()
                    .map(|(x, y)| (x, state.y_scale.transform(y)))
                    .collect()
            } else {
                downsampled
            }
        })
        .collect();

    // Transform effective min/max through the scale
    let (y_bound_min, y_bound_max) = if is_log {
        (
            state
                .y_scale
                .transform(effective_min.max(f64::MIN_POSITIVE)),
            state
                .y_scale
                .transform(effective_max.max(f64::MIN_POSITIVE)),
        )
    } else {
        (effective_min, effective_max)
    };

    // Build threshold data vectors (with scale transforms)
    let threshold_data: Vec<Vec<(f64, f64)>> = state
        .thresholds
        .iter()
        .map(|t| {
            let y = if is_log {
                state.y_scale.transform(t.value.max(f64::MIN_POSITIVE))
            } else {
                t.value
            };
            vec![(0.0, y), (max_x, y)]
        })
        .collect();

    // Build vertical line data vectors (with scale transforms)
    let scale = &state.y_scale;
    let vline_data: Vec<Vec<(f64, f64)>> = state
        .vertical_lines
        .iter()
        .map(|v| {
            let tv_min = scale.transform(effective_min);
            let tv_max = scale.transform(effective_max);
            vec![(v.x_value, tv_min), (v.x_value, tv_max)]
        })
        .collect();

    // Build datasets referencing the data vectors
    let mut datasets: Vec<Dataset> = state
        .series
        .iter()
        .enumerate()
        .map(|(i, s)| {
            let style = if disabled {
                theme.disabled_style()
            } else if i == state.active_series {
                Style::default().fg(s.color()).add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(s.color())
            };
            // Use empty name to suppress ratatui's internal legend box;
            // our custom legend below the chart handles all entries.
            Dataset::default()
                .name("")
                .data(&series_data[i])
                .marker(symbols::Marker::Braille)
                .graph_type(graph_type)
                .style(style)
        })
        .collect();

    // Add threshold lines as additional datasets
    for (i, threshold) in state.thresholds.iter().enumerate() {
        let style = Style::default().fg(threshold.color);
        datasets.push(
            Dataset::default()
                .name("")
                .data(&threshold_data[i])
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(style),
        );
    }

    // Add vertical reference lines as additional datasets
    for (i, vline) in state.vertical_lines.iter().enumerate() {
        let style = Style::default().fg(vline.color);
        datasets.push(
            Dataset::default()
                .name("")
                .data(&vline_data[i])
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(style),
        );
    }

    // Add crosshair cursor as a vertical line dataset
    let crosshair_data = if state.show_crosshair {
        state.cursor_position.map(|pos| {
            let x = pos as f64;
            let y_min = scale.transform(effective_min);
            let y_max = scale.transform(effective_max);
            vec![(x, y_min), (x, y_max)]
        })
    } else {
        None
    };
    if let Some(ref data) = crosshair_data {
        datasets.push(
            Dataset::default()
                .name("")
                .data(data)
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(Color::White)),
        );
    }

    // Generate tick labels
    let max_x_ticks = (area.width / 10).max(2) as usize;
    let max_y_ticks = (area.height / 3).max(2) as usize;

    let (x_labels, x_bound_min, x_bound_max) = if let Some(custom_labels) = &state.x_labels {
        let labels = select_x_labels(custom_labels, max_x_ticks);
        (labels, min_x_data, max_x_data)
    } else {
        let x_ticks = super::ticks::nice_ticks(min_x_data, max_x, max_x_ticks);
        let labels: Vec<String> = x_ticks
            .iter()
            .map(|&v| {
                super::ticks::format_tick(
                    v,
                    x_ticks.get(1).copied().unwrap_or(1.0)
                        - x_ticks.first().copied().unwrap_or(0.0),
                )
            })
            .collect();
        let bound_min = x_ticks.first().copied().unwrap_or(0.0);
        let bound_max = x_ticks.last().copied().unwrap_or(max_x);
        (labels, bound_min, bound_max)
    };

    // Generate Y ticks
    let (y_ticks_values, y_labels) = if is_log {
        let ticks = super::scale::log_ticks(
            effective_min.max(f64::MIN_POSITIVE),
            effective_max.max(f64::MIN_POSITIVE),
            max_y_ticks,
        );
        let labels: Vec<String> = ticks
            .iter()
            .map(|&v| super::scale::format_log_tick(v))
            .collect();
        let transformed: Vec<f64> = ticks.iter().map(|&v| state.y_scale.transform(v)).collect();
        (transformed, labels)
    } else {
        let ticks = super::ticks::nice_ticks(effective_min, effective_max, max_y_ticks);
        let step = ticks.get(1).copied().unwrap_or(effective_max)
            - ticks.first().copied().unwrap_or(effective_min);
        let labels: Vec<String> = ticks
            .iter()
            .map(|&v| super::ticks::format_tick(v, step))
            .collect();
        (ticks, labels)
    };

    let y_axis_min = y_ticks_values.first().copied().unwrap_or(y_bound_min);
    let y_axis_max = y_ticks_values.last().copied().unwrap_or(y_bound_max);

    // Save label strings for graph area computation before axes consume them
    let x_labels_for_layout = x_labels.clone();
    let y_labels_for_layout = y_labels.clone();

    // Build axes with tick labels
    let x_axis = RatatuiAxis::default()
        .bounds([x_bound_min, x_bound_max])
        .labels(x_labels);

    let y_axis = RatatuiAxis::default()
        .bounds([y_axis_min, y_axis_max])
        .labels(y_labels)
        .labels_alignment(Alignment::Right);

    let chart = RatatuiChart::new(datasets).x_axis(x_axis).y_axis(y_axis);

    frame.render_widget(chart, area);

    // Render error bands / confidence intervals for series that have bounds.
    let has_bounds = state
        .series
        .iter()
        .any(|s| s.upper_bound().is_some() || s.lower_bound().is_some());
    if has_bounds {
        let graph_area = compute_graph_area(area, &y_labels_for_layout, &x_labels_for_layout);
        if graph_area.width > 0 && graph_area.height > 0 {
            super::error_bands::fill_error_bands(
                state,
                frame,
                graph_area,
                super::annotations::AxisBounds {
                    x_min: x_bound_min,
                    x_max: x_bound_max,
                    y_min: y_axis_min,
                    y_max: y_axis_max,
                    is_log,
                },
                disabled,
                theme,
            );
        }
    }

    // For area charts, fill below the curve after the line has been rendered.
    if state.kind == ChartKind::Area && !state.series.is_empty() {
        let graph_area = compute_graph_area(area, &y_labels_for_layout, &x_labels_for_layout);
        if graph_area.width > 0 && graph_area.height > 0 {
            fill_area_below_curve(
                state,
                frame,
                graph_area,
                &series_data,
                super::annotations::AxisBounds {
                    x_min: x_bound_min,
                    x_max: x_bound_max,
                    y_min: y_axis_min,
                    y_max: y_axis_max,
                    is_log,
                },
                disabled,
                theme,
            );
        }
    }

    if state.show_grid {
        render_grid_lines(frame, area, &y_ticks_values, y_axis_min, y_axis_max);
    }

    // Render annotations after all other chart content
    super::annotations::render_annotations(
        state,
        frame,
        area,
        &y_labels_for_layout,
        &x_labels_for_layout,
        super::annotations::AxisBounds {
            x_min: x_bound_min,
            x_max: x_bound_max,
            y_min: y_axis_min,
            y_max: y_axis_max,
            is_log,
        },
    );
}

/// Renders the crosshair value readout overlay at the top of the chart area.
pub(super) fn render_crosshair_readout(
    state: &ChartState,
    frame: &mut Frame,
    area: Rect,
    cursor_pos: usize,
) {
    if area.height < 2 || area.width < 10 {
        return;
    }

    let mut spans = vec![Span::styled(
        format!("x:{}", cursor_pos),
        Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD),
    )];

    for series in &state.series {
        if let Some(&value) = series.values().get(cursor_pos) {
            spans.push(Span::raw(" | "));
            spans.push(Span::styled(
                format!("{}: {}", series.label(), smart_format(value, None)),
                Style::default().fg(series.color()),
            ));
        }
    }

    let line = Line::from(spans);
    let readout = Paragraph::new(line)
        .style(Style::default().bg(Color::DarkGray).fg(Color::White))
        .alignment(Alignment::Left);

    let readout_area = Rect::new(area.x, area.y, area.width, 1);
    frame.render_widget(readout, readout_area);
}

/// Computes the graph area by replicating ratatui's internal Chart layout logic.
pub(super) fn compute_graph_area(area: Rect, y_labels: &[String], x_labels: &[String]) -> Rect {
    if area.height == 0 || area.width == 0 {
        return Rect::default();
    }
    let mut x = area.left();
    let mut y = area.bottom().saturating_sub(1);
    let has_x_labels = !x_labels.is_empty();
    if has_x_labels && y > area.top() {
        y = y.saturating_sub(1);
    }
    let has_y_labels = !y_labels.is_empty();
    let y_label_max_width = y_labels.iter().map(|l| l.len() as u16).max().unwrap_or(0);
    let first_x_label_width = x_labels.first().map(|l| l.len() as u16).unwrap_or(0);
    let x_label_left_width = if has_y_labels {
        first_x_label_width.saturating_sub(1)
    } else {
        first_x_label_width
    };
    let max_label_width = y_label_max_width.max(x_label_left_width);
    let capped_label_width = max_label_width.min(area.width / 3);
    x += capped_label_width;
    if has_x_labels && y > area.top() {
        y = y.saturating_sub(1);
    }
    if has_y_labels && x + 1 < area.right() {
        x += 1;
    }
    let graph_width = area.right().saturating_sub(x);
    let graph_height = y.saturating_sub(area.top()).saturating_add(1);
    Rect::new(x, area.top(), graph_width, graph_height)
}

/// Fills the area below each series curve for area charts.
fn fill_area_below_curve(
    state: &ChartState,
    frame: &mut Frame,
    graph_area: Rect,
    series_data: &[Vec<(f64, f64)>],
    bounds: super::annotations::AxisBounds,
    disabled: bool,
    theme: &Theme,
) {
    let x_range = bounds.x_max - bounds.x_min;
    let y_range = bounds.y_max - bounds.y_min;
    if x_range <= 0.0 || y_range <= 0.0 {
        return;
    }
    let buf = frame.buffer_mut();
    for (series_idx, series) in state.series.iter().enumerate() {
        let color = if disabled {
            theme.disabled_style().fg.unwrap_or(Color::DarkGray)
        } else {
            series.color()
        };
        let data = &series_data[series_idx];
        if data.len() < 2 {
            if let Some(&(dx, dy)) = data.first() {
                let x_frac = (dx - bounds.x_min) / x_range;
                let screen_x = graph_area.x + (x_frac * (graph_area.width as f64 - 1.0)) as u16;
                let y_frac = (dy - bounds.y_min) / y_range;
                let line_y = graph_area
                    .bottom()
                    .saturating_sub(1)
                    .saturating_sub((y_frac * (graph_area.height as f64 - 1.0)) as u16);
                fill_column(buf, screen_x, line_y + 1, graph_area.bottom(), color);
            }
            continue;
        }
        for screen_x in graph_area.x..graph_area.right() {
            let x_frac =
                (screen_x - graph_area.x) as f64 / (graph_area.width as f64 - 1.0).max(1.0);
            let data_x = bounds.x_min + x_frac * x_range;
            let data_y = interpolate_y(data, data_x);
            if let Some(dy) = data_y {
                let y_frac = ((dy - bounds.y_min) / y_range).clamp(0.0, 1.0);
                let line_y = graph_area
                    .bottom()
                    .saturating_sub(1)
                    .saturating_sub((y_frac * (graph_area.height as f64 - 1.0)) as u16);
                fill_column(buf, screen_x, line_y + 1, graph_area.bottom(), color);
            }
        }
    }
}

/// Fills a single column of cells with the area fill character.
fn fill_column(buf: &mut Buffer, x: u16, y_start: u16, y_end: u16, color: Color) {
    for y in y_start..y_end {
        if let Some(cell) = buf.cell_mut(Position::new(x, y)) {
            if cell.symbol() == " " {
                cell.set_char('\u{2591}');
                cell.set_fg(color);
            }
        }
    }
}

/// Linearly interpolates the Y value for a given X within a sorted data series.
pub(super) fn interpolate_y(data: &[(f64, f64)], x: f64) -> Option<f64> {
    if data.is_empty() {
        return None;
    }
    let (first_x, _) = data[0];
    let (last_x, _) = data[data.len() - 1];
    if x < first_x || x > last_x {
        return None;
    }
    for window in data.windows(2) {
        let (x0, y0) = window[0];
        let (x1, y1) = window[1];
        if x >= x0 && x <= x1 {
            if (x1 - x0).abs() < f64::EPSILON {
                return Some(y0);
            }
            let t = (x - x0) / (x1 - x0);
            return Some(y0 + t * (y1 - y0));
        }
    }
    Some(data[data.len() - 1].1)
}

/// Selects a subset of custom X-axis labels that fit within `max_labels` slots.
///
/// If all labels fit, they are returned as-is. Otherwise, labels are sampled
/// at evenly spaced intervals, always including the first and last label.
pub(super) fn select_x_labels(labels: &[String], max_labels: usize) -> Vec<String> {
    if labels.is_empty() {
        return Vec::new();
    }
    let count = labels.len();
    if count <= max_labels {
        return labels.to_vec();
    }
    // Always include first and last; sample evenly in between
    let mut result = Vec::with_capacity(max_labels);
    for i in 0..max_labels {
        let idx = if max_labels <= 1 {
            0
        } else {
            (i * (count - 1)) / (max_labels - 1)
        };
        result.push(labels[idx].clone());
    }
    result
}

/// Renders horizontal grid lines at Y-axis tick positions.
fn render_grid_lines(
    frame: &mut Frame,
    area: Rect,
    y_ticks_values: &[f64],
    y_axis_min: f64,
    y_axis_max: f64,
) {
    let y_range = y_axis_max - y_axis_min;
    if y_range <= 0.0 || area.height < 2 {
        return;
    }
    for &tick_val in y_ticks_values {
        let y_frac = (tick_val - y_axis_min) / y_range;
        let screen_y =
            area.bottom().saturating_sub(1) - (y_frac * (area.height as f64 - 1.0)) as u16;
        if screen_y > area.y && screen_y < area.bottom().saturating_sub(1) {
            for x in area.x..area.right() {
                let cell = frame.buffer_mut().cell_mut(Position::new(x, screen_y));
                if let Some(cell) = cell {
                    if cell.symbol() == " " {
                        cell.set_char('·');
                        cell.set_fg(Color::DarkGray);
                    }
                }
            }
        }
    }
}