teksilo-data 0.9.1

Reactive data models for Teksilo — list, tree, selection and sort-filter projections, with no GUI dependency.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `ChartModel<T>` — concrete reactive multi-series chart data model.
//!
//! `ChartModel<T>` owns an ordered collection of named series, each holding a
//! `Vec<ChartDatum<T>>` (a `category: T` paired with a numeric `value: f32`),
//! in a flat SlotMap arena — the same shape as [`crate::TreeModel`]. Every
//! mutation (series add/remove/move/rename/recolor/show-hide, point
//! push/insert/remove/update/replace) emits a [`ChartChange`] to all
//! registered observers *and* bumps one of two reactive version signals:
//! [`ChartModel::style_version`] (color changes only — a paint-only signal a
//! chart can bind at `BindingLevel::RepaintOnly`) or
//! [`ChartModel::structure_version`] (everything else — series/point shape,
//! bound at `BindingLevel::Relayout`/`Rebuild`). Series identity is a stable,
//! versioned [`SeriesId`] (a SlotMap key) that is never reused after removal.
//!
//! Cloning produces a second handle to the **same** data — all handles share
//! series/points and receive the same change notifications. Register
//! observers via [`observe_changes`](ChartModel::observe_changes); the
//! returned `ObserverHandle` is RAII — dropping it unregisters the callback.
//!
//! For a bounded "last N points" streaming view use
//! [`ChartWindow`](crate::ChartWindow). For bucketed/rolled-up display use
//! [`ChartAggregate`](crate::ChartAggregate). For point-level selection use
//! [`ChartSelection`](crate::ChartSelection).
//!
//! ```rust
//! # use teksilo_data::{ChartModel, ChartSeries, ChartDatum};
//! let model = ChartModel::from_series_vec(vec![
//!     ChartSeries::new("Revenue").data(vec![
//!         ChartDatum::new("Q1".to_string(), 10.0),
//!         ChartDatum::new("Q2".to_string(), 20.0),
//!     ]),
//! ]);
//! assert_eq!(model.series_count(), 1);
//! let s = model.series_id_at(0).unwrap();
//! assert_eq!(model.point_count(s), 2);
//!
//! model.push_point(s, "Q3".to_string(), 30.0);
//! assert_eq!(model.point_count(s), 3);
//! ```

use std::cell::RefCell;
use std::rc::Rc;

use slotmap::SlotMap;

use teksilo_core::ObserverHandle;
use teksilo_core::color_prop::ColorProp;
use teksilo_core::signal::Signal;

use crate::chart_change::{ChartChange, SeriesId};
use crate::series_pattern::SeriesPattern;

/// One numeric data point at a category/x-axis position, with an optional
/// per-point color that overrides the series color (bar charts only).
#[derive(Debug, Clone)]
pub struct ChartDatum<T> {
    pub category: T,
    pub value: f32,
    pub color: Option<ColorProp>,
}

impl<T> ChartDatum<T> {
    pub fn new(category: T, value: f32) -> Self {
        Self {
            category,
            value,
            color: None,
        }
    }

    /// Override this point's color (a bar's fill). Ignored by line/pie charts,
    /// which color by series.
    pub fn with_color(mut self, color: impl Into<ColorProp>) -> Self {
        self.color = Some(color.into());
        self
    }
}

/// A named series of data points with an optional explicit color and a
/// visibility flag, used to construct a [`ChartModel`] (via
/// [`ChartModel::from_series_vec`]) or to describe one series' desired
/// shape. Unlike the model, `visible` here is a plain `bool` — reactivity
/// lives in the model's [`ChartModel::structure_version`] /
/// [`ChartModel::style_version`] signals, not in this construction DTO.
pub struct ChartSeries<T> {
    pub name: String,
    pub color: Option<ColorProp>,
    /// The non-colour channel identifying this series — a dash pattern on a
    /// line, a marker shape on a point, a hatch on a filled region. `None`
    /// takes the pattern for the series' position
    /// ([`SeriesPattern::for_index`]), which is why the channel exists even
    /// with no application code. Set it when a series' identity must survive a
    /// reorder. See [`SeriesPattern`].
    pub pattern: Option<SeriesPattern>,
    pub visible: bool,
    pub points: Vec<ChartDatum<T>>,
}

impl<T> std::fmt::Debug for ChartSeries<T>
where
    T: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChartSeries")
            .field("name", &self.name)
            .field("pattern", &self.pattern)
            .field("visible", &self.visible)
            .field("len", &self.points.len())
            .finish()
    }
}

impl<T> Clone for ChartSeries<T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            color: self.color.clone(),
            pattern: self.pattern,
            visible: self.visible,
            points: self.points.clone(),
        }
    }
}

impl<T> ChartSeries<T> {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            color: None,
            pattern: None,
            visible: true,
            points: Vec::new(),
        }
    }

    pub fn color(mut self, color: impl Into<ColorProp>) -> Self {
        self.color = Some(color.into());
        self
    }

    /// Pin this series' non-colour channel instead of taking the one its
    /// position implies. See [`SeriesPattern`].
    pub fn pattern(mut self, pattern: SeriesPattern) -> Self {
        self.pattern = Some(pattern);
        self
    }

    pub fn visibility(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    pub fn push(&mut self, category: T, value: f32) {
        self.points.push(ChartDatum::new(category, value));
    }

    pub fn data(mut self, points: Vec<ChartDatum<T>>) -> Self {
        self.points = points;
        self
    }
}

