blinc_animation 0.5.1

Blinc animation system - spring physics, keyframes, and timeline orchestration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
//! Animation scheduler
//!
//! Manages all active animations and updates them each frame.
//! Animations are implicitly registered when created through wrapper types:
//! - `AnimatedValue` - Spring-based physics animations
//! - `AnimatedKeyframe` - Keyframe-based timed animations
//! - `AnimatedTimeline` - Timeline orchestration of multiple animations

use crate::easing::Easing;
use crate::keyframe::{Keyframe, KeyframeAnimation};
use crate::spring::{Spring, SpringConfig};
use crate::timeline::Timeline;
use blinc_core::AnimationAccess;
use slotmap::{new_key_type, SlotMap};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::thread::JoinHandle;
// `web_time::Instant` is a drop-in replacement for `std::time::Instant`.
// On native targets it re-exports the std type with zero overhead. On
// `wasm32-unknown-unknown` it routes through `performance.now()`,
// which is the only way to get a monotonic clock in a browser — the
// std impl panics with "time not implemented on this platform" the
// moment `Instant::now()` is actually called.
use web_time::Instant;
// `Duration` and `thread` are only used by the desktop background-thread
// loop; `start_raf()` lets `requestAnimationFrame` pace itself to the
// display, and the `thread_handle` field on wasm32 is just an inert
// `Option<JoinHandle>` that's always `None`.
#[cfg(not(target_arch = "wasm32"))]
use std::thread;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;

// ============================================================================
// Global Animation Scheduler State
// ============================================================================

/// Global scheduler handle for access from anywhere in the application
static GLOBAL_SCHEDULER: OnceLock<SchedulerHandle> = OnceLock::new();

/// Set the global animation scheduler handle
///
/// This should be called once at app startup after creating the AnimationScheduler.
/// Typically called from `WindowedApp::run()` after the scheduler is configured.
///
/// # Panics
///
/// Panics if called more than once.
pub fn set_global_scheduler(handle: SchedulerHandle) {
    if GLOBAL_SCHEDULER.set(handle).is_err() {
        panic!("set_global_scheduler() called more than once");
    }
}

/// Get the global animation scheduler handle
///
/// Returns the scheduler handle for creating animated values, keyframes, and timelines.
/// This enables components to create animations without needing explicit context passing.
///
/// # Panics
///
/// Panics if `set_global_scheduler()` has not been called.
///
/// # Example
///
/// ```ignore
/// use blinc_animation::{get_scheduler, AnimatedValue, SpringConfig};
///
/// let handle = get_scheduler();
/// let mut opacity = AnimatedValue::new(handle.clone(), 1.0, SpringConfig::stiff());
/// opacity.set_target(0.5);
/// ```
pub fn get_scheduler() -> SchedulerHandle {
    GLOBAL_SCHEDULER
        .get()
        .expect("Animation scheduler not initialized. Call set_global_scheduler() at app startup.")
        .clone()
}

/// Try to get the global scheduler (returns None if not initialized)
pub fn try_get_scheduler() -> Option<SchedulerHandle> {
    GLOBAL_SCHEDULER.get().cloned()
}

/// Check if the global scheduler has been initialized
pub fn is_scheduler_initialized() -> bool {
    GLOBAL_SCHEDULER.get().is_some()
}

new_key_type! {
    /// Handle to a registered spring animation
    pub struct SpringId;
    /// Handle to a registered keyframe animation
    pub struct KeyframeId;
    /// Handle to a registered timeline
    pub struct TimelineId;
}

impl SpringId {
    /// Convert to raw u64 for atomic storage
    ///
    /// Use with `from_raw()` for lock-free animation ID passing.
    pub fn to_raw(self) -> u64 {
        self.0.as_ffi()
    }

    /// Reconstruct from raw u64
    ///
    /// # Safety
    /// The raw value must have been created by `to_raw()` on a valid SpringId.
    pub fn from_raw(raw: u64) -> Self {
        SpringId::from(slotmap::KeyData::from_ffi(raw))
    }
}

/// Tick callback type - called each frame with delta time in seconds
pub type TickCallback = Arc<Mutex<dyn FnMut(f32) + Send + Sync>>;

new_key_type! {
    /// Handle to a registered tick callback
    pub struct TickCallbackId;
}

impl TickCallbackId {
    /// Convert to raw u64 for storage
    pub fn to_raw(self) -> u64 {
        self.0.as_ffi()
    }

    /// Reconstruct from raw u64
    pub fn from_raw(raw: u64) -> Self {
        TickCallbackId::from(slotmap::KeyData::from_ffi(raw))
    }
}

/// Internal state of the animation scheduler
struct SchedulerInner {
    springs: SlotMap<SpringId, Spring>,
    keyframes: SlotMap<KeyframeId, KeyframeAnimation>,
    timelines: SlotMap<TimelineId, Timeline>,
    tick_callbacks: SlotMap<TickCallbackId, TickCallback>,
    last_frame: Instant,
    target_fps: u32,
}

/// Callback type for waking up the main thread from the animation thread.
///
/// This is called when there are active animations that need to be rendered.
/// The callback should wake up the event loop (e.g., via EventLoopProxy).
///
/// On native targets the callback is invoked from the scheduler's background
/// thread, so it must be `Send + Sync`. On `wasm32-unknown-unknown` the rAF
/// driver fires the callback synchronously on the main browser thread, so the
/// `Send + Sync` bound is dropped — the web runner needs to capture an
/// `Rc<RefCell<WebApp>>` (which is `!Send`) to render a frame.
#[cfg(not(target_arch = "wasm32"))]
pub type WakeCallback = Arc<dyn Fn() + Send + Sync>;
#[cfg(target_arch = "wasm32")]
pub type WakeCallback = Arc<dyn Fn()>;

/// The animation scheduler that ticks all active animations
///
/// This is typically held by the application context and shared via `SchedulerHandle`.
/// Animations register themselves implicitly when created.
///
/// # Background Thread Mode
///
/// The scheduler can run on its own background thread via `start_background()`.
/// This ensures animations continue even when the window loses focus.
///
/// ```ignore
/// let scheduler = AnimationScheduler::new();
/// scheduler.start_background(); // Runs at 120fps in background thread
/// ```
pub struct AnimationScheduler {
    inner: Arc<Mutex<SchedulerInner>>,
    /// Stop signal for background thread
    stop_flag: Arc<AtomicBool>,
    /// Flag set by background thread when animations need redraw
    /// The main thread should check and clear this to request window redraws
    needs_redraw: Arc<AtomicBool>,
    /// Flag to request continuous redraws (e.g., for cursor blink)
    /// When set, the background thread will keep signaling redraws
    continuous_redraw: Arc<AtomicBool>,
    /// Background thread handle (if running)
    thread_handle: Option<JoinHandle<()>>,
    /// Optional callback to wake up the main thread
    wake_callback: Option<WakeCallback>,
}

// SAFETY: On wasm32 the wake callback is `Arc<dyn Fn()>` (no `Send +
// Sync`) because the rAF driver and the runner's render closure both
// run on the main browser thread. The wgpu surface, web_sys event
// handlers, and the rest of the dep tree assume single-threaded
// access. We manually opt the scheduler back into `Send + Sync` so
// downstream types — `Mutex<AnimationScheduler>`, `Weak<Mutex<…>>`,
// the `static FOCUSED_TEXT_AREA: Mutex<…>` slot — keep their existing
// auto-derived `Send + Sync` and don't ripple the relaxed bound
// throughout `blinc_layout`. This mirrors the same single-threaded-
// platform pattern used by `blinc_platform_harmony::HarmonyAssetLoader`
// and `blinc_platform_web::WebWindow`. There are no other threads on
// wasm32 to send to, so the `unsafe impl` cannot fire a real footgun.
#[cfg(target_arch = "wasm32")]
unsafe impl Send for AnimationScheduler {}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for AnimationScheduler {}

