strata-dom 0.1.4

Core DOM, reactive signals, and synthetic event routing for Strata
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
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
//! Fine-grained reactive dependency tracking graph (SolidJS-grade, zero Virtual DOM).

use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;

pub type SignalId = usize;
pub type ScopeId = usize;

/// Generational subscriber identifier preventing stale-reference memory leaks and ABA hazards.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubscriberId {
    pub index: u32,
    pub generation: u32,
}

impl std::fmt::Display for SubscriberId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:v{}", self.index, self.generation)
    }
}

thread_local! {
    static RUNTIME: ReactiveRuntime = ReactiveRuntime::new();
}

pub type SubscriberCallback = Rc<RefCell<dyn FnMut()>>;

/// Per-signal read/write/subscriber telemetry entry for DevTools and rebuild attribution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignalTelemetryEntry {
    pub signal_id: SignalId,
    pub name: String,
    pub read_count: u64,
    pub write_count: u64,
    pub subscriber_count: usize,
    pub is_dirty: bool,
}

/// Live snapshot of the thread-local reactive signal graph and read/write activity.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReactiveTelemetrySnapshot {
    pub active_signals: usize,
    pub active_subscribers: usize,
    pub total_reads: u64,
    pub total_writes: u64,
    pub total_flushes: u64,
    pub cycle_guard_trips: u64,
    pub dirty_signal_names: Vec<String>,
    pub signals: Vec<SignalTelemetryEntry>,
    pub edges: Vec<(SignalId, SubscriberId)>,
}

/// Central thread-local reactive graph coordinator.
pub struct ReactiveRuntime {
    current_subscriber: Cell<Option<SubscriberId>>,
    evaluating_subscribers: RefCell<Vec<SubscriberId>>,
    signal_subscribers: RefCell<BTreeMap<SignalId, BTreeSet<SubscriberId>>>,
    subscriber_signals: RefCell<BTreeMap<SubscriberId, BTreeSet<SignalId>>>,
    signal_producer: RefCell<BTreeMap<SignalId, SubscriberId>>,
    subscriber_ranks: RefCell<BTreeMap<SubscriberId, usize>>,
    subscribers: RefCell<BTreeMap<SubscriberId, SubscriberCallback>>,
    pending_subscribers: RefCell<BTreeSet<(usize, SubscriberId)>>,
    subscriber_generations: RefCell<Vec<u32>>,
    free_subscriber_indices: RefCell<Vec<u32>>,
    batch_depth: Cell<usize>,
    dirty_signals: Cell<bool>,
    dirty_signal_ids: RefCell<Vec<SignalId>>,
    signal_names: RefCell<BTreeMap<SignalId, String>>,
    signal_read_counts: RefCell<BTreeMap<SignalId, u64>>,
    signal_write_counts: RefCell<BTreeMap<SignalId, u64>>,
    total_reads: Cell<u64>,
    total_writes: Cell<u64>,
    total_flushes: Cell<u64>,
    cycle_guard_trips: Cell<u64>,
    next_signal_id: Cell<SignalId>,
    next_scope_id: Cell<ScopeId>,
}

impl ReactiveRuntime {
    fn new() -> Self {
        Self {
            current_subscriber: Cell::new(None),
            evaluating_subscribers: RefCell::new(Vec::new()),
            signal_subscribers: RefCell::new(BTreeMap::new()),
            subscriber_signals: RefCell::new(BTreeMap::new()),
            signal_producer: RefCell::new(BTreeMap::new()),
            subscriber_ranks: RefCell::new(BTreeMap::new()),
            subscribers: RefCell::new(BTreeMap::new()),
            pending_subscribers: RefCell::new(BTreeSet::new()),
            subscriber_generations: RefCell::new(Vec::new()),
            free_subscriber_indices: RefCell::new(Vec::new()),
            batch_depth: Cell::new(0),
            dirty_signals: Cell::new(false),
            dirty_signal_ids: RefCell::new(Vec::new()),
            signal_names: RefCell::new(BTreeMap::new()),
            signal_read_counts: RefCell::new(BTreeMap::new()),
            signal_write_counts: RefCell::new(BTreeMap::new()),
            total_reads: Cell::new(0),
            total_writes: Cell::new(0),
            total_flushes: Cell::new(0),
            cycle_guard_trips: Cell::new(0),
            next_signal_id: Cell::new(1),
            next_scope_id: Cell::new(1),
        }
    }

    pub fn alloc_signal_id() -> SignalId {
        RUNTIME.with(|rt| {
            let id = rt.next_signal_id.get();
            rt.next_signal_id.set(id + 1);
            id
        })
    }

    pub fn alloc_subscriber_id() -> SubscriberId {
        RUNTIME.with(|rt| {
            let mut free = rt.free_subscriber_indices.borrow_mut();
            let mut gens = rt.subscriber_generations.borrow_mut();
            if let Some(idx) = free.pop() {
                let gen = gens[idx as usize];
                SubscriberId {
                    index: idx,
                    generation: gen,
                }
            } else {
                let idx = gens.len() as u32;
                gens.push(1);
                SubscriberId {
                    index: idx,
                    generation: 1,
                }
            }
        })
    }

    pub fn is_subscriber_alive(sub_id: SubscriberId) -> bool {
        RUNTIME
            .try_with(|rt| {
                if let Ok(gens) = rt.subscriber_generations.try_borrow() {
                    if let Some(&gen) = gens.get(sub_id.index as usize) {
                        return gen == sub_id.generation;
                    }
                }
                false
            })
            .unwrap_or(false)
    }

    pub fn active_subscriber_count() -> usize {
        RUNTIME
            .try_with(|rt| rt.subscribers.try_borrow().map(|s| s.len()).unwrap_or(0))
            .unwrap_or(0)
    }

    pub fn signal_subscription_count(signal_id: SignalId) -> usize {
        RUNTIME
            .try_with(|rt| {
                rt.signal_subscribers
                    .try_borrow()
                    .ok()
                    .and_then(|ss| ss.get(&signal_id).map(|s| s.len()))
                    .unwrap_or(0)
            })
            .unwrap_or(0)
    }

    pub fn alloc_scope_id() -> ScopeId {
        RUNTIME.with(|rt| {
            let id = rt.next_scope_id.get();
            rt.next_scope_id.set(id + 1);
            id
        })
    }

    pub fn has_dirty_signals() -> bool {
        RUNTIME
            .try_with(|rt| rt.dirty_signals.get())
            .unwrap_or(false)
    }

