embedded-charts 0.3.0

A rich graph framework for embedded systems using embedded-graphics with std/no_std 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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
//! Line chart implementation with no_std compatibility.
//!
//! This module provides a comprehensive line chart implementation optimized for embedded systems.
//! It supports multiple styling options, markers, area fills, and smooth curves while maintaining
//! memory efficiency and performance suitable for resource-constrained environments.
//!
//! # Features
//!
//! - **Multi-series support**: Display multiple data series with different colors
//! - **Marker customization**: Various shapes (circle, square, diamond, triangle) with configurable size and color
//! - **Area filling**: Fill the area under the line with customizable colors
//! - **Smooth curves**: Optional bezier curve smoothing for professional appearance
//! - **Grid integration**: Support for both legacy and modern grid systems
//! - **Axis integration**: Full support for linear axes with labels and ticks
//! - **Animation support**: Real-time data streaming and smooth transitions (feature-gated)
//! - **Memory efficient**: Static allocation with compile-time bounds
//!
//! # Basic Usage
//!
//! ```rust
//! use embedded_charts::prelude::*;
//! use embedded_graphics::pixelcolor::Rgb565;
//!
//! // Create sample data
//! let mut data: StaticDataSeries<Point2D, 256> = StaticDataSeries::new();
//! data.push(Point2D::new(0.0, 10.0))?;
//! data.push(Point2D::new(1.0, 20.0))?;
//! data.push(Point2D::new(2.0, 15.0))?;
//!
//! // Create a basic line chart
//! let chart = LineChart::builder()
//!     .line_color(Rgb565::BLUE)
//!     .line_width(2)
//!     .build()?;
//!
//! // Configure the chart
//! let config: ChartConfig<Rgb565> = ChartConfig::default();
//! let viewport = Rectangle::new(Point::zero(), Size::new(320, 240));
//!
//! // Render to display (display would be provided by your embedded target)  
//! // chart.draw(&data, &config, viewport, &mut display)?;
//! # Ok::<(), embedded_charts::error::ChartError>(())
//! ```
//!
//! # Advanced Styling
//!
//! ```rust
//! use embedded_charts::prelude::*;
//! use embedded_graphics::pixelcolor::Rgb565;
//!
//! let chart = LineChart::builder()
//!     .line_color(Rgb565::BLUE)
//!     .line_width(3)
//!     .fill_area(Rgb565::CSS_LIGHT_BLUE)
//!     .with_markers(MarkerStyle {
//!         shape: MarkerShape::Circle,
//!         size: 8,
//!         color: Rgb565::RED,
//!         visible: true,
//!     })
//!     .smooth(true)
//!     .build()?;
//! # Ok::<(), embedded_charts::error::ChartError>(())
//! ```
//!
//! # With Axes and Grid
//!
//! ```rust
//! use embedded_charts::prelude::*;
//! use embedded_graphics::pixelcolor::Rgb565;
//!
//! // Simple example with line chart styling
//! let chart = LineChart::builder()
//!     .line_color(Rgb565::BLUE)
//!     .line_width(2)
//!     .build()?;
//!
//! // Axes and grids can be configured through the chart config
//! // This is a simplified example focusing on basic line chart usage
//! # Ok::<(), embedded_charts::error::ChartError>(())
//! ```

use crate::axes::traits::Axis;
use crate::chart::traits::AxisChart;
use crate::chart::traits::{Chart, ChartBuilder, ChartConfig, Margins};
use crate::data::{DataBounds, DataPoint, DataSeries};
use crate::error::{ChartError, ChartResult};
use crate::math::NumericConversion;
use embedded_graphics::{
    draw_target::DrawTarget,
    prelude::*,
    primitives::{Circle, Line, PrimitiveStyle, Rectangle},
};