impl AnimationScheduler {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(SchedulerInner {
                springs: SlotMap::with_key(),
                keyframes: SlotMap::with_key(),
                timelines: SlotMap::with_key(),
                tick_callbacks: SlotMap::with_key(),
                last_frame: Instant::now(),
                target_fps: 120,
            })),
            stop_flag: Arc::new(AtomicBool::new(false)),
            needs_redraw: Arc::new(AtomicBool::new(false)),
            continuous_redraw: Arc::new(AtomicBool::new(false)),
            thread_handle: None,
            wake_callback: None,
        }
    }

    /// Set a wake callback that will be called when animations need a redraw.
    ///
    /// On native: invoked from the scheduler's background thread, so `F`
    /// must be `Send + Sync`. Use this to wake an event loop from
    /// another thread (e.g. via `EventLoopProxy::wake`).
    ///
    /// On wasm32: invoked synchronously from inside the rAF closure on
    /// the main browser thread, so the `Send + Sync` bound is dropped.
    /// The web runner uses this to install a closure that re-borrows
    /// its `Rc<RefCell<WebApp>>` and renders a frame.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let wake_proxy = event_loop.wake_proxy();
    /// scheduler.set_wake_callback(move || wake_proxy.wake());
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    pub fn set_wake_callback<F>(&mut self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.wake_callback = Some(Arc::new(callback));
    }

    /// Wasm32 sibling of [`Self::set_wake_callback`] without the
    /// `Send + Sync` bound. See the native version's docs for the
    /// rationale; the only difference is the relaxed bound.
    #[cfg(target_arch = "wasm32")]
    pub fn set_wake_callback<F>(&mut self, callback: F)
    where
        F: Fn() + 'static,
    {
        self.wake_callback = Some(Arc::new(callback));
    }

    /// Tick everything once: springs, keyframes, timelines, and tick
    /// callbacks. Returns `(has_active, dt_secs)` so callers can decide
    /// whether to schedule another frame.
    ///
    /// This is the per-frame body shared by both the desktop background
    /// thread (see [`start_background`](Self::start_background)) and the
    /// browser `requestAnimationFrame` driver
    /// (see `start_raf` on wasm32). Extracted from the original
    /// `start_background` thread closure verbatim — no semantic change.
    fn tick_frame_inner(
        inner: &Arc<Mutex<SchedulerInner>>,
        needs_redraw: &Arc<AtomicBool>,
        wants_continuous: bool,
        wake_callback: Option<&WakeCallback>,
    ) -> (bool, f32) {
        let (has_active, tick_callbacks_to_call, dt) = {
            let mut inner = inner.lock().unwrap();
            let now = Instant::now();
            let dt = (now - inner.last_frame).as_secs_f32();
            let dt_ms = dt * 1000.0;
            inner.last_frame = now;

            // Update all springs
            for (_, spring) in inner.springs.iter_mut() {
                spring.step(dt);
            }

            // Update all keyframe animations
            for (_, keyframe) in inner.keyframes.iter_mut() {
                keyframe.tick(dt_ms);
            }

            // Update all timelines
            for (_, timeline) in inner.timelines.iter_mut() {
                timeline.tick(dt_ms);
            }

            // Collect tick callbacks to call (we'll call them after releasing the lock)
            let callbacks: Vec<_> = inner
                .tick_callbacks
                .iter()
                .map(|(_, cb)| Arc::clone(cb))
                .collect();

            // NOTE: We do NOT remove animations here!
            // Springs, keyframes, and timelines are only removed when:
            // 1. Their wrapper (AnimatedValue, AnimatedKeyframe, AnimatedTimeline) is dropped
            // 2. set_immediate() is called on springs
            // This ensures animations can be restarted after completing.

            // Check if any animations are still active (playing, not just present)
            // Tick callbacks count as active - they need continuous updates
            let has_active = inner.springs.iter().any(|(_, s)| !s.is_settled())
                || inner.keyframes.iter().any(|(_, k)| k.is_playing())
                || inner.timelines.iter().any(|(_, t)| t.is_playing())
                || !inner.tick_callbacks.is_empty();

            (has_active, callbacks, dt)
        };

        // Call tick callbacks outside the lock to avoid deadlocks
        for callback in tick_callbacks_to_call {
            if let Ok(mut cb) = callback.lock() {
                cb(dt);
            }
        }

        // Signal main thread that it needs to redraw
        // Either from active animations OR continuous redraw request (cursor blink)
        if has_active || wants_continuous {
            needs_redraw.store(true, Ordering::Release);

            // Wake up the event loop if a callback is set
            if let Some(callback) = wake_callback {
                // Only log occasionally to avoid spam
                static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
                let count = COUNTER.fetch_add(1, Ordering::Relaxed);
                if count % 120 == 0 {
                    // Log once per second at 120fps
                    tracing::debug!(
                        "Animation tick: waking driver (continuous={}, active={})",
                        wants_continuous,
                        has_active
                    );
                }
                callback();
            }
        }

        (has_active || wants_continuous, dt)
    }

    /// Start the scheduler on a background thread
    ///
    /// This ensures animations continue even when the window loses focus.
    /// The thread runs at the configured target FPS (default 120).
    ///
    /// The thread sets the `needs_redraw` flag whenever there are active
    /// animations. The main thread should call `take_needs_redraw()` to
    /// check and clear this flag, then request a window redraw.
    ///
    /// If a wake callback is set via `set_wake_callback()`, it will be called
    /// to wake up the main thread's event loop when animations are active.
    ///
    /// **Not available on `wasm32-unknown-unknown`** — the browser
    /// doesn't expose threads. Use `Self::start_raf` instead, which
    /// drives the same per-frame work from `requestAnimationFrame`.
    /// (Plain code reference rather than an intra-doc link because
    /// `start_raf` itself is `#[cfg(target_arch = "wasm32")]`-gated
    /// and isn't visible to rustdoc on host targets.)
    #[cfg(not(target_arch = "wasm32"))]
    pub fn start_background(&mut self) {
        if self.thread_handle.is_some() {
            return; // Already running
        }

        let inner = Arc::clone(&self.inner);
        let stop_flag = Arc::clone(&self.stop_flag);
        let needs_redraw = Arc::clone(&self.needs_redraw);
        let continuous_redraw = Arc::clone(&self.continuous_redraw);
        let wake_callback = self.wake_callback.clone();

        self.thread_handle = Some(thread::spawn(move || {
            let frame_duration = Duration::from_micros(1_000_000 / 120); // 120fps

            while !stop_flag.load(Ordering::Relaxed) {
                let start = Instant::now();

                // Check if continuous redraw is requested (e.g., for cursor blink)
                let wants_continuous = continuous_redraw.load(Ordering::Relaxed);

                Self::tick_frame_inner(
                    &inner,
                    &needs_redraw,
                    wants_continuous,
                    wake_callback.as_ref(),
                );

                // Sleep for remaining frame time
                let elapsed = start.elapsed();
                if elapsed < frame_duration {
                    thread::sleep(frame_duration - elapsed);
                }
            }
        }));
    }

    /// Stop the background thread
    #[cfg(not(target_arch = "wasm32"))]
    pub fn stop_background(&mut self) {
        self.stop_flag.store(true, Ordering::Relaxed);
        if let Some(handle) = self.thread_handle.take() {
            let _ = handle.join();
        }
        self.stop_flag.store(false, Ordering::Relaxed);
    }

    /// Start the scheduler on the browser's `requestAnimationFrame`.
    ///
    /// The wasm32 sibling of [`Self::start_background`]. Where the
    /// desktop version spawns an OS thread that ticks at 120 fps and
    /// signals the main thread via the wake callback, this version
    /// installs a `requestAnimationFrame` callback chain that ticks
    /// the same per-frame body once per browser frame and calls the
    /// wake callback synchronously inside the rAF closure.
    ///
    /// The frame budget is whatever the browser hands you (typically
    /// 60 fps, occasionally 120 on high-refresh displays). There is no
    /// `target_fps` cap — `requestAnimationFrame` already paces itself
    /// to the display.
    ///
    /// Set the wake callback **before** calling this. The wake
    /// callback is what the runner uses to actually render a frame —
    /// the scheduler doesn't know about wgpu surfaces, it just knows
    /// "tick everything, then call wake if anything moved".
    ///
    /// The rAF chain self-perpetuates: each closure invocation
    /// schedules the next via `window.requestAnimationFrame(self)`.
    /// Stopping it requires dropping the `Closure` that owns the
    /// chain — currently we leak it for the lifetime of the app
    /// (matching how `start_background()` runs forever on native).
    /// A future `stop_raf()` could swap out the captured closure
    /// reference if we ever need teardown.
    ///
    /// # Panics
    ///
    /// Panics if there is no global `window` object (e.g. running in
    /// a Web Worker). Use a try-construction site if you need to
    /// gracefully degrade.
    #[cfg(target_arch = "wasm32")]
    pub fn start_raf(&self) {
        use std::cell::RefCell;
        use std::rc::Rc;
        use wasm_bindgen::closure::Closure;
        use wasm_bindgen::JsCast;

        let window = web_sys::window().expect("AnimationScheduler::start_raf needs `window`");

        // Per-frame state — captured by the rAF closure. Cloning these
        // Arcs is cheap; the closure owns its own clones for the
        // lifetime of the app.
        let inner = Arc::clone(&self.inner);
        let needs_redraw = Arc::clone(&self.needs_redraw);
        let continuous_redraw = Arc::clone(&self.continuous_redraw);
        let wake_callback = self.wake_callback.clone();

        // Self-referential closure cell. The outer `Rc` is what the
        // closure schedules itself with via
        // `window.request_animation_frame(closure.borrow().as_ref().unchecked_ref())`.
        // The borrow only happens *inside* the closure body, never on
        // the same call frame, so there's no aliasing issue.
        // (clippy::type_complexity is allowed locally because the type
        // *is* genuinely the rAF closure-cell shape — extracting a
        // type alias here would just rename the same complexity.)
        #[allow(clippy::type_complexity)]
        let closure_cell: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::new(RefCell::new(None));
        let closure_cell_for_init = Rc::clone(&closure_cell);

        // The window handle the closure needs to schedule the next frame.
        let window_for_closure = window.clone();

        *closure_cell_for_init.borrow_mut() = Some(Closure::wrap(Box::new(move || {
            let wants_continuous = continuous_redraw.load(Ordering::Relaxed);
            Self::tick_frame_inner(
                &inner,
                &needs_redraw,
                wants_continuous,
                wake_callback.as_ref(),
            );

            // Schedule the next frame. Borrowing closure_cell here is
            // safe because the prior borrow_mut at install time has
            // already been released.
            if let Some(ref c) = *closure_cell.borrow() {
                let _ = window_for_closure.request_animation_frame(c.as_ref().unchecked_ref());
            }
        }) as Box<dyn FnMut()>));

        // Kick off the first frame.
        if let Some(ref c) = *closure_cell_for_init.borrow() {
            let _ = window.request_animation_frame(c.as_ref().unchecked_ref());
        }

        // Intentionally leak the closure cell — its only owner from
        // here on is the rAF callback chain itself, which keeps a
        // reference for as long as the chain runs (i.e. forever, like
        // `start_background()` on native). If a future `stop_raf()`
        // wants to break the chain, it can hold a Weak<RefCell<…>>
        // and clear the inner Option.
        std::mem::forget(closure_cell_for_init);
    }

    /// Check if the background thread is running
    pub fn is_background_running(&self) -> bool {
        self.thread_handle.is_some()
    }

    /// Check and clear the needs_redraw flag
    ///
    /// The background thread sets this flag when animations are active.
    /// Call this from the main thread's event loop to check if a redraw
    /// is needed, then request a window redraw if true.
    ///
    /// This is an atomic swap operation that returns the previous value
    /// and clears the flag in one operation.
    pub fn take_needs_redraw(&self) -> bool {
        self.needs_redraw.swap(false, Ordering::Acquire)
    }

    /// Manually request a redraw
    ///
    /// This sets the needs_redraw flag, which will be picked up by the
    /// main thread on its next event loop iteration.
    pub fn request_redraw(&self) {
        self.needs_redraw.store(true, Ordering::Release);
    }

    /// Enable continuous redraw mode
    ///
    /// When enabled, the background thread will continuously signal redraws
    /// even without active animations. Use this for features like cursor blink
    /// that need regular redraws without registering full animations.
    ///
    /// Call `set_continuous_redraw(false)` when no longer needed.
    pub fn set_continuous_redraw(&self, enabled: bool) {
        tracing::debug!("AnimationScheduler: set_continuous_redraw({})", enabled);
        self.continuous_redraw.store(enabled, Ordering::Release);
    }

    /// Check if continuous redraw mode is enabled
    pub fn is_continuous_redraw(&self) -> bool {
        self.continuous_redraw.load(Ordering::Relaxed)
    }

    /// Get a handle to this scheduler for passing to components
    pub fn handle(&self) -> SchedulerHandle {
        SchedulerHandle {
            inner: Arc::downgrade(&self.inner),
            needs_redraw: Arc::clone(&self.needs_redraw),
        }
    }

    pub fn set_target_fps(&mut self, fps: u32) {
        self.inner.lock().unwrap().target_fps = fps;
    }

    /// Tick all animations
    ///
    /// Returns true if any animations are still active (need another tick).
    pub fn tick(&self) -> bool {
        let mut inner = self.inner.lock().unwrap();
        let now = Instant::now();
        let dt = (now - inner.last_frame).as_secs_f32();
        let dt_ms = dt * 1000.0;
        inner.last_frame = now;

        // Update all springs
        for (_, spring) in inner.springs.iter_mut() {
            spring.step(dt);
        }

        // Update all keyframe animations
        for (_, keyframe) in inner.keyframes.iter_mut() {
            keyframe.tick(dt_ms);
        }

        // Update all timelines
        for (_, timeline) in inner.timelines.iter_mut() {
            timeline.tick(dt_ms);
        }

        // NOTE: We do NOT remove animations here!
        // Springs, keyframes, and timelines are only removed when their wrappers drop.
        // This ensures animations can be restarted after completing.

        // Return true if there are still active (playing, not just present) animations
        inner.springs.iter().any(|(_, s)| !s.is_settled())
            || inner.keyframes.iter().any(|(_, k)| k.is_playing())
            || inner.timelines.iter().any(|(_, t)| t.is_playing())
    }

    /// Check if any animations are still active
    pub fn has_active_animations(&self) -> bool {
        let inner = self.inner.lock().unwrap();
        inner.springs.iter().any(|(_, s)| !s.is_settled())
            || inner.keyframes.iter().any(|(_, k)| k.is_playing())
            || inner.timelines.iter().any(|(_, t)| t.is_playing())
    }

    /// Get the number of active springs
    pub fn spring_count(&self) -> usize {
        self.inner.lock().unwrap().springs.len()
    }

    /// Get the number of active keyframe animations
    pub fn keyframe_count(&self) -> usize {
        self.inner.lock().unwrap().keyframes.len()
    }

    /// Get the number of active timelines
    pub fn timeline_count(&self) -> usize {
        self.inner.lock().unwrap().timelines.len()
    }

    // =========================================================================
    // Direct Spring Access (for advanced use cases)
    // =========================================================================

    pub fn add_spring(&self, spring: Spring) -> SpringId {
        self.inner.lock().unwrap().springs.insert(spring)
    }

    pub fn get_spring(&self, id: SpringId) -> Option<Spring> {
        self.inner.lock().unwrap().springs.get(id).copied()
    }

    /// Apply a function to modify a spring if it exists
    pub fn with_spring_mut<F, R>(&self, id: SpringId, f: F) -> Option<R>
    where
        F: FnOnce(&mut Spring) -> R,
    {
        self.inner.lock().unwrap().springs.get_mut(id).map(f)
    }

    pub fn get_spring_value(&self, id: SpringId) -> Option<f32> {
        self.inner
            .lock()
            .unwrap()
            .springs
            .get(id)
            .map(|s| s.value())
    }

    pub fn set_spring_target(&self, id: SpringId, target: f32) {
        if let Some(spring) = self.inner.lock().unwrap().springs.get_mut(id) {
            spring.set_target(target);
        }
    }

    pub fn remove_spring(&self, id: SpringId) -> Option<Spring> {
        self.inner.lock().unwrap().springs.remove(id)
    }

    /// Iterate over all springs mutably
    ///
    /// This is useful for manual animation loops where you want to step all springs.
    /// Returns an iterator adapter that holds the mutex lock.
    pub fn springs_iter_mut(&self) -> SpringsIterMut<'_> {
        SpringsIterMut {
            guard: self.inner.lock().unwrap(),
        }
    }

    // =========================================================================
    // Direct Keyframe Access (for advanced use cases)
    // =========================================================================

    pub fn add_keyframe(&self, keyframe: KeyframeAnimation) -> KeyframeId {
        self.inner.lock().unwrap().keyframes.insert(keyframe)
    }

    pub fn get_keyframe_value(&self, id: KeyframeId) -> Option<f32> {
        self.inner
            .lock()
            .unwrap()
            .keyframes
            .get(id)
            .map(|k| k.value())
    }

    pub fn start_keyframe(&self, id: KeyframeId) {
        if let Some(keyframe) = self.inner.lock().unwrap().keyframes.get_mut(id) {
            keyframe.start();
        }
    }

    pub fn stop_keyframe(&self, id: KeyframeId) {
        if let Some(keyframe) = self.inner.lock().unwrap().keyframes.get_mut(id) {
            keyframe.stop();
        }
    }

    pub fn remove_keyframe(&self, id: KeyframeId) -> Option<KeyframeAnimation> {
        self.inner.lock().unwrap().keyframes.remove(id)
    }

    // =========================================================================
    // Direct Timeline Access (for advanced use cases)
    // =========================================================================

    pub fn add_timeline(&self, timeline: Timeline) -> TimelineId {
        self.inner.lock().unwrap().timelines.insert(timeline)
    }

    pub fn start_timeline(&self, id: TimelineId) {
        if let Some(timeline) = self.inner.lock().unwrap().timelines.get_mut(id) {
            timeline.start();
        }
    }

    pub fn stop_timeline(&self, id: TimelineId) {
        if let Some(timeline) = self.inner.lock().unwrap().timelines.get_mut(id) {
            timeline.stop();
        }
    }

    pub fn remove_timeline(&self, id: TimelineId) -> Option<Timeline> {
        self.inner.lock().unwrap().timelines.remove(id)
    }

    // =========================================================================
    // Tick Callback API (for custom per-frame updates like ECS systems)
    // =========================================================================

    /// Register a tick callback that runs each frame
    ///
    /// The callback receives delta time in seconds. Use this to integrate
    /// custom systems (like ECS) with the animation scheduler's background thread.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let world = Arc::new(Mutex::new(World::new()));
    /// let world_clone = world.clone();
    /// let id = scheduler.add_tick_callback(move |dt| {
    ///     let mut world = world_clone.lock().unwrap();
    ///     // Run ECS systems with delta time
    ///     world.run_systems(dt);
    /// });
    /// ```
    pub fn add_tick_callback<F>(&self, callback: F) -> TickCallbackId
    where
        F: FnMut(f32) + Send + Sync + 'static,
    {
        self.inner
            .lock()
            .unwrap()
            .tick_callbacks
            .insert(Arc::new(Mutex::new(callback)))
    }

    /// Remove a tick callback
    pub fn remove_tick_callback(&self, id: TickCallbackId) {
        self.inner.lock().unwrap().tick_callbacks.remove(id);
    }

    /// Get the number of registered tick callbacks
    pub fn tick_callback_count(&self) -> usize {
        self.inner.lock().unwrap().tick_callbacks.len()
    }
}

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