    pub fn take_dirty_signals() -> bool {
        RUNTIME
            .try_with(|rt| {
                if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
                    dirty_ids.clear();
                }
                rt.dirty_signals.replace(false)
            })
            .unwrap_or(false)
    }

    pub fn set_signal_name(signal_id: SignalId, name: impl Into<String>) {
        let name = name.into();
        let _ = RUNTIME.try_with(|rt| {
            if let Ok(mut names) = rt.signal_names.try_borrow_mut() {
                names.insert(signal_id, name);
            }
        });
    }

    pub fn signal_name(signal_id: SignalId) -> String {
        RUNTIME
            .try_with(|rt| {
                rt.signal_names
                    .try_borrow()
                    .ok()
                    .and_then(|names| names.get(&signal_id).cloned())
            })
            .ok()
            .flatten()
            .unwrap_or_else(|| format!("signal_{signal_id}"))
    }

    pub fn peek_dirty_signal_names() -> Vec<String> {
        RUNTIME
            .try_with(|rt| {
                let ids = rt
                    .dirty_signal_ids
                    .try_borrow()
                    .map(|v| v.clone())
                    .unwrap_or_default();
                let names = rt.signal_names.try_borrow().ok();
                ids.into_iter()
                    .map(|id| {
                        names
                            .as_ref()
                            .and_then(|m| m.get(&id).cloned())
                            .unwrap_or_else(|| format!("signal_{id}"))
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    pub fn take_dirty_signal_names() -> Vec<String> {
        RUNTIME
            .try_with(|rt| {
                rt.dirty_signals.set(false);
                let ids = if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
                    std::mem::take(&mut *dirty_ids)
                } else {
                    Vec::new()
                };
                let names = rt.signal_names.try_borrow().ok();
                ids.into_iter()
                    .map(|id| {
                        names
                            .as_ref()
                            .and_then(|m| m.get(&id).cloned())
                            .unwrap_or_else(|| format!("signal_{id}"))
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    pub fn telemetry_snapshot() -> ReactiveTelemetrySnapshot {
        RUNTIME
            .try_with(|rt| {
                let names = rt.signal_names.try_borrow().ok();
                let reads = rt.signal_read_counts.try_borrow().ok();
                let writes = rt.signal_write_counts.try_borrow().ok();
                let sig_subs = rt.signal_subscribers.try_borrow().ok();
                let dirty_ids: BTreeSet<SignalId> = rt
                    .dirty_signal_ids
                    .try_borrow()
                    .map(|v| v.iter().copied().collect())
                    .unwrap_or_default();

                let mut known_ids: BTreeSet<SignalId> = BTreeSet::new();
                if let Some(ref m) = names {
                    known_ids.extend(m.keys().copied());
                }
                if let Some(ref m) = reads {
                    known_ids.extend(m.keys().copied());
                }
                if let Some(ref m) = writes {
                    known_ids.extend(m.keys().copied());
                }
                if let Some(ref m) = sig_subs {
                    known_ids.extend(m.keys().copied());
                }

                let mut signals = Vec::with_capacity(known_ids.len());
                for id in known_ids {
                    let name = names
                        .as_ref()
                        .and_then(|m| m.get(&id).cloned())
                        .unwrap_or_else(|| format!("signal_{id}"));
                    let read_count = reads
                        .as_ref()
                        .and_then(|m| m.get(&id).copied())
                        .unwrap_or(0);
                    let write_count = writes
                        .as_ref()
                        .and_then(|m| m.get(&id).copied())
                        .unwrap_or(0);
                    let subscriber_count = sig_subs
                        .as_ref()
                        .and_then(|m| m.get(&id).map(|s| s.len()))
                        .unwrap_or(0);
                    signals.push(SignalTelemetryEntry {
                        signal_id: id,
                        name,
                        read_count,
                        write_count,
                        subscriber_count,
                        is_dirty: dirty_ids.contains(&id),
                    });
                }
                signals.sort_by(|a, b| {
                    b.write_count
                        .cmp(&a.write_count)
                        .then_with(|| b.read_count.cmp(&a.read_count))
                        .then_with(|| a.signal_id.cmp(&b.signal_id))
                });

                let mut edges = Vec::new();
                if let Some(ref m) = sig_subs {
                    for (&sig_id, subs) in m.iter() {
                        for &sub in subs {
                            edges.push((sig_id, sub));
                        }
                    }
                }

                let dirty_signal_names = dirty_ids
                    .iter()
                    .map(|id| {
                        names
                            .as_ref()
                            .and_then(|m| m.get(id).cloned())
                            .unwrap_or_else(|| format!("signal_{id}"))
                    })
                    .collect();

                let active_subscribers = rt
                    .subscribers
                    .try_borrow()
                    .map(|s| s.len())
                    .unwrap_or(0);

                ReactiveTelemetrySnapshot {
                    active_signals: signals.len(),
                    active_subscribers,
                    total_reads: rt.total_reads.get(),
                    total_writes: rt.total_writes.get(),
                    total_flushes: rt.total_flushes.get(),
                    cycle_guard_trips: rt.cycle_guard_trips.get(),
                    dirty_signal_names,
                    signals,
                    edges,
                }
            })
            .unwrap_or_default()
    }

    pub fn mark_dirty() {
        let _ = RUNTIME.try_with(|rt| rt.dirty_signals.set(true));
    }

    pub fn push_evaluating(sub_id: SubscriberId) -> bool {
        RUNTIME.with(|rt| {
            if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
                if stack.contains(&sub_id) {
                    false
                } else {
                    stack.push(sub_id);
                    true
                }
            } else {
                false
            }
        })
    }

    pub fn pop_evaluating(sub_id: SubscriberId) {
        let _ = RUNTIME.try_with(|rt| {
            if let Ok(mut stack) = rt.evaluating_subscribers.try_borrow_mut() {
                if let Some(pos) = stack.iter().rposition(|&id| id == sub_id) {
                    stack.remove(pos);
                }
            }
        });
    }

    pub fn is_evaluating(sub_id: SubscriberId) -> bool {
        RUNTIME
            .try_with(|rt| {
                rt.evaluating_subscribers
                    .try_borrow()
                    .map(|stack| stack.contains(&sub_id))
                    .unwrap_or(false)
            })
            .unwrap_or(false)
    }

    pub fn register_signal_producer(signal_id: SignalId, sub_id: SubscriberId) {
        RUNTIME.with(|rt| {
            if let Ok(mut map) = rt.signal_producer.try_borrow_mut() {
                map.insert(signal_id, sub_id);
            }
        });
    }

    pub fn track(signal_id: SignalId) {
        RUNTIME.with(|rt| {
            rt.total_reads.set(rt.total_reads.get().wrapping_add(1));
            if let Ok(mut reads) = rt.signal_read_counts.try_borrow_mut() {
                let c = reads.entry(signal_id).or_insert(0);
                *c = c.wrapping_add(1);
            }
            if let Some(sub_id) = rt.current_subscriber.get() {
                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
                    sig_subs.entry(signal_id).or_default().insert(sub_id);
                }
                if let Ok(mut sub_sigs) = rt.subscriber_signals.try_borrow_mut() {
                    sub_sigs.entry(sub_id).or_default().insert(signal_id);
                }

                // If this signal is produced by an upstream subscriber, update current subscriber's topological rank
                let producer_id = if let Ok(producers) = rt.signal_producer.try_borrow() {
                    producers.get(&signal_id).copied()
                } else {
                    None
                };

                if let Some(producer) = producer_id {
                    let producer_rank = if let Ok(ranks) = rt.subscriber_ranks.try_borrow() {
                        ranks.get(&producer).copied().unwrap_or(0)
                    } else {
                        0
                    };
                    if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
                        let current_rank = ranks.entry(sub_id).or_insert(0);
                        if *current_rank <= producer_rank {
                            *current_rank = producer_rank + 1;
                        }
                    }
                }
            }
        });
    }

    pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
        RUNTIME.with(|rt| {
            let prev = rt.current_subscriber.replace(None);
            let res = f();
            rt.current_subscriber.set(prev);
            res
        })
    }

    pub fn register_subscriber(sub_id: SubscriberId, runner: Rc<RefCell<dyn FnMut()>>) {
        RUNTIME.with(|rt| {
            if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
                subs.insert(sub_id, runner);
            }
        });
    }

    pub fn clear_subscriber_dependencies(sub_id: SubscriberId) {
        let _ = RUNTIME.try_with(|rt| {
            let signals = if let Ok(mut sub_signals) = rt.subscriber_signals.try_borrow_mut() {
                sub_signals.remove(&sub_id)
            } else {
                None
            };
            if let Some(signals) = signals {
                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
                    let mut empty_signals = Vec::new();
                    for sig in signals {
                        if let Some(subs) = sig_subs.get_mut(&sig) {
                            subs.remove(&sub_id);
                            if subs.is_empty() {
                                empty_signals.push(sig);
                            }
                        }
                    }
                    for sig in empty_signals {
                        sig_subs.remove(&sig);
                    }
                }
            }
        });
    }

    pub fn unregister_subscriber(sub_id: SubscriberId) {
        let was_valid = RUNTIME
            .try_with(|rt| {
                if let Ok(gens) = rt.subscriber_generations.try_borrow() {
                    if let Some(&gen) = gens.get(sub_id.index as usize) {
                        gen == sub_id.generation
                    } else {
                        false
                    }
                } else {
                    false
                }
            })
            .unwrap_or(false);

        if !was_valid {
            return;
        }

        Self::clear_subscriber_dependencies(sub_id);

        let removed = RUNTIME
            .try_with(|rt| {
                if let Ok(mut ranks) = rt.subscriber_ranks.try_borrow_mut() {
                    if let Some(rank) = ranks.remove(&sub_id) {
                        if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
                            pending.remove(&(rank, sub_id));
                        }
                    }
                }
                if let Ok(mut producers) = rt.signal_producer.try_borrow_mut() {
                    producers.retain(|_, &mut prod_sub| prod_sub != sub_id);
                }
                if let Ok(mut gens) = rt.subscriber_generations.try_borrow_mut() {
                    if let Some(gen) = gens.get_mut(sub_id.index as usize) {
                        *gen = gen.wrapping_add(1);
                    }
                }
                if let Ok(mut free) = rt.free_subscriber_indices.try_borrow_mut() {
                    free.push(sub_id.index);
                }
                if let Ok(mut evaluating) = rt.evaluating_subscribers.try_borrow_mut() {
                    evaluating.retain(|&id| id != sub_id);
                }
                if let Ok(mut subs) = rt.subscribers.try_borrow_mut() {
                    subs.remove(&sub_id)
                } else {
                    None
                }
            })
            .ok()
            .flatten();
        drop(removed);
    }

    pub fn notify(signal_id: SignalId) {
        let _ = RUNTIME.try_with(|rt| {
            rt.dirty_signals.set(true);
            rt.total_writes.set(rt.total_writes.get().wrapping_add(1));
            if let Ok(mut writes) = rt.signal_write_counts.try_borrow_mut() {
                let c = writes.entry(signal_id).or_insert(0);
                *c = c.wrapping_add(1);
            }
            if let Ok(mut dirty_ids) = rt.dirty_signal_ids.try_borrow_mut() {
                if dirty_ids.len() < 64 && !dirty_ids.contains(&signal_id) {
                    dirty_ids.push(signal_id);
                }
            }
            let mut stale_subs: Option<Vec<SubscriberId>> = None;

            if let Ok(sig_subs) = rt.signal_subscribers.try_borrow() {
                if let Some(subs_set) = sig_subs.get(&signal_id) {
                    if subs_set.is_empty() {
                        return;
                    }
                    let gens = rt.subscriber_generations.try_borrow().ok();
                    let ranks = rt.subscriber_ranks.try_borrow().ok();
                    if let Ok(mut pending) = rt.pending_subscribers.try_borrow_mut() {
                        for &sub in subs_set {
                            let is_alive = if let Some(ref g) = gens {
                                g.get(sub.index as usize).copied() == Some(sub.generation)
                            } else {
                                true
                            };
                            if is_alive {
                                let rank = ranks
                                    .as_ref()
                                    .and_then(|r| r.get(&sub).copied())
                                    .unwrap_or(0);
                                pending.insert((rank, sub));
                            } else {
                                stale_subs.get_or_insert_with(Vec::new).push(sub);
                            }
                        }
                    }
                } else {
                    return;
                }
            } else {
                return;
            }

            // Evict stale subscriptions automatically only when stale subscribers are encountered
            if let Some(stale_list) = stale_subs {
                if let Ok(mut sig_subs) = rt.signal_subscribers.try_borrow_mut() {
                    if let Some(subs_set) = sig_subs.get_mut(&signal_id) {
                        for stale in stale_list {
                            subs_set.remove(&stale);
                        }
                        if subs_set.is_empty() {
                            sig_subs.remove(&signal_id);
                        }
                    }
                }
            }

            if rt.batch_depth.get() == 0 {
                Self::flush();
            }
        });
    }

    pub fn batch<R>(f: impl FnOnce() -> R) -> R {
        RUNTIME.with(|rt| {
            let depth = rt.batch_depth.get();
            rt.batch_depth.set(depth + 1);

            let res = f();

            rt.batch_depth.set(depth);
            if depth == 0 {
                Self::flush();
            }
            res
        })
    }

    pub fn flush() {
        RUNTIME.with(|rt| {
            let mut loop_count: usize = 0;
            let mut ran_any = false;
            let mut run_counts: Option<std::collections::HashMap<SubscriberId, usize>> = None;
            const MAX_RUNS_PER_SUBSCRIBER: usize = 50;

            loop {
                let next_sub = {
                    let mut pending = if let Ok(p) = rt.pending_subscribers.try_borrow_mut() {
                        p
                    } else {
                        break;
                    };
                    if let Some(&(rank, sub_id)) = pending.iter().next() {
                        pending.remove(&(rank, sub_id));
                        Some(sub_id)
                    } else {
                        None
                    }
                };

                let sub_id = match next_sub {
                    Some(id) => id,
                    None => break,
                };

                if !Self::is_subscriber_alive(sub_id) {
                    continue;
                }

                loop_count += 1;
                if loop_count > 64 {
                    let map = run_counts.get_or_insert_with(std::collections::HashMap::new);
                    let count = map.entry(sub_id).or_insert(0);
                    *count += 1;
                    if *count > MAX_RUNS_PER_SUBSCRIBER {
                        rt.cycle_guard_trips
                            .set(rt.cycle_guard_trips.get().wrapping_add(1));
                        eprintln!(
                            "Strata Reactive Guard: Subscriber {} exceeded maximum recursive executions (possible circular dependency).",
                            sub_id
                        );
                        continue;
                    }
                }

                let runner = {
                    if let Ok(subs) = rt.subscribers.try_borrow() {
                        subs.get(&sub_id).cloned()
                    } else {
                        None
                    }
                };

                if let Some(runner) = runner {
                    ran_any = true;
                    Self::clear_subscriber_dependencies(sub_id);
                    let prev = rt.current_subscriber.replace(Some(sub_id));
                    if let Ok(mut r) = runner.try_borrow_mut() {
                        (*r)();
                    }
                    rt.current_subscriber.set(prev);
                }
            }
            if ran_any {
                rt.total_flushes.set(rt.total_flushes.get().wrapping_add(1));
            }
        });
    }
}

/// Fine-grained reactive state container.
#[derive(Clone)]
pub struct Signal<T> {
    id: SignalId,
    value: Rc<RefCell<T>>,
}

impl<T: Clone + 'static> Signal<T> {
    pub fn new(initial: T) -> Self {
        Self {
            id: ReactiveRuntime::alloc_signal_id(),
            value: Rc::new(RefCell::new(initial)),
        }
    }

    /// Creates a signal with an explicit debug/telemetry name for rebuild-reason attribution.
    pub fn named(initial: T, name: impl Into<String>) -> Self {
        let sig = Self::new(initial);
        ReactiveRuntime::set_signal_name(sig.id, name);
        sig
    }

    /// Assigns a debug/telemetry name to this signal and returns it.
    pub fn with_name(self, name: impl Into<String>) -> Self {
        ReactiveRuntime::set_signal_name(self.id, name);
        self
    }

    pub fn id(&self) -> SignalId {
        self.id
    }

    pub fn get(&self) -> T {
        ReactiveRuntime::track(self.id);
        self.value.borrow().clone()
    }

    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        ReactiveRuntime::track(self.id);
        f(&*self.value.borrow())
    }

    pub fn untracked_get(&self) -> T {
        self.value.borrow().clone()
    }

    /// Updates the inner signal value without marking reactive subscribers dirty (used for HMR hydration).
    pub fn set_untracked(&self, new_val: T) {
        *self.value.borrow_mut() = new_val;
    }

    pub fn set(&self, new_val: T) {
        *self.value.borrow_mut() = new_val;
        ReactiveRuntime::notify(self.id);
    }

    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        let res = f(&mut *self.value.borrow_mut());
        ReactiveRuntime::notify(self.id);
        res
    }

    pub fn read(&self) -> std::cell::Ref<'_, T> {
        ReactiveRuntime::track(self.id);
        self.value.borrow()
    }

    /// Splits this combined signal into decoupled read-only and write-only capabilities.
    pub fn split(&self) -> (ReadSignal<T>, WriteSignal<T>) {
        (
            ReadSignal {
                id: self.id,
                value: self.value.clone(),
            },
            WriteSignal {
                id: self.id,
                value: self.value.clone(),
            },
        )
    }
}

