tdsl-render 1.18.0

SVG, HTML, and PDF rendering for Timeline DSL IR
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
use std::collections::HashMap;

use tdsl_core::ir::{Item, Lane, TimelineIr, end_frac, start_frac};

/// Colorblind-friendly 8-color palette for per-lane fill colors.
///
/// Single source of truth for palette shared by all emitters.
pub(crate) const LANE_PALETTE: &[&str] = &[
    "#4682B4", // steel blue
    "#E67E22", // orange
    "#27AE60", // green
    "#8E44AD", // purple
    "#E74C3C", // red
    "#1ABC9C", // teal
    "#F39C12", // amber
    "#2980B9", // blue
];

/// Timeline layout orientation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Orientation {
    /// Time axis runs left→right; lanes are stacked top→bottom. (default)
    #[default]
    Horizontal,
    /// Time axis runs top→bottom; lanes are arranged left→right.
    Vertical,
}

/// Color/style theme for HTML output.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Theme {
    #[default]
    Default,
    Dark,
    Print,
    Pastel,
}

/// Grid line style for the time axis.
///
/// Auxiliary grid lines are drawn at regular intervals to improve readability
/// on long timelines. `None` disables all grid lines (default, preserves
/// existing SVG output unchanged).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum GridStyle {
    /// No grid lines (default). SVG output is identical to pre-grid behavior.
    #[default]
    None,
    /// Grid lines every 10 years.
    Decade,
    /// Grid lines every year.
    Year,
    /// Grid lines every month.
    ///
    /// Note: month-grid uses 1/12-year intervals regardless of item precision.
    /// This is a visual aid only and does not require `unit = "month"`.
    Month,
}

/// Rendering options. Pixel dimensions and styling parameters.
#[derive(Debug, Clone)]
pub struct RenderOptions {
    /// Pixels per year on the horizontal axis.
    pub scale: f64,
    /// Height of each lane in pixels.
    pub lane_height: f64,
    /// Width of the left-hand gutter that holds lane labels.
    pub left_gutter: f64,
    /// Top margin reserved for the time axis.
    pub top_margin: f64,
    /// Right margin.
    pub right_margin: f64,
    /// Bottom margin.
    pub bottom_margin: f64,
    /// Color/style theme.
    pub theme: Theme,
    /// Optional custom CSS (content, not a file path) injected after the theme CSS.
    pub custom_css: Option<String>,
    /// Tag-to-color overrides. Key: tag name, Value: CSS color string (e.g. "#cc0000").
    pub color_map: std::collections::HashMap<String, String>,
    /// Enable interactive mode (zoom, pan, search, legend, detail panel).
    pub interactive: bool,
    /// Custom font-family CSS value for SVG text. When None, uses the built-in CJK-friendly stack.
    pub font_family: Option<String>,
    /// Timeline layout orientation: horizontal (default) or vertical.
    pub orientation: Orientation,
    /// Auxiliary grid line style. `None` (default) disables grid lines entirely.
    pub grid: GridStyle,
    /// When true, an HTML table listing all items is appended after the SVG in HTML output.
    /// Has no effect for SVG, PNG, or PDF output formats.
    pub show_table: bool,
    /// When true, labels (and optionally dates) are always rendered next to Event and EventRange
    /// dots/bars as SVG text elements.  Disabled by default to keep the chart uncluttered.
    pub show_event_labels: bool,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            scale: 2.0,
            lane_height: 60.0,
            left_gutter: 120.0,
            top_margin: 40.0,
            right_margin: 20.0,
            bottom_margin: 20.0,
            theme: Theme::Default,
            custom_css: None,
            color_map: std::collections::HashMap::new(),
            interactive: false,
            font_family: None,
            orientation: Orientation::Horizontal,
            grid: GridStyle::None,
            show_table: false,
            show_event_labels: false,
        }
    }
}

/// Pre-computed lane background band geometry.
#[derive(Debug, Clone)]
pub struct LaneBandModel {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    /// `true` for even-indexed lanes (0-based), `false` for odd.
    pub even: bool,
}

/// Item kind in its laid-out form (y offset from lane center already applied).
///
/// `color` is the resolved CSS color string (from tag overrides or lane palette).
/// `tooltip` is the formatted tooltip text before XML escaping.
#[derive(Debug, Clone)]
pub enum LaidItem<'a> {
    Span {
        item: &'a Item,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        /// Resolved CSS color (e.g. `"#4682B4"`).
        color: String,
        /// Formatted tooltip text (XML-unescaped).
        tooltip: String,
    },
    EventRange {
        item: &'a Item,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        /// Resolved CSS color (base; emitters may add fill-opacity).
        color: String,
        /// Formatted tooltip text (XML-unescaped).
        tooltip: String,
    },
    Event {
        item: &'a Item,
        x: f64,
        y_top: f64,
        y_bottom: f64,
        y_dot: f64,
        /// Resolved CSS color.
        color: String,
        /// Formatted tooltip text (XML-unescaped).
        tooltip: String,
    },
}