/// Line chart implementation for displaying continuous data series.
///
/// A line chart connects data points with straight lines (or smooth curves when enabled),
/// making it ideal for showing trends over time or continuous relationships between variables.
/// This implementation is optimized for embedded systems with static memory allocation
/// and efficient rendering.
///
/// # Features
///
/// - Configurable line styling (color, width, smoothing)
/// - Optional markers at data points with various shapes
/// - Area filling under the line
/// - Integration with grid systems and axes
/// - Support for animations and real-time data streaming
///
/// # Memory Usage
///
/// The line chart uses static allocation with a maximum of 256 data points per series.
/// Additional memory is used for:
/// - Screen coordinate transformation (256 points)
/// - Area fill polygon vertices (258 points maximum)
/// - Grid and axis rendering buffers
///
/// # Examples
///
/// Basic line chart:
/// ```rust
/// use embedded_charts::prelude::*;
/// use embedded_graphics::pixelcolor::Rgb565;
///
/// let chart: LineChart<Rgb565> = LineChart::new();
/// let mut data: StaticDataSeries<Point2D, 256> = StaticDataSeries::new();
/// data.push(Point2D::new(0.0, 10.0))?;
/// data.push(Point2D::new(1.0, 20.0))?;
/// # Ok::<(), embedded_charts::error::DataError>(())
/// ```
///
/// Styled line chart with markers:
/// ```rust
/// use embedded_charts::prelude::*;
/// use embedded_graphics::pixelcolor::Rgb565;
///
/// let chart = LineChart::builder()
///     .line_color(Rgb565::BLUE)
///     .line_width(2)
///     .with_markers(MarkerStyle {
///         shape: MarkerShape::Circle,
///         size: 6,
///         color: Rgb565::RED,
///         visible: true,
///     })
///     .build()?;
/// # Ok::<(), embedded_charts::error::ChartError>(())
/// ```
#[derive(Debug)]
pub struct LineChart<C: PixelColor> {
    style: LineChartStyle<C>,
    config: ChartConfig<C>,
    grid: Option<crate::grid::GridSystem<C>>,
    x_axis: Option<crate::axes::LinearAxis<f32, C>>,
    y_axis: Option<crate::axes::LinearAxis<f32, C>>,
}

/// Style configuration for line charts.
///
/// This structure contains all visual styling options for line charts,
/// including line appearance, markers, and area fills.
///
/// # Examples
///
/// ```rust
/// use embedded_charts::prelude::*;
/// use embedded_graphics::pixelcolor::Rgb565;
///
/// let style = LineChartStyle {
///     line_color: Rgb565::BLUE,
///     line_width: 2,
///     fill_area: true,
///     fill_color: Some(Rgb565::CSS_LIGHT_BLUE),
///     markers: Some(MarkerStyle::default()),
///     smooth: false,
///     smooth_subdivisions: 8,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct LineChartStyle<C: PixelColor> {
    /// Color of the line connecting data points.
    pub line_color: C,
    /// Width of the line in pixels (recommended range: 1-10).
    ///
    /// Larger widths may impact performance on resource-constrained devices.
    pub line_width: u32,
    /// Whether to fill the area under the line.
    ///
    /// When enabled, creates a filled polygon from the line to the chart baseline.
    pub fill_area: bool,
    /// Fill color for the area under the line.
    ///
    /// Only used when `fill_area` is `true`. If `None`, no fill is drawn.
    pub fill_color: Option<C>,
    /// Marker style for data points.
    ///
    /// When `Some`, markers are drawn at each data point. When `None`, no markers are shown.
    pub markers: Option<MarkerStyle<C>>,
    /// Whether to smooth the line using interpolation.
    ///
    /// When enabled, creates smooth curves between data points instead of straight lines.
    /// Uses Catmull-Rom spline interpolation for balanced smoothness and performance.
    /// This feature may impact performance and is recommended for larger displays.
    pub smooth: bool,
    /// Number of subdivisions for smooth curves (only used when smooth = true)
    pub smooth_subdivisions: u32,
}

/// Marker style configuration for data points.
///
/// Markers are visual indicators drawn at each data point to make individual
/// values easier to identify. This is particularly useful for sparse data
/// or when precise values need to be highlighted.
///
/// # Examples
///
/// ```rust
/// use embedded_charts::prelude::*;
/// use embedded_graphics::pixelcolor::Rgb565;
///
/// let marker_style = MarkerStyle {
///     shape: MarkerShape::Circle,
///     size: 8,
///     color: Rgb565::RED,
///     visible: true,
/// };
/// ```
#[derive(Debug, Clone, Copy)]
pub struct MarkerStyle<C: PixelColor> {
    /// Shape of the marker.
    pub shape: MarkerShape,
    /// Size of the marker in pixels.
    ///
    /// This represents the diameter for circles or the side length for squares.
    /// Recommended range: 4-16 pixels for optimal visibility.
    pub size: u32,
    /// Color of the marker.
    pub color: C,
    /// Whether markers should be visible.
    ///
    /// When `false`, markers are not drawn even if a `MarkerStyle` is provided.
    pub visible: bool,
}

/// Available shapes for data point markers.
///
/// Each shape provides different visual characteristics:
/// - `Circle`: Smooth, traditional marker shape
/// - `Square`: Sharp, geometric appearance
/// - `Diamond`: Distinctive diamond shape
/// - `Triangle`: Directional appearance, good for indicating trends
///
/// # Performance Notes
///
/// - `Circle` and `Square` use embedded-graphics primitives (fastest)
/// - `Diamond` and `Triangle` use custom rendering (slightly slower)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkerShape {
    /// Circular marker - smooth and traditional appearance.
    Circle,
    /// Square marker - sharp, geometric appearance.
    Square,
    /// Diamond marker - distinctive diamond shape.
    Diamond,
    /// Triangle marker - directional appearance.
    Triangle,
}