/// A read-only, borrowed view over one series — returned by
/// [`ChartModel::with_series_view`] / [`ChartModel::with_all_series`].
pub struct SeriesView<'a, T> {
    pub id: SeriesId,
    pub name: &'a str,
    pub color: Option<&'a ColorProp>,
    /// The series' explicit non-colour channel, or `None` to take the one its
    /// position implies. See [`SeriesPattern`].
    pub pattern: Option<SeriesPattern>,
    pub visible: bool,
    pub points: &'a [ChartDatum<T>],
}

struct SeriesEntry<T> {
    name: String,
    color: Option<ColorProp>,
    pattern: Option<SeriesPattern>,
    visible: bool,
    points: Vec<ChartDatum<T>>,
}

struct ObserverEntry {
    id: u64,
    callback: Rc<dyn Fn(&ChartChange)>,
}

/// Structural equality for `ColorProp`, which has no general `PartialEq`
/// (a `Signal` carries no value-equality of its own). `Static`/role variants
/// compare by value; `Bound`/`Dynamic*` variants compare by `Signal`
/// identity ([`Signal::same`]). Anything else (different variants, or
/// either side `Undimmed`) is conservatively "different" so a genuine value
/// swap is never mistaken for a no-op — used only to gate the idempotency
/// short-circuit in [`ChartModel::set_series_color`].
fn color_prop_eq(a: &ColorProp, b: &ColorProp) -> bool {
    match (a, b) {
        (ColorProp::Static(x), ColorProp::Static(y)) => x == y,
        (ColorProp::Bound(x), ColorProp::Bound(y)) => Signal::same(x, y),
        (ColorProp::TextRole(x), ColorProp::TextRole(y)) => x == y,
        (ColorProp::SurfaceRole(x), ColorProp::SurfaceRole(y)) => x == y,
        (ColorProp::BorderRole(x), ColorProp::BorderRole(y)) => x == y,
        (ColorProp::DynamicTextRole(x), ColorProp::DynamicTextRole(y)) => Signal::same(x, y),
        (ColorProp::DynamicSurfaceRole(x), ColorProp::DynamicSurfaceRole(y)) => Signal::same(x, y),
        (ColorProp::DynamicBorderRole(x), ColorProp::DynamicBorderRole(y)) => Signal::same(x, y),
        _ => false,
    }
}

struct ChartModelInner<T> {
    arena: SlotMap<slotmap::DefaultKey, SeriesEntry<T>>,
    order: Vec<SeriesId>,
    observers: Vec<ObserverEntry>,
    next_observer_id: u64,
    /// Structural version — bumped by every mutation except a color change.
    structure_version: Signal<u64>,
    /// Style version — bumped only by `SeriesColorChanged`.
    style_version: Signal<u64>,
    /// Strong handle to the debug-registry adapter for this model. Owned
    /// here so that the registration drops automatically when the inner is
    /// freed (the adapter holds only a `Weak` to inner, breaking the
    /// cycle). `None` until `.debug_named()` is called. Compiled out in
    /// release.
    #[cfg(debug_assertions)]
    debug_adapter: Option<Rc<dyn crate::debug_registry::ModelDebug>>,
}

/// A concrete reactive multi-series chart data model.
///
/// `ChartModel<T>` is `Clone` — cloning produces a second handle to the same
/// data. Multiple charts can hold clones and all see the same series and
/// points, and receive the same [`ChartChange`] notifications.
pub struct ChartModel<T: 'static> {
    inner: Rc<RefCell<ChartModelInner<T>>>,
}