/// Read-only reactive signal capability.
#[derive(Clone)]
pub struct ReadSignal<T> {
    id: SignalId,
    value: Rc<RefCell<T>>,
}

impl<T: Clone + 'static> ReadSignal<T> {
    pub fn id(&self) -> SignalId {
        self.id
    }

    pub fn get(&self) -> T {
        ReactiveRuntime::track(self.id);
        self.value.borrow().clone()
    }

    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        ReactiveRuntime::track(self.id);
        f(&*self.value.borrow())
    }

    pub fn untracked_get(&self) -> T {
        self.value.borrow().clone()
    }

    pub fn read(&self) -> std::cell::Ref<'_, T> {
        ReactiveRuntime::track(self.id);
        self.value.borrow()
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for ReadSignal<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReadSignal")
            .field("id", &self.id)
            .field("value", &*self.value.borrow())
            .finish()
    }
}

/// Write-only reactive signal capability.
#[derive(Clone)]
pub struct WriteSignal<T> {
    id: SignalId,
    value: Rc<RefCell<T>>,
}

impl<T: Clone + 'static> WriteSignal<T> {
    pub fn id(&self) -> SignalId {
        self.id
    }

    pub fn set(&self, new_val: T) {
        *self.value.borrow_mut() = new_val;
        ReactiveRuntime::notify(self.id);
    }

    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        let res = f(&mut *self.value.borrow_mut());
        ReactiveRuntime::notify(self.id);
        res
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for WriteSignal<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WriteSignal").field("id", &self.id).finish()
    }
}

/// Idiomatic SolidJS/Leptos alias for write capability.
pub type SetSignal<T> = WriteSignal<T>;

/// Creates an atomic reactive cell with decoupled read and write capabilities.
pub fn create_signal<T: Clone + 'static>(initial: T) -> (ReadSignal<T>, WriteSignal<T>) {
    let sig = Signal::new(initial);
    sig.split()
}

/// RAII guard tracking an actively evaluating subscriber on the thread-local call stack.
pub struct EvaluatingGuard(SubscriberId);

impl EvaluatingGuard {
    pub fn new(sub_id: SubscriberId) -> Option<Self> {
        if ReactiveRuntime::push_evaluating(sub_id) {
            Some(Self(sub_id))
        } else {
            None
        }
    }
}

impl Drop for EvaluatingGuard {
    fn drop(&mut self) {
        ReactiveRuntime::pop_evaluating(self.0);
    }
}

struct MemoInner {
    subscriber_id: SubscriberId,
}

impl Drop for MemoInner {
    fn drop(&mut self) {
        ReactiveRuntime::unregister_subscriber(self.subscriber_id);
    }
}

/// Derived computed value that caches its output and only recomputes when dependencies change.
#[derive(Clone)]
pub struct Memo<T> {
    id: SignalId,
    value: Rc<RefCell<Option<T>>>,
    _inner: Rc<MemoInner>,
}