impl<C: PixelColor> LineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    /// Create a new line chart with default styling.
    ///
    /// This creates a line chart with:
    /// - Blue line color
    /// - 1-pixel line width
    /// - No area fill
    /// - No markers
    /// - No smoothing
    /// - Default margins (10 pixels on all sides)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use embedded_charts::prelude::*;
    /// use embedded_graphics::pixelcolor::Rgb565;
    ///
    /// let chart: LineChart<Rgb565> = LineChart::new();
    /// ```
    pub fn new() -> Self {
        Self {
            style: LineChartStyle::default(),
            config: ChartConfig::default(),
            grid: None,
            x_axis: None,
            y_axis: None,
        }
    }

    /// Create a builder for configuring the line chart.
    ///
    /// The builder pattern provides a fluent interface for configuring
    /// all aspects of the line chart before creation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use embedded_charts::prelude::*;
    /// use embedded_graphics::pixelcolor::Rgb565;
    ///
    /// let chart = LineChart::builder()
    ///     .line_color(Rgb565::BLUE)
    ///     .line_width(2)
    ///     .with_markers(MarkerStyle::default())
    ///     .build()?;
    /// # Ok::<(), embedded_charts::error::ChartError>(())
    /// ```
    pub fn builder() -> LineChartBuilder<C> {
        LineChartBuilder::new()
    }

    /// Set the line style configuration.
    ///
    /// This replaces the entire style configuration with the provided one.
    /// Use the builder pattern for more granular control.
    ///
    /// # Arguments
    ///
    /// * `style` - The new line chart style configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use embedded_charts::prelude::*;
    /// use embedded_graphics::pixelcolor::Rgb565;
    ///
    /// let mut chart = LineChart::new();
    /// let style = LineChartStyle {
    ///     line_color: Rgb565::RED,
    ///     line_width: 3,
    ///     fill_area: true,
    ///     fill_color: Some(Rgb565::CSS_LIGHT_CORAL),
    ///     markers: None,
    ///     smooth: false,
    ///     smooth_subdivisions: 8,
    /// };
    /// chart.set_style(style);
    /// ```
    pub fn set_style(&mut self, style: LineChartStyle<C>) {
        self.style = style;
    }

    /// Get the current line style configuration.
    ///
    /// Returns a reference to the current style configuration,
    /// allowing inspection of current settings.
    ///
    /// # Returns
    ///
    /// A reference to the current `LineChartStyle`
    pub fn style(&self) -> &LineChartStyle<C> {
        &self.style
    }

    /// Set the chart configuration.
    ///
    /// This includes general chart settings like title, background color,
    /// margins, and grid visibility.
    ///
    /// # Arguments
    ///
    /// * `config` - The new chart configuration
    pub fn set_config(&mut self, config: ChartConfig<C>) {
        self.config = config;
    }

    /// Get the current chart configuration.
    ///
    /// # Returns
    ///
    /// A reference to the current `ChartConfig`
    pub fn config(&self) -> &ChartConfig<C> {
        &self.config
    }

    /// Set the grid system for the chart.
    ///
    /// The grid system draws background grid lines to help with data reading.
    /// Pass `None` to disable the grid.
    ///
    /// # Arguments
    ///
    /// * `grid` - Optional grid system configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use embedded_charts::prelude::*;
    /// use embedded_graphics::pixelcolor::Rgb565;
    ///
    /// let mut chart: LineChart<Rgb565> = LineChart::new();
    /// // Grid configuration is simplified in this example
    /// let grid: LinearGrid<Rgb565> = LinearGrid::new(GridOrientation::Horizontal, GridSpacing::DataUnits(10.0));
    /// // chart.set_grid(Some(grid)); // Grid system API still evolving
    /// # Ok::<(), embedded_charts::error::ChartError>(())
    /// ```
    pub fn set_grid(&mut self, grid: Option<crate::grid::GridSystem<C>>) {
        self.grid = grid;
    }

    /// Get the current grid system configuration.
    ///
    /// # Returns
    ///
    /// An optional reference to the current grid system
    pub fn grid(&self) -> Option<&crate::grid::GridSystem<C>> {
        self.grid.as_ref()
    }

    /// Transform data coordinates to screen coordinates using math abstraction
    fn transform_point<P>(
        &self,
        point: &P,
        data_bounds: &DataBounds<P::X, P::Y>,
        viewport: Rectangle,
    ) -> Point
    where
        P: DataPoint,
        P::X: NumericConversion<P::X> + Into<f32> + Copy,
        P::Y: NumericConversion<P::Y> + Into<f32> + Copy,
    {
        // Convert to our math abstraction layer
        let data_x = point.x().into().to_number();
        let data_y = point.y().into().to_number();

        // Use axis ranges if available, otherwise fall back to data bounds
        let (min_x, max_x) = if let Some(ref x_axis) = self.x_axis {
            let axis_min: f32 = x_axis.min();
            let axis_max: f32 = x_axis.max();
            (axis_min.to_number(), axis_max.to_number())
        } else {
            (
                data_bounds.min_x.into().to_number(),
                data_bounds.max_x.into().to_number(),
            )
        };

        let (min_y, max_y) = if let Some(ref y_axis) = self.y_axis {
            let axis_min: f32 = y_axis.min();
            let axis_max: f32 = y_axis.max();
            (axis_min.to_number(), axis_max.to_number())
        } else {
            (
                data_bounds.min_y.into().to_number(),
                data_bounds.max_y.into().to_number(),
            )
        };

        // Apply margins to get the actual drawing area
        let draw_area = self.config.margins.apply_to(viewport);

        // Normalize to 0-1 range using math abstraction
        let norm_x = if f32::from_number(max_x) > f32::from_number(min_x) {
            let range_x = f32::from_number(max_x - min_x);
            let offset_x = f32::from_number(data_x - min_x);
            (offset_x / range_x).to_number()
        } else {
            0.5f32.to_number()
        };

        let norm_y = if f32::from_number(max_y) > f32::from_number(min_y) {
            let range_y = f32::from_number(max_y - min_y);
            let offset_y = f32::from_number(data_y - min_y);
            (offset_y / range_y).to_number()
        } else {
            0.5f32.to_number()
        };

        // Transform to screen coordinates (Y is flipped)
        let norm_x_f32 = f32::from_number(norm_x);
        let norm_y_f32 = f32::from_number(norm_y);

        let screen_x =
            draw_area.top_left.x + (norm_x_f32 * (draw_area.size.width as f32 - 1.0)) as i32;
        let screen_y = draw_area.top_left.y + draw_area.size.height as i32
            - 1
            - (norm_y_f32 * (draw_area.size.height as f32 - 1.0)) as i32;

        Point::new(screen_x, screen_y)
    }

    /// Draw markers at data points
    fn draw_markers<D>(
        &self,
        data: &crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>,
        data_bounds: &DataBounds<f32, f32>,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        if let Some(marker_style) = &self.style.markers {
            if marker_style.visible {
                for point in data.iter() {
                    let screen_point = self.transform_point(&point, data_bounds, viewport);
                    self.draw_marker(screen_point, marker_style, target)?;
                }
            }
        }
        Ok(())
    }

    /// Draw a single marker
    fn draw_marker<D>(
        &self,
        center: Point,
        marker_style: &MarkerStyle<C>,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        let style = PrimitiveStyle::with_fill(marker_style.color);
        let radius = marker_style.size / 2;

        match marker_style.shape {
            MarkerShape::Circle => {
                Circle::new(
                    Point::new(center.x - radius as i32, center.y - radius as i32),
                    marker_style.size,
                )
                .into_styled(style)
                .draw(target)
                .map_err(|_| ChartError::RenderingError)?;
            }
            MarkerShape::Square => {
                Rectangle::new(
                    Point::new(center.x - radius as i32, center.y - radius as i32),
                    Size::new(marker_style.size, marker_style.size),
                )
                .into_styled(style)
                .draw(target)
                .map_err(|_| ChartError::RenderingError)?;
            }
            MarkerShape::Diamond => {
                use crate::render::PrimitiveRenderer;
                use crate::style::FillStyle;

                let fill_style = FillStyle::solid(marker_style.color);
                PrimitiveRenderer::draw_diamond(
                    center,
                    marker_style.size,
                    None,
                    Some(&fill_style),
                    target,
                )
                .map_err(|_| ChartError::RenderingError)?;
            }
            MarkerShape::Triangle => {
                use crate::render::PrimitiveRenderer;
                use crate::style::FillStyle;

                let fill_style = FillStyle::solid(marker_style.color);
                let half_size = marker_style.size as i32 / 2;
                let p1 = Point::new(center.x, center.y - half_size);
                let p2 = Point::new(center.x - half_size, center.y + half_size);
                let p3 = Point::new(center.x + half_size, center.y + half_size);

                PrimitiveRenderer::draw_triangle(p1, p2, p3, None, Some(&fill_style), target)
                    .map_err(|_| ChartError::RenderingError)?;
            }
        }

        Ok(())
    }

    /// Draw area fill under the line
    fn draw_area_fill<D>(
        &self,
        screen_points: &heapless::Vec<Point, 512>,
        fill_color: C,
        viewport: Rectangle,
        _data_bounds: &DataBounds<f32, f32>,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        if screen_points.len() < 2 {
            return Ok(());
        }

        // Get the chart area (with margins applied)
        let chart_area = self.config.margins.apply_to(viewport);
        let baseline_y = chart_area.top_left.y + chart_area.size.height as i32 - 1;

        use embedded_graphics::primitives::{Line, PrimitiveStyle};
        let line_style = PrimitiveStyle::with_stroke(fill_color, 1);

        // Draw horizontal fill lines using scanline approach
        let min_x = screen_points
            .iter()
            .map(|p| p.x)
            .min()
            .unwrap_or(chart_area.top_left.x);
        let max_x = screen_points
            .iter()
            .map(|p| p.x)
            .max()
            .unwrap_or(chart_area.top_left.x);

        // For each x position, find the curve y and draw a vertical line to baseline
        for x in min_x..=max_x {
            if x < chart_area.top_left.x
                || x >= chart_area.top_left.x + chart_area.size.width as i32
            {
                continue;
            }

            // Find the y value on the curve at this x position
            let mut curve_y = baseline_y;

            // Linear interpolation between adjacent points
            for window in screen_points.windows(2) {
                if let [p1, p2] = window {
                    if (p1.x <= x && x <= p2.x) || (p2.x <= x && x <= p1.x) {
                        if p1.x == p2.x {
                            curve_y = p1.y.min(p2.y);
                        } else {
                            let t = (x - p1.x) as f32 / (p2.x - p1.x) as f32;
                            curve_y = (p1.y as f32 + t * (p2.y - p1.y) as f32) as i32;
                        }
                        break;
                    }
                }
            }

            // Clip curve_y to chart area
            curve_y = curve_y.clamp(
                chart_area.top_left.y,
                chart_area.top_left.y + chart_area.size.height as i32 - 1,
            );

            // Draw vertical line from curve to baseline
            if curve_y <= baseline_y {
                let top_point = Point::new(x, curve_y);
                let bottom_point = Point::new(x, baseline_y);

                Line::new(top_point, bottom_point)
                    .into_styled(line_style)
                    .draw(target)
                    .map_err(|_| ChartError::RenderingError)?;
            }
        }

        Ok(())
    }
}