/// Iterator adapter for mutable access to springs
///
/// Holds the mutex lock for the duration of iteration.
/// Use in a `for` loop to step all springs.
pub struct SpringsIterMut<'a> {
    guard: std::sync::MutexGuard<'a, SchedulerInner>,
}

impl SpringsIterMut<'_> {
    /// Get an iterator over springs mutably
    ///
    /// Use this with `for (id, spring) in iter.iter_mut() { ... }`
    pub fn for_each<F>(&mut self, mut f: F)
    where
        F: FnMut(SpringId, &mut Spring),
    {
        for (id, spring) in self.guard.springs.iter_mut() {
            f(id, spring);
        }
    }
}

impl<'a> IntoIterator for &'a mut SpringsIterMut<'_> {
    type Item = (SpringId, &'a mut Spring);
    type IntoIter = slotmap::basic::IterMut<'a, SpringId, Spring>;

    fn into_iter(self) -> Self::IntoIter {
        self.guard.springs.iter_mut()
    }
}

impl Clone for AnimationScheduler {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            stop_flag: Arc::clone(&self.stop_flag),
            needs_redraw: Arc::clone(&self.needs_redraw),
            continuous_redraw: Arc::clone(&self.continuous_redraw),
            // Cloned scheduler doesn't own the background thread
            thread_handle: None,
            wake_callback: self.wake_callback.clone(),
        }
    }
}