impl<T: Clone + PartialEq + 'static> Memo<T> {
    pub fn new(compute: impl FnMut() -> T + 'static) -> Self {
        Self::new_with_compare(compute, |a, b| a == b)
    }

    pub fn new_with_compare(
        compute: impl FnMut() -> T + 'static,
        is_equal: impl Fn(&T, &T) -> bool + 'static,
    ) -> Self {
        let signal_id = ReactiveRuntime::alloc_signal_id();
        let subscriber_id = ReactiveRuntime::alloc_subscriber_id();

        ReactiveRuntime::register_signal_producer(signal_id, subscriber_id);

        let value = Rc::new(RefCell::new(None));
        let compute_cell = Rc::new(RefCell::new(compute));
        let eq_cell = Rc::new(is_equal);

        let value_clone = value.clone();
        let compute_clone = compute_cell.clone();
        let eq_clone = eq_cell.clone();

        let runner = Rc::new(RefCell::new(move || {
            let _guard = match EvaluatingGuard::new(subscriber_id) {
                Some(guard) => guard,
                None => {
                    eprintln!(
                        "Strata Reactive Guard: Circular memo dependency detected for subscriber {}. Returning cached value.",
                        subscriber_id
                    );
                    return;
                }
            };

            ReactiveRuntime::clear_subscriber_dependencies(subscriber_id);
            let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
            let maybe_new_val = match compute_clone.try_borrow_mut() {
                Ok(mut compute) => Some(compute()),
                Err(_) => {
                    eprintln!(
                        "Strata Reactive Guard: Memo compute closure already borrowed for subscriber {}. Returning cached value.",
                        subscriber_id
                    );
                    None
                }
            };
            RUNTIME.with(|rt| rt.current_subscriber.set(prev));

            if let Some(new_val) = maybe_new_val {
                let changed = match value_clone.try_borrow().as_deref() {
                    Ok(Some(old_val)) => !eq_clone(old_val, &new_val),
                    Ok(None) => true,
                    Err(_) => true,
                };

                if let Ok(mut val) = value_clone.try_borrow_mut() {
                    *val = Some(new_val);
                }

                // Halt downstream propagation if output has not changed (O(1) memoization)
                if changed {
                    ReactiveRuntime::notify(signal_id);
                }
            }
        }));

        ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());

        // Initial evaluation
        if let Ok(r) = runner.try_borrow_mut() {
            (*r)();
        }

        Self {
            id: signal_id,
            value,
            _inner: Rc::new(MemoInner { subscriber_id }),
        }
    }

    pub fn id(&self) -> SignalId {
        self.id
    }

    pub fn get(&self) -> T {
        ReactiveRuntime::track(self.id);
        match self.value.borrow().as_ref() {
            Some(v) => v.clone(),
            None => panic!(
                "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
            ),
        }
    }

    pub fn try_get(&self) -> Option<T> {
        ReactiveRuntime::track(self.id);
        self.value.borrow().as_ref().cloned()
    }

    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        ReactiveRuntime::track(self.id);
        match self.value.borrow().as_ref() {
            Some(v) => f(v),
            None => panic!(
                "Strata Reactive Guard: Memo read before initial value could be computed (unresolvable circular dependency during initialization)."
            ),
        }
    }

    pub fn untracked_get(&self) -> T {
        match self.value.borrow().as_ref() {
            Some(v) => v.clone(),
            None => {
                panic!("Strata Reactive Guard: Memo read before initial value could be computed.")
            }
        }
    }
}

pub type CleanupFn = Option<Box<dyn FnOnce()>>;
pub type CleanupCell = Rc<RefCell<CleanupFn>>;

/// Reactive effect executing side-effects when subscribed signals mutate.
#[derive(Clone)]
pub struct Effect {
    subscriber_id: SubscriberId,
    disposed: Rc<Cell<bool>>,
    cleanup: CleanupCell,
}

impl Effect {
    pub fn new<F, R>(mut effect_fn: F) -> Self
    where
        F: FnMut() -> R + 'static,
        R: IntoEffectCleanup,
    {
        let subscriber_id = ReactiveRuntime::alloc_subscriber_id();
        let cleanup: CleanupCell = Rc::new(RefCell::new(None));
        let disposed = Rc::new(Cell::new(false));

        let cleanup_runner = cleanup.clone();
        let disposed_runner = disposed.clone();

        let runner = Rc::new(RefCell::new(move || {
            if disposed_runner.get() {
                return;
            }

            let _guard = match EvaluatingGuard::new(subscriber_id) {
                Some(guard) => guard,
                None => {
                    eprintln!(
                        "Strata Reactive Guard: Circular effect dependency detected for subscriber {}.",
                        subscriber_id
                    );
                    return;
                }
            };

            // Run previous cleanup closure if any
            if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
                if let Some(prev_clean) = cleanup.take() {
                    prev_clean();
                }
            }

            // Run effect
            let next_clean = {
                let _effect_guard = EffectBodyGuard::enter();
                effect_fn().into_effect_cleanup()
            };
            if let Ok(mut cleanup) = cleanup_runner.try_borrow_mut() {
                *cleanup = next_clean;
            }
        }));

        ReactiveRuntime::register_subscriber(subscriber_id, runner.clone());

        // Initial run
        {
            let prev = RUNTIME.with(|rt| rt.current_subscriber.replace(Some(subscriber_id)));
            if let Ok(mut r) = runner.try_borrow_mut() {
                (*r)();
            }
            RUNTIME.with(|rt| rt.current_subscriber.set(prev));
        }

        Self {
            subscriber_id,
            disposed,
            cleanup,
        }
    }

    pub fn dispose(&self) {
        if !self.disposed.replace(true) {
            ReactiveRuntime::unregister_subscriber(self.subscriber_id);
            if let Ok(mut cleanup) = self.cleanup.try_borrow_mut() {
                if let Some(clean) = cleanup.take() {
                    clean();
                }
            }
        }
    }
    /// Converts the effect into an RAII guard that disposes the effect when dropped.
    pub fn into_guard(self) -> EffectGuard {
        EffectGuard { effect: self }
    }
}

/// RAII guard that automatically disposes an effect when dropped.
pub struct EffectGuard {
    effect: Effect,
}

impl Drop for EffectGuard {
    fn drop(&mut self) {
        self.effect.dispose();
    }
}