impl<C: PixelColor> Default for LineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<C: PixelColor + 'static> Chart<C> for LineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    type Data = crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>;
    type Config = ChartConfig<C>;

    fn draw<D>(
        &self,
        data: &Self::Data,
        config: &Self::Config,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
        Self::Data: DataSeries,
        <Self::Data as DataSeries>::Item: DataPoint,
        <<Self::Data as DataSeries>::Item as DataPoint>::X: Into<f32> + Copy + PartialOrd,
        <<Self::Data as DataSeries>::Item as DataPoint>::Y: Into<f32> + Copy + PartialOrd,
    {
        if data.is_empty() {
            return Err(ChartError::InsufficientData);
        }

        // Calculate data bounds
        let data_bounds = data.bounds()?;

        // Draw background if specified
        if let Some(bg_color) = config.background_color {
            Rectangle::new(viewport.top_left, viewport.size)
                .into_styled(PrimitiveStyle::with_fill(bg_color))
                .draw(target)
                .map_err(|_| ChartError::RenderingError)?;
        }

        // First, draw grid lines from axes (background layer)
        {
            let chart_area = config.margins.apply_to(viewport);

            // Draw grid lines from X-axis
            if let Some(ref x_axis) = self.x_axis {
                x_axis.draw_grid_lines(chart_area, chart_area, target)?;
            }

            // Draw grid lines from Y-axis
            if let Some(ref y_axis) = self.y_axis {
                y_axis.draw_grid_lines(chart_area, chart_area, target)?;
            }
        }

        // Draw grid if present (legacy grid system)
        if let Some(ref grid) = self.grid {
            let chart_area = config.margins.apply_to(viewport);
            grid.draw(chart_area, target)?;
        }

        // Collect and potentially smooth the data points
        let data_to_render = if self.style.smooth && data.len() > 2 {
            // Create interpolated smooth curve
            use crate::math::interpolation::{
                CurveInterpolator, InterpolationConfig, InterpolationType,
            };

            let mut input_points = heapless::Vec::<crate::data::Point2D, 256>::new();
            for point in data.iter() {
                input_points
                    .push(point)
                    .map_err(|_| ChartError::MemoryFull)?;
            }

            let interpolation_config = InterpolationConfig {
                interpolation_type: InterpolationType::CatmullRom,
                subdivisions: self.style.smooth_subdivisions,
                tension: 0.5,
                closed: false,
            };

            let interpolated =
                CurveInterpolator::interpolate(&input_points, &interpolation_config)?;

            // Create a temporary data series with interpolated points
            let mut smooth_data = crate::data::series::StaticDataSeries::new();
            for point in interpolated.iter() {
                smooth_data
                    .push(*point)
                    .map_err(|_| ChartError::MemoryFull)?;
            }
            smooth_data
        } else {
            // Use original data
            data.clone()
        };

        // Transform data points to screen coordinates
        let mut screen_points = heapless::Vec::<Point, 512>::new();
        for point in data_to_render.iter() {
            let screen_point = self.transform_point(&point, &data_bounds, viewport);
            screen_points
                .push(screen_point)
                .map_err(|_| ChartError::MemoryFull)?;
        }

        // Draw area fill if enabled
        if self.style.fill_area {
            if let Some(fill_color) = self.style.fill_color {
                self.draw_area_fill(&screen_points, fill_color, viewport, &data_bounds, target)?;
            }
        }

        // Draw lines between consecutive points
        let line_style = PrimitiveStyle::with_stroke(self.style.line_color, self.style.line_width);
        for window in screen_points.windows(2) {
            if let [p1, p2] = window {
                Line::new(*p1, *p2)
                    .into_styled(line_style)
                    .draw(target)
                    .map_err(|_| ChartError::RenderingError)?;
            }
        }

        // Draw markers
        self.draw_markers(data, &data_bounds, viewport, target)?;

        // Finally, draw axis lines, ticks, and labels (foreground layer)
        {
            let chart_area = config.margins.apply_to(viewport);

            // Draw X-axis (without grid lines)
            if let Some(ref x_axis) = self.x_axis {
                x_axis.draw_axis_only(chart_area, target)?;
            }

            // Draw Y-axis (without grid lines)
            if let Some(ref y_axis) = self.y_axis {
                y_axis.draw_axis_only(chart_area, target)?;
            }
        }

        Ok(())
    }
}