impl Drop for AnimationScheduler {
    fn drop(&mut self) {
        // Stop background thread when scheduler is dropped. The web
        // path doesn't have a thread to stop — its `requestAnimationFrame`
        // chain is intentionally leaked for the lifetime of the app
        // (matching native's "thread runs forever" semantics) and the
        // browser tears it down on page unload.
        #[cfg(not(target_arch = "wasm32"))]
        self.stop_background();
    }
}

/// Implement AnimationAccess for AnimationScheduler
///
/// This allows the scheduler to be used directly with ValueContext for
/// resolving dynamic animation values at render time.
impl AnimationAccess for AnimationScheduler {
    fn get_spring_value(&self, id: u64, generation: u32) -> Option<f32> {
        // Reconstruct SpringId from raw parts
        // slotmap keys are 64-bit with version in upper bits
        let key_data = slotmap::KeyData::from_ffi((id as u32 as u64) | ((generation as u64) << 32));
        let spring_id = SpringId::from(key_data);
        self.inner
            .lock()
            .unwrap()
            .springs
            .get(spring_id)
            .map(|s| s.value())
    }

    fn get_keyframe_value(&self, id: u64) -> Option<f32> {
        // For keyframes, we use the full id (version is in upper 32 bits)
        let key_data = slotmap::KeyData::from_ffi(id);
        let keyframe_id = KeyframeId::from(key_data);
        self.inner
            .lock()
            .unwrap()
            .keyframes
            .get(keyframe_id)
            .map(|k| k.value())
    }

    fn get_timeline_value(&self, timeline_id: u64, _property: &str) -> Option<f32> {
        // Timeline values are accessed through entry IDs, not property names
        // This is a placeholder - timeline access is more complex
        let key_data = slotmap::KeyData::from_ffi(timeline_id);
        let tid = TimelineId::from(key_data);
        // For now, return None as timeline access requires entry IDs
        // Future: parse property as "entry_{id}" and look up
        self.inner.lock().unwrap().timelines.get(tid).map(|_t| 0.0) // Placeholder
    }
}

/// A weak handle to the animation scheduler
///
/// This is passed to components that need to register animations.
/// It won't prevent the scheduler from being dropped.
#[derive(Clone)]
pub struct SchedulerHandle {
    inner: Weak<Mutex<SchedulerInner>>,
    needs_redraw: Arc<AtomicBool>,
}

impl SchedulerHandle {
    /// Request a redraw from anywhere — fires the scheduler's
    /// `needs_redraw` flag which the main thread's event loop picks up.
    /// Use this from background threads (e.g. video decode) that need
    /// the UI to repaint without registering a full animation.
    pub fn request_redraw(&self) {
        self.needs_redraw.store(true, Ordering::Release);
    }

    // =========================================================================
    // Spring Operations
    // =========================================================================