// ============================================================================
// Component-Scoped Hook Cursor Stack & Lifecycle Management
// ============================================================================

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct ComponentSegment {
    component_id: String,
    instance_key: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct ComponentPath(Vec<ComponentSegment>);

struct PendingHookSlot;

struct ComponentInstance {
    slots: Vec<Box<dyn std::any::Any>>,
    mounted_children: std::collections::HashSet<ComponentPath>,
}

impl ComponentInstance {
    fn new() -> Self {
        Self {
            slots: Vec::new(),
            mounted_children: std::collections::HashSet::new(),
        }
    }
}

struct ActiveComponentFrame {
    path: ComponentPath,
    hook_cursor: usize,
    child_ordinals: std::collections::HashMap<String, usize>,
    visited_children: std::collections::HashSet<ComponentPath>,
    provided_context_count: usize,
}

struct HookStoreState {
    instances: std::collections::HashMap<ComponentPath, ComponentInstance>,
    active_stack: Vec<ActiveComponentFrame>,
    pending_key: Option<String>,
    next_hook_id: usize,
}

impl HookStoreState {
    fn new() -> Self {
        Self {
            instances: std::collections::HashMap::new(),
            active_stack: Vec::new(),
            pending_key: None,
            next_hook_id: 0,
        }
    }
}

struct ContextEntry {
    context_id: u64,
    value: Box<dyn std::any::Any>,
}

thread_local! {
    static HOOK_STORE: RefCell<HookStoreState> = RefCell::new(HookStoreState::new());
    static CONTEXT_STACK: RefCell<Vec<ContextEntry>> = const { RefCell::new(Vec::new()) };
    static NEXT_CONTEXT_ID: Cell<u64> = const { Cell::new(1) };
}

/// RAII guard emitted automatically at the top of every `#[component]` function body.
///
/// Tracks the component's hierarchical instance identity, resets its hook cursor to `0`
/// for the current render pass, pops component-scoped context providers on exit, and
/// disposes unmounted child component subtrees (running their `use_effect` cleanups)
/// when the render finishes without unwinding.
pub struct ComponentScopeGuard {
    _private: (),
}

impl ComponentScopeGuard {
    /// Enters a component render scope for `component_id`.
    pub fn enter(component_id: &'static str) -> Self {
        HOOK_STORE.with(|store| {
            let mut st = store.borrow_mut();
            let explicit_key = st.pending_key.take();

            let path = if let Some(parent) = st.active_stack.last_mut() {
                let instance_key = match explicit_key {
                    Some(k) => format!("k:{k}"),
                    None => {
                        let ord = parent
                            .child_ordinals
                            .entry(component_id.to_string())
                            .or_insert(0);
                        let current = *ord;
                        *ord += 1;
                        format!("#{current}")
                    }
                };
                let mut segs = parent.path.0.clone();
                segs.push(ComponentSegment {
                    component_id: component_id.to_string(),
                    instance_key,
                });
                let child_path = ComponentPath(segs);
                parent.visited_children.insert(child_path.clone());
                child_path
            } else {
                let instance_key = match explicit_key {
                    Some(k) => format!("k:{k}"),
                    None => "#0".to_string(),
                };
                ComponentPath(vec![ComponentSegment {
                    component_id: component_id.to_string(),
                    instance_key,
                }])
            };

            st.instances
                .entry(path.clone())
                .or_insert_with(ComponentInstance::new);

            st.active_stack.push(ActiveComponentFrame {
                path,
                hook_cursor: 0,
                child_ordinals: std::collections::HashMap::new(),
                visited_children: std::collections::HashSet::new(),
                provided_context_count: 0,
            });
        });

        Self { _private: () }
    }
}

fn collect_unmounted_subtree(
    instances: &mut std::collections::HashMap<ComponentPath, ComponentInstance>,
    root: &ComponentPath,
    out: &mut Vec<ComponentInstance>,
) {
    if let Some(inst) = instances.remove(root) {
        let children: Vec<ComponentPath> = inst.mounted_children.iter().cloned().collect();
        out.push(inst);
        for child in children {
            collect_unmounted_subtree(instances, &child, out);
        }
    }
}

impl Drop for ComponentScopeGuard {
    fn drop(&mut self) {
        let unwinding = std::thread::panicking();
        let (pop_contexts, evicted) = HOOK_STORE.with(|store| {
            let mut st = store.borrow_mut();
            let Some(frame) = st.active_stack.pop() else {
                return (0usize, Vec::new());
            };
            let mut evicted = Vec::new();
            if !unwinding {
                let prev_children = st
                    .instances
                    .get_mut(&frame.path)
                    .map(|inst| {
                        std::mem::replace(&mut inst.mounted_children, frame.visited_children.clone())
                    })
                    .unwrap_or_default();
                for stale in prev_children {
                    if !frame.visited_children.contains(&stale) {
                        collect_unmounted_subtree(&mut st.instances, &stale, &mut evicted);
                    }
                }
            }
            (frame.provided_context_count, evicted)
        });

        if pop_contexts > 0 {
            CONTEXT_STACK.with(|stack| {
                let mut stack = stack.borrow_mut();
                let new_len = stack.len().saturating_sub(pop_contexts);
                stack.truncate(new_len);
            });
        }

        // Drop evicted component instances OUTSIDE any HOOK_STORE borrow so `use_effect`
        // cleanup callbacks can freely inspect or update signals without borrow conflicts.
        drop(evicted);
    }
}

/// Assigns an explicit reconciliation key to the immediate child component rendered inside `f`,
/// preserving its hook state across list reorderings.
pub fn with_component_key<R>(key: impl std::fmt::Display, f: impl FnOnce() -> R) -> R {
    struct KeyRestoreGuard(Option<String>);
    impl Drop for KeyRestoreGuard {
        fn drop(&mut self) {
            let prev = self.0.take();
            let _ = HOOK_STORE.try_with(|store| {
                if let Ok(mut st) = store.try_borrow_mut() {
                    st.pending_key = prev;
                }
            });
        }
    }

    let prev = HOOK_STORE.with(|store| store.borrow_mut().pending_key.replace(key.to_string()));
    let _guard = KeyRestoreGuard(prev);
    f()
}

/// Evaluates `f` inside an implicit root component scope when no `#[component]` scope is
/// active on the current thread.
///
/// Wrapping plain root view closures (e.g. `|| rsx! { <> <Child /> <Child /> </> }`) gives
/// top-level unkeyed sibling components distinct ordinals (`#0`, `#1`, ...) instead of colliding
/// on `#0`, and runs child unmount / `use_effect` cleanup when siblings are toggled off.
pub fn with_root_component_scope<R>(f: impl FnOnce() -> R) -> R {
    let has_active = HOOK_STORE.with(|store| !store.borrow().active_stack.is_empty());
    if has_active {
        f()
    } else {
        let _root_scope = ComponentScopeGuard::enter("__strata_root__");
        f()
    }
}

/// Clears all persisted component-scoped hook state and runs pending effect cleanups on this
/// thread. Intended for test isolation or full application resets.
pub fn reset_component_hooks() {
    let evicted: Vec<ComponentInstance> = HOOK_STORE.with(|store| {
        let mut st = store.borrow_mut();
        st.active_stack.clear();
        st.pending_key = None;
        st.next_hook_id = 0;
        st.instances.drain().map(|(_, inst)| inst).collect()
    });
    CONTEXT_STACK.with(|stack| stack.borrow_mut().clear());
    drop(evicted);
}

thread_local! {
    static EFFECT_BODY_DEPTH: Cell<usize> = const { Cell::new(0) };
}

struct EffectBodyGuard;

impl EffectBodyGuard {
    #[inline]
    fn enter() -> Self {
        EFFECT_BODY_DEPTH.with(|d| d.set(d.get() + 1));
        Self
    }
}

impl Drop for EffectBodyGuard {
    #[inline]
    fn drop(&mut self) {
        let _ = EFFECT_BODY_DEPTH.try_with(|d| d.set(d.get().saturating_sub(1)));
    }
}

/// Returns `true` when executing directly inside a `#[component]` render body (not inside an
/// `Effect` or `use_effect_with_deps` callback where hook slots must not be allocated).
#[inline]
pub(crate) fn in_component_hook_context() -> bool {
    let in_effect = EFFECT_BODY_DEPTH.with(|d| d.get() > 0);
    if in_effect {
        return false;
    }
    HOOK_STORE.with(|store| !store.borrow().active_stack.is_empty())
}

/// Looks up or initializes the current hook slot for the active component frame.
///
/// Returns `None` when called outside any `#[component]` scope so standalone unit tests
/// and top-level state builders continue working without a component frame.
pub(crate) fn use_hook_slot_cloned<T: Clone + 'static>(init: impl FnOnce() -> T) -> Option<T> {
    enum Lookup<T> {
        NoScope,
        Hit(T),
        Miss(ComponentPath, usize),
    }

    let lookup = HOOK_STORE.with(|store| {
        let mut st = store.borrow_mut();
        let Some(frame) = st.active_stack.last_mut() else {
            return Lookup::NoScope;
        };
        let path = frame.path.clone();
        let idx = frame.hook_cursor;
        frame.hook_cursor += 1;

        let inst = st
            .instances
            .entry(path.clone())
            .or_insert_with(ComponentInstance::new);

        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
            let existing = inst.slots[idx]
                .downcast_ref::<T>()
                .unwrap_or_else(|| {
                    panic!(
                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
                        path.0
                            .last()
                            .map(|s| s.component_id.as_str())
                            .unwrap_or("<root>")
                    )
                })
                .clone();
            Lookup::Hit(existing)
        } else {
            while inst.slots.len() <= idx {
                inst.slots.push(Box::new(PendingHookSlot));
            }
            Lookup::Miss(path, idx)
        }
    });

    match lookup {
        Lookup::NoScope => None,
        Lookup::Hit(val) => Some(val),
        Lookup::Miss(path, idx) => {
            // Run `init()` completely outside any HOOK_STORE borrow so closures may
            // read/write signals, access context, or construct reactive subscribers safely.
            let val = init();
            HOOK_STORE.with(|store| {
                let mut st = store.borrow_mut();
                if let Some(inst) = st.instances.get_mut(&path) {
                    if idx < inst.slots.len() {
                        inst.slots[idx] = Box::new(val.clone());
                    }
                }
            });
            Some(val)
        }
    }
}

/// Like [`use_hook_slot_cloned`], but falls back directly to `init()` when outside a
/// `#[component]` scope so non-`Clone` `FnOnce` initializers are only moved once.
fn use_hook_slot_or_init<T: Clone + 'static>(init: impl FnOnce() -> T) -> T {
    enum Lookup<T> {
        NoScope,
        Hit(T),
        Miss(ComponentPath, usize),
    }

    let lookup = HOOK_STORE.with(|store| {
        let mut st = store.borrow_mut();
        let Some(frame) = st.active_stack.last_mut() else {
            return Lookup::NoScope;
        };
        let path = frame.path.clone();
        let idx = frame.hook_cursor;
        frame.hook_cursor += 1;

        let inst = st
            .instances
            .entry(path.clone())
            .or_insert_with(ComponentInstance::new);

        if idx < inst.slots.len() && !inst.slots[idx].is::<PendingHookSlot>() {
            let existing = inst.slots[idx]
                .downcast_ref::<T>()
                .unwrap_or_else(|| {
                    panic!(
                        "Strata Rules of Hooks violation at slot #{idx} in component `{}`: hook type mismatch across renders (avoid calling hooks conditionally).",
                        path.0
                            .last()
                            .map(|s| s.component_id.as_str())
                            .unwrap_or("<root>")
                    )
                })
                .clone();
            Lookup::Hit(existing)
        } else {
            while inst.slots.len() <= idx {
                inst.slots.push(Box::new(PendingHookSlot));
            }
            Lookup::Miss(path, idx)
        }
    });

    match lookup {
        Lookup::NoScope => init(),
        Lookup::Hit(val) => val,
        Lookup::Miss(path, idx) => {
            let val = init();
            HOOK_STORE.with(|store| {
                let mut st = store.borrow_mut();
                if let Some(inst) = st.instances.get_mut(&path) {
                    if idx < inst.slots.len() {
                        inst.slots[idx] = Box::new(val.clone());
                    }
                }
            });
            val
        }
    }
}