/// Pre-computed layout: every coordinate needed by the renderer.
pub struct LayoutModel<'a> {
    pub ir: &'a TimelineIr,
    pub opts: RenderOptions,
    pub year_min: i64,
    pub year_max: i64,
    pub total_width: f64,
    pub total_height: f64,
    pub lanes_ordered: Vec<&'a Lane>,
    pub lane_y: HashMap<String, f64>,
    pub tick_step: i64,
    pub items: Vec<LaidItem<'a>>,
    /// Pre-computed lane background bands (index-ordered, same order as `lanes_ordered`).
    pub lane_bands: Vec<LaneBandModel>,
    /// Mapping from lane ID to resolved CSS color (palette-assigned).
    pub lane_colors: HashMap<String, String>,
}

impl<'a> LayoutModel<'a> {
    pub fn compute(ir: &'a TimelineIr, opts: RenderOptions) -> Self {
        let (year_min, year_max) = ir.meta.range;
        let (year_min, year_max) = if year_max > year_min {
            (year_min, year_max)
        } else if year_max == year_min {
            // 同一年内のレンジ(例: range 1939-09..1939-10): items から導出せず一年幅を確保
            (year_min, year_max + 1)
        } else {
            // Fallback: if range is degenerate, derive from items.
            derive_range_from_items(ir).unwrap_or((0, 2000))
        };

        let mut lanes_ordered: Vec<&Lane> = ir.lanes.iter().collect();
        lanes_ordered.sort_by_key(|l| (l.order, l.id.clone()));

        let is_vertical = opts.orientation == Orientation::Vertical;
        let n_lanes = lanes_ordered.len();
        let time_span = (year_max - year_min) as f64;

        // lane_y stores:
        //   horizontal → lane center Y coordinate
        //   vertical   → lane center X coordinate (reusing the same field for "lane primary axis")
        let mut lane_y = HashMap::new();
        if is_vertical {
            for (idx, lane) in lanes_ordered.iter().enumerate() {
                // left_gutter is reserved for the time-axis labels on the left; lanes go rightward.
                let center = opts.left_gutter + (idx as f64 + 0.5) * opts.lane_height;
                lane_y.insert(lane.id.clone(), center);
            }
        } else {
            for (idx, lane) in lanes_ordered.iter().enumerate() {
                let center = opts.top_margin + (idx as f64 + 0.5) * opts.lane_height;
                lane_y.insert(lane.id.clone(), center);
            }
        }

        let (total_width, total_height) = if is_vertical {
            // vertical: time axis is Y, lanes are X columns.
            // lane_height is reused as the lane column width.
            let w = opts.left_gutter + n_lanes as f64 * opts.lane_height + opts.right_margin;
            let h = opts.top_margin + time_span * opts.scale + opts.bottom_margin;
            (w, h)
        } else {
            let w = opts.left_gutter + time_span * opts.scale + opts.right_margin;
            let h = opts.top_margin + n_lanes as f64 * opts.lane_height + opts.bottom_margin;
            (w, h)
        };

        let tick_step = pick_tick_step(year_max - year_min, opts.scale, AXIS_LABEL_PX);

        // lane_colors: palette-assigned CSS color per lane ID.
        let lane_colors: HashMap<String, String> = lanes_ordered
            .iter()
            .enumerate()
            .map(|(idx, lane)| {
                (
                    lane.id.clone(),
                    LANE_PALETTE[idx % LANE_PALETTE.len()].to_string(),
                )
            })
            .collect();

        // lane_bands: background band geometry per lane.
        let lane_bands: Vec<LaneBandModel> = if is_vertical {
            let content_height = total_height - opts.top_margin - opts.bottom_margin;
            lanes_ordered
                .iter()
                .enumerate()
                .map(|(idx, _lane)| LaneBandModel {
                    x: opts.left_gutter + idx as f64 * opts.lane_height,
                    y: opts.top_margin,
                    width: opts.lane_height,
                    height: content_height,
                    even: idx % 2 == 0,
                })
                .collect()
        } else {
            let content_width = total_width - opts.left_gutter - opts.right_margin;
            lanes_ordered
                .iter()
                .enumerate()
                .map(|(idx, _lane)| LaneBandModel {
                    x: opts.left_gutter,
                    y: opts.top_margin + idx as f64 * opts.lane_height,
                    width: content_width,
                    height: opts.lane_height,
                    even: idx % 2 == 0,
                })
                .collect()
        };

        let mut items = Vec::new();
        for item in &ir.items {
            let lane_id = item_lane_id(item);
            let Some(&lane_axis) = lane_y.get(lane_id) else {
                continue;
            };
            let item_tags = get_item_tags(item);
            let color = resolve_item_color(item_tags, &opts.color_map, lane_id, &lane_colors);
            let tooltip = item_tooltip(item);
            compute_item(
                item,
                &mut items,
                ItemLayoutArgs {
                    lane_axis,
                    year_min,
                    year_max,
                    opts: &opts,
                    orientation: opts.orientation.clone(),
                    color,
                    tooltip,
                },
            );
        }

        Self {
            ir,
            opts,
            year_min,
            year_max,
            total_width,
            total_height,
            lanes_ordered,
            lane_y,
            tick_step,
            items,
            lane_bands,
            lane_colors,
        }
    }

    /// Returns `true` when the layout uses a vertical (top-to-bottom time axis) orientation.
    pub fn is_vertical(&self) -> bool {
        self.opts.orientation == Orientation::Vertical
    }