    /// Register a spring and return its ID
    pub fn register_spring(&self, spring: Spring) -> Option<SpringId> {
        self.inner.upgrade().map(|inner| {
            let mut guard = inner.lock().unwrap();
            // Reset last_frame to now to prevent huge dt on first tick
            // This ensures new springs start animating smoothly from their current frame
            guard.last_frame = Instant::now();
            guard.springs.insert(spring)
        })
    }

    /// Update a spring's target
    pub fn set_spring_target(&self, id: SpringId, target: f32) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(spring) = inner.lock().unwrap().springs.get_mut(id) {
                spring.set_target(target);
            }
        }
    }

    /// Get current spring value
    pub fn get_spring_value(&self, id: SpringId) -> Option<f32> {
        self.inner
            .upgrade()
            .and_then(|inner| inner.lock().unwrap().springs.get(id).map(|s| s.value()))
    }

    /// Check if a spring has settled (at rest at target)
    ///
    /// Returns `true` if the spring exists and has settled, or if the spring
    /// doesn't exist (considered settled since there's nothing animating).
    pub fn is_spring_settled(&self, id: SpringId) -> bool {
        self.inner
            .upgrade()
            .and_then(|inner| {
                inner
                    .lock()
                    .unwrap()
                    .springs
                    .get(id)
                    .map(|s| s.is_settled())
            })
            .unwrap_or(true) // If spring gone, consider settled
    }

    /// Remove a spring
    pub fn remove_spring(&self, id: SpringId) {
        if let Some(inner) = self.inner.upgrade() {
            inner.lock().unwrap().springs.remove(id);
        }
    }

    /// Pause a spring — freezes at current position
    pub fn pause_spring(&self, id: SpringId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(spring) = inner.lock().unwrap().springs.get_mut(id) {
                spring.pause();
            }
        }
    }

    /// Resume a paused spring
    pub fn resume_spring(&self, id: SpringId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(spring) = inner.lock().unwrap().springs.get_mut(id) {
                spring.resume();
            }
        }
    }

    // =========================================================================
    // Keyframe Operations
    // =========================================================================

    /// Register a keyframe animation and return its ID
    pub fn register_keyframe(&self, keyframe: KeyframeAnimation) -> Option<KeyframeId> {
        self.inner
            .upgrade()
            .map(|inner| inner.lock().unwrap().keyframes.insert(keyframe))
    }

    /// Get current keyframe animation value
    pub fn get_keyframe_value(&self, id: KeyframeId) -> Option<f32> {
        self.inner
            .upgrade()
            .and_then(|inner| inner.lock().unwrap().keyframes.get(id).map(|k| k.value()))
    }

    /// Get keyframe animation progress (0.0 to 1.0)
    pub fn get_keyframe_progress(&self, id: KeyframeId) -> Option<f32> {
        self.inner.upgrade().and_then(|inner| {
            inner
                .lock()
                .unwrap()
                .keyframes
                .get(id)
                .map(|k| k.progress())
        })
    }

    /// Check if keyframe animation is playing
    pub fn is_keyframe_playing(&self, id: KeyframeId) -> bool {
        self.inner
            .upgrade()
            .and_then(|inner| {
                inner
                    .lock()
                    .unwrap()
                    .keyframes
                    .get(id)
                    .map(|k| k.is_playing())
            })
            .unwrap_or(false)
    }

    /// Start a keyframe animation
    pub fn start_keyframe(&self, id: KeyframeId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(keyframe) = inner.lock().unwrap().keyframes.get_mut(id) {
                keyframe.start();
            }
        }
    }

    /// Stop a keyframe animation
    pub fn stop_keyframe(&self, id: KeyframeId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(keyframe) = inner.lock().unwrap().keyframes.get_mut(id) {
                keyframe.stop();
            }
        }
    }

    /// Remove a keyframe animation
    pub fn remove_keyframe(&self, id: KeyframeId) {
        if let Some(inner) = self.inner.upgrade() {
            inner.lock().unwrap().keyframes.remove(id);
        }
    }

    // =========================================================================
    // Timeline Operations
    // =========================================================================

    /// Register a timeline and return its ID
    pub fn register_timeline(&self, timeline: Timeline) -> Option<TimelineId> {
        self.inner
            .upgrade()
            .map(|inner| inner.lock().unwrap().timelines.insert(timeline))
    }

    /// Check if timeline is playing
    pub fn is_timeline_playing(&self, id: TimelineId) -> bool {
        self.inner
            .upgrade()
            .and_then(|inner| {
                inner
                    .lock()
                    .unwrap()
                    .timelines
                    .get(id)
                    .map(|t| t.is_playing())
            })
            .unwrap_or(false)
    }

    /// Start a timeline
    pub fn start_timeline(&self, id: TimelineId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(timeline) = inner.lock().unwrap().timelines.get_mut(id) {
                timeline.start();
            }
        }
    }

    /// Stop a timeline
    pub fn stop_timeline(&self, id: TimelineId) {
        if let Some(inner) = self.inner.upgrade() {
            if let Some(timeline) = inner.lock().unwrap().timelines.get_mut(id) {
                timeline.stop();
            }
        }
    }

    /// Remove a timeline
    pub fn remove_timeline(&self, id: TimelineId) {
        if let Some(inner) = self.inner.upgrade() {
            inner.lock().unwrap().timelines.remove(id);
        }
    }

    /// Access a timeline to add entries or get values
    ///
    /// The closure receives a mutable reference to the timeline.
    /// Returns None if the scheduler is dropped or timeline doesn't exist.
    pub fn with_timeline<F, R>(&self, id: TimelineId, f: F) -> Option<R>
    where
        F: FnOnce(&mut Timeline) -> R,
    {
        self.inner
            .upgrade()
            .and_then(|inner| inner.lock().unwrap().timelines.get_mut(id).map(f))
    }

    /// Check if the scheduler is still alive
    pub fn is_alive(&self) -> bool {
        self.inner.strong_count() > 0
    }

    // =========================================================================
    // Tick Callback Operations
    // =========================================================================

    /// Register a tick callback that runs each frame
    ///
    /// The callback receives delta time in seconds. Use this to integrate
    /// custom systems (like ECS) with the animation scheduler's background thread.
    ///
    /// Returns None if the scheduler has been dropped.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let world = Arc::new(Mutex::new(World::new()));
    /// let world_clone = world.clone();
    /// let id = handle.register_tick_callback(move |dt| {
    ///     let mut world = world_clone.lock().unwrap();
    ///     // Run ECS systems with delta time
    ///     world.run_systems(dt);
    /// });
    /// ```
    pub fn register_tick_callback<F>(&self, callback: F) -> Option<TickCallbackId>
    where
        F: FnMut(f32) + Send + Sync + 'static,
    {
        self.inner.upgrade().map(|inner| {
            inner
                .lock()
                .unwrap()
                .tick_callbacks
                .insert(Arc::new(Mutex::new(callback)))
        })
    }

    /// Remove a tick callback
    pub fn remove_tick_callback(&self, id: TickCallbackId) {
        if let Some(inner) = self.inner.upgrade() {
            inner.lock().unwrap().tick_callbacks.remove(id);
        }
    }
}

/// Implement AnimationAccess for SchedulerHandle
///
/// This allows the handle to be used with ValueContext for resolving
/// dynamic animation values at render time.
impl AnimationAccess for SchedulerHandle {
    fn get_spring_value(&self, id: u64, generation: u32) -> Option<f32> {
        self.inner.upgrade().and_then(|inner| {
            let key_data =
                slotmap::KeyData::from_ffi((id as u32 as u64) | ((generation as u64) << 32));
            let spring_id = SpringId::from(key_data);
            inner
                .lock()
                .unwrap()
                .springs
                .get(spring_id)
                .map(|s| s.value())
        })
    }

    fn get_keyframe_value(&self, id: u64) -> Option<f32> {
        self.inner.upgrade().and_then(|inner| {
            let key_data = slotmap::KeyData::from_ffi(id);
            let keyframe_id = KeyframeId::from(key_data);
            inner
                .lock()
                .unwrap()
                .keyframes
                .get(keyframe_id)
                .map(|k| k.value())
        })
    }