impl<C: PixelColor> Default for LineChartStyle<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self {
            line_color: embedded_graphics::pixelcolor::Rgb565::BLUE.into(),
            line_width: 1,
            fill_area: false,
            fill_color: None,
            markers: None,
            smooth: false,
            smooth_subdivisions: 8,
        }
    }
}

impl<C: PixelColor> Default for MarkerStyle<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self {
            shape: MarkerShape::Circle,
            size: 4,
            color: embedded_graphics::pixelcolor::Rgb565::RED.into(),
            visible: true,
        }
    }
}

/// Builder for line charts
#[derive(Debug)]
pub struct LineChartBuilder<C: PixelColor> {
    style: LineChartStyle<C>,
    config: ChartConfig<C>,
    grid: Option<crate::grid::GridSystem<C>>,
    x_axis: Option<crate::axes::LinearAxis<f32, C>>,
    y_axis: Option<crate::axes::LinearAxis<f32, C>>,
}

impl<C: PixelColor> LineChartBuilder<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    /// Create a new line chart builder
    pub fn new() -> Self {
        Self {
            style: LineChartStyle::default(),
            config: ChartConfig::default(),
            grid: None,
            x_axis: None,
            y_axis: None,
        }
    }

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

    /// Set the line width
    pub fn line_width(mut self, width: u32) -> Self {
        self.style.line_width = width.clamp(1, 10);
        self
    }

    /// Enable area filling with the specified color
    pub fn fill_area(mut self, color: C) -> Self {
        self.style.fill_area = true;
        self.style.fill_color = Some(color);
        self
    }

    /// Add markers to data points
    pub fn with_markers(mut self, marker_style: MarkerStyle<C>) -> Self {
        self.style.markers = Some(marker_style);
        self
    }

    /// Set the chart title
    pub fn with_title(mut self, title: &str) -> Self {
        if let Ok(title_string) = heapless::String::try_from(title) {
            self.config.title = Some(title_string);
        }
        self
    }

    /// Set the background color
    pub fn background_color(mut self, color: C) -> Self {
        self.config.background_color = Some(color);
        self
    }

    /// Set the chart margins
    pub fn margins(mut self, margins: Margins) -> Self {
        self.config.margins = margins;
        self
    }

    /// Enable smooth line rendering
    pub fn smooth(mut self, smooth: bool) -> Self {
        self.style.smooth = smooth;
        self
    }

    /// Set the number of subdivisions for smooth curves
    pub fn smooth_subdivisions(mut self, subdivisions: u32) -> Self {
        self.style.smooth_subdivisions = subdivisions.clamp(2, 16);
        self
    }

    /// Set the grid system
    pub fn with_grid(mut self, grid: crate::grid::GridSystem<C>) -> Self {
        self.grid = Some(grid);
        self
    }

    /// Set the X-axis configuration
    pub fn with_x_axis(mut self, axis: crate::axes::LinearAxis<f32, C>) -> Self {
        self.x_axis = Some(axis);
        self
    }

    /// Set the Y-axis configuration
    pub fn with_y_axis(mut self, axis: crate::axes::LinearAxis<f32, C>) -> Self {
        self.y_axis = Some(axis);
        self
    }
}