/// Owned wrapper stored inside a component's hook slot so unmounting the component
/// automatically disposes its `Effect` and executes the cleanup closure.
#[derive(Clone)]
struct OwnedComponentEffect {
    effect: Effect,
    _owner: Rc<EffectDropGuard>,
}

struct EffectDropGuard(Effect);

impl Drop for EffectDropGuard {
    fn drop(&mut self) {
        self.0.dispose();
    }
}

/// Owned wrapper for dependency-tracked `use_effect_with_deps` cleanup closures.
struct OwnedDepsEffect<D> {
    deps: Rc<RefCell<D>>,
    cleanup: CleanupCell,
    _owner: Rc<CleanupDropGuard>,
}

impl<D> Clone for OwnedDepsEffect<D> {
    fn clone(&self) -> Self {
        Self {
            deps: Rc::clone(&self.deps),
            cleanup: Rc::clone(&self.cleanup),
            _owner: Rc::clone(&self._owner),
        }
    }
}

struct CleanupDropGuard(CleanupCell);

impl Drop for CleanupDropGuard {
    fn drop(&mut self) {
        if let Ok(mut cell) = self.0.try_borrow_mut() {
            if let Some(clean) = cell.take() {
                clean();
            }
        }
    }
}

/// Trait allowing [`use_state`] to accept either a direct initial value (`use_state(0)`)
/// or a lazy initializer closure (`use_state(|| expensive())`), matching React's `useState`.
pub trait IntoInitialState<T, Marker = ()> {
    fn into_initial_state(self) -> T;
}

impl<T> IntoInitialState<T, ()> for T {
    #[inline]
    fn into_initial_state(self) -> T {
        self
    }
}

impl<T, F: FnOnce() -> T> IntoInitialState<T, ((),)> for F {
    #[inline]
    fn into_initial_state(self) -> T {
        self()
    }
}

// ============================================================================
// Ergonomic Component Hooks
// ============================================================================

/// Creates or retrieves a component-scoped reactive [`Signal`].
///
/// Inside a `#[component]`, the signal persists across re-renders at this hook cursor slot;
/// outside any component scope, allocates a fresh standalone `Signal`.
pub fn use_signal<T: Clone + 'static>(initial: T) -> Signal<T> {
    use_hook_slot_or_init(|| Signal::new(initial))
}

thread_local! {
    static PERSISTENT_SIGNALS: RefCell<std::collections::HashMap<String, Box<dyn std::any::Any>>> =
        RefCell::new(std::collections::HashMap::new());
}

/// Returns a signal that survives root re-invocation, identified by an explicit `key`.
///
/// Useful when sharing keyed state across disconnected subtrees or outside `#[component]`.
/// Asking for the same key with a different type panics, since that is a key clash.
pub fn use_persistent_signal<T: Clone + 'static>(key: &str, init: impl FnOnce() -> T) -> Signal<T> {
    PERSISTENT_SIGNALS.with(|store| {
        let mut store = store.borrow_mut();
        if let Some(existing) = store.get(key) {
            return existing
                .downcast_ref::<Signal<T>>()
                .unwrap_or_else(|| panic!("persistent signal key `{key}` reused with another type"))
                .clone();
        }
        let signal = Signal::new(init());
        store.insert(key.to_string(), Box::new(signal.clone()));
        signal
    })
}

/// Drops all persistent signals and component-scoped hooks on this thread. Intended for tests.
pub fn clear_persistent_signals() {
    PERSISTENT_SIGNALS.with(|store| store.borrow_mut().clear());
    reset_component_hooks();
}

/// React-style component-scoped state hook returning decoupled `(ReadSignal<T>, WriteSignal<T>)`.
///
/// Accepts either a direct value (`use_state(0)`) or a lazy initializer closure
/// (`use_state(|| compute_initial())`). Inside a `#[component]`, the initializer runs only on
/// mount and the underlying signal persists across re-renders via the component hook cursor.
pub fn use_state<T: Clone + 'static, M>(
    initial: impl IntoInitialState<T, M>,
) -> (ReadSignal<T>, WriteSignal<T>) {
    let sig = use_hook_slot_or_init(|| Signal::new(initial.into_initial_state()));
    sig.split()
}

/// Component-scoped derived [`Memo`] that persists its reactive subscription across re-renders
/// and unregisters automatically when the component unmounts.
pub fn use_memo<T: Clone + PartialEq + 'static>(compute: impl FnMut() -> T + 'static) -> Memo<T> {
    use_hook_slot_or_init(|| Memo::new(compute))
}

/// React-style dependency-array memoization hook (`useMemo(() => compute(&deps), [deps])`).
///
/// Computes `compute(&deps)` on mount and recomputes only when `deps` changes (`PartialEq`)
/// across component re-renders, returning a cached clone in between.
pub fn use_memo_with_deps<D, T, F>(deps: D, compute: F) -> T
where
    D: PartialEq + 'static,
    T: Clone + 'static,
    F: FnOnce(&D) -> T,
{
    let mut deps_opt = Some(deps);
    let mut compute_opt = Some(compute);

    if let Some(cell) = use_hook_slot_cloned(|| {
        let initial_deps = deps_opt.take().unwrap();
        let initial_val = (compute_opt.take().unwrap())(&initial_deps);
        Rc::new(RefCell::new((initial_deps, initial_val)))
    }) {
        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), compute_opt.take()) {
            let changed = cell.borrow().0 != new_deps;
            if changed {
                let next_val = run_fn(&new_deps);
                let mut guard = cell.borrow_mut();
                guard.0 = new_deps;
                guard.1 = next_val;
            }
        }
        return cell.borrow().1.clone();
    }

    let d = deps_opt.take().unwrap();
    (compute_opt.take().unwrap())(&d)
}

/// Component-scoped reactive [`Effect`] that tracks read signals, runs cleanup before each
/// re-execution, avoids duplicate registrations across re-renders, and automatically runs its
/// cleanup closure when the owning component unmounts.
pub fn use_effect<F, R>(effect_fn: F) -> Effect
where
    F: FnMut() -> R + 'static,
    R: IntoEffectCleanup,
{
    let mut effect_opt = Some(effect_fn);
    if let Some(owned) = use_hook_slot_cloned(|| {
        let eff = Effect::new(effect_opt.take().unwrap());
        OwnedComponentEffect {
            effect: eff.clone(),
            _owner: Rc::new(EffectDropGuard(eff)),
        }
    }) {
        owned.effect
    } else {
        Effect::new(effect_opt.take().unwrap())
    }
}

/// Converts the return value of a [`use_effect_with_deps`] callback into an optional cleanup closure.
///
/// Implemented for `()` (no cleanup, eliminating trailing `None`),
/// `Option<Box<dyn FnOnce()>>` (backward compatible), `Box<dyn FnOnce()>`, and `Box<F>` for any
/// `F: FnOnce() + 'static` without requiring manual trait-object casts.
pub trait IntoEffectCleanup {
    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>>;
}

impl IntoEffectCleanup for () {
    #[inline]
    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        None
    }
}

impl IntoEffectCleanup for Option<Box<dyn FnOnce()>> {
    #[inline]
    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        self
    }
}

impl IntoEffectCleanup for Box<dyn FnOnce()> {
    #[inline]
    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        Some(self)
    }
}

impl<F: FnOnce() + 'static> IntoEffectCleanup for Box<F> {
    #[inline]
    fn into_effect_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        Some(self)
    }
}

/// React-style dependency-array effect hook.
///
/// Runs `effect_fn(&deps)` on mount and whenever `deps` changes (`PartialEq`) across component
/// re-renders, invoking the prior cleanup closure before re-running and again on unmount.
/// Callbacks may return `()` (no cleanup), `Box::new(move || ...)` / `Box<dyn FnOnce()>`,
/// or `Option<Box<dyn FnOnce()>>`.
pub fn use_effect_with_deps<D, R, F>(deps: D, effect_fn: F)
where
    D: PartialEq + 'static,
    R: IntoEffectCleanup,
    F: FnOnce(&D) -> R,
{
    let mut effect_opt = Some(effect_fn);
    let mut deps_opt = Some(deps);

    if let Some(slot) = use_hook_slot_cloned(|| {
        let initial_deps = deps_opt.take().unwrap();
        let initial_clean = {
            let _effect_guard = EffectBodyGuard::enter();
            (effect_opt.take().unwrap())(&initial_deps).into_effect_cleanup()
        };
        let cleanup: CleanupCell = Rc::new(RefCell::new(initial_clean));
        OwnedDepsEffect {
            deps: Rc::new(RefCell::new(initial_deps)),
            cleanup: cleanup.clone(),
            _owner: Rc::new(CleanupDropGuard(cleanup)),
        }
    }) {
        // If `effect_opt` is still `Some`, this is a re-render (slot already existed on mount).
        if let (Some(new_deps), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
            let changed = *slot.deps.borrow() != new_deps;
            if changed {
                let prev_clean = slot.cleanup.borrow_mut().take();
                if let Some(clean) = prev_clean {
                    clean();
                }
                let next_clean = {
                    let _effect_guard = EffectBodyGuard::enter();
                    run_fn(&new_deps).into_effect_cleanup()
                };
                *slot.deps.borrow_mut() = new_deps;
                *slot.cleanup.borrow_mut() = next_clean;
            }
        }
    } else if let (Some(d), Some(run_fn)) = (deps_opt.take(), effect_opt.take()) {
        // Standalone execution outside any component scope: run immediately.
        let _effect_guard = EffectBodyGuard::enter();
        let _ = run_fn(&d).into_effect_cleanup();
    }
}