    fn get_timeline_value(&self, _timeline_id: u64, _property: &str) -> Option<f32> {
        // Placeholder - timeline access is more complex
        None
    }
}

// ============================================================================
// Animated Value (Spring-based)
// ============================================================================

/// An animated value that automatically registers with the scheduler
///
/// When the target changes, the value smoothly animates to it using spring physics.
/// The animation is automatically registered with the scheduler and ticked each frame.
///
/// # Example
///
/// ```ignore
/// // Create an animated value (auto-registers with scheduler)
/// let opacity = AnimatedValue::new(ctx.animation_handle(), 1.0, SpringConfig::stiff());
///
/// // Change target - automatically animates
/// opacity.set_target(0.5);
///
/// // Get current animated value (interpolated)
/// let current = opacity.get();
/// ```
#[derive(Clone)]
pub struct AnimatedValue {
    handle: SchedulerHandle,
    spring_id: Option<SpringId>,
    config: SpringConfig,
    /// The last known value (updated when spring settles)
    current: f32,
    /// The target value we're animating towards
    target: f32,
}

impl AnimatedValue {
    /// Create a new animated value with the given initial value
    pub fn new(handle: SchedulerHandle, initial: f32, config: SpringConfig) -> Self {
        // Don't register immediately - only when we have a target change
        Self {
            handle,
            spring_id: None,
            config,
            current: initial,
            target: initial,
        }
    }

    /// Create with default spring config (stiff)
    pub fn with_default(handle: SchedulerHandle, initial: f32) -> Self {
        Self::new(handle, initial, SpringConfig::stiff())
    }

    /// Set the target value - starts animation if different from current
    pub fn set_target(&mut self, target: f32) {
        self.target = target;

        // If we have a spring, just update its target (spring persists until dropped)
        if let Some(id) = self.spring_id {
            self.handle.set_spring_target(id, target);
        } else {
            // No spring yet - create one if target differs from current
            if (target - self.current).abs() > 0.001 {
                let spring = Spring::new(self.config, self.current);
                if let Some(id) = self.handle.register_spring(spring) {
                    self.spring_id = Some(id);
                    self.handle.set_spring_target(id, target);
                    // Auto-register to current suspension scope
                    crate::suspension::register_spring(id);
                }
            }
        }
    }

    /// Get the current animated value
    pub fn get(&self) -> f32 {
        if let Some(id) = self.spring_id {
            // Try to get spring value; if spring was removed (settled), use target
            self.handle.get_spring_value(id).unwrap_or(self.target)
        } else {
            self.current
        }
    }

    /// Set value immediately without animation
    pub fn set_immediate(&mut self, value: f32) {
        // Remove any active spring
        if let Some(id) = self.spring_id.take() {
            self.handle.remove_spring(id);
        }
        self.current = value;
        self.target = value;
    }

    /// Pause the spring — freezes at current position, step() is no-op
    pub fn pause(&mut self) {
        if let Some(id) = self.spring_id {
            self.handle.pause_spring(id);
        }
    }

    /// Resume from paused state
    pub fn resume(&mut self) {
        if let Some(id) = self.spring_id {
            self.handle.resume_spring(id);
        }
    }

    /// Check if currently animating
    pub fn is_animating(&self) -> bool {
        if let Some(id) = self.spring_id {
            // Check actual settled state, not just existence
            !self.handle.is_spring_settled(id)
        } else {
            false
        }
    }

    /// Snap immediately to the target value, stopping any active animation
    ///
    /// This removes the spring entirely and sets the current value to the target.
    /// Useful for immediately completing an animation.
    pub fn snap_to_target(&mut self) {
        self.set_immediate(self.target);
    }

    /// Get the current target value
    pub fn target(&self) -> f32 {
        self.target
    }
}

impl Drop for AnimatedValue {
    fn drop(&mut self) {
        if let Some(id) = self.spring_id {
            crate::suspension::unregister_spring(id);
            self.handle.remove_spring(id);
        }
    }
}

// ============================================================================
// Animated Keyframe
// ============================================================================

/// A keyframe animation that automatically registers with the scheduler
///
/// Provides timed animations with easing functions between keyframes.
/// The animation is automatically registered and ticked by the scheduler.
///
/// # Example
///
/// ```ignore
/// use blinc_animation::{AnimatedKeyframe, Keyframe, Easing};
///
/// // Create a keyframe animation
/// let mut anim = AnimatedKeyframe::new(ctx.animation_handle(), 1000); // 1 second
///
/// // Add keyframes
/// anim.keyframe(0.0, 0.0, Easing::Linear);      // Start at 0
/// anim.keyframe(0.5, 100.0, Easing::EaseOut);   // Middle at 100
/// anim.keyframe(1.0, 50.0, Easing::EaseInOut);  // End at 50
///
/// // Start the animation
/// anim.start();
///
/// // Get current value (updated by scheduler)
/// let value = anim.get();
/// ```
#[derive(Clone)]
pub struct AnimatedKeyframe {
    handle: SchedulerHandle,
    keyframe_id: Option<KeyframeId>,
    duration_ms: u32,
    keyframes: Vec<Keyframe>,
    auto_start: bool,
    /// Number of iterations (-1 for infinite, 0 for none, 1 for once, etc.)
    iterations: i32,
    /// Whether to reverse direction on each iteration (ping-pong)
    ping_pong: bool,
    /// Current iteration count
    current_iteration: i32,
    /// Whether currently playing in reverse
    reversed: bool,
    /// Delay before animation starts (ms)
    delay_ms: u32,
    /// Time when animation started (for delay tracking)
    start_time: Option<Instant>,
}

impl AnimatedKeyframe {
    /// Create a new keyframe animation with the given duration
    pub fn new(handle: SchedulerHandle, duration_ms: u32) -> Self {
        Self {
            handle,
            keyframe_id: None,
            duration_ms,
            keyframes: Vec::new(),
            auto_start: false,
            iterations: 1, // Play once by default
            ping_pong: false,
            current_iteration: 0,
            reversed: false,
            delay_ms: 0,
            start_time: None,
        }
    }

    /// Add a keyframe at the given time position (0.0 to 1.0)
    pub fn keyframe(mut self, time: f32, value: f32, easing: Easing) -> Self {
        self.keyframes.push(Keyframe {
            time,
            value,
            easing,
        });
        self
    }

    /// Set whether to auto-start when registered
    pub fn auto_start(mut self, auto: bool) -> Self {
        self.auto_start = auto;
        self
    }

    /// Set number of iterations (-1 for infinite)
    pub fn iterations(mut self, count: i32) -> Self {
        self.iterations = count;
        self
    }

    /// Enable infinite looping
    pub fn loop_infinite(mut self) -> Self {
        self.iterations = -1;
        self
    }

    /// Enable ping-pong mode (reverse direction on each iteration)
    pub fn ping_pong(mut self, enabled: bool) -> Self {
        self.ping_pong = enabled;
        self
    }

    /// Set delay before animation starts (in milliseconds)
    pub fn delay(mut self, delay_ms: u32) -> Self {
        self.delay_ms = delay_ms;
        self
    }