impl<C: PixelColor + 'static> ChartBuilder<C> for LineChartBuilder<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    type Chart = LineChart<C>;
    type Error = ChartError;

    fn build(self) -> Result<Self::Chart, Self::Error> {
        Ok(LineChart {
            style: self.style,
            config: self.config,
            grid: self.grid,
            x_axis: self.x_axis,
            y_axis: self.y_axis,
        })
    }
}

impl<C: PixelColor> Default for LineChartBuilder<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_line_chart_creation() {
        let chart: LineChart<Rgb565> = LineChart::new();
        assert_eq!(chart.style().line_width, 1);
    }

    #[test]
    fn test_line_chart_builder() {
        let chart = LineChart::builder()
            .line_color(Rgb565::RED)
            .line_width(3)
            .build()
            .unwrap();

        assert_eq!(chart.style().line_color, Rgb565::RED);
        assert_eq!(chart.style().line_width, 3);
    }

    #[test]
    fn test_marker_style() {
        let marker = MarkerStyle {
            shape: MarkerShape::Diamond,
            size: 8,
            color: Rgb565::GREEN,
            visible: true,
        };

        assert_eq!(marker.shape, MarkerShape::Diamond);
        assert_eq!(marker.size, 8);
    }
}

impl<C: PixelColor + 'static> AxisChart<C> for LineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    type XAxis = crate::axes::LinearAxis<f32, C>;
    type YAxis = crate::axes::LinearAxis<f32, C>;

    fn set_x_axis(&mut self, axis: crate::axes::LinearAxis<f32, C>) {
        self.x_axis = Some(axis);
    }

    fn set_y_axis(&mut self, axis: crate::axes::LinearAxis<f32, C>) {
        self.y_axis = Some(axis);
    }

    fn x_axis(&self) -> ChartResult<&crate::axes::LinearAxis<f32, C>> {
        self.x_axis.as_ref().ok_or(ChartError::InvalidConfiguration)
    }

    fn y_axis(&self) -> ChartResult<&crate::axes::LinearAxis<f32, C>> {
        self.y_axis.as_ref().ok_or(ChartError::InvalidConfiguration)
    }
}