    /// Convert a year to the primary axis coordinate.
    ///
    /// - Horizontal: returns the X coordinate.
    /// - Vertical:   returns the Y coordinate.
    pub fn year_to_primary(&self, year: i64) -> f64 {
        if self.is_vertical() {
            self.opts.top_margin + (year - self.year_min) as f64 * self.opts.scale
        } else {
            year_to_x(year, self.year_min, self.opts.scale, self.opts.left_gutter)
        }
    }

    pub fn year_to_x(&self, year: i64) -> f64 {
        year_to_x(year, self.year_min, self.opts.scale, self.opts.left_gutter)
    }

    /// Month minor-tick positions for `unit=month` timelines.
    ///
    /// Returns `(year, month)` pairs where month ∈ 2..=12 (month=1 overlaps the year tick).
    /// Empty when `unit != "month"` or when the scale is too small to show sub-year ticks.
    pub fn month_ticks(&self) -> Vec<(i64, u8)> {
        if self.ir.meta.unit != "month" {
            return Vec::new();
        }
        if self.opts.scale / 12.0 < 1.0 {
            return Vec::new();
        }
        let mut ticks = Vec::new();
        for year in self.year_min..=self.year_max {
            for month in 2u8..=12 {
                let frac = to_year_frac(year, Some(month), None);
                if frac < self.year_max as f64 {
                    ticks.push((year, month));
                }
            }
        }
        ticks
    }

    /// X coordinate for a (year, month) fractional position.
    pub fn frac_year_to_x(&self, year: i64, month: u8) -> f64 {
        let frac = to_year_frac(year, Some(month), None);
        frac_to_x(frac, self.year_min, self.opts.scale, self.opts.left_gutter)
    }

    /// X coordinate for a (year, month, day) fractional position.
    pub fn day_frac_to_x(&self, year: i64, month: u8, day: u8) -> f64 {
        let frac = to_year_frac(year, Some(month), Some(day));
        frac_to_x(frac, self.year_min, self.opts.scale, self.opts.left_gutter)
    }

    /// Day-level minor-tick positions for `unit=day` timelines.
    ///
    /// Returns `(year, month, day)` triples covering the visible range.
    /// 過密回避のため、1日あたりの pixel-per-day が小さい場合は step を 7/14/30 日に切り替える。
    /// `unit != "day"` または 1 日あたりのピクセルが小さすぎる場合は空配列を返す。
    pub fn day_ticks(&self) -> Vec<(i64, u8, u8)> {
        if self.ir.meta.unit != "day" {
            return Vec::new();
        }

        let pixels_per_day = self.opts.scale / 365.25;
        // 最低でも 1px の間隔を要求。完全に詰まる場合は描画しない(年単位描画に委ねる)
        if pixels_per_day < 0.5 {
            return Vec::new();
        }

        // 1 tick あたり最低 6 px を確保するための step(日数)
        let step = if pixels_per_day >= 6.0 {
            1
        } else if pixels_per_day >= 3.0 {
            2
        } else if pixels_per_day >= 1.5 {
            7
        } else {
            30
        };

        let mut ticks = Vec::new();
        for year in self.year_min..=self.year_max {
            for month in 1u8..=12 {
                let last = tdsl_core::ir::days_in_month(year, month);
                let mut day = 1u8;
                while day <= last {
                    if day == 1 || ((day - 1) as usize).is_multiple_of(step) {
                        let frac = to_year_frac(year, Some(month), Some(day));
                        if frac < self.year_max as f64 {
                            ticks.push((year, month, day));
                        }
                    }
                    day = day.saturating_add(1);
                    if day == 0 {
                        break;
                    }
                }
            }
        }
        ticks
    }

    /// Tick positions (year values) within [year_min, year_max], inclusive of year_min if aligned.
    pub fn ticks(&self) -> Vec<i64> {
        let step = self.tick_step.max(1);
        let first = div_floor(self.year_min, step) * step;
        let mut ticks = Vec::new();
        let mut y = first;
        while y <= self.year_max {
            if y >= self.year_min {
                ticks.push(y);
            }
            y += step;
        }
        ticks
    }

    /// Grid line positions for the current `GridStyle`.
    ///
    /// Returns fractional year values (f64) covering [year_min, year_max].
    /// - `GridStyle::None`   → empty (no grid lines drawn)
    /// - `GridStyle::Decade` → one position per 10 years
    /// - `GridStyle::Year`   → one position per year
    /// - `GridStyle::Month`  → one position per 1/12 year (12 per year)
    ///
    /// Positions that coincide with existing axis ticks are included; the SVG
    /// renderer draws grid lines behind tick marks so duplicates are invisible.
    pub fn grid_positions(&self) -> Vec<f64> {
        match self.opts.grid {
            GridStyle::None => Vec::new(),
            GridStyle::Decade => {
                let first = div_floor(self.year_min, 10) * 10;
                let mut positions = Vec::new();
                let mut y = first;
                while y <= self.year_max {
                    if y >= self.year_min {
                        positions.push(y as f64);
                    }
                    y += 10;
                }
                positions
            }
            GridStyle::Year => (self.year_min..=self.year_max).map(|y| y as f64).collect(),
            GridStyle::Month => {
                let mut positions = Vec::new();
                for year in self.year_min..=self.year_max {
                    for month in 0u8..12 {
                        let frac = year as f64 + month as f64 / 12.0;
                        if frac >= self.year_min as f64 && frac <= self.year_max as f64 {
                            positions.push(frac);
                        }
                    }
                }
                positions
            }
        }
    }
}

// --- item layout helpers ---