impl<T: 'static> ChartModel<T> {
    /// Create an empty chart model with no series.
    pub fn new() -> Self {
        Self {
            inner: Rc::new(RefCell::new(ChartModelInner {
                arena: SlotMap::new(),
                order: Vec::new(),
                observers: Vec::new(),
                next_observer_id: 1,
                structure_version: Signal::new(0),
                style_version: Signal::new(0),
                #[cfg(debug_assertions)]
                debug_adapter: None,
            })),
        }
    }

    /// Build a model directly from a vector of [`ChartSeries`] DTOs — the
    /// primary constructor. Populates the arena in one pass with no
    /// per-item notification (mirrors [`crate::ListModel::from_vec`]).
    pub fn from_series_vec(series: Vec<ChartSeries<T>>) -> Self {
        let model = Self::new();
        {
            let mut guard = model.inner.borrow_mut();
            for s in series {
                let key = guard.arena.insert(SeriesEntry {
                    name: s.name,
                    color: s.color,
                    pattern: s.pattern,
                    visible: s.visible,
                    points: s.points,
                });
                let id = SeriesId::from_key(key);
                guard.order.push(id);
            }
        }
        model
    }

    /// Build a model with a single anonymous, visible series holding
    /// `points` — the flat/pie-chart path where series structure doesn't
    /// matter.
    pub fn from_points(points: Vec<ChartDatum<T>>) -> Self {
        Self::from_series_vec(vec![ChartSeries::new(String::new()).data(points)])
    }

    /// The model's sole series id, iff it has exactly one series.
    pub fn only_series(&self) -> Option<SeriesId> {
        let guard = self.inner.borrow();
        if guard.order.len() == 1 {
            Some(guard.order[0])
        } else {
            None
        }
    }

    // --- Series mutations ---

    /// Append a new, empty, visible series named `name`.
    pub fn add_series(&self, name: impl Into<String>) -> SeriesId {
        let (id, index) = {
            let mut guard = self.inner.borrow_mut();
            let key = guard.arena.insert(SeriesEntry {
                name: name.into(),
                color: None,
                pattern: None,
                visible: true,
                points: Vec::new(),
            });
            let id = SeriesId::from_key(key);
            let index = guard.order.len();
            guard.order.push(id);
            (id, index)
        };
        self.notify(ChartChange::SeriesInserted { index, series: id });
        self.bump_structure();
        id
    }

    /// Insert a new, empty, visible series named `name` at `index`.
    ///
    /// # Panics
    /// Panics if `index > series_count()`.
    pub fn insert_series(&self, index: usize, name: impl Into<String>) -> SeriesId {
        let id = {
            let mut guard = self.inner.borrow_mut();
            let key = guard.arena.insert(SeriesEntry {
                name: name.into(),
                color: None,
                pattern: None,
                visible: true,
                points: Vec::new(),
            });
            let id = SeriesId::from_key(key);
            guard.order.insert(index, id);
            id
        };
        self.notify(ChartChange::SeriesInserted { index, series: id });
        self.bump_structure();
        id
    }

    /// Remove a series and all of its points.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn remove_series(&self, series: SeriesId) {
        {
            let mut guard = self.inner.borrow_mut();
            guard.arena.remove(series.key()).expect("unknown SeriesId");
            guard.order.retain(|&id| id != series);
        }
        self.notify(ChartChange::SeriesRemoved { series });
        self.bump_structure();
    }

    /// Rename a series. A no-op (no notify, no version bump) if `name`
    /// already matches the current value.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn rename_series(&self, series: SeriesId, name: impl Into<String>) {
        let name = name.into();
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry.name == name {
                false
            } else {
                entry.name = name;
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesRenamed { series });
        self.bump_structure();
    }

    /// Set a series' explicit color. Bumps [`Self::style_version`] (not
    /// [`Self::structure_version`]) — this is a paint-only change. A no-op
    /// (no notify, no version bump) if `color` already matches the current
    /// value.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn set_series_color(&self, series: SeriesId, color: impl Into<ColorProp>) {
        let color = color.into();
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry
                .color
                .as_ref()
                .is_some_and(|c| color_prop_eq(c, &color))
            {
                false
            } else {
                entry.color = Some(color);
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesColorChanged { series });
        self.bump_style();
    }

    /// Clear a series' explicit color (falls back to the chart's palette).
    /// Bumps [`Self::style_version`]. A no-op (no notify, no version bump)
    /// if the series already has no explicit color.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn clear_series_color(&self, series: SeriesId) {
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry.color.is_none() {
                false
            } else {
                entry.color = None;
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesColorChanged { series });
        self.bump_style();
    }

    /// Set a series' explicit [`SeriesPattern`] — the non-colour channel that
    /// identifies it. Bumps [`Self::style_version`] (paint-only), like
    /// [`set_series_color`](Self::set_series_color). A no-op if unchanged.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn set_series_pattern(&self, series: SeriesId, pattern: SeriesPattern) {
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry.pattern == Some(pattern) {
                false
            } else {
                entry.pattern = Some(pattern);
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesPatternChanged { series });
        self.bump_style();
    }

    /// Clear a series' explicit pattern, falling back to the one its position
    /// implies. Bumps [`Self::style_version`]. A no-op if already unset.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn clear_series_pattern(&self, series: SeriesId) {
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry.pattern.is_none() {
                false
            } else {
                entry.pattern = None;
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesPatternChanged { series });
        self.bump_style();
    }

    /// Show or hide a series. A no-op (no notify, no version bump) if
    /// `visible` already matches the current value.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn set_series_visible(&self, series: SeriesId, visible: bool) {
        let changed = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            if entry.visible == visible {
                false
            } else {
                entry.visible = visible;
                true
            }
        };
        if !changed {
            return;
        }
        self.notify(ChartChange::SeriesVisibilityChanged { series });
        self.bump_structure();
    }

    /// Move a series to a new position among its siblings. A no-op (no
    /// notify, no version bump) if `to` is already the series' position.
    ///
    /// # Panics
    /// Panics if `series` is unknown or `to` is out of bounds.
    pub fn move_series(&self, series: SeriesId, to: usize) {
        let from = {
            let guard = self.inner.borrow();
            guard
                .order
                .iter()
                .position(|&id| id == series)
                .expect("unknown SeriesId")
        };
        if from == to {
            return;
        }
        {
            let mut guard = self.inner.borrow_mut();
            let id = guard.order.remove(from);
            guard.order.insert(to, id);
        }
        self.notify(ChartChange::SeriesMoved { series, from, to });
        self.bump_structure();
    }

    /// Remove every series.
    pub fn clear(&self) {
        {
            let mut guard = self.inner.borrow_mut();
            guard.arena.clear();
            guard.order.clear();
        }
        self.notify(ChartChange::Reset);
        self.bump_structure();
    }

    // --- Point mutations ---

    /// Append a point to the end of `series`.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn push_point(&self, series: SeriesId, category: T, value: f32) {
        let index = {
            let mut guard = self.inner.borrow_mut();
            let entry = &mut guard.arena[series.key()];
            let index = entry.points.len();
            entry.points.push(ChartDatum::new(category, value));
            index
        };
        self.notify(ChartChange::PointsInserted {
            series,
            range: index..index + 1,
        });
        self.bump_structure();
    }

    /// Insert a point at `index` within `series`.
    ///
    /// # Panics
    /// Panics if `series` is unknown or `index > point_count(series)`.
    pub fn insert_point(&self, series: SeriesId, index: usize, category: T, value: f32) {
        {
            let mut guard = self.inner.borrow_mut();
            guard.arena[series.key()]
                .points
                .insert(index, ChartDatum::new(category, value));
        }
        self.notify(ChartChange::PointsInserted {
            series,
            range: index..index + 1,
        });
        self.bump_structure();
    }

    /// Remove and return the point at `index` within `series`.
    ///
    /// # Panics
    /// Panics if `series` is unknown or `index >= point_count(series)`.
    pub fn remove_point(&self, series: SeriesId, index: usize) -> ChartDatum<T> {
        let datum = {
            let mut guard = self.inner.borrow_mut();
            guard.arena[series.key()].points.remove(index)
        };
        self.notify(ChartChange::PointsRemoved {
            series,
            range: index..index + 1,
        });
        self.bump_structure();
        datum
    }

    /// Replace the point at `index` within `series`.
    ///
    /// # Panics
    /// Panics if `series` is unknown or `index >= point_count(series)`.
    pub fn update_point(&self, series: SeriesId, index: usize, category: T, value: f32) {
        {
            let mut guard = self.inner.borrow_mut();
            guard.arena[series.key()].points[index] = ChartDatum::new(category, value);
        }
        self.notify(ChartChange::PointUpdated { series, index });
        self.bump_structure();
    }

    /// Replace `series`' entire point list.
    ///
    /// # Panics
    /// Panics if `series` is unknown.
    pub fn replace_series_data(&self, series: SeriesId, points: Vec<ChartDatum<T>>) {
        {
            let mut guard = self.inner.borrow_mut();
            guard.arena[series.key()].points = points;
        }
        self.notify(ChartChange::SeriesDataReplaced { series });
        self.bump_structure();
    }

    // --- Queries ---

    /// Number of series.
    pub fn series_count(&self) -> usize {
        self.inner.borrow().order.len()
    }

    /// The series ids, in display order.
    pub fn series_ids(&self) -> Vec<SeriesId> {
        self.inner.borrow().order.clone()
    }

    /// The series id at `index`, if any.
    pub fn series_id_at(&self, index: usize) -> Option<SeriesId> {
        self.inner.borrow().order.get(index).copied()
    }

    /// The display index of `series`, if it exists.
    pub fn series_index_of(&self, series: SeriesId) -> Option<usize> {
        self.inner
            .borrow()
            .order
            .iter()
            .position(|&id| id == series)
    }

    /// Number of points in `series` (0 if unknown).
    pub fn point_count(&self, series: SeriesId) -> usize {
        self.inner
            .borrow()
            .arena
            .get(series.key())
            .map(|e| e.points.len())
            .unwrap_or(0)
    }

    /// Access a series' metadata (name, color, visibility) via a callback.
    /// Returns `None` if `series` is unknown.
    pub fn with_series<R>(
        &self,
        series: SeriesId,
        f: impl FnOnce(&str, Option<&ColorProp>, bool) -> R,
    ) -> Option<R> {
        let guard = self.inner.borrow();
        guard
            .arena
            .get(series.key())
            .map(|e| f(&e.name, e.color.as_ref(), e.visible))
    }

    /// Access a point within `series` via a callback. Returns `None` if the
    /// series or index is unknown.
    pub fn with_point<R>(
        &self,
        series: SeriesId,
        index: usize,
        f: impl FnOnce(&ChartDatum<T>) -> R,
    ) -> Option<R> {
        let guard = self.inner.borrow();
        guard
            .arena
            .get(series.key())
            .and_then(|e| e.points.get(index))
            .map(f)
    }

    /// Access a whole-series view (metadata + points slice) via a callback.
    /// Returns `None` if `series` is unknown.
    pub fn with_series_view<R>(
        &self,
        series: SeriesId,
        f: impl FnOnce(SeriesView<'_, T>) -> R,
    ) -> Option<R> {
        let guard = self.inner.borrow();
        guard.arena.get(series.key()).map(|e| {
            f(SeriesView {
                id: series,
                name: &e.name,
                color: e.color.as_ref(),
                pattern: e.pattern,
                visible: e.visible,
                points: &e.points,
            })
        })
    }

    /// Access every series as an ordered slice of views via a callback.
    pub fn with_all_series<R>(&self, f: impl FnOnce(&[SeriesView<'_, T>]) -> R) -> R {
        let guard = self.inner.borrow();
        let views: Vec<SeriesView<'_, T>> = guard
            .order
            .iter()
            .filter_map(|&id| {
                guard.arena.get(id.key()).map(|e| SeriesView {
                    id,
                    name: &e.name,
                    color: e.color.as_ref(),
                    pattern: e.pattern,
                    visible: e.visible,
                    points: &e.points,
                })
            })
            .collect();
        f(&views)
    }

    // --- Reactivity ---

    /// Structural version signal — bumped by every mutation except a color
    /// change (series add/remove/move/rename/show-hide, all point ops).
    /// Bind at `BindingLevel::Relayout` or `Rebuild`.
    ///
    /// Ordering: every mutator notifies the `ChartChange` observers
    /// registered via [`Self::observe_changes`] *before* bumping this
    /// signal — see the note on `observe_changes` for what that means for a
    /// callback that reads the signal back synchronously.
    pub fn structure_version(&self) -> Signal<u64> {
        self.inner.borrow().structure_version.clone()
    }

    /// Style version signal — bumped only by a series color change. Bind at
    /// `BindingLevel::RepaintOnly`. Same notify-before-bump ordering as
    /// [`Self::structure_version`] — see [`Self::observe_changes`].
    pub fn style_version(&self) -> Signal<u64> {
        self.inner.borrow().style_version.clone()
    }

    /// Register an observer that is called on every mutation.
    /// Returns an `ObserverHandle` — dropping it removes the callback.
    ///
    /// **Ordering contract:** every mutator calls this observer *before*
    /// bumping [`Self::structure_version`] / [`Self::style_version`] (see
    /// e.g. `rename_series`, `push_point`) — notify, then bump. This is
    /// intentional, not an implementation accident: it lets a `ChartChange`
    /// callback distinguish "did I get here via the change I'm reacting to"
    /// from "did something else bump the version already", by comparing the
    /// version signal's value inside the callback against a value captured
    /// before the mutation. The flip side: a callback that reads
    /// `structure_version()`/`style_version()` synchronously **inside**
    /// itself always observes the **pre-bump** value for the mutation
    /// currently being notified — the bump hasn't happened yet. Don't use
    /// the version signal from inside a `ChartChange` observer as a proxy
    /// for "has this specific mutation been applied" — the `ChartChange`
    /// argument already tells you that; use the signal for *external*
    /// bind-and-rerun consumers (widgets), not from within the notify path
    /// itself.
    pub fn observe_changes(&self, f: impl Fn(&ChartChange) + 'static) -> ObserverHandle {
        let mut guard = self.inner.borrow_mut();
        let id = guard.next_observer_id;
        guard.next_observer_id += 1;
        guard.observers.push(ObserverEntry {
            id,
            callback: Rc::new(f),
        });
        let inner = self.inner.clone();
        ObserverHandle::new(
            self.inner.clone(),
            id,
            Rc::new(move |observer_id| {
                inner.borrow_mut().observers.retain(|e| e.id != observer_id);
            }),
        )
    }

    fn notify(&self, change: ChartChange) {
        let callbacks: Vec<Rc<dyn Fn(&ChartChange)>> = self
            .inner
            .borrow()
            .observers
            .iter()
            .map(|e| e.callback.clone())
            .collect();
        for cb in &callbacks {
            cb(&change);
        }
    }

    /// Bump `structure_version`. Clones the signal handle under a short
    /// borrow and drops it before calling `.set(...)` — an observer bound
    /// to the signal may read back into this model, and holding the
    /// `RefCell` borrow across that call would panic (re-entrant borrow).
    fn bump_structure(&self) {
        let sig = self.inner.borrow().structure_version.clone();
        sig.set(sig.get().wrapping_add(1));
    }

    /// Bump `style_version`. Same drop-borrow-before-set discipline as
    /// [`Self::bump_structure`].
    fn bump_style(&self) {
        let sig = self.inner.borrow().style_version.clone();
        sig.set(sig.get().wrapping_add(1));
    }
}

impl<T: std::fmt::Debug + 'static> ChartModel<T> {
    /// Register this model with the debug inspector under `name`. In
    /// release builds (`!cfg(debug_assertions)`) this is a no-op
    /// pass-through so call sites stay free of `#[cfg]` lines.
    ///
    /// Idempotent on repeated calls — the latest registration wins.
    /// The registration drops automatically when the last `ChartModel`
    /// handle is freed (the adapter the registry holds is `Weak`).
    pub fn debug_named(self, _name: impl Into<String>) -> Self {
        #[cfg(debug_assertions)]
        {
            let weak = Rc::downgrade(&self.inner);
            let adapter: Rc<dyn crate::debug_registry::ModelDebug> =
                Rc::new(ChartModelDebug::<T> { weak });
            let name = _name.into();
            crate::debug_registry::register(name, Rc::downgrade(&adapter));
            self.inner.borrow_mut().debug_adapter = Some(adapter);
        }
        self
    }
}

#[cfg(debug_assertions)]
struct ChartModelDebug<T> {
    weak: std::rc::Weak<RefCell<ChartModelInner<T>>>,
}

#[cfg(debug_assertions)]
impl<T: std::fmt::Debug + 'static> crate::debug_registry::ModelDebug for ChartModelDebug<T> {
    fn kind(&self) -> &'static str {
        "ChartModel"
    }
    fn len(&self) -> usize {
        self.weak
            .upgrade()
            .map(|inner| inner.borrow().arena.values().map(|e| e.points.len()).sum())
            .unwrap_or(0)
    }
    fn debug_dump(&self, out: &mut dyn std::fmt::Write) {
        let Some(inner) = self.weak.upgrade() else {
            return;
        };
        let guard = inner.borrow();
        for (i, &id) in guard.order.iter().enumerate() {
            if let Some(e) = guard.arena.get(id.key()) {
                let _ = writeln!(
                    out,
                    "[{}] {:?} ({} pts, visible={})",
                    i,
                    e.name,
                    e.points.len(),
                    e.visible
                );
            }
        }
    }
}