/// Animated line chart that extends LineChart with animation capabilities
#[cfg(feature = "animations")]
#[derive(Debug)]
pub struct AnimatedLineChart<C: PixelColor> {
    /// Base line chart
    base_chart: LineChart<C>,
    /// Current animated data (interpolated values)
    current_data: Option<crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>>,
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> AnimatedLineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    /// Create a new animated line chart
    pub fn new() -> Self {
        Self {
            base_chart: LineChart::new(),
            current_data: None,
        }
    }

    /// Create a builder for configuring the animated line chart
    pub fn builder() -> AnimatedLineChartBuilder<C> {
        AnimatedLineChartBuilder::new()
    }

    /// Set the line style
    pub fn set_style(&mut self, style: LineChartStyle<C>) {
        self.base_chart.set_style(style);
    }

    /// Get the current line style
    pub fn style(&self) -> &LineChartStyle<C> {
        self.base_chart.style()
    }

    /// Set the chart configuration
    pub fn set_config(&mut self, config: ChartConfig<C>) {
        self.base_chart.set_config(config);
    }

    /// Get the chart configuration
    pub fn config(&self) -> &ChartConfig<C> {
        self.base_chart.config()
    }

    /// Set the grid system
    pub fn set_grid(&mut self, grid: Option<crate::grid::GridSystem<C>>) {
        self.base_chart.set_grid(grid);
    }

    /// Get the grid system
    pub fn grid(&self) -> Option<&crate::grid::GridSystem<C>> {
        self.base_chart.grid()
    }

    /// Set the current animated data for rendering
    pub fn set_animated_data(
        &mut self,
        data: Option<crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>>,
    ) {
        self.current_data = data;
    }

    /// Get the current animated data
    pub fn animated_data(
        &self,
    ) -> Option<&crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>> {
        self.current_data.as_ref()
    }

    /// Get access to the base chart for configuration
    pub fn base_chart(&self) -> &LineChart<C> {
        &self.base_chart
    }

    /// Get mutable access to the base chart for configuration
    pub fn base_chart_mut(&mut self) -> &mut LineChart<C> {
        &mut self.base_chart
    }

    /// Interpolate between two data series using a ChartAnimator
    pub fn interpolate_with_animator(
        animator: &crate::animation::ChartAnimator<
            crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>,
        >,
        progress: crate::animation::Progress,
    ) -> Option<crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>> {
        animator.value_at(progress)
    }
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> Default for AnimatedLineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> Chart<C> for AnimatedLineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    type Data = crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>;
    type Config = ChartConfig<C>;