/// Arguments for [`compute_item`].
///
/// Bundling them collapses the orientation-specific compute functions into one
/// and removes the `too_many_arguments` clippy escape that the previous
/// horizontal/vertical pair required.
struct ItemLayoutArgs<'a> {
    /// Lane axis position. For horizontal layouts this is the lane center Y
    /// coordinate; for vertical layouts it is the lane center X coordinate.
    lane_axis: f64,
    year_min: i64,
    year_max: i64,
    opts: &'a RenderOptions,
    orientation: Orientation,
    color: String,
    tooltip: String,
}

/// Compute the laid-out coordinates for a single item.
///
/// The orientation-specific projection collapses into a single primary/cross
/// axis pair: the time axis is the *primary* axis (X horizontally, Y
/// vertically) and the lane axis is the *cross* axis. The final
/// [`LaidItem`] fields are populated by mapping (primary, cross) back into
/// (x, y) using [`ItemLayoutArgs::orientation`].
///
/// For [`Item::Event`] in vertical orientation, the `LaidItem::Event` fields
/// are reused with shifted semantics: `x` holds the lane axis, and
/// `y_top`/`y_bottom`/`y_dot` hold time-axis values. The SVG emitter detects
/// this via [`LayoutModel::is_vertical`] and renders the stem horizontally.
fn compute_item<'a>(item: &'a Item, items: &mut Vec<LaidItem<'a>>, args: ItemLayoutArgs<'_>) {
    let ItemLayoutArgs {
        lane_axis,
        year_min,
        year_max,
        opts,
        orientation,
        color,
        tooltip,
    } = args;
    let is_vertical = orientation == Orientation::Vertical;
    let primary_anchor = if is_vertical {
        opts.top_margin
    } else {
        opts.left_gutter
    };

    match item {
        Item::Span {
            start,
            end,
            start_month,
            start_day,
            end_month,
            end_day,
            ..
        } => {
            // 仕様 §1.4: start は year/月の頭、end は year/月の末日を採用(混在精度補完)
            let sf = start_frac(*start, *start_month, *start_day);
            let ef = end_frac(*end, *end_month, *end_day);
            let (primary_start, primary_extent) =
                primary_axis_segment(sf, ef, year_min, year_max, opts.scale, primary_anchor);
            let cross_start = lane_axis - SPAN_HALF_H;
            let cross_extent = SPAN_HALF_H * 2.0;
            let (x, y, width, height) = if is_vertical {
                (cross_start, primary_start, cross_extent, primary_extent)
            } else {
                (primary_start, cross_start, primary_extent, cross_extent)
            };
            items.push(LaidItem::Span {
                item,
                x,
                y,
                width,
                height,
                color,
                tooltip,
            });
        }
        Item::EventRange {
            start,
            end,
            start_month,
            start_day,
            end_month,
            end_day,
            ..
        } => {
            let sf = start_frac(*start, *start_month, *start_day);
            let ef = end_frac(*end, *end_month, *end_day);
            let (primary_start, primary_extent) =
                primary_axis_segment(sf, ef, year_min, year_max, opts.scale, primary_anchor);
            // Horizontal bands sit just below the lane center
            // (EVENT_RANGE_Y_OFFSET); vertical bands are centered on the lane
            // axis. This asymmetry is preserved verbatim from the original
            // split implementation.
            let (x, y, width, height) = if is_vertical {
                (
                    lane_axis - EVENT_RANGE_H / 2.0,
                    primary_start,
                    EVENT_RANGE_H,
                    primary_extent,
                )
            } else {
                (
                    primary_start,
                    lane_axis + EVENT_RANGE_Y_OFFSET,
                    primary_extent,
                    EVENT_RANGE_H,
                )
            };
            items.push(LaidItem::EventRange {
                item,
                x,
                y,
                width,
                height,
                color,
                tooltip,
            });
        }
        Item::Event {
            time,
            time_month,
            time_day,
            ..
        } => {
            if !year_in_range(*time, year_min, year_max) {
                return;
            }
            let frac = to_year_frac(*time, *time_month, *time_day);
            let primary = primary_anchor + (frac - year_min as f64) * opts.scale;
            let (x, y_top, y_bottom, y_dot) = if is_vertical {
                // x = lane axis; y_top/y_bottom/y_dot all live on the time axis.
                (
                    lane_axis,
                    primary - EVENT_STEM_H,
                    primary + EVENT_STEM_H,
                    primary,
                )
            } else {
                // x = time axis; y_top/y_bottom/y_dot live on the lane axis.
                (
                    primary,
                    lane_axis - EVENT_STEM_H,
                    lane_axis + EVENT_STEM_H,
                    lane_axis,
                )
            };
            items.push(LaidItem::Event {
                item,
                x,
                y_top,
                y_bottom,
                y_dot,
                color,
                tooltip,
            });
        }
    }
}

// --- sub-layout constants ---
const SPAN_HALF_H: f64 = 12.0;
/// Approximate rendered width (px) of the longest axis label ("BC9999" at 11 px font-size).
const AXIS_LABEL_PX: f64 = 40.0;
const EVENT_RANGE_Y_OFFSET: f64 = 14.0;
const EVENT_RANGE_H: f64 = 10.0;
const EVENT_STEM_H: f64 = 20.0;