    /// Build and register the animation, returning self for chaining
    pub fn build(mut self) -> Self {
        // Sort keyframes by time
        self.keyframes.sort_by(|a, b| {
            a.time
                .partial_cmp(&b.time)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Create the underlying animation (don't start it yet - we handle that)
        let animation = KeyframeAnimation::new(self.duration_ms, self.keyframes.clone());

        if let Some(id) = self.handle.register_keyframe(animation) {
            self.keyframe_id = Some(id);
        }

        // If auto_start, call our start() method which handles delay properly
        if self.auto_start {
            self.start();
        }

        self
    }

    /// Start the animation
    pub fn start(&mut self) {
        self.current_iteration = 0;
        self.reversed = false;

        // Track start time for delay
        if self.delay_ms > 0 {
            self.start_time = Some(Instant::now());
        } else {
            self.start_time = None;
        }

        if let Some(id) = self.keyframe_id {
            if self.delay_ms == 0 {
                self.handle.start_keyframe(id);
            }
            // If there's a delay, don't start yet - check_and_update will handle it
        } else {
            // Not yet registered - register now
            self.keyframes.sort_by(|a, b| {
                a.time
                    .partial_cmp(&b.time)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            let mut animation = KeyframeAnimation::new(self.duration_ms, self.keyframes.clone());
            if self.delay_ms == 0 {
                animation.start();
            }

            if let Some(id) = self.handle.register_keyframe(animation) {
                self.keyframe_id = Some(id);
            }
        }
    }

    /// Stop the animation
    pub fn stop(&mut self) {
        self.start_time = None;
        if let Some(id) = self.keyframe_id {
            self.handle.stop_keyframe(id);
        }
    }

    /// Restart the animation from the beginning
    pub fn restart(&mut self) {
        self.stop();
        self.start();
    }

    /// Check and handle iteration completion, delay, etc.
    /// Returns true if animation should continue running.
    fn check_and_update(&mut self) -> bool {
        // Handle delay
        if let Some(start_time) = self.start_time {
            let elapsed = start_time.elapsed().as_millis() as u32;
            if elapsed < self.delay_ms {
                return true; // Still in delay period
            }
            // Delay complete - start the actual animation
            self.start_time = None;
            if let Some(id) = self.keyframe_id {
                self.handle.start_keyframe(id);
            }
        }

        // Check if current iteration completed
        if let Some(id) = self.keyframe_id {
            if !self.handle.is_keyframe_playing(id) {
                // Animation finished this iteration
                self.current_iteration += 1;

                // Check if we should continue
                let should_continue =
                    self.iterations < 0 || self.current_iteration < self.iterations;

                if should_continue {
                    // Handle ping-pong
                    if self.ping_pong {
                        self.reversed = !self.reversed;
                    }
                    // Restart the animation for next iteration
                    self.handle.start_keyframe(id);
                    return true;
                }
            } else {
                return true; // Still playing
            }
        }

        false
    }

    /// Get the current animated value
    pub fn get(&mut self) -> f32 {
        // Check for iteration completion and handle looping
        self.check_and_update();

        // If in delay period, return initial value
        if self.start_time.is_some() {
            return self.get_initial_value();
        }

        if let Some(id) = self.keyframe_id {
            let raw_value = self.handle.get_keyframe_value(id).unwrap_or(0.0);

            // Apply reverse if in ping-pong and on reverse phase
            if self.reversed && !self.keyframes.is_empty() {
                // Map value from [start, end] to [end, start]
                let first = self.keyframes.first().map(|k| k.value).unwrap_or(0.0);
                let last = self.keyframes.last().map(|k| k.value).unwrap_or(0.0);
                // Reverse: if raw is at 'first' position, return 'last', and vice versa
                first + last - raw_value
            } else {
                raw_value
            }
        } else {
            self.get_initial_value()
        }
    }

    /// Get immutable value (doesn't check iteration)
    fn get_initial_value(&self) -> f32 {
        if !self.keyframes.is_empty() {
            self.keyframes[0].value
        } else {
            0.0
        }
    }

    /// Get the current progress (0.0 to 1.0)
    pub fn progress(&self) -> f32 {
        if let Some(id) = self.keyframe_id {
            let raw_progress = self.handle.get_keyframe_progress(id).unwrap_or(0.0);
            if self.reversed {
                1.0 - raw_progress
            } else {
                raw_progress
            }
        } else {
            0.0
        }
    }

    /// Check if the animation is playing (including during delay and looping)
    pub fn is_playing(&mut self) -> bool {
        // In delay period counts as playing
        if self.start_time.is_some() {
            return true;
        }

        // Check and update iteration state
        self.check_and_update();

        // Check if underlying animation is playing
        if let Some(id) = self.keyframe_id {
            if self.handle.is_keyframe_playing(id) {
                return true;
            }
            // If not playing, check if we should continue looping
            self.iterations < 0 || self.current_iteration < self.iterations
        } else {
            false
        }
    }
}

impl Drop for AnimatedKeyframe {
    fn drop(&mut self) {
        if let Some(id) = self.keyframe_id {
            self.handle.remove_keyframe(id);
        }
    }
}

// ============================================================================
// Animated Timeline
// ============================================================================

/// Trait for types that can be returned from `AnimatedTimeline::configure()`
///
/// Implemented for single `TimelineEntryId` and tuples of entry IDs.
/// This allows `configure()` to reconstruct the return value from stored entry IDs
/// when the timeline is already configured.
pub trait ConfigureResult {
    /// Reconstruct the result from a list of entry IDs
    fn from_entry_ids(ids: &[crate::timeline::TimelineEntryId]) -> Self;
}

impl ConfigureResult for crate::timeline::TimelineEntryId {
    fn from_entry_ids(ids: &[crate::timeline::TimelineEntryId]) -> Self {
        ids[0]
    }
}

impl ConfigureResult
    for (
        crate::timeline::TimelineEntryId,
        crate::timeline::TimelineEntryId,
    )
{
    fn from_entry_ids(ids: &[crate::timeline::TimelineEntryId]) -> Self {
        (ids[0], ids[1])
    }
}

impl ConfigureResult
    for (
        crate::timeline::TimelineEntryId,
        crate::timeline::TimelineEntryId,
        crate::timeline::TimelineEntryId,
    )
{
    fn from_entry_ids(ids: &[crate::timeline::TimelineEntryId]) -> Self {
        (ids[0], ids[1], ids[2])
    }
}

impl ConfigureResult for Vec<crate::timeline::TimelineEntryId> {
    fn from_entry_ids(ids: &[crate::timeline::TimelineEntryId]) -> Self {
        ids.to_vec()
    }
}

/// A timeline animation that automatically registers with the scheduler
///
/// Orchestrates multiple animations with offsets and looping support.
/// The timeline is automatically registered and ticked by the scheduler.
///
/// # Example
///
/// ```ignore
/// use blinc_animation::AnimatedTimeline;
///
/// // Create a timeline
/// let mut timeline = AnimatedTimeline::new(ctx.animation_handle());
///
/// // Add animations at different offsets
/// let opacity_id = timeline.add(0, 500, 0.0, 1.0);      // Fade in from 0-500ms
/// let scale_id = timeline.add(250, 500, 0.8, 1.0);      // Scale up from 250-750ms
/// let slide_id = timeline.add(0, 750, -100.0, 0.0);     // Slide in from 0-750ms
///
/// // Configure looping
/// timeline.set_loop(-1); // Infinite loop
///
/// // Start the timeline
/// timeline.start();
///
/// // Get values for each animation
/// let opacity = timeline.get(opacity_id);
/// let scale = timeline.get(scale_id);
/// let slide = timeline.get(slide_id);
/// ```
pub struct AnimatedTimeline {
    handle: SchedulerHandle,
    timeline_id: Option<TimelineId>,
}

impl AnimatedTimeline {
    /// Create a new timeline animation
    pub fn new(handle: SchedulerHandle) -> Self {
        // Register an empty timeline immediately
        let timeline = Timeline::new();
        let timeline_id = handle.register_timeline(timeline);

        Self {
            handle,
            timeline_id,
        }
    }

    /// Configure the timeline if not already configured, returning entry IDs
    ///
    /// The closure is only called on the first invocation (when the timeline has no entries).
    /// On subsequent calls, it returns the existing entry IDs.
    ///
    /// This is the recommended way to set up persisted timelines, as it handles
    /// both initial configuration and retrieval of existing entries in one call.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let timeline = ctx.use_animated_timeline();
    /// let entry_id = timeline.lock().unwrap().configure(|t| {
    ///     let id = t.add(0, 1000, 0.0, 1.0);
    ///     t.set_loop(-1);
    ///     t.start();
    ///     id  // Return entry ID(s) for later use
    /// });
    /// ```
    pub fn configure<T, F>(&mut self, f: F) -> T
    where
        F: FnOnce(&mut Self) -> T,
        T: ConfigureResult,
    {
        if self.has_entries() {
            // Already configured - return existing entry IDs
            T::from_entry_ids(&self.entry_ids())
        } else {
            // First time - run configuration
            f(self)
        }
    }

    /// Add an animation to the timeline
    ///
    /// Returns an entry ID that can be used to get the current value.
    pub fn add(
        &mut self,
        offset_ms: i32,
        duration_ms: u32,
        start_value: f32,
        end_value: f32,
    ) -> crate::timeline::TimelineEntryId {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| {
                    timeline.add(offset_ms, duration_ms, start_value, end_value)
                })
                .expect("Timeline should exist")
        } else {
            panic!("Timeline not registered - scheduler may have been dropped")
        }
    }

    /// Add an animation with a specific easing function
    pub fn add_with_easing(
        &mut self,
        offset_ms: i32,
        duration_ms: u32,
        start_value: f32,
        end_value: f32,
        easing: Easing,
    ) -> crate::timeline::TimelineEntryId {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| {
                    timeline.add_with_easing(offset_ms, duration_ms, start_value, end_value, easing)
                })
                .expect("Timeline should exist")
        } else {
            panic!("Timeline not registered - scheduler may have been dropped")
        }
    }

    /// Set loop count (-1 for infinite)
    pub fn set_loop(&mut self, count: i32) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.set_loop(count);
            });
        }
    }

    /// Enable/disable alternate (ping-pong) mode
    ///
    /// When enabled, the timeline reverses direction each loop instead of
    /// jumping back to the start.
    pub fn set_alternate(&mut self, enabled: bool) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.set_alternate(enabled);
            });
        }
    }

    /// Set playback rate (1.0 = normal speed, 2.0 = 2x speed)
    pub fn set_playback_rate(&mut self, rate: f32) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.set_playback_rate(rate);
            });
        }
    }

    /// Start the timeline
    ///
    /// If the timeline has finished and been removed from the scheduler,
    /// use `restart()` instead to re-register it.
    pub fn start(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.start_timeline(id);
        }
    }

    /// Restart the timeline from the beginning
    ///
    /// Resets the timeline to time 0 and starts playing.
    /// This works even after the timeline has completed.
    pub fn restart(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.start(); // start() already resets time to 0
            });
        }
    }

    /// Stop the timeline
    pub fn stop(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.stop_timeline(id);
        }
    }

    /// Pause the timeline (can be resumed)
    pub fn pause(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.pause();
            });
        }
    }

    /// Resume a paused timeline
    pub fn resume(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.resume();
            });
        }
    }

    /// Reverse the playback direction
    pub fn reverse(&self) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.reverse();
            });
        }
    }

    /// Seek to a specific time position (in milliseconds)
    pub fn seek(&self, time_ms: f32) {
        if let Some(id) = self.timeline_id {
            self.handle.with_timeline(id, |timeline| {
                timeline.seek(time_ms);
            });
        }
    }

    /// Get the current value for a timeline entry
    pub fn get(&self, entry_id: crate::timeline::TimelineEntryId) -> Option<f32> {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| timeline.value(entry_id))
                .flatten()
        } else {
            None
        }
    }

    /// Check if the timeline is playing
    pub fn is_playing(&self) -> bool {
        if let Some(id) = self.timeline_id {
            self.handle.is_timeline_playing(id)
        } else {
            false
        }
    }

    /// Get the overall timeline progress (0.0 to 1.0)
    pub fn progress(&self) -> f32 {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| timeline.progress())
                .unwrap_or(0.0)
        } else {
            0.0
        }
    }

    /// Get progress of a specific entry (0.0 to 1.0)
    pub fn entry_progress(&self, entry_id: crate::timeline::TimelineEntryId) -> Option<f32> {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| timeline.entry_progress(entry_id))
                .flatten()
        } else {
            None
        }
    }

    /// Check if the timeline has any entries
    ///
    /// Returns true if at least one animation has been added to the timeline.
    /// Useful for checking if a persisted timeline needs configuration.
    pub fn has_entries(&self) -> bool {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| timeline.entry_count() > 0)
                .unwrap_or(false)
        } else {
            false
        }
    }

    /// Get all entry IDs in this timeline
    ///
    /// Useful for retrieving persisted entry IDs after a timeline has been restored.
    pub fn entry_ids(&self) -> Vec<crate::timeline::TimelineEntryId> {
        if let Some(id) = self.timeline_id {
            self.handle
                .with_timeline(id, |timeline| timeline.entry_ids())
                .unwrap_or_default()
        } else {
            Vec::new()
        }
    }
}