impl<T: 'static> Default for ChartModel<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: 'static> Clone for ChartModel<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: std::fmt::Debug + 'static> std::fmt::Debug for ChartModel<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let guard = self.inner.borrow();
        f.debug_struct("ChartModel")
            .field("series_count", &guard.order.len())
            .finish()
    }
}

#[cfg(test)]
impl<T: 'static> ChartModel<T> {
    /// Test-only introspection: number of live observers. Not part of the
    /// public API surface.
    pub(crate) fn observer_count(&self) -> usize {
        self.inner.borrow().observers.len()
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use super::*;

    #[test]
    fn datum_with_color_sets_a_per_point_override() {
        use teksilo_core::color_prop::ColorProp;
        use teksilo_tokens::SurfaceRole;
        let plain = ChartDatum::new("Q1".to_string(), 5.0);
        assert!(plain.color.is_none(), "a plain datum has no color override");
        let colored = ChartDatum::new("Q1".to_string(), 5.0).with_color(SurfaceRole::StatusError);
        assert!(matches!(
            colored.color,
            Some(ColorProp::SurfaceRole(SurfaceRole::StatusError))
        ));
        // The 2-arg constructor is unchanged, so existing call sites still compile.
        let _ = ChartDatum::new("Q2".to_string(), 1.0);
    }

    fn sample() -> (ChartModel<String>, SeriesId, SeriesId) {
        let model = ChartModel::from_series_vec(vec![
            ChartSeries::new("Revenue").data(vec![
                ChartDatum::new("Q1".to_string(), 10.0),
                ChartDatum::new("Q2".to_string(), 20.0),
            ]),
            ChartSeries::new("Costs").data(vec![ChartDatum::new("Q1".to_string(), 5.0)]),
        ]);
        let a = model.series_id_at(0).unwrap();
        let b = model.series_id_at(1).unwrap();
        (model, a, b)
    }

    #[test]
    fn from_series_vec_builds_correctly() {
        let (model, a, b) = sample();
        assert_eq!(model.series_count(), 2);
        assert_eq!(model.point_count(a), 2);
        assert_eq!(model.point_count(b), 1);
        assert_eq!(
            model.with_series(a, |name, _, visible| (name.to_string(), visible)),
            Some(("Revenue".to_string(), true))
        );
    }

    #[test]
    fn new_is_empty() {
        let model: ChartModel<String> = ChartModel::new();
        assert_eq!(model.series_count(), 0);
        assert_eq!(model.only_series(), None);
    }

    #[test]
    fn only_series_some_iff_exactly_one() {
        let model: ChartModel<String> = ChartModel::new();
        assert_eq!(model.only_series(), None);
        let a = model.add_series("A");
        assert_eq!(model.only_series(), Some(a));
        model.add_series("B");
        assert_eq!(model.only_series(), None);
    }

    #[test]
    fn from_points_builds_single_anonymous_series() {
        let model = ChartModel::from_points(vec![
            ChartDatum::new("a".to_string(), 1.0),
            ChartDatum::new("b".to_string(), 2.0),
        ]);
        assert_eq!(model.series_count(), 1);
        let s = model.only_series().unwrap();
        assert_eq!(model.point_count(s), 2);
        assert_eq!(model.with_series(s, |_, _, visible| visible), Some(true));
    }

    fn track_changes(
        model: &ChartModel<String>,
    ) -> (Rc<RefCell<Vec<ChartChange>>>, ObserverHandle) {
        let log: Rc<RefCell<Vec<ChartChange>>> = Rc::new(RefCell::new(Vec::new()));
        let l = log.clone();
        let handle = model.observe_changes(move |c| l.borrow_mut().push(c.clone()));
        (log, handle)
    }

    #[test]
    fn add_series_emits_inserted_and_bumps_structure() {
        let model: ChartModel<String> = ChartModel::new();
        let structure = model.structure_version();
        let style = model.style_version();
        let (log, _handle) = track_changes(&model);

        let s = model.add_series("A");
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesInserted {
                index: 0,
                series: s
            }
        );
        assert_eq!(structure.get(), 1);
        assert_eq!(style.get(), 0);
    }

    #[test]
    fn observer_sees_pre_bump_structure_version_during_notify() {
        let model: ChartModel<String> = ChartModel::new();
        let structure = model.structure_version();
        let seen_during_callback: Rc<Cell<Option<u64>>> = Rc::new(Cell::new(None));
        let seen = seen_during_callback.clone();
        let sig = structure.clone();
        let _handle = model.observe_changes(move |_| seen.set(Some(sig.get())));

        let before = structure.get();
        model.add_series("A");
        let after = structure.get();

        assert_eq!(after, before + 1, "the mutation did bump the signal");
        assert_eq!(
            seen_during_callback.get(),
            Some(before),
            "notify runs before the version bump, so a ChartChange observer \
             reading structure_version() synchronously sees the pre-bump value"
        );
    }

    #[test]
    fn observer_sees_pre_bump_style_version_during_notify() {
        let (model, a, _b) = sample();
        let style = model.style_version();
        let seen_during_callback: Rc<Cell<Option<u64>>> = Rc::new(Cell::new(None));
        let seen = seen_during_callback.clone();
        let sig = style.clone();
        let _handle = model.observe_changes(move |_| seen.set(Some(sig.get())));

        let before = style.get();
        model.set_series_color(a, test_color());
        let after = style.get();

        assert_eq!(after, before + 1);
        assert_eq!(seen_during_callback.get(), Some(before));
    }

    #[test]
    fn insert_series_at_index() {
        let (model, a, b) = sample();
        let c = model.insert_series(1, "Middle");
        assert_eq!(model.series_ids(), vec![a, c, b]);
    }

    #[test]
    fn remove_series_emits_removed_and_bumps_structure() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.remove_series(a);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(log.borrow()[0], ChartChange::SeriesRemoved { series: a });
        assert_eq!(model.series_count(), 1);
        assert!(model.structure_version().get() > structure_before);
    }

    #[test]
    fn rename_series_emits_renamed_and_bumps_structure() {
        let (model, a, _b) = sample();
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.rename_series(a, "New Name");
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(log.borrow()[0], ChartChange::SeriesRenamed { series: a });
        assert_eq!(
            model.with_series(a, |name, _, _| name.to_string()),
            Some("New Name".to_string())
        );
        assert_eq!(
            model.style_version().get(),
            style_before,
            "renaming is not a style change"
        );
    }

    #[test]
    fn rename_series_noop_does_not_notify() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.rename_series(a, "Revenue"); // already the name
        assert_eq!(log.borrow().len(), 0);
        assert_eq!(model.structure_version().get(), structure_before);
    }

    #[test]
    fn set_series_color_bumps_style_not_structure() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.set_series_color(a, test_color());
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesColorChanged { series: a }
        );
        assert_eq!(
            model.structure_version().get(),
            structure_before,
            "color change must not bump structure_version"
        );
        assert!(model.style_version().get() > style_before);
        assert!(model.with_series(a, |_, color, _| color.is_some()).unwrap());
    }

    #[test]
    fn set_series_color_noop_does_not_notify() {
        let (model, a, _b) = sample();
        model.set_series_color(a, test_color());
        let structure_before = model.structure_version().get();
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.set_series_color(a, test_color()); // same static color again
        assert_eq!(log.borrow().len(), 0);
        assert_eq!(model.structure_version().get(), structure_before);
        assert_eq!(model.style_version().get(), style_before);
    }

    #[test]
    fn clear_series_color_bumps_style_and_clears() {
        let (model, a, _b) = sample();
        model.set_series_color(a, test_color());
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.clear_series_color(a);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesColorChanged { series: a }
        );
        assert!(model.style_version().get() > style_before);
        assert!(!model.with_series(a, |_, color, _| color.is_some()).unwrap());
    }

    #[test]
    fn clear_series_color_noop_does_not_notify_when_already_none() {
        let (model, a, _b) = sample();
        // Freshly-built series has no explicit color.
        let structure_before = model.structure_version().get();
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.clear_series_color(a);
        assert_eq!(log.borrow().len(), 0);
        assert_eq!(model.structure_version().get(), structure_before);
        assert_eq!(model.style_version().get(), style_before);
    }

    #[test]
    fn set_series_visible_bumps_structure() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.set_series_visible(a, false);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesVisibilityChanged { series: a }
        );
        assert!(model.structure_version().get() > structure_before);
        assert_eq!(model.with_series(a, |_, _, visible| visible), Some(false));
    }

    #[test]
    fn set_series_visible_noop_does_not_notify() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.set_series_visible(a, true); // already true
        assert_eq!(log.borrow().len(), 0);
        assert_eq!(model.structure_version().get(), structure_before);
    }

    #[test]
    fn move_series_emits_moved_and_bumps_structure() {
        let (model, a, b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.move_series(a, 1);
        assert_eq!(model.series_ids(), vec![b, a]);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesMoved {
                series: a,
                from: 0,
                to: 1
            }
        );
        assert!(model.structure_version().get() > structure_before);
    }

    #[test]
    fn move_series_noop_does_not_notify() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.move_series(a, 0); // already at 0
        assert_eq!(log.borrow().len(), 0);
        assert_eq!(model.structure_version().get(), structure_before);
    }

    #[test]
    fn push_point_emits_inserted_and_bumps_structure() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let (log, _handle) = track_changes(&model);

        model.push_point(a, "Q3".to_string(), 30.0);
        assert_eq!(model.point_count(a), 3);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::PointsInserted {
                series: a,
                range: 2..3
            }
        );
        assert!(model.structure_version().get() > structure_before);
    }

    #[test]
    fn insert_point_at_index() {
        let (model, a, _b) = sample();
        model.insert_point(a, 1, "Q1.5".to_string(), 15.0);
        assert_eq!(model.point_count(a), 3);
        assert_eq!(
            model.with_point(a, 1, |d| d.category.clone()),
            Some("Q1.5".to_string())
        );
    }

    #[test]
    fn remove_point_emits_removed_and_returns_datum() {
        let (model, a, _b) = sample();
        let (log, _handle) = track_changes(&model);

        let removed = model.remove_point(a, 0);
        assert_eq!(removed.category, "Q1");
        assert_eq!(model.point_count(a), 1);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::PointsRemoved {
                series: a,
                range: 0..1
            }
        );
    }

    #[test]
    fn update_point_bumps_structure_not_style() {
        let (model, a, _b) = sample();
        let structure_before = model.structure_version().get();
        let style_before = model.style_version().get();
        let (log, _handle) = track_changes(&model);

        model.update_point(a, 0, "Q1-revised".to_string(), 99.0);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::PointUpdated {
                series: a,
                index: 0
            }
        );
        assert!(model.structure_version().get() > structure_before);
        assert_eq!(model.style_version().get(), style_before);
        assert_eq!(model.with_point(a, 0, |d| d.value), Some(99.0));
    }

    #[test]
    fn replace_series_data_emits_replaced() {
        let (model, a, _b) = sample();
        let (log, _handle) = track_changes(&model);

        model.replace_series_data(a, vec![ChartDatum::new("X".to_string(), 1.0)]);
        assert_eq!(model.point_count(a), 1);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(
            log.borrow()[0],
            ChartChange::SeriesDataReplaced { series: a }
        );
    }

    #[test]
    fn clear_emits_reset() {
        let (model, _a, _b) = sample();
        let (log, _handle) = track_changes(&model);

        model.clear();
        assert_eq!(model.series_count(), 0);
        assert_eq!(log.borrow().len(), 1);
        assert_eq!(log.borrow()[0], ChartChange::Reset);
    }

    #[test]
    fn observer_removed_on_handle_drop() {
        let model: ChartModel<String> = ChartModel::new();
        let count = Rc::new(Cell::new(0));
        let c = count.clone();
        let handle = model.observe_changes(move |_| c.set(c.get() + 1));

        model.add_series("A");
        assert_eq!(count.get(), 1);

        drop(handle);
        model.add_series("B");
        assert_eq!(count.get(), 1);
    }

    #[test]
    fn multiple_observers() {
        let model: ChartModel<String> = ChartModel::new();
        let count = Rc::new(Cell::new(0));
        let c1 = count.clone();
        let c2 = count.clone();
        let _h1 = model.observe_changes(move |_| c1.set(c1.get() + 1));
        let _h2 = model.observe_changes(move |_| c2.set(c2.get() + 1));

        model.add_series("A");
        assert_eq!(count.get(), 2);
    }

    #[test]
    fn clone_shares_data_and_observers() {
        let (model, _a, _b) = sample();
        let clone = model.clone();
        let count = Rc::new(Cell::new(0));
        let c = count.clone();
        let _handle = model.observe_changes(move |_| c.set(c.get() + 1));

        clone.add_series("New");
        assert_eq!(model.series_count(), 3);
        assert_eq!(count.get(), 1);
    }

    #[test]
    fn with_all_series_returns_views_in_order() {
        let (model, a, b) = sample();
        let ids: Vec<SeriesId> =
            model.with_all_series(|views| views.iter().map(|v| v.id).collect());
        assert_eq!(ids, vec![a, b]);
        let names: Vec<String> =
            model.with_all_series(|views| views.iter().map(|v| v.name.to_string()).collect());
        assert_eq!(names, vec!["Revenue".to_string(), "Costs".to_string()]);
    }

    #[test]
    fn with_point_out_of_bounds_returns_none() {
        let (model, a, _b) = sample();
        assert_eq!(model.with_point(a, 99, |d| d.value), None);
    }

    /// A `SeriesId` that is guaranteed stale **within `model`'s own arena**.
    /// A `SeriesId` minted by a *different* `ChartModel` is not a safe
    /// stand-in — `SlotMap` keys are per-arena, so two freshly-created
    /// arenas hand out colliding keys (both start at index 0, generation
    /// 1). Removing a series from `model` itself bumps that slot's
    /// generation, so its old id is reliably rejected by this same arena.
    fn stale_id(model: &ChartModel<String>) -> SeriesId {
        let ghost = model.add_series("Ghost");
        model.remove_series(ghost);
        ghost
    }

    #[test]
    fn with_series_unknown_id_returns_none() {
        let (model, _a, _b) = sample();
        let ghost = stale_id(&model);
        assert_eq!(model.with_series(ghost, |_, _, _| ()), None);
        assert_eq!(model.with_point(ghost, 0, |d| d.value), None);
    }

    #[test]
    #[should_panic(expected = "unknown SeriesId")]
    fn remove_series_unknown_id_panics() {
        let (model, _a, _b) = sample();
        let ghost = stale_id(&model);
        model.remove_series(ghost);
    }

    #[test]
    #[should_panic]
    fn rename_series_unknown_id_panics() {
        let (model, _a, _b) = sample();
        let ghost = stale_id(&model);
        model.rename_series(ghost, "X");
    }

    #[test]
    #[should_panic]
    fn push_point_unknown_series_panics() {
        let (model, _a, _b) = sample();
        let ghost = stale_id(&model);
        model.push_point(ghost, "X".to_string(), 1.0);
    }

    #[test]
    #[should_panic(expected = "unknown SeriesId")]
    fn move_series_unknown_id_panics() {
        let (model, _a, _b) = sample();
        let ghost = stale_id(&model);
        model.move_series(ghost, 0);
    }

    // A minimal ColorProp value, built without a direct teksilo-tokens
    // *production* dependency — `teksilo-tokens` is pulled in as a
    // dev-dependency solely so tests can construct a concrete `Color`.
    fn test_color() -> teksilo_tokens::Color {
        teksilo_tokens::Color::from_hex("#FF0000")
    }
}