fn item_lane_id(item: &Item) -> &str {
    match item {
        Item::Span { lane, .. } | Item::Event { lane, .. } | Item::EventRange { lane, .. } => lane,
    }
}

fn get_item_tags(item: &Item) -> &[String] {
    match item {
        Item::Span { tags, .. } | Item::Event { tags, .. } | Item::EventRange { tags, .. } => tags,
    }
}

/// Resolve item fill color: tag overrides take priority over lane palette.
pub(crate) fn resolve_item_color(
    tags: &[String],
    color_map: &HashMap<String, String>,
    lane_id: &str,
    lane_colors: &HashMap<String, String>,
) -> String {
    for tag in tags {
        if let Some(color) = color_map.get(tag.as_str()) {
            return color.clone();
        }
    }
    lane_colors
        .get(lane_id)
        .cloned()
        .unwrap_or_else(|| "#4682B4".to_string())
}

/// Format a year for display: negative years get a "BC" prefix.
pub(crate) fn format_year(year: i64) -> String {
    if year < 0 {
        format!("BC{}", -year)
    } else {
        format!("{year}")
    }
}

/// Short three-letter English month abbreviation.
pub(crate) fn month_abbr(m: u8) -> &'static str {
    match m {
        1 => "Jan",
        2 => "Feb",
        3 => "Mar",
        4 => "Apr",
        5 => "May",
        6 => "Jun",
        7 => "Jul",
        8 => "Aug",
        9 => "Sep",
        10 => "Oct",
        11 => "Nov",
        12 => "Dec",
        _ => "?",
    }
}

/// Format a date for display, with optional month and day precision.
pub(crate) fn format_date(year: i64, month: Option<u8>, day: Option<u8>) -> String {
    let y = format_year(year);
    match (month, day) {
        (Some(m), Some(d)) => format!("{} {} {}", y, month_abbr(m), d),
        (Some(m), None) => format!("{} {}", y, month_abbr(m)),
        _ => y,
    }
}

fn push_common(
    lines: &mut Vec<String>,
    tags: &[String],
    source: &Option<String>,
    origin: &Option<String>,
    id: &str,
) {
    if !tags.is_empty() {
        lines.push(format!("tags: {}", tags.join(", ")));
    }
    if let Some(src) = source {
        lines.push(format!("source: {src}"));
    }
    if let Some(org) = origin {
        lines.push(format!("origin: {org}"));
    }
    lines.push(format!("id: {id}"));
}

/// Build the tooltip text for an item (XML-unescaped).
fn item_tooltip(item: &Item) -> String {
    let mut lines = Vec::new();
    match item {
        Item::Span {
            label,
            start,
            end,
            tags,
            source,
            origin,
            id,
            start_month,
            start_day,
            end_month,
            end_day,
            ..
        } => {
            lines.push(label.to_string());
            lines.push(format!(
                "{}{}",
                format_date(*start, *start_month, *start_day),
                format_date(*end, *end_month, *end_day),
            ));
            push_common(&mut lines, tags, source, origin, id);
        }
        Item::Event {
            label,
            time,
            tags,
            source,
            origin,
            id,
            time_month,
            time_day,
            ..
        } => {
            lines.push(label.to_string());
            lines.push(format_date(*time, *time_month, *time_day));
            push_common(&mut lines, tags, source, origin, id);
        }
        Item::EventRange {
            label,
            start,
            end,
            tags,
            source,
            origin,
            id,
            start_month,
            start_day,
            end_month,
            end_day,
            ..
        } => {
            lines.push(label.to_string());
            lines.push(format!(
                "{}{}",
                format_date(*start, *start_month, *start_day),
                format_date(*end, *end_month, *end_day),
            ));
            push_common(&mut lines, tags, source, origin, id);
        }
    }
    lines.join("\n")
}

fn year_to_x(year: i64, year_min: i64, scale: f64, left_gutter: f64) -> f64 {
    left_gutter + (year - year_min) as f64 * scale
}

/// Convert year + optional month + optional day to a fractional year value.
fn to_year_frac(year: i64, month: Option<u8>, day: Option<u8>) -> f64 {
    let mut frac = year as f64;
    if let Some(m) = month {
        frac += (m.clamp(1, 12) - 1) as f64 / 12.0;
        if let Some(d) = day {
            frac += (d.clamp(1, 31) - 1) as f64 / 365.25;
        }
    }
    frac
}

fn frac_to_x(frac: f64, year_min: i64, scale: f64, left_gutter: f64) -> f64 {
    left_gutter + (frac - year_min as f64) * scale
}

fn year_in_range(year: i64, year_min: i64, year_max: i64) -> bool {
    year >= year_min && year <= year_max
}

/// Compute the (start, extent) of a span/event-range projected onto the time
/// (primary) axis.
///
/// `anchor` is the pixel coordinate where `year_min` falls on the primary
/// axis: `left_gutter` for horizontal layouts, `top_margin` for vertical
/// layouts. The same formula serves both orientations.
fn primary_axis_segment(
    start_frac: f64,
    end_frac: f64,
    year_min: i64,
    year_max: i64,
    scale: f64,
    anchor: f64,
) -> (f64, f64) {
    let s = start_frac.max(year_min as f64);
    let e = end_frac.min(year_max as f64);
    if e < s {
        return (anchor + (start_frac - year_min as f64) * scale, 0.0);
    }
    (anchor + (s - year_min as f64) * scale, (e - s) * scale)
}

