chartml-chart-cartesian 4.0.0

ChartML bar, line, and area chart renderers
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
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
use chartml_core::data::DataTable;
use chartml_core::element::{ChartElement, Dimensions};
use chartml_core::error::ChartError;
use chartml_core::plugin::{ChartConfig, ChartRenderer};
use chartml_core::spec::VisualizeSpec;

mod bar;
mod line;
mod area;
pub(crate) mod helpers;

pub use bar::{bar_animation_origin, render_bar};
pub use line::render_line;
pub use area::render_area;

pub struct CartesianRenderer;

impl CartesianRenderer {
    pub fn new() -> Self {
        Self
    }
}

impl Default for CartesianRenderer {
    fn default() -> Self {
        Self::new()
    }
}

impl ChartRenderer for CartesianRenderer {
    fn render(&self, data: &DataTable, config: &ChartConfig) -> Result<ChartElement, ChartError> {
        match config.visualize.chart_type.as_str() {
            "bar" => bar::render_bar(data, config),
            "line" => line::render_line(data, config),
            "area" => area::render_area(data, config),
            other => Err(ChartError::UnknownChartType(other.to_string())),
        }
    }

    fn default_dimensions(&self, _spec: &VisualizeSpec) -> Option<Dimensions> {
        Some(Dimensions::new(400.0))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chartml_core::element::count_elements;
    use chartml_core::data::{Row, DataTable};
    use serde_json::json;

    fn make_bar_rows() -> Vec<Row> {
        vec![
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(100))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(200))].into_iter().collect(),
            [("month".to_string(), json!("Mar")), ("revenue".to_string(), json!(150))].into_iter().collect(),
        ]
    }

    fn make_bar_data() -> DataTable {
        DataTable::from_rows(&make_bar_rows()).unwrap()
    }

    fn make_bar_config() -> ChartConfig {
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            columns: month
            rows: revenue
        "#).unwrap();
        ChartConfig {
            visualize: viz,
            title: Some("Test Bar".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string(), "#4A7C59".to_string()],
            theme: chartml_core::theme::Theme::default(),
        }
    }

    fn make_line_config() -> ChartConfig {
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: line
            columns: month
            rows: revenue
        "#).unwrap();
        ChartConfig {
            visualize: viz,
            title: Some("Test Line".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string(), "#4A7C59".to_string()],
            theme: chartml_core::theme::Theme::default(),
        }
    }

    fn make_area_config() -> ChartConfig {
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: area
            columns: month
            rows: revenue
        "#).unwrap();
        ChartConfig {
            visualize: viz,
            title: Some("Test Area".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string(), "#4A7C59".to_string()],
            theme: chartml_core::theme::Theme::default(),
        }
    }

    // ----- Phase 4: theme typography wiring -----

    /// Verify that non-default Theme typography values flow through to the
    /// emitted `ChartElement::Text` nodes. Specifically: a custom label
    /// family, letter-spacing, and text-transform must appear on every
    /// `axis-label` / `tick-value` / `legend-label` text element, while
    /// defaults continue to produce the omitted-attribute legacy path.
    #[test]
    fn phase4_theme_typography_flows_to_axis_label_text() {
        use chartml_core::theme::{TextTransform, Theme};

        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.label_font_family = "serif".into();
        t.label_letter_spacing = 1.5;
        t.label_text_transform = TextTransform::Uppercase;
        t.label_font_weight = 600;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();

        // Walk the tree: for every axis-label text, assert the new fields
        // are set from the theme override.
        fn walk<'a>(el: &'a ChartElement, out: &mut Vec<&'a ChartElement>) {
            match el {
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    for c in children {
                        walk(c, out);
                    }
                }
                _ => out.push(el),
            }
        }
        let mut leaves = Vec::new();
        walk(&element, &mut leaves);

        let mut axis_label_count = 0usize;
        for leaf in &leaves {
            if let ChartElement::Text {
                class,
                font_family,
                letter_spacing,
                text_transform,
                font_weight,
                ..
            } = leaf
            {
                // Only inspect axis-label role (which reads the label_* group).
                let is_axis_label = class
                    .split_whitespace()
                    .any(|c| c == "axis-label");
                if !is_axis_label {
                    continue;
                }
                axis_label_count += 1;

                assert_eq!(
                    font_family.as_deref(),
                    Some("serif"),
                    "axis-label text must carry theme.label_font_family"
                );
                assert_eq!(
                    letter_spacing.as_deref(),
                    Some("1.5"),
                    "axis-label text must carry theme.label_letter_spacing"
                );
                assert_eq!(
                    text_transform.as_deref(),
                    Some("uppercase"),
                    "axis-label text must carry theme.label_text_transform"
                );
                assert_eq!(
                    font_weight.as_deref(),
                    Some("600"),
                    "axis-label text must carry theme.label_font_weight"
                );
            }
        }
        assert!(
            axis_label_count > 0,
            "bar chart should have at least one axis-label text"
        );
    }

    /// Verify the same properties propagate to `tick-value` (numeric) text
    /// elements, which read from the `numeric_*` group for family/size but
    /// inherit `label_*` for weight, letter-spacing, and text-transform.
    #[test]
    fn phase4_theme_typography_flows_to_tick_value_text() {
        use chartml_core::theme::{TextTransform, Theme};

        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.numeric_font_family = "monospace".into();
        t.label_letter_spacing = 0.75;
        t.label_text_transform = TextTransform::Lowercase;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();

        let mut found = false;
        fn visit<F: FnMut(&ChartElement)>(el: &ChartElement, f: &mut F) {
            f(el);
            match el {
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    for c in children {
                        visit(c, f);
                    }
                }
                _ => {}
            }
        }
        visit(&element, &mut |el| {
            if let ChartElement::Text {
                class,
                font_family,
                letter_spacing,
                text_transform,
                ..
            } = el
            {
                if class
                    .split_whitespace()
                    .any(|c| c == "tick-value")
                {
                    found = true;
                    assert_eq!(
                        font_family.as_deref(),
                        Some("monospace"),
                        "tick-value text must carry theme.numeric_font_family"
                    );
                    assert_eq!(
                        letter_spacing.as_deref(),
                        Some("0.75"),
                        "tick-value text must inherit theme.label_letter_spacing"
                    );
                    assert_eq!(
                        text_transform.as_deref(),
                        Some("lowercase"),
                        "tick-value text must inherit theme.label_text_transform"
                    );
                }
            }
        });
        assert!(found, "bar chart should emit at least one tick-value text");
    }

    #[test]
    fn bar_chart_renders() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_bar_config();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Bar render failed: {:?}", result.err());
        let element = result.unwrap();
        let rect_count = count_elements(&element, &|e| matches!(e, ChartElement::Rect { .. }));
        assert_eq!(rect_count, 3, "Should have 3 bars for 3 data points, got {}", rect_count);
    }

    #[test]
    fn bar_chart_has_svg_root() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_bar_config();
        let element = renderer.render(&data, &config).unwrap();
        assert!(matches!(element, ChartElement::Svg { .. }), "Root should be Svg");
    }

    #[test]
    fn bar_chart_has_no_title_in_svg() {
        // Title is rendered as HTML outside the SVG (matching JS chartml).
        // The SVG element tree must NOT contain a chart-title text element.
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_bar_config();
        let element = renderer.render(&data, &config).unwrap();
        let title_count = count_elements(&element, &|e| {
            matches!(e, ChartElement::Text { class, .. } if class == "chart-title")
        });
        assert_eq!(title_count, 0, "Title must not be in the SVG element tree");
    }

    #[test]
    fn bar_chart_has_axes() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_bar_config();
        let element = renderer.render(&data, &config).unwrap();
        let axis_line_count = count_elements(&element, &|e| {
            matches!(e, ChartElement::Line { class, .. } if class == "axis-line")
        });
        assert!(axis_line_count >= 1, "Should have axis lines, got {}", axis_line_count);
    }

    #[test]
    fn line_chart_renders() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_line_config();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Line render failed: {:?}", result.err());
        let element = result.unwrap();
        let path_count = count_elements(&element, &|e| matches!(e, ChartElement::Path { .. }));
        assert!(path_count >= 1, "Should have at least 1 path for the line, got {}", path_count);
    }

    #[test]
    fn line_chart_path_has_stroke() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_line_config();
        let element = renderer.render(&data, &config).unwrap();
        // Find the path and check it has a stroke
        fn find_path(el: &ChartElement) -> Option<&ChartElement> {
            match el {
                ChartElement::Path { .. } => Some(el),
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    children.iter().find_map(find_path)
                }
                _ => None,
            }
        }
        let path = find_path(&element).expect("Should find a path element");
        match path {
            ChartElement::Path { stroke, .. } => {
                assert!(stroke.is_some(), "Line path should have a stroke");
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn area_chart_renders() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_area_config();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Area render failed: {:?}", result.err());
        let element = result.unwrap();
        let path_count = count_elements(&element, &|e| matches!(e, ChartElement::Path { .. }));
        assert!(path_count >= 1, "Should have at least 1 path for the area, got {}", path_count);
    }

    #[test]
    fn area_chart_path_has_fill() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let config = make_area_config();
        let element = renderer.render(&data, &config).unwrap();
        fn find_path(el: &ChartElement) -> Option<&ChartElement> {
            match el {
                ChartElement::Path { .. } => Some(el),
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    children.iter().find_map(find_path)
                }
                _ => None,
            }
        }
        let path = find_path(&element).expect("Should find a path element");
        match path {
            ChartElement::Path { fill, .. } => {
                assert!(fill.is_some(), "Area path should have a fill");
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn unknown_type_errors() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config();
        config.visualize.chart_type = "unknown".to_string();
        let result = renderer.render(&data, &config);
        assert!(result.is_err(), "Unknown chart type should produce error");
        match result.unwrap_err() {
            ChartError::UnknownChartType(t) => assert_eq!(t, "unknown"),
            other => panic!("Expected UnknownChartType, got {:?}", other),
        }
    }

    #[test]
    fn bar_chart_no_title() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config();
        config.title = None;
        let element = renderer.render(&data, &config).unwrap();
        let title_count = count_elements(&element, &|e| {
            matches!(e, ChartElement::Text { class, .. } if class == "chart-title")
        });
        assert_eq!(title_count, 0, "Should have no title element when title is None");
    }

    #[test]
    fn default_dimensions_returns_some() {
        let renderer = CartesianRenderer::new();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            columns: x
            rows: y
        "#).unwrap();
        let dims = renderer.default_dimensions(&viz);
        assert!(dims.is_some());
        assert_eq!(dims.unwrap().height, 400.0);
    }

    #[test]
    fn bar_chart_adaptive_padding_2_bars() {
        // With n=2 bars and adaptive padding=0.2, each bar should be ~36.4% of inner_width.
        // inner_width = 800 - left_margin - right_margin ≈ 800 - 60 - 20 = 720
        // bandwidth = 0.8/2.2 * inner_width ≈ 0.3636 * inner_width ≈ 261px
        // Bar should NOT be close to 50% (which would indicate no padding).
        let rows: Vec<Row> = vec![
            [("region".to_string(), json!("US")), ("revenue".to_string(), json!(55000))].into_iter().collect(),
            [("region".to_string(), json!("EU")), ("revenue".to_string(), json!(40000))].into_iter().collect(),
        ];
        let data = DataTable::from_rows(&rows).unwrap();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            columns: region
            rows: revenue
        "#).unwrap();
        let config = ChartConfig {
            visualize: viz,
            title: Some("Regional Revenue".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string()],
            theme: chartml_core::theme::Theme::default(),
        };
        let renderer = CartesianRenderer::new();
        let element = renderer.render(&data, &config).unwrap();

        // Find all Rect elements (bars)
        let mut bar_widths = Vec::new();
        fn collect_bar_widths(el: &ChartElement, widths: &mut Vec<f64>) {
            match el {
                ChartElement::Rect { width, class, .. } if class.split_whitespace().any(|c| c == "bar") => {
                    widths.push(*width);
                }
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    for child in children { collect_bar_widths(child, widths); }
                }
                _ => {}
            }
        }
        collect_bar_widths(&element, &mut bar_widths);

        assert_eq!(bar_widths.len(), 2, "Should have 2 bars");
        let bar_width = bar_widths[0];
        println!("Bar width: {:.2}px", bar_width);

        // JS applies maxBarWidth = inner_width * 0.2 clamp.
        // With y_tick_labels pre-computation: for revenue values 100/200, the
        // tick label "200" ≈ 21px + 15px buffer = 36px left margin.
        // inner_width = 800 - 36 - 30 = 734px → maxBarWidth = 146.8px.
        // bandwidth for 2 bars, padding=0.2 = ~234px → clamped to ~146.8px.
        assert!(
            bar_width <= 150.0,
            "Bar width {:.1}px exceeds maxBarWidth clamp",
            bar_width
        );
        assert!(
            bar_width > 50.0,
            "Bar width {:.1}px is unreasonably narrow",
            bar_width
        );
    }

    #[test]
    fn stacked_bar_chart_renders() {
        let rows: Vec<Row> = vec![
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(100)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(50)), ("product".to_string(), json!("B"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(200)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(80)), ("product".to_string(), json!("B"))].into_iter().collect(),
        ];
        let data = DataTable::from_rows(&rows).unwrap();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            mode: stacked
            columns: month
            rows: revenue
            marks:
              color: product
        "#).unwrap();
        let config = ChartConfig {
            visualize: viz,
            title: Some("Stacked Bar".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string()],
            theme: chartml_core::theme::Theme::default(),
        };
        let renderer = CartesianRenderer::new();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Stacked bar render failed: {:?}", result.err());
        let element = result.unwrap();
        let rect_count = count_elements(&element, &|e| matches!(e, ChartElement::Rect { class, .. } if class.split_whitespace().any(|c| c == "bar")));
        assert_eq!(rect_count, 4, "Should have 4 bars (2 categories x 2 series), got {}", rect_count);
    }

    #[test]
    fn grouped_bar_chart_renders() {
        let rows: Vec<Row> = vec![
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(100)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(50)), ("product".to_string(), json!("B"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(200)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(80)), ("product".to_string(), json!("B"))].into_iter().collect(),
        ];
        let data = DataTable::from_rows(&rows).unwrap();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            mode: grouped
            columns: month
            rows: revenue
            marks:
              color: product
        "#).unwrap();
        let config = ChartConfig {
            visualize: viz,
            title: None,
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string()],
            theme: chartml_core::theme::Theme::default(),
        };
        let renderer = CartesianRenderer::new();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Grouped bar render failed: {:?}", result.err());
        let element = result.unwrap();
        let rect_count = count_elements(&element, &|e| matches!(e, ChartElement::Rect { class, .. } if class.split_whitespace().any(|c| c == "bar")));
        assert_eq!(rect_count, 4, "Should have 4 bars (2 categories x 2 series), got {}", rect_count);
    }

    #[test]
    fn multi_series_line_chart_renders() {
        let rows: Vec<Row> = vec![
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(100)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(50)), ("product".to_string(), json!("B"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(200)), ("product".to_string(), json!("A"))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(80)), ("product".to_string(), json!("B"))].into_iter().collect(),
        ];
        let data = DataTable::from_rows(&rows).unwrap();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: line
            columns: month
            rows: revenue
            marks:
              color: product
        "#).unwrap();
        let config = ChartConfig {
            visualize: viz,
            title: Some("Multi Line".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string(), "#D4A445".to_string()],
            theme: chartml_core::theme::Theme::default(),
        };
        let renderer = CartesianRenderer::new();
        let result = renderer.render(&data, &config);
        assert!(result.is_ok(), "Multi-series line render failed: {:?}", result.err());
        let element = result.unwrap();
        let path_count = count_elements(&element, &|e| matches!(e, ChartElement::Path { class, .. } if class.split_whitespace().any(|c| c == "chartml-line-path")));
        assert_eq!(path_count, 2, "Should have 2 line paths for 2 series, got {}", path_count);
    }

    #[test]
    fn empty_data_returns_error() {
        let renderer = CartesianRenderer::new();
        let data = DataTable::from_rows(&Vec::<Row>::new()).unwrap();
        let config = make_bar_config();
        let result = renderer.render(&data, &config);
        assert!(result.is_err(), "Empty data should produce an error");
    }

    #[test]
    fn x_axis_horizontal_few_labels() {
        use crate::helpers::{generate_x_axis, GridConfig};
        let labels = vec!["A".into(), "B".into(), "C".into()];
        let result = generate_x_axis(&crate::helpers::XAxisParams {
            labels: &labels, display_label_overrides: None,
            range: (0.0, 800.0), y_position: 350.0, available_width: 800.0,
            x_format: None, chart_height: None, grid: &GridConfig::default(), axis_label: None,
            theme: &chartml_core::theme::Theme::default(),
        });
        // Should be horizontal — no transforms on text elements
        let text_with_transform = result.elements.iter().filter(|e| {
            matches!(e, ChartElement::Text { transform: Some(_), .. })
        }).count();
        assert_eq!(text_with_transform, 0, "Horizontal strategy should have no transforms");
    }

    #[test]
    fn x_axis_rotated_many_labels() {
        use crate::helpers::{generate_x_axis, GridConfig};
        let labels: Vec<String> = (0..20).map(|i| format!("Category Number {}", i)).collect();
        let result = generate_x_axis(&crate::helpers::XAxisParams {
            labels: &labels, display_label_overrides: None,
            range: (0.0, 300.0), y_position: 350.0, available_width: 300.0,
            x_format: None, chart_height: None, grid: &GridConfig::default(), axis_label: None,
            theme: &chartml_core::theme::Theme::default(),
        });
        // Should be rotated — text elements have transforms
        let text_with_transform = result.elements.iter().filter(|e| {
            matches!(e, ChartElement::Text { transform: Some(_), .. })
        }).count();
        assert!(text_with_transform > 0, "Rotated strategy should have transforms");
    }

    #[test]
    fn x_axis_sampled_100_labels() {
        use crate::helpers::{generate_x_axis, GridConfig};
        let labels: Vec<String> = (0..100).map(|i| format!("Long Category Name {}", i)).collect();
        let result = generate_x_axis(&crate::helpers::XAxisParams {
            labels: &labels, display_label_overrides: None,
            range: (0.0, 400.0), y_position: 350.0, available_width: 400.0,
            x_format: None, chart_height: None, grid: &GridConfig::default(), axis_label: None,
            theme: &chartml_core::theme::Theme::default(),
        });
        // Should be sampled — fewer label texts than total categories
        let label_count = result.elements.iter().filter(|e| {
            matches!(e, ChartElement::Text { class, .. } if class.split_whitespace().any(|c| c == "tick-label"))
        }).count();
        assert!(label_count < 100, "Sampled should show fewer labels: got {}", label_count);
        assert!(label_count >= 3, "Should show at least a few labels");
    }

    #[test]
    fn line_chart_grid_dash_array() {
        let data = make_bar_data();
        // Use unquoted dashArray value (matching the examples_source.md spec)
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
type: line
columns: month
rows: revenue
style:
  grid:
    x: true
    y: true
    color: '#e0e0e0'
    opacity: 0.5
    dashArray: 4,4
  showDots: true
"#).unwrap();

        // Verify the grid spec parsed correctly
        let grid_spec = viz.style.as_ref().unwrap().grid.as_ref().unwrap();
        assert_eq!(grid_spec.dash_array, Some("4,4".to_string()), "GridSpec.dash_array should parse from YAML");
        assert_eq!(grid_spec.x, Some(true), "grid.x should be true");
        assert_eq!(grid_spec.y, Some(true), "grid.y should be true");

        let config = ChartConfig {
            visualize: viz,
            title: Some("Dashed Grid Test".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string()],
            theme: chartml_core::theme::Theme::default(),
        };

        // Verify GridConfig resolves correctly
        let grid_config = crate::helpers::GridConfig::from_config(&config);
        assert_eq!(grid_config.dash_array, Some("4,4".to_string()), "GridConfig.dash_array should be set");
        assert!(grid_config.show_x, "grid.show_x should be true");
        assert!(grid_config.show_y, "grid.show_y should be true");

        let renderer = CartesianRenderer::new();
        let element = renderer.render(&data, &config).unwrap();

        // Count grid lines and verify ALL have stroke_dasharray set
        let mut dashed_grid_count = 0;
        let mut total_grid_count = 0;
        fn check_grid(el: &ChartElement, dashed: &mut usize, total: &mut usize) {
            match el {
                ChartElement::Line { class, stroke_dasharray, .. } if class.contains("grid-line") => {
                    *total += 1;
                    if let Some(da) = stroke_dasharray {
                        if !da.is_empty() {
                            *dashed += 1;
                        }
                    }
                }
                ChartElement::Svg { children, .. } | ChartElement::Group { children, .. } => {
                    for child in children {
                        check_grid(child, dashed, total);
                    }
                }
                _ => {}
            }
        }
        check_grid(&element, &mut dashed_grid_count, &mut total_grid_count);

        assert!(total_grid_count > 0, "Should have grid lines, got {}", total_grid_count);
        assert_eq!(dashed_grid_count, total_grid_count,
            "All {} grid lines should have stroke_dasharray='4,4', but only {} do",
            total_grid_count, dashed_grid_count);
    }

    // ----- Phase 5: theme shape/stroke wiring -----

    /// Collect every `Path` stroke_width on elements whose class matches
    /// `series-line` (the series-weight role wired in Phase 5).
    fn collect_series_stroke_widths(el: &ChartElement, out: &mut Vec<f64>) {
        match el {
            ChartElement::Path { stroke_width: Some(w), class, .. }
                if class.split_whitespace().any(|c| c == "series-line") =>
            {
                out.push(*w);
            }
            ChartElement::Svg { children, .. }
            | ChartElement::Group { children, .. } => {
                for c in children {
                    collect_series_stroke_widths(c, out);
                }
            }
            _ => {}
        }
    }

    /// Collect every `Line` stroke_width bucketed by role
    /// (`axis-line`, `grid-line`, `tick`).
    fn collect_line_stroke_widths_by_class(
        el: &ChartElement,
        out: &mut std::collections::HashMap<String, Vec<f64>>,
    ) {
        match el {
            ChartElement::Line { stroke_width: Some(w), class, .. } => {
                for token in class.split_whitespace() {
                    if matches!(token, "axis-line" | "grid-line" | "tick") {
                        out.entry(token.to_string()).or_default().push(*w);
                    }
                }
            }
            ChartElement::Svg { children, .. }
            | ChartElement::Group { children, .. } => {
                for c in children {
                    collect_line_stroke_widths_by_class(c, out);
                }
            }
            _ => {}
        }
    }

    /// Collect all `(rx, ry)` pairs on `Rect` elements with a `bar` class.
    fn collect_bar_corner_radii(
        el: &ChartElement,
        out: &mut Vec<(Option<f64>, Option<f64>)>,
    ) {
        match el {
            ChartElement::Rect { rx, ry, class, .. }
                if class.split_whitespace().any(|c| c == "bar") =>
            {
                out.push((*rx, *ry));
            }
            ChartElement::Svg { children, .. }
            | ChartElement::Group { children, .. } => {
                for c in children {
                    collect_bar_corner_radii(c, out);
                }
            }
            _ => {}
        }
    }

    /// Collect every `Circle.r` on elements whose class contains `dot-marker`.
    fn collect_dot_radii(el: &ChartElement, out: &mut Vec<f64>) {
        match el {
            ChartElement::Circle { r, class, .. }
                if class.split_whitespace().any(|c| c == "dot-marker") =>
            {
                out.push(*r);
            }
            ChartElement::Svg { children, .. }
            | ChartElement::Group { children, .. } => {
                for c in children {
                    collect_dot_radii(c, out);
                }
            }
            _ => {}
        }
    }

    #[test]
    fn phase5_bar_corner_radius_omitted_by_default() {
        // Default theme MUST NOT emit rx/ry on bar rects (byte-identical contract).
        let renderer = CartesianRenderer::new();
        let element = renderer
            .render(&make_bar_data(), &make_bar_config())
            .expect("render");

        let mut radii = Vec::new();
        collect_bar_corner_radii(&element, &mut radii);
        assert!(!radii.is_empty(), "expected bar rects in default bar chart");
        for (rx, ry) in &radii {
            assert!(rx.is_none(), "default theme must leave Rect.rx == None");
            assert!(ry.is_none(), "default theme must leave Rect.ry == None");
        }
    }

    #[test]
    fn phase5_custom_bar_corner_radius_emits_rx_ry() {
        use chartml_core::theme::{BarCornerRadius, Theme};
        let renderer = CartesianRenderer::new();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.bar_corner_radius = BarCornerRadius::Uniform(8.0);
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut radii = Vec::new();
        collect_bar_corner_radii(&element, &mut radii);
        assert!(!radii.is_empty());
        for (rx, ry) in &radii {
            assert_eq!(*rx, Some(8.0), "rx must match theme.bar_corner_radius");
            assert_eq!(*ry, Some(8.0), "ry must match theme.bar_corner_radius");
        }
    }

    // ---- Phase follow-up: BarCornerRadius::Top top-only rounding ----

    fn collect_bar_elements<'a>(el: &'a ChartElement, out: &mut Vec<&'a ChartElement>) {
        match el {
            ChartElement::Rect { class, .. } | ChartElement::Path { class, .. }
                if class.split_whitespace().any(|c| c == "bar-rect") =>
            {
                out.push(el);
            }
            ChartElement::Svg { children, .. } | ChartElement::Group { children, .. } => {
                for c in children {
                    collect_bar_elements(c, out);
                }
            }
            _ => {}
        }
    }

    #[test]
    fn phase_followup_bar_top_rounding_zero_is_plain_rect() {
        use chartml_core::theme::{BarCornerRadius, Theme};
        let renderer = CartesianRenderer::new();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.bar_corner_radius = BarCornerRadius::Top(0.0);
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut bars = Vec::new();
        collect_bar_elements(&element, &mut bars);
        assert!(!bars.is_empty());
        for b in &bars {
            match b {
                ChartElement::Rect { rx, ry, .. } => {
                    assert!(rx.is_none(), "Top(0.0) must emit Rect with rx=None");
                    assert!(ry.is_none(), "Top(0.0) must emit Rect with ry=None");
                }
                other => panic!("Top(0.0) must emit Rect, got {:?}", other),
            }
        }
    }

    #[test]
    fn phase_followup_bar_top_rounding_vertical() {
        use chartml_core::theme::{BarCornerRadius, Theme};
        let renderer = CartesianRenderer::new();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.bar_corner_radius = BarCornerRadius::Top(8.0);
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut bars = Vec::new();
        collect_bar_elements(&element, &mut bars);
        assert!(!bars.is_empty(), "expected bar elements");
        for b in &bars {
            match b {
                ChartElement::Path { d, .. } => {
                    assert_eq!(
                        d.matches("A 8,8").count(),
                        2,
                        "vertical Top(8) must produce 2 arcs, got d={d}"
                    );
                }
                other => panic!("vertical Top(8) must emit Path, got {:?}", other),
            }
        }
    }

    #[test]
    fn phase_followup_bar_top_rounding_horizontal() {
        use chartml_core::theme::{BarCornerRadius, Theme};
        let renderer = CartesianRenderer::new();
        let mut config = make_bar_config();
        config.visualize.orientation = Some(chartml_core::spec::Orientation::Horizontal);
        let mut t = Theme::default();
        t.bar_corner_radius = BarCornerRadius::Top(8.0);
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut bars = Vec::new();
        collect_bar_elements(&element, &mut bars);
        assert!(!bars.is_empty(), "expected bar elements (horizontal)");
        for b in &bars {
            match b {
                ChartElement::Path { d, .. } => {
                    assert_eq!(
                        d.matches("A 8,8").count(),
                        2,
                        "horizontal Top(8) must produce 2 arcs, got d={d}"
                    );
                }
                other => panic!("horizontal Top(8) must emit Path, got {:?}", other),
            }
        }
    }

    #[test]
    fn phase_followup_bar_top_rounding_negative_vertical() {
        // Drive build_bar_element directly so the test doesn't depend on a
        // chart spec that emits negative values.
        use chartml_core::theme::{BarCornerRadius, Theme};
        use crate::bar::{build_bar_element, BarRectSpec};

        let mut theme = Theme::default();
        theme.bar_corner_radius = BarCornerRadius::Top(8.0);

        let pos = build_bar_element(
            BarRectSpec {
                x: 100.0, y: 50.0, width: 40.0, height: 200.0,
                is_horizontal: false, is_negative: false,
                fill: "#000".into(),
                class: "bar bar-rect".into(),
                data: None,
            },
            &theme,
        );
        let neg = build_bar_element(
            BarRectSpec {
                x: 100.0, y: 50.0, width: 40.0, height: 200.0,
                is_horizontal: false, is_negative: true,
                fill: "#000".into(),
                class: "bar bar-rect".into(),
                data: None,
            },
            &theme,
        );

        let pos_d = match &pos {
            ChartElement::Path { d, .. } => d.clone(),
            _ => panic!("pos must be Path"),
        };
        let neg_d = match &neg {
            ChartElement::Path { d, .. } => d.clone(),
            _ => panic!("neg must be Path"),
        };

        assert_eq!(pos_d.matches("A 8,8").count(), 2);
        assert_eq!(neg_d.matches("A 8,8").count(), 2);

        // Positive vertical: top rounding → path starts at (x, y+r) = (100, 58).
        assert!(
            pos_d.starts_with("M 100,58"),
            "pos vertical Top path should start at y+r=58, got {pos_d}"
        );
        // Negative vertical: bottom rounding → path starts at the (square)
        // top-left corner (100, 50).
        assert!(
            neg_d.starts_with("M 100,50"),
            "neg vertical Top path should start at (x, y)=(100, 50), got {neg_d}"
        );
        // Negative path must reference the bottom-edge-minus-r coordinate
        // y1-r = 50+200-8 = 242 where its arcs live.
        assert!(
            neg_d.contains(",242"),
            "neg vertical Top path should contain y1-r=242, got {neg_d}"
        );
    }

    #[test]
    fn phase5_custom_series_line_weight_flows_to_line_path() {
        use chartml_core::theme::Theme;
        let renderer = CartesianRenderer::new();
        let mut config = make_line_config();
        let mut t = Theme::default();
        t.series_line_weight = 4.0;
        config.theme = t;
        let element = renderer
            .render(&make_bar_data(), &config)
            .expect("render");

        let mut widths = Vec::new();
        collect_series_stroke_widths(&element, &mut widths);
        assert!(!widths.is_empty(), "expected at least one series-line path");
        for w in &widths {
            assert_eq!(*w, 4.0, "series-line stroke_width must read from theme");
        }
    }

    #[test]
    fn phase5_custom_series_line_weight_flows_to_area_outline() {
        use chartml_core::theme::Theme;
        let renderer = CartesianRenderer::new();
        let mut config = make_area_config();
        let mut t = Theme::default();
        t.series_line_weight = 3.5;
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut widths = Vec::new();
        collect_series_stroke_widths(&element, &mut widths);
        assert!(!widths.is_empty(), "expected area outline series-line path");
        for w in &widths {
            assert_eq!(*w, 3.5);
        }
    }

    #[test]
    fn phase5_custom_dot_radius_flows_to_line_markers() {
        use chartml_core::theme::Theme;
        let renderer = CartesianRenderer::new();
        let mut config = make_line_config();
        let mut t = Theme::default();
        t.dot_radius = 10.0;
        config.theme = t;
        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut radii = Vec::new();
        collect_dot_radii(&element, &mut radii);
        assert!(!radii.is_empty(), "expected dot-marker circles on line chart");
        for r in &radii {
            assert_eq!(*r, 10.0);
        }
    }

    #[test]
    fn phase5_custom_axis_and_grid_line_weights_flow_to_line_strokes() {
        use chartml_core::theme::Theme;
        let renderer = CartesianRenderer::new();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.axis_line_weight = 2.5;
        t.grid_line_weight = 0.5;
        config.theme = t;

        let element = renderer.render(&make_bar_data(), &config).expect("render");

        let mut by_class: std::collections::HashMap<String, Vec<f64>> =
            std::collections::HashMap::new();
        collect_line_stroke_widths_by_class(&element, &mut by_class);

        let axis = by_class.get("axis-line").cloned().unwrap_or_default();
        let ticks = by_class.get("tick").cloned().unwrap_or_default();
        let grid = by_class.get("grid-line").cloned().unwrap_or_default();

        assert!(!axis.is_empty(), "expected axis-line elements");
        assert!(!ticks.is_empty(), "expected tick elements");
        assert!(!grid.is_empty(), "expected grid-line elements");

        for w in &axis {
            assert_eq!(*w, 2.5, "axis-line stroke_width must read from theme.axis_line_weight");
        }
        for w in &ticks {
            assert_eq!(*w, 2.5, "tick stroke_width must read from theme.axis_line_weight");
        }
        for w in &grid {
            assert_eq!(*w, 0.5, "grid-line stroke_width must read from theme.grid_line_weight");
        }
    }

    #[test]
    fn x_axis_date_labels_reformatted() {
        use crate::helpers::{generate_x_axis, GridConfig};
        let labels: Vec<String> = vec![
            "2024-01-01".into(), "2024-01-02".into(), "2024-01-03".into()
        ];
        let result = generate_x_axis(&crate::helpers::XAxisParams {
            labels: &labels, display_label_overrides: None,
            range: (0.0, 800.0), y_position: 350.0, available_width: 800.0,
            x_format: None, chart_height: None, grid: &GridConfig::default(), axis_label: None,
            theme: &chartml_core::theme::Theme::default(),
        });
        // Labels should be reformatted as "Jan 01", "Jan 02", etc.
        let has_reformatted = result.elements.iter().any(|e| {
            matches!(e, ChartElement::Text { content, .. } if content.starts_with("Jan"))
        });
        assert!(has_reformatted, "Date labels should be reformatted");
    }

    // ----- Phase 6: theme.grid_style gating -----

    /// Walk an element tree and count grid-line-x (vertical) and grid-line-y
    /// (horizontal) gridlines emitted by the cartesian renderer.
    fn count_grid_lines(el: &ChartElement) -> (usize, usize) {
        let (mut vx, mut hy) = (0usize, 0usize);
        fn visit(el: &ChartElement, vx: &mut usize, hy: &mut usize) {
            match el {
                ChartElement::Line { class, .. } => {
                    let has_x = class.split_whitespace().any(|c| c == "grid-line-x");
                    let has_y = class.split_whitespace().any(|c| c == "grid-line-y");
                    if has_x {
                        *vx += 1;
                    }
                    if has_y {
                        *hy += 1;
                    }
                }
                ChartElement::Svg { children, .. }
                | ChartElement::Group { children, .. } => {
                    for c in children {
                        visit(c, vx, hy);
                    }
                }
                _ => {}
            }
        }
        visit(el, &mut vx, &mut hy);
        (vx, hy)
    }

    /// Build a bar-chart config with both horizontal and vertical gridlines
    /// enabled (show_y defaults to true; explicitly force show_x via spec).
    fn make_bar_config_both_grids() -> ChartConfig {
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            columns: month
            rows: revenue
            style:
              grid:
                x: true
                y: true
        "#).unwrap();
        ChartConfig {
            visualize: viz,
            title: Some("Test Bar GridStyle".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string()],
            theme: chartml_core::theme::Theme::default(),
        }
    }

    #[test]
    fn phase6_grid_style_both_default_emits_both_orientations() {
        use chartml_core::theme::{GridStyle, Theme};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config_both_grids();
        let mut t = Theme::default();
        t.grid_style = GridStyle::Both;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        let (vx, hy) = count_grid_lines(&element);
        assert!(vx > 0, "Both: expected vertical gridlines (grid-line-x)");
        assert!(hy > 0, "Both: expected horizontal gridlines (grid-line-y)");
    }

    #[test]
    fn phase6_grid_style_horizontal_only_skips_vertical() {
        use chartml_core::theme::{GridStyle, Theme};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config_both_grids();
        let mut t = Theme::default();
        t.grid_style = GridStyle::HorizontalOnly;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        let (vx, hy) = count_grid_lines(&element);
        assert_eq!(vx, 0, "HorizontalOnly: no grid-line-x expected, got {}", vx);
        assert!(hy > 0, "HorizontalOnly: expected grid-line-y lines");
    }

    #[test]
    fn phase6_grid_style_vertical_only_skips_horizontal() {
        use chartml_core::theme::{GridStyle, Theme};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config_both_grids();
        let mut t = Theme::default();
        t.grid_style = GridStyle::VerticalOnly;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        let (vx, hy) = count_grid_lines(&element);
        assert!(vx > 0, "VerticalOnly: expected grid-line-x lines");
        assert_eq!(hy, 0, "VerticalOnly: no grid-line-y expected, got {}", hy);
    }

    #[test]
    fn phase6_grid_style_none_skips_all_gridlines() {
        use chartml_core::theme::{GridStyle, Theme};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_bar_config_both_grids();
        let mut t = Theme::default();
        t.grid_style = GridStyle::None;
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        let (vx, hy) = count_grid_lines(&element);
        assert_eq!(vx, 0, "None: no grid-line-x expected, got {}", vx);
        assert_eq!(hy, 0, "None: no grid-line-y expected, got {}", hy);
    }

    // ----- Phase 7: zero-line wiring -----

    fn make_bar_data_crossing_zero() -> DataTable {
        let rows = vec![
            [("month".to_string(), json!("Jan")), ("revenue".to_string(), json!(-5))].into_iter().collect(),
            [("month".to_string(), json!("Feb")), ("revenue".to_string(), json!(0))].into_iter().collect(),
            [("month".to_string(), json!("Mar")), ("revenue".to_string(), json!(10))].into_iter().collect(),
        ];
        DataTable::from_rows(&rows).unwrap()
    }

    fn count_zero_lines(el: &ChartElement) -> usize {
        count_elements(el, &|e| {
            matches!(e, ChartElement::Line { class, .. } if class.split_whitespace().any(|c| c == "zero-line"))
        })
    }

    /// With the default theme (`zero_line: None`), no zero-line element must
    /// ever be emitted — even when the data range obviously crosses zero.
    #[test]
    fn phase7_default_theme_emits_no_zero_line() {
        let renderer = CartesianRenderer::new();
        let data = make_bar_data_crossing_zero();
        let config = make_bar_config();
        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(count_zero_lines(&element), 0, "default theme must not emit zero-line");
    }

    /// With a non-default `zero_line` spec AND data that strictly crosses zero,
    /// exactly one `zero-line` Line must be emitted with the spec'd color/width.
    #[test]
    fn phase7_bar_crossing_zero_emits_one_zero_line() {
        use chartml_core::theme::{Theme, ZeroLineSpec};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data_crossing_zero();
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.zero_line = Some(ZeroLineSpec { color: "#ff0000".into(), width: 1.5 });
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(count_zero_lines(&element), 1, "expected exactly one zero-line");

        // Verify the emitted element has the configured stroke + width.
        fn find_zero_line(el: &ChartElement) -> Option<(String, Option<f64>)> {
            match el {
                ChartElement::Line { class, stroke, stroke_width, .. }
                    if class.split_whitespace().any(|c| c == "zero-line") =>
                {
                    Some((stroke.clone(), *stroke_width))
                }
                ChartElement::Group { children, .. } | ChartElement::Svg { children, .. } => {
                    children.iter().find_map(find_zero_line)
                }
                _ => None,
            }
        }
        let (stroke, width) = find_zero_line(&element).expect("zero-line present");
        assert_eq!(stroke, "#ff0000");
        assert_eq!(width, Some(1.5));
    }

    /// Horizontal bar parity: crossing-zero data + non-default zero_line must
    /// emit exactly one zero-line, and for a horizontal bar chart (numeric axis
    /// is x) that line must run vertically — x1 == x2 and y1 != y2.
    #[test]
    fn phase7_horizontal_bar_crossing_zero_emits_one_zero_line() {
        use chartml_core::theme::{Theme, ZeroLineSpec};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data_crossing_zero();
        let viz: VisualizeSpec = serde_yaml::from_str(r#"
            type: bar
            orientation: horizontal
            columns: month
            rows: revenue
        "#).unwrap();
        let mut theme = Theme::default();
        theme.zero_line = Some(ZeroLineSpec { color: "#ff0000".into(), width: 1.5 });
        let config = ChartConfig {
            visualize: viz,
            title: Some("Test Horizontal Bar".to_string()),
            width: 800.0,
            height: 400.0,
            colors: vec!["#2E7D9A".to_string()],
            theme,
        };

        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(count_zero_lines(&element), 1, "expected exactly one zero-line");

        // Find the emitted zero-line Line and assert it runs vertically with
        // the spec'd stroke + width.
        struct ZeroLineGeom {
            x1: f64,
            y1: f64,
            x2: f64,
            y2: f64,
            stroke: String,
            stroke_width: Option<f64>,
        }
        fn find_zero_line_geom(el: &ChartElement) -> Option<ZeroLineGeom> {
            match el {
                ChartElement::Line { class, x1, y1, x2, y2, stroke, stroke_width, .. }
                    if class.split_whitespace().any(|c| c == "zero-line") =>
                {
                    Some(ZeroLineGeom {
                        x1: *x1,
                        y1: *y1,
                        x2: *x2,
                        y2: *y2,
                        stroke: stroke.clone(),
                        stroke_width: *stroke_width,
                    })
                }
                ChartElement::Group { children, .. } | ChartElement::Svg { children, .. } => {
                    children.iter().find_map(find_zero_line_geom)
                }
                _ => None,
            }
        }
        let ZeroLineGeom { x1, y1, x2, y2, stroke, stroke_width: width } =
            find_zero_line_geom(&element).expect("zero-line present");
        assert!(
            (x1 - x2).abs() < f64::EPSILON,
            "horizontal-bar zero-line must be vertical: x1={x1} x2={x2}",
        );
        assert!(
            (y1 - y2).abs() > f64::EPSILON,
            "horizontal-bar zero-line must have non-zero height: y1={y1} y2={y2}",
        );
        assert_eq!(stroke, "#ff0000");
        assert_eq!(width, Some(1.5));
    }

    /// With a non-default `zero_line` spec BUT data entirely positive (so the
    /// domain floor is 0 and doesn't strictly cross zero), no zero-line is emitted.
    #[test]
    fn phase7_bar_all_positive_emits_no_zero_line() {
        use chartml_core::theme::{Theme, ZeroLineSpec};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data(); // values: 100, 200, 150 — all positive
        let mut config = make_bar_config();
        let mut t = Theme::default();
        t.zero_line = Some(ZeroLineSpec { color: "#ff0000".into(), width: 1.5 });
        config.theme = t;

        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(
            count_zero_lines(&element),
            0,
            "all-positive data must not emit a zero-line",
        );
    }

    /// Line chart parity: crossing-zero data + non-default zero_line emits one line.
    #[test]
    fn phase7_line_crossing_zero_emits_one_zero_line() {
        use chartml_core::theme::{Theme, ZeroLineSpec};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data_crossing_zero();
        let mut config = make_line_config();
        let mut t = Theme::default();
        t.zero_line = Some(ZeroLineSpec { color: "#00ff00".into(), width: 2.0 });
        config.theme = t;
        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(count_zero_lines(&element), 1);
    }

    // ----- Phase 8: dot_halo wiring -----

    fn count_halos(el: &ChartElement) -> usize {
        count_elements(el, &|e| matches!(e, ChartElement::Path { class, .. } if class == "dot-halo"))
    }

    fn count_dot_markers(el: &ChartElement) -> usize {
        count_elements(el, &|e| matches!(e, ChartElement::Circle { class, .. } if class.contains("dot-marker")))
    }

    #[test]
    fn phase8_line_default_theme_emits_no_halo() {
        let renderer = CartesianRenderer::new();
        let element = renderer.render(&make_bar_data(), &make_line_config()).unwrap();
        assert_eq!(count_halos(&element), 0, "default theme line chart must emit zero halos");
    }

    #[test]
    fn phase8_line_halo_matches_dot_count_and_ordering() {
        use chartml_core::theme::Theme;
        let renderer = CartesianRenderer::new();
        let data = make_bar_data();
        let mut config = make_line_config();
        let mut t = Theme::default();
        t.dot_halo_color = Some("#ffffff".to_string());
        t.dot_halo_width = 1.5;
        config.theme = t;
        let element = renderer.render(&data, &config).unwrap();

        let dot_n = count_dot_markers(&element);
        let halo_n = count_halos(&element);
        assert!(dot_n > 0, "line chart should produce at least one dot-marker");
        assert_eq!(halo_n, dot_n, "one halo per dot-marker required");

        // Halo must precede its dot: in the lines group, walk children and
        // assert every dot-halo Path is immediately followed by a Circle.
        fn walk_lines_group(el: &ChartElement) -> Option<&Vec<ChartElement>> {
            match el {
                ChartElement::Group { class, children, .. } if class == "lines" => Some(children),
                ChartElement::Svg { children, .. } | ChartElement::Group { children, .. } => {
                    children.iter().find_map(walk_lines_group)
                }
                _ => None,
            }
        }
        let lines = walk_lines_group(&element).expect("lines group");
        let mut pair = 0;
        let mut iter = lines.iter().peekable();
        while let Some(el) = iter.next() {
            if let ChartElement::Path { class, .. } = el {
                if class == "dot-halo" {
                    match iter.peek() {
                        Some(ChartElement::Circle { class: cc, .. }) => {
                            assert!(cc.contains("dot-marker"));
                            pair += 1;
                        }
                        other => panic!("halo not followed by dot: {:?}", other.map(|_| "other")),
                    }
                }
            }
        }
        assert_eq!(pair, dot_n);

        // Verify stroke / stroke-width on first halo.
        fn first_halo(el: &ChartElement) -> Option<(String, f64)> {
            match el {
                ChartElement::Path { class, stroke, stroke_width, .. } if class == "dot-halo" => {
                    Some((stroke.clone().unwrap_or_default(), stroke_width.unwrap_or(-1.0)))
                }
                ChartElement::Svg { children, .. } | ChartElement::Group { children, .. } => {
                    children.iter().find_map(first_halo)
                }
                _ => None,
            }
        }
        let (stroke, width) = first_halo(&element).unwrap();
        assert_eq!(stroke, "#ffffff");
        assert!((width - 1.5).abs() < 1e-9);
    }

    /// Area chart parity: crossing-zero data + non-default zero_line emits one line.
    #[test]
    fn phase7_area_crossing_zero_emits_one_zero_line() {
        use chartml_core::theme::{Theme, ZeroLineSpec};
        let renderer = CartesianRenderer::new();
        let data = make_bar_data_crossing_zero();
        let mut config = make_area_config();
        let mut t = Theme::default();
        t.zero_line = Some(ZeroLineSpec { color: "#0000ff".into(), width: 1.0 });
        config.theme = t;
        let element = renderer.render(&data, &config).unwrap();
        assert_eq!(count_zero_lines(&element), 1);
    }
}