struct ReducerSlot<S: Clone + 'static, A: 'static, R: 'static> {
    state: Signal<S>,
    reducer: Rc<RefCell<R>>,
    dispatch: Rc<dyn Fn(A)>,
}

impl<S: Clone + 'static, A: 'static, R: 'static> Clone for ReducerSlot<S, A, R> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            reducer: Rc::clone(&self.reducer),
            dispatch: Rc::clone(&self.dispatch),
        }
    }
}

/// React-style `useReducer` hook returning `(ReadSignal<S>, Rc<dyn Fn(A)>)`.
///
/// Persists state, reducer closure, and `dispatch` handle in the component hook slot so
/// `dispatch` preserves pointer identity (`Rc::ptr_eq`) across re-renders.
pub fn use_reducer<S, A, R>(reducer: R, initial_state: S) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
where
    S: Clone + 'static,
    A: 'static,
    R: FnMut(&S, A) -> S + 'static,
{
    use_reducer_init(reducer, initial_state, |s| s)
}

/// React-style 3-argument `useReducer` hook with lazy state initialization (`init(initial_arg)`).
///
/// Preserves the `dispatch` `Rc` identity across component re-renders while refreshing the active
/// reducer closure so inline reducers always see up-to-date prop captures.
pub fn use_reducer_init<S, A, I, R, F>(
    reducer: R,
    initial_arg: I,
    init: F,
) -> (ReadSignal<S>, Rc<dyn Fn(A)>)
where
    S: Clone + 'static,
    A: 'static,
    R: FnMut(&S, A) -> S + 'static,
    F: FnOnce(I) -> S,
{
    let mut reducer_opt = Some(reducer);
    let mut init_opt = Some((initial_arg, init));

    let slot = use_hook_slot_or_init(|| {
        let (arg, init_fn) = init_opt.take().unwrap();
        let state = Signal::new(init_fn(arg));
        let reducer_cell = Rc::new(RefCell::new(reducer_opt.take().unwrap()));
        let dispatch_sig = state.clone();
        let dispatch_reducer = Rc::clone(&reducer_cell);
        let dispatch: Rc<dyn Fn(A)> = Rc::new(move |action: A| {
            let current = dispatch_sig.untracked_get();
            let next = {
                let mut r = dispatch_reducer.borrow_mut();
                r(&current, action)
            };
            dispatch_sig.set(next);
        });
        ReducerSlot {
            state,
            reducer: reducer_cell,
            dispatch,
        }
    });

    if let Some(latest_reducer) = reducer_opt.take() {
        *slot.reducer.borrow_mut() = latest_reducer;
    }

    (slot.state.split().0, slot.dispatch)
}

/// Mutable, non-reactive reference container persisted across component re-renders (React `useRef`).
///
/// Mutating a [`Ref`] never marks the reactive graph dirty or triggers a re-render.
pub struct Ref<T> {
    inner: Rc<RefCell<T>>,
}

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

impl<T: std::fmt::Debug> std::fmt::Debug for Ref<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ref")
            .field("current", &*self.inner.borrow())
            .finish()
    }
}

impl<T: 'static> Ref<T> {
    pub fn new(initial: T) -> Self {
        Self {
            inner: Rc::new(RefCell::new(initial)),
        }
    }

    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.inner.borrow().clone()
    }

    pub fn set(&self, value: T) {
        *self.inner.borrow_mut() = value;
    }

    pub fn replace(&self, value: T) -> T {
        std::mem::replace(&mut *self.inner.borrow_mut(), value)
    }

    pub fn borrow(&self) -> std::cell::Ref<'_, T> {
        self.inner.borrow()
    }

    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
        self.inner.borrow_mut()
    }

    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        f(&*self.inner.borrow())
    }

    pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        f(&mut *self.inner.borrow_mut())
    }
}

/// React-style `useRef` hook returning a mutable [`Ref<T>`] that persists across re-renders
/// without triggering reactive updates.
pub fn use_ref<T: 'static>(initial: T) -> Ref<T> {
    use_hook_slot_or_init(|| Ref::new(initial))
}

/// React-style `useCallback` hook that memoizes a closure `Rc<F>` across re-renders while
/// `deps` remains equal (`PartialEq`).
///
/// When `deps` is unchanged, the returned `Rc<F>` preserves exact pointer identity (`Rc::ptr_eq`).
pub fn use_callback<D, F>(deps: D, callback: F) -> Rc<F>
where
    D: PartialEq + 'static,
    F: 'static,
{
    let mut deps_opt = Some(deps);
    let mut cb_opt = Some(callback);

    if let Some(cell) = use_hook_slot_cloned(|| {
        Rc::new(RefCell::new((
            deps_opt.take().unwrap(),
            Rc::new(cb_opt.take().unwrap()),
        )))
    }) {
        if let (Some(new_deps), Some(new_cb)) = (deps_opt.take(), cb_opt.take()) {
            let mut guard = cell.borrow_mut();
            if guard.0 != new_deps {
                guard.0 = new_deps;
                guard.1 = Rc::new(new_cb);
            }
            return Rc::clone(&guard.1);
        }
        return Rc::clone(&cell.borrow().1);
    }

    Rc::new(cb_opt.take().unwrap())
}

/// React-style `useId` hook generating a stable unique identifier (e.g. `":r0:"`) that persists
/// across re-renders of the same component instance and is unique across sibling instances.
pub fn use_id() -> String {
    let alloc = || {
        HOOK_STORE.with(|store| {
            let mut st = store.borrow_mut();
            let id = st.next_hook_id;
            st.next_hook_id += 1;
            format!(":r{id}:")
        })
    };
    use_hook_slot_cloned(alloc).unwrap_or_else(alloc)
}

// ============================================================================
// React-Style Context API (`create_context` / `provide_context` / `use_context`)
// ============================================================================

/// Typed context handle created by [`create_context`].
///
/// Provide values to descendant components either via [`provide_context`] (scoped to the
/// enclosing `#[component]`) or [`Context::provide`] (scoped to an explicit closure).
pub struct Context<T: Clone + 'static> {
    id: u64,
    default_value: Rc<T>,
}

impl<T: Clone + 'static> Clone for Context<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            default_value: Rc::clone(&self.default_value),
        }
    }
}

impl<T: Clone + std::fmt::Debug + 'static> std::fmt::Debug for Context<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Context")
            .field("id", &self.id)
            .field("default_value", &*self.default_value)
            .finish()
    }
}

impl<T: Clone + 'static> Context<T> {
    /// Returns this context's unique identifier.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Returns a clone of the default fallback value supplied at creation time.
    pub fn default_value(&self) -> T {
        (*self.default_value).clone()
    }

    /// Provides `value` to all components evaluated within `f`, restoring the previous
    /// context value automatically even if `f` unwinds.
    pub fn provide<R>(&self, value: T, f: impl FnOnce() -> R) -> R {
        struct ContextPopGuard;
        impl Drop for ContextPopGuard {
            fn drop(&mut self) {
                let _ = CONTEXT_STACK.try_with(|stack| {
                    if let Ok(mut st) = stack.try_borrow_mut() {
                        st.pop();
                    }
                });
            }
        }

        CONTEXT_STACK.with(|stack| {
            stack.borrow_mut().push(ContextEntry {
                context_id: self.id,
                value: Box::new(value),
            });
        });
        let _guard = ContextPopGuard;
        f()
    }
}

/// Creates a new typed [`Context<T>`] with a fallback `default_value`.
pub fn create_context<T: Clone + 'static>(default_value: T) -> Context<T> {
    let id = NEXT_CONTEXT_ID.with(|next| {
        let id = next.get();
        next.set(id + 1);
        id
    });
    Context {
        id,
        default_value: Rc::new(default_value),
    }
}

/// Provides `value` for `context` to all child components rendered in the remainder of the
/// current `#[component]` scope.
///
/// The provided entry is automatically popped when the enclosing `#[component]` finishes
/// rendering. Outside a `#[component]` scope, prefer [`Context::provide`].
pub fn provide_context<T: Clone + 'static>(context: &Context<T>, value: T) {
    CONTEXT_STACK.with(|stack| {
        stack.borrow_mut().push(ContextEntry {
            context_id: context.id,
            value: Box::new(value),
        });
    });
    HOOK_STORE.with(|store| {
        let mut st = store.borrow_mut();
        if let Some(frame) = st.active_stack.last_mut() {
            frame.provided_context_count += 1;
        }
    });
}