fn derive_range_from_items(ir: &TimelineIr) -> Option<(i64, i64)> {
    let mut min: Option<i64> = None;
    let mut max: Option<i64> = None;
    for item in &ir.items {
        match item {
            Item::Span { start, end, .. } | Item::EventRange { start, end, .. } => {
                min = Some(min.map_or(*start, |m| m.min(*start)));
                max = Some(max.map_or(*end, |m| m.max(*end)));
            }
            Item::Event { time, .. } => {
                min = Some(min.map_or(*time, |m| m.min(*time)));
                max = Some(max.map_or(*time, |m| m.max(*time)));
            }
        }
    }
    match (min, max) {
        (Some(a), Some(b)) if b > a => Some((a, b)),
        (Some(a), Some(b)) => Some((a - 10, b + 10)),
        _ => None,
    }
}

/// Pick a tick step so that labels do not visually overlap.
/// `step * scale` must be at least `label_px + 8` px (minimum inter-label gap).
fn pick_tick_step(range: i64, scale: f64, label_px: f64) -> i64 {
    if range <= 0 {
        return 1;
    }
    let min_pitch = label_px + 8.0;
    const CANDIDATES: &[i64] = &[
        1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 5000,
    ];
    for &step in CANDIDATES {
        if (step as f64) * scale >= min_pitch {
            return step;
        }
    }
    10000
}