impl Drop for AnimatedTimeline {
    fn drop(&mut self) {
        if let Some(id) = self.timeline_id {
            self.handle.remove_timeline(id);
        }
    }
}

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

    #[test]
    fn test_scheduler_tick() {
        let scheduler = AnimationScheduler::new();

        // Add a spring
        let spring = Spring::new(SpringConfig::stiff(), 0.0);
        let id = scheduler.add_spring(spring);
        scheduler.set_spring_target(id, 100.0);

        // Tick
        assert!(scheduler.tick());

        // Value should have moved
        let value = scheduler.get_spring_value(id).unwrap();
        assert!(value > 0.0);
    }

    #[test]
    fn test_animated_value() {
        let scheduler = AnimationScheduler::new();
        let handle = scheduler.handle();

        let mut value = AnimatedValue::new(handle, 0.0, SpringConfig::stiff());

        assert_eq!(value.get(), 0.0);
        assert!(!value.is_animating());

        // Set target
        value.set_target(100.0);
        assert!(value.is_animating());

        // Tick scheduler
        scheduler.tick();

        // Value should have moved
        assert!(value.get() > 0.0);
    }

    #[test]
    fn test_animated_keyframe() {
        let scheduler = AnimationScheduler::new();
        let handle = scheduler.handle();

        let mut anim = AnimatedKeyframe::new(handle, 1000)
            .keyframe(0.0, 0.0, Easing::Linear)
            .keyframe(1.0, 100.0, Easing::Linear);

        // Start animation
        anim.start();
        assert!(anim.is_playing());

        // Initial value should be 0
        assert_eq!(anim.get(), 0.0);

        // Tick scheduler (simulates time passing)
        scheduler.tick();

        // Animation should still be playing
        assert!(anim.is_playing());
    }

    #[test]
    fn test_animated_timeline() {
        let scheduler = AnimationScheduler::new();
        let handle = scheduler.handle();

        let mut timeline = AnimatedTimeline::new(handle);

        // Add an animation
        let entry = timeline.add(0, 1000, 0.0, 100.0);

        // Start timeline
        timeline.start();
        assert!(timeline.is_playing());

        // Initial value should be 0
        assert_eq!(timeline.get(entry), Some(0.0));

        // Tick scheduler
        scheduler.tick();

        // Timeline should still be playing
        assert!(timeline.is_playing());
    }

    #[test]
    fn test_handle_weak_reference() {
        let handle = {
            let scheduler = AnimationScheduler::new();
            scheduler.handle()
        };

        // Scheduler is dropped, handle should not be alive
        assert!(!handle.is_alive());

        // Operations should safely no-op
        assert!(handle
            .register_spring(Spring::new(SpringConfig::stiff(), 0.0))
            .is_none());
    }

    #[test]
    fn test_scheduler_counts() {
        let scheduler = AnimationScheduler::new();

        assert_eq!(scheduler.spring_count(), 0);
        assert_eq!(scheduler.keyframe_count(), 0);
        assert_eq!(scheduler.timeline_count(), 0);

        // Add animations
        let spring = Spring::new(SpringConfig::stiff(), 0.0);
        scheduler.add_spring(spring);

        let mut keyframe = KeyframeAnimation::new(
            1000,
            vec![Keyframe {
                time: 0.0,
                value: 0.0,
                easing: Easing::Linear,
            }],
        );
        keyframe.start();
        scheduler.add_keyframe(keyframe);

        let mut timeline = Timeline::new();
        timeline.add(0, 1000, 0.0, 100.0);
        timeline.start();
        scheduler.add_timeline(timeline);

        assert_eq!(scheduler.spring_count(), 1);
        assert_eq!(scheduler.keyframe_count(), 1);
        assert_eq!(scheduler.timeline_count(), 1);
    }
}