/// Reads the nearest ancestor value provided for `context`, or its default value when no
/// ancestor provider is active.
pub fn use_context<T: Clone + 'static>(context: &Context<T>) -> T {
    CONTEXT_STACK.with(|stack| {
        let stack = stack.borrow();
        for entry in stack.iter().rev() {
            if entry.context_id == context.id {
                if let Some(val) = entry.value.downcast_ref::<T>() {
                    return val.clone();
                }
            }
        }
        context.default_value()
    })
}

pub fn batch<R>(f: impl FnOnce() -> R) -> R {
    ReactiveRuntime::batch(f)
}

pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
    ReactiveRuntime::untrack(f)
}

pub fn has_dirty_signals() -> bool {
    ReactiveRuntime::has_dirty_signals()
}

pub fn take_dirty_signals() -> bool {
    ReactiveRuntime::take_dirty_signals()
}

pub fn mark_dirty() {
    ReactiveRuntime::mark_dirty()
}

pub fn set_signal_name(signal_id: SignalId, name: impl Into<String>) {
    ReactiveRuntime::set_signal_name(signal_id, name);
}

pub fn signal_name(signal_id: SignalId) -> String {
    ReactiveRuntime::signal_name(signal_id)
}

pub fn peek_dirty_signal_names() -> Vec<String> {
    ReactiveRuntime::peek_dirty_signal_names()
}

pub fn take_dirty_signal_names() -> Vec<String> {
    ReactiveRuntime::take_dirty_signal_names()
}

pub fn reactive_telemetry_snapshot() -> ReactiveTelemetrySnapshot {
    ReactiveRuntime::telemetry_snapshot()
}

// ---------------------------------------------------------------------------
// State-Preserving Hot Module Replacement (HMR) Signal Codec & Registry
// ---------------------------------------------------------------------------

/// Zero-dependency binary codec allowing reactive signal values to survive
/// dynamic `.so`/`.dylib`/`.dll` hot reloads cleanly across module epochs.
pub trait HmrCodec: Sized {
    /// Serializes this value into an opaque byte vector for HMR snapshotting.
    fn encode_hmr(&self) -> Vec<u8>;
    /// Restores a value from bytes captured before a hot reload.
    fn decode_hmr(bytes: &[u8]) -> Option<Self>;
}

impl HmrCodec for bool {
    fn encode_hmr(&self) -> Vec<u8> {
        vec![if *self { 1 } else { 0 }]
    }
    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
        bytes.first().map(|&b| b != 0)
    }
}

macro_rules! impl_hmr_numeric {
    ($($ty:ty),*) => {
        $(
            impl HmrCodec for $ty {
                fn encode_hmr(&self) -> Vec<u8> {
                    self.to_le_bytes().to_vec()
                }
                fn decode_hmr(bytes: &[u8]) -> Option<Self> {
                    let arr: [u8; std::mem::size_of::<$ty>()] = bytes.try_into().ok()?;
                    Some(<$ty>::from_le_bytes(arr))
                }
            }
        )*
    };
}

impl_hmr_numeric!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64);

impl HmrCodec for String {
    fn encode_hmr(&self) -> Vec<u8> {
        self.as_bytes().to_vec()
    }
    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
        String::from_utf8(bytes.to_vec()).ok()
    }
}

impl<T: HmrCodec> HmrCodec for Option<T> {
    fn encode_hmr(&self) -> Vec<u8> {
        match self {
            None => vec![0u8],
            Some(v) => {
                let inner = v.encode_hmr();
                let mut out = Vec::with_capacity(1 + inner.len());
                out.push(1u8);
                out.extend_from_slice(&inner);
                out
            }
        }
    }
    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
        let (&tag, rest) = bytes.split_first()?;
        if tag == 0 {
            Some(None)
        } else {
            Some(Some(T::decode_hmr(rest)?))
        }
    }
}

impl<T: HmrCodec> HmrCodec for Vec<T> {
    fn encode_hmr(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&(self.len() as u32).to_le_bytes());
        for item in self {
            let encoded = item.encode_hmr();
            out.extend_from_slice(&(encoded.len() as u32).to_le_bytes());
            out.extend_from_slice(&encoded);
        }
        out
    }
    fn decode_hmr(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < 4 {
            return None;
        }
        let count = u32::from_le_bytes(bytes[0..4].try_into().ok()?) as usize;
        let mut pos = 4usize;
        let mut out = Vec::with_capacity(count.min(65_536));
        for _ in 0..count {
            if pos + 4 > bytes.len() {
                return None;
            }
            let len = u32::from_le_bytes(bytes[pos..pos + 4].try_into().ok()?) as usize;
            pos += 4;
            if pos + len > bytes.len() {
                return None;
            }
            out.push(T::decode_hmr(&bytes[pos..pos + len])?);
            pos += len;
        }
        Some(out)
    }
}

type HmrExportFn = Box<dyn Fn() -> Vec<u8>>;
type HmrImportFn = Box<dyn Fn(&[u8]) -> bool>;

struct HmrLiveSlot {
    type_name: String,
    export: HmrExportFn,
    import: HmrImportFn,
}

#[derive(Default)]
struct HmrStateRegistry {
    live_slots: BTreeMap<String, HmrLiveSlot>,
    hydrated_blobs: BTreeMap<String, Vec<u8>>,
}

thread_local! {
    static HMR_STATE_REGISTRY: RefCell<HmrStateRegistry> = RefCell::new(HmrStateRegistry::default());
}

/// Creates or reconnects a state-preserving HMR reactive signal keyed by `key`.
///
/// - During normal re-renders in the same binary epoch, behaves like [`use_persistent_signal`]
///   and returns the existing [`Signal<T>`].
/// - Across dynamic `.so`/`.dylib`/`.dll` hot reloads, automatically hydrates from any
///   snapshot imported via [`import_hmr_signals`] and registers live export/import hooks
///   so subsequent reloads preserve every mutation.
pub fn use_hmr_signal<T: HmrCodec + Clone + 'static>(
    key: impl Into<String>,
    initial: T,
) -> Signal<T> {
    let key_str = key.into();
    let hydrated_initial = HMR_STATE_REGISTRY.with(|reg| {
        reg.borrow()
            .hydrated_blobs
            .get(&key_str)
            .and_then(|bytes| T::decode_hmr(bytes))
    });

    let sig = use_persistent_signal(&key_str, move || hydrated_initial.unwrap_or(initial));

    // If a fresh HMR snapshot blob was imported after this signal already existed, hydrate in-place.
    let pending_blob = HMR_STATE_REGISTRY.with(|reg| reg.borrow_mut().hydrated_blobs.remove(&key_str));
    if let Some(bytes) = pending_blob {
        if let Some(val) = T::decode_hmr(&bytes) {
            sig.set_untracked(val);
        }
    }

    let sig_for_export = sig.clone();
    let sig_for_import = sig.clone();
    HMR_STATE_REGISTRY.with(|reg| {
        reg.borrow_mut().live_slots.insert(
            key_str,
            HmrLiveSlot {
                type_name: std::any::type_name::<T>().to_string(),
                export: Box::new(move || sig_for_export.untracked_get().encode_hmr()),
                import: Box::new(move |bytes: &[u8]| {
                    if let Some(val) = T::decode_hmr(bytes) {
                        sig_for_import.set(val);
                        true
                    } else {
                        false
                    }
                }),
            },
        );
    });

    sig
}

/// Exports all registered HMR signals (plus any unconsumed hydrated blobs) as
/// `(key, type_name, encoded_bytes)` tuples prior to unloading/reloading a dynamic module.
pub fn export_hmr_signals() -> Vec<(String, String, Vec<u8>)> {
    HMR_STATE_REGISTRY.with(|reg| {
        let reg = reg.borrow();
        let mut out = Vec::with_capacity(reg.live_slots.len() + reg.hydrated_blobs.len());
        for (key, slot) in &reg.live_slots {
            out.push((key.clone(), slot.type_name.clone(), (slot.export)()));
        }
        for (key, bytes) in &reg.hydrated_blobs {
            if !reg.live_slots.contains_key(key) {
                out.push((key.clone(), "raw".to_string(), bytes.clone()));
            }
        }
        out
    })
}

/// Imports HMR signal payloads captured before a hot reload.
///
/// Updates any currently mounted signals in-place immediately AND stages raw blobs
/// for components mounted during the next render pass. Returns the number of entries applied/staged.
pub fn import_hmr_signals(entries: &[(String, Vec<u8>)]) -> usize {
    HMR_STATE_REGISTRY.with(|reg| {
        let mut reg = reg.borrow_mut();
        let mut count = 0usize;
        for (key, bytes) in entries {
            let mut applied_live = false;
            if let Some(slot) = reg.live_slots.get(key) {
                if (slot.import)(bytes) {
                    applied_live = true;
                    count += 1;
                }
            }
            if !applied_live {
                reg.hydrated_blobs.insert(key.clone(), bytes.clone());
                count += 1;
            }
        }
        count
    })
}

/// Clears all HMR signal registry entries (useful for isolated unit/integration tests).
pub fn clear_hmr_signals() {
    HMR_STATE_REGISTRY.with(|reg| {
        let mut reg = reg.borrow_mut();
        reg.live_slots.clear();
        reg.hydrated_blobs.clear();
    });
}