    fn draw<D>(
        &self,
        data: &Self::Data,
        config: &Self::Config,
        viewport: Rectangle,
        target: &mut D,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
        Self::Data: crate::data::DataSeries,
        <Self::Data as crate::data::DataSeries>::Item: crate::data::DataPoint,
        <<Self::Data as crate::data::DataSeries>::Item as crate::data::DataPoint>::X:
            Into<f32> + Copy + PartialOrd,
        <<Self::Data as crate::data::DataSeries>::Item as crate::data::DataPoint>::Y:
            Into<f32> + Copy + PartialOrd,
    {
        // Use animated data if available, otherwise use provided data
        if let Some(ref animated_data) = self.current_data {
            self.base_chart
                .draw(animated_data, config, viewport, target)
        } else {
            self.base_chart.draw(data, config, viewport, target)
        }
    }
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> crate::chart::traits::AnimatedChart<C> for AnimatedLineChart<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    type AnimatedData = crate::data::series::StaticDataSeries<crate::data::point::Point2D, 256>;

    fn draw_animated<D>(
        &self,
        data: &Self::Data,
        config: &Self::Config,
        viewport: Rectangle,
        target: &mut D,
        _progress: crate::animation::Progress,
    ) -> ChartResult<()>
    where
        D: DrawTarget<Color = C>,
    {
        // Use the provided data which should already be interpolated by the caller
        self.base_chart.draw(data, config, viewport, target)
    }

    fn create_transition_animator(
        &self,
        from_data: Self::AnimatedData,
        to_data: Self::AnimatedData,
        easing: crate::animation::EasingFunction,
    ) -> crate::animation::ChartAnimator<Self::AnimatedData> {
        crate::animation::ChartAnimator::new(from_data, to_data, easing)
    }

    fn extract_animated_data(&self, data: &Self::Data) -> ChartResult<Self::AnimatedData> {
        // Clone the data series for animation
        Ok(data.clone())
    }
}

/// Builder for animated line charts
#[cfg(feature = "animations")]
#[derive(Debug)]
pub struct AnimatedLineChartBuilder<C: PixelColor> {
    base_builder: LineChartBuilder<C>,
    frame_rate: u32,
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> AnimatedLineChartBuilder<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    /// Create a new animated line chart builder
    pub fn new() -> Self {
        Self {
            base_builder: LineChartBuilder::new(),
            frame_rate: 60,
        }
    }

    /// Set the target frame rate
    pub fn frame_rate(mut self, fps: u32) -> Self {
        self.frame_rate = fps.clamp(1, 120);
        self
    }

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

    /// Set the line width
    pub fn line_width(mut self, width: u32) -> Self {
        self.base_builder = self.base_builder.line_width(width);
        self
    }

    /// Enable area fill with color
    pub fn fill_area(mut self, color: C) -> Self {
        self.base_builder = self.base_builder.fill_area(color);
        self
    }

    /// Add markers to data points
    pub fn with_markers(mut self, marker_style: MarkerStyle<C>) -> Self {
        self.base_builder = self.base_builder.with_markers(marker_style);
        self
    }

    /// Set the chart title
    pub fn with_title(mut self, title: &str) -> Self {
        self.base_builder = self.base_builder.with_title(title);
        self
    }

    /// Set the background color
    pub fn background_color(mut self, color: C) -> Self {
        self.base_builder = self.base_builder.background_color(color);
        self
    }

    /// Set chart margins
    pub fn margins(mut self, margins: Margins) -> Self {
        self.base_builder = self.base_builder.margins(margins);
        self
    }

    /// Enable smooth lines
    pub fn smooth(mut self, smooth: bool) -> Self {
        self.base_builder = self.base_builder.smooth(smooth);
        self
    }

    /// Set the number of subdivisions for smooth curves
    pub fn smooth_subdivisions(mut self, subdivisions: u32) -> Self {
        self.base_builder = self.base_builder.smooth_subdivisions(subdivisions);
        self
    }

    /// Add grid system
    pub fn with_grid(mut self, grid: crate::grid::GridSystem<C>) -> Self {
        self.base_builder = self.base_builder.with_grid(grid);
        self
    }

    /// Add X-axis
    pub fn with_x_axis(mut self, axis: crate::axes::LinearAxis<f32, C>) -> Self {
        self.base_builder = self.base_builder.with_x_axis(axis);
        self
    }

    /// Add Y-axis
    pub fn with_y_axis(mut self, axis: crate::axes::LinearAxis<f32, C>) -> Self {
        self.base_builder = self.base_builder.with_y_axis(axis);
        self
    }

    /// Build the animated line chart
    pub fn build(self) -> ChartResult<AnimatedLineChart<C>> {
        let base_chart = self.base_builder.build()?;

        Ok(AnimatedLineChart {
            base_chart,
            current_data: None,
        })
    }
}

#[cfg(feature = "animations")]
impl<C: PixelColor + 'static> Default for AnimatedLineChartBuilder<C>
where
    C: From<embedded_graphics::pixelcolor::Rgb565>,
{
    fn default() -> Self {
        Self::new()
    }
}