fn div_floor(a: i64, b: i64) -> i64 {
    let q = a / b;
    let r = a % b;
    if (r != 0) && ((r < 0) != (b < 0)) {
        q - 1
    } else {
        q
    }
}

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

    fn mk_meta(range: (i64, i64)) -> tdsl_core::ir::Meta {
        tdsl_core::ir::Meta {
            title: "t".into(),
            unit: "year".into(),
            range,
            calendar: "proleptic_gregorian".into(),
            color_map: std::collections::HashMap::new(),
            ..Default::default()
        }
    }

    #[test]
    fn year_to_x_basic() {
        let ir = TimelineIr {
            meta: mk_meta((-500, 2000)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        // With scale=2.0 and left_gutter=120, year -500 → x=120, year 0 → x=120+500*2=1120
        assert_eq!(layout.year_to_x(-500), 120.0);
        assert_eq!(layout.year_to_x(0), 1120.0);
        assert_eq!(layout.year_to_x(2000), 120.0 + 2500.0 * 2.0);
    }

    #[test]
    fn tick_step_no_overlap_for_various_scales() {
        // scale=2.0, label_px=40.0 → min_pitch=48 → step=25 (25*2=50 ≥ 48)
        assert_eq!(pick_tick_step(80, 2.0, 40.0), 25);
        // range=79 previously jumped to step=5 (10px pitch) which caused overlap; now stays 25
        assert_eq!(pick_tick_step(79, 2.0, 40.0), 25);
        assert_eq!(pick_tick_step(20, 2.0, 40.0), 25);
        assert_eq!(pick_tick_step(10, 2.0, 40.0), 25);
        // scale=4.0 → step=20 (20*4=80 ≥ 48)
        assert_eq!(pick_tick_step(80, 4.0, 40.0), 20);
        // scale=1.0 → step=50 (50*1=50 ≥ 48)
        assert_eq!(pick_tick_step(100, 1.0, 40.0), 50);
        // scale=0.5 → step=100 (100*0.5=50 ≥ 48)
        assert_eq!(pick_tick_step(2500, 0.5, 40.0), 100);
    }

    #[test]
    fn tick_step_no_overlap_invariant() {
        // Core invariant: step * scale >= label_px + min_gap for all representative combinations.
        let label_px = 40.0_f64;
        let min_gap = 8.0_f64;
        for range in [10_i64, 20, 79, 80] {
            for scale in [0.5_f64, 1.0, 2.0, 4.0] {
                let step = pick_tick_step(range, scale, label_px);
                let pitch = (step as f64) * scale;
                assert!(
                    pitch >= label_px + min_gap,
                    "range={range}, scale={scale}: step={step}, pitch={pitch:.1} < min_pitch={min_pitch}",
                    min_pitch = label_px + min_gap,
                );
            }
        }
    }

    #[test]
    fn div_floor_handles_negative() {
        assert_eq!(div_floor(-500, 100), -5);
        assert_eq!(div_floor(-501, 100), -6);
        assert_eq!(div_floor(501, 100), 5);
    }

    // ─── unit day レンダリング (#248) ─────────────────────────────────

    fn mk_meta_with_unit(unit: &str, range: (i64, i64)) -> tdsl_core::ir::Meta {
        tdsl_core::ir::Meta {
            title: "t".into(),
            unit: unit.into(),
            range,
            calendar: "proleptic_gregorian".into(),
            color_map: std::collections::HashMap::new(),
            ..Default::default()
        }
    }

    #[test]
    fn day_ticks_empty_when_unit_not_day() {
        let ir = TimelineIr {
            meta: mk_meta_with_unit("year", (1939, 1945)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        assert!(layout.day_ticks().is_empty());
    }

    #[test]
    fn day_ticks_empty_when_unit_month() {
        let ir = TimelineIr {
            meta: mk_meta_with_unit("month", (1939, 1945)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        assert!(layout.day_ticks().is_empty());
    }

    #[test]
    fn day_ticks_produced_for_short_unit_day_range() {
        // 1ヶ月分(30日)を大きめスケールで描画 → 1日 step
        let ir = TimelineIr {
            meta: mk_meta_with_unit("day", (1939, 1940)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 365.25 * 6.0, // pixels_per_day = 6 → step=1
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        let ticks = layout.day_ticks();
        // 1939年内+1940年の日々
        assert!(!ticks.is_empty(), "expected day ticks but got none");
        // 1939-01-01 が含まれる
        assert!(ticks.contains(&(1939, 1, 1)));
        // 1939-12-31 が含まれる
        assert!(ticks.contains(&(1939, 12, 31)));
    }

    #[test]
    fn day_ticks_step_thins_for_lower_density() {
        // 中スケール → 1日あたり 3px (step=2): 月初+奇数日が描画される
        let ir = TimelineIr {
            meta: mk_meta_with_unit("day", (1939, 1940)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 365.25 * 3.0,
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        let ticks = layout.day_ticks();
        // 月初は常に含まれる
        assert!(ticks.contains(&(1939, 1, 1)));
        assert!(ticks.contains(&(1939, 2, 1)));
        // step=2 のとき、1, 3, 5, ... のみが描画される
        assert!(ticks.contains(&(1939, 1, 3)));
        assert!(!ticks.contains(&(1939, 1, 2)));
    }

    #[test]
    fn day_ticks_thinning_to_weekly_for_low_density() {
        // pixels_per_day ≈ 1.5 → step=7
        let ir = TimelineIr {
            meta: mk_meta_with_unit("day", (1939, 1940)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 365.25 * 2.0, // pixels_per_day=2 → step=7
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        let ticks = layout.day_ticks();
        // 月初は描画
        assert!(ticks.contains(&(1939, 1, 1)));
        // 1, 8, 15, 22, 29 が含まれる(step=7)
        assert!(ticks.contains(&(1939, 1, 8)));
        // 2, 3, 4 は含まれない
        assert!(!ticks.contains(&(1939, 1, 2)));
        assert!(!ticks.contains(&(1939, 1, 4)));
    }

    #[test]
    fn day_ticks_empty_when_scale_too_small() {
        let ir = TimelineIr {
            meta: mk_meta_with_unit("day", (1900, 2000)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 2.0, // pixels_per_day ≈ 0.0055 → 描画不可
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        assert!(layout.day_ticks().is_empty());
    }

    #[test]
    fn span_uses_start_frac_end_frac_for_year_precision() {
        // `span x 1939..1945` は start=1939-01-01, end=1945-12-31 として描画されるべき
        let ir = TimelineIr {
            meta: mk_meta_with_unit("year", (1900, 2000)),
            lanes: vec![Lane {
                id: "x".into(),
                label: "X".into(),
                kind: "custom".into(),
                order: 1,
                group: None,
                source_span: None,
            }],
            items: vec![Item::Span {
                id: "s1".into(),
                lane: "x".into(),
                start: 1939,
                end: 1945,
                label: "WW2".into(),
                tags: vec![],
                source: None,
                origin: None,
                start_month: None,
                start_day: None,
                end_month: None,
                end_day: None,
                source_span: None,
            }],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        let span = layout
            .items
            .iter()
            .find_map(|i| match i {
                LaidItem::Span { x, width, .. } => Some((*x, *width)),
                _ => None,
            })
            .expect("span should be laid out");
        // start_frac(1939)=1939.0, end_frac(1945)≈1945.998
        // x = left_gutter(120) + (1939-1900)*scale(2) = 120 + 78 = 198
        // width = (end_frac - start_frac) * scale ≈ 6.998 * 2 ≈ 13.996
        assert!(
            (span.0 - 198.0).abs() < 0.01,
            "expected x ≈ 198, got {}",
            span.0
        );
        // 旧実装 (to_year_frac) なら width = (1945 - 1939) * 2 = 12.0、
        // 新実装 (end_frac) なら ≈ 13.996。明確に差が出る。
        assert!(
            span.1 > 13.0,
            "expected width > 13 (end-of-year extension), got {}",
            span.1
        );
    }

    #[test]
    fn lane_y_ordered_by_order_field() {
        let ir = TimelineIr {
            meta: mk_meta((-100, 100)),
            lanes: vec![
                Lane {
                    id: "b".into(),
                    label: "B".into(),
                    kind: "k".into(),
                    order: 20,
                    group: None,
                    source_span: None,
                },
                Lane {
                    id: "a".into(),
                    label: "A".into(),
                    kind: "k".into(),
                    order: 10,
                    group: None,
                    source_span: None,
                },
            ],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        let ya = layout.lane_y["a"];
        let yb = layout.lane_y["b"];
        assert!(
            ya < yb,
            "lane a (order 10) should be above lane b (order 20)"
        );
    }

    #[test]
    fn empty_ir_does_not_panic() {
        let ir = TimelineIr {
            meta: mk_meta((0, 100)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        assert!(layout.items.is_empty());
    }

    #[test]
    fn span_clamps_to_range() {
        let (x, w) = primary_axis_segment(-600.0, 300.0, -500, 200, 2.0, 120.0);
        // start clamped to -500 → x=120
        assert_eq!(x, 120.0);
        // end clamped to 200 → width = (200-(-500))*2 = 1400
        assert_eq!(w, 1400.0);
    }

    #[test]
    fn primary_axis_segment_matches_anchor_for_vertical() {
        // Same arithmetic as the horizontal case but with a different anchor
        // (top_margin instead of left_gutter); ensures the unified helper
        // covers the orientation that previously had its own
        // span_y_height_frac_vertical implementation.
        let (y, h) = primary_axis_segment(-600.0, 300.0, -500, 200, 2.0, 40.0);
        assert_eq!(y, 40.0);
        assert_eq!(h, 1400.0);
    }

    #[test]
    fn month_precision_shifts_x_position() {
        // February (month=2) should be 1/12 of a year to the right of January (no month).
        let x_jan = frac_to_x(to_year_frac(100, None, None), 0, 2.0, 0.0);
        let x_feb = frac_to_x(to_year_frac(100, Some(2), None), 0, 2.0, 0.0);
        assert!((x_feb - x_jan - 2.0 / 12.0).abs() < 0.001);
    }

    // ─── to_year_frac 精度テスト ──────────────────────────────────────────

    #[test]
    fn to_year_frac_year_only() {
        // 年のみ指定: フラクショナル値 = 整数年
        assert_eq!(to_year_frac(1939, None, None), 1939.0);
        assert_eq!(to_year_frac(-206, None, None), -206.0);
        assert_eq!(to_year_frac(0, None, None), 0.0);
    }

    #[test]
    fn to_year_frac_with_month() {
        // month=1 は +0/12、month=7 は +6/12 ≈ +0.5
        assert_eq!(to_year_frac(1939, Some(1), None), 1939.0);
        let mid = to_year_frac(1939, Some(7), None);
        assert!(
            (mid - 1939.5).abs() < 0.001,
            "month=7 should be ~0.5 offset, got {mid}"
        );
        // month=12 は +11/12 ≈ +0.917
        let dec = to_year_frac(1939, Some(12), None);
        assert!(
            (dec - (1939.0 + 11.0 / 12.0)).abs() < 0.001,
            "month=12 offset wrong, got {dec}"
        );
    }

    #[test]
    fn to_year_frac_with_month_and_day() {
        // month=1, day=1: オフセットなし
        assert_eq!(to_year_frac(1939, Some(1), Some(1)), 1939.0);
        // month=1, day=2: +1/365.25 オフセット
        let d2 = to_year_frac(1939, Some(1), Some(2));
        assert!(
            (d2 - (1939.0 + 1.0 / 365.25)).abs() < 0.0001,
            "day=2 offset wrong, got {d2}"
        );
        // month=3, day=15: month offset + day offset
        let m3d15 = to_year_frac(1939, Some(3), Some(15));
        let expected = 1939.0 + 2.0 / 12.0 + 14.0 / 365.25;
        assert!(
            (m3d15 - expected).abs() < 0.0001,
            "month=3,day=15 wrong, got {m3d15}"
        );
    }

    // ─── month_ticks テスト ──────────────────────────────────────────────

    #[test]
    fn month_ticks_empty_when_unit_not_month() {
        let ir = TimelineIr {
            meta: mk_meta_with_unit("year", (1939, 1945)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        assert!(layout.month_ticks().is_empty());
    }

    #[test]
    fn month_ticks_empty_when_scale_too_small() {
        // scale/12 < 1.0 のとき空配列
        let ir = TimelineIr {
            meta: mk_meta_with_unit("month", (1939, 1945)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 6.0, // 6/12 = 0.5 < 1.0
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        assert!(layout.month_ticks().is_empty());
    }

    #[test]
    fn month_ticks_produced_for_month_unit_sufficient_scale() {
        // scale/12 >= 1.0 のとき month=2..=12 のティックを返す
        let ir = TimelineIr {
            meta: mk_meta_with_unit("month", (1939, 1940)),
            lanes: vec![],
            items: vec![],
            imports: vec![],
            sources: vec![],
        };
        let opts = RenderOptions {
            scale: 24.0, // 24/12 = 2.0 >= 1.0
            ..RenderOptions::default()
        };
        let layout = LayoutModel::compute(&ir, opts);
        let ticks = layout.month_ticks();
        assert!(!ticks.is_empty(), "expected month ticks for month unit");
        // 月初 (month=1) はティックに含まれない(年目盛と重複回避)
        assert!(
            !ticks.contains(&(1939, 1)),
            "month=1 should not appear in month_ticks"
        );
        // February は含まれる
        assert!(
            ticks.contains(&(1939, 2)),
            "expected (1939,2) in month_ticks"
        );
        // December は含まれる
        assert!(
            ticks.contains(&(1939, 12)),
            "expected (1939,12) in month_ticks"
        );
    }

    #[test]
    fn event_outside_range_is_skipped() {
        let ir = TimelineIr {
            meta: mk_meta((0, 100)),
            lanes: vec![Lane {
                id: "x".into(),
                label: "X".into(),
                kind: "k".into(),
                order: 1,
                group: None,
                source_span: None,
            }],
            items: vec![Item::Event {
                id: "e1".into(),
                lane: "x".into(),
                time: 500,
                label: "outside".into(),
                tags: vec![],
                source: None,
                origin: None,
                time_month: None,
                time_day: None,
                source_span: None,
            }],
            imports: vec![],
            sources: vec![],
        };
        let layout = LayoutModel::compute(&ir, RenderOptions::default());
        assert!(layout.items.is_empty());
    }
}