reratui 1.1.0

A modern, reactive TUI framework for Rust with React-inspired hooks and components, powered by ratatui
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
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
//! State batching system for grouping multiple state updates.
//!
//! This module provides React-like state batching, where multiple state updates
//! within the same event handler are batched into a single re-render.
//!
//! # Example
//!
//! ```rust,ignore
//! use reratui_fiber::scheduler::batch::{begin_batch, end_batch, queue_update};
//!
//! // Start batching
//! begin_batch();
//!
//! // Multiple updates are queued, not applied immediately
//! queue_update(fiber_id, StateUpdate { hook_index: 0, update: StateUpdateKind::Value(Box::new(1)) });
//! queue_update(fiber_id, StateUpdate { hook_index: 0, update: StateUpdateKind::Value(Box::new(2)) });
//!
//! // End batching - applies all updates and returns dirty fibers
//! let dirty = end_batch(&mut tree);
//! ```

use std::any::Any;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::thread::ThreadId;

use crate::fiber::FiberId;
use crate::fiber_tree::FiberTree;

thread_local! {
    /// Thread-local state batch for the current render context
    static STATE_BATCH: RefCell<StateBatch> = RefCell::new(StateBatch::new());
}

// ============================================================================
// Cross-thread update infrastructure
// ============================================================================

/// Global queue for cross-thread state updates.
/// Background tasks (from use_interval, use_timeout) write to this queue,
/// and the main render loop drains it into the thread-local batch.
static CROSS_THREAD_UPDATES: Mutex<Vec<CrossThreadUpdate>> = Mutex::new(Vec::new());

/// Thread ID of the main render thread (set during render initialization).
/// Uses RwLock instead of OnceLock to allow resetting in tests.
static MAIN_THREAD_ID: std::sync::RwLock<Option<ThreadId>> = std::sync::RwLock::new(None);

/// A state update that can be sent across threads.
/// This is the cross-thread equivalent of StateUpdate.
pub struct CrossThreadUpdate {
    /// The fiber to update
    pub fiber_id: FiberId,
    /// Index of the hook being updated
    pub hook_index: usize,
    /// The update to apply
    pub update: CrossThreadUpdateKind,
}

/// Thread-safe update kinds for cross-thread state updates.
/// Uses Arc for functional updaters to allow sharing across threads.
pub enum CrossThreadUpdateKind {
    /// Direct value replacement (thread-safe via Box<dyn Any + Send>)
    Value(Box<dyn Any + Send>),
    /// Functional update (thread-safe via Arc wrapper around Mutex<Option<FnOnce>>)
    /// The Mutex<Option<>> pattern allows FnOnce to be called from an Fn context
    Updater(Arc<Mutex<Option<StateUpdaterFn>>>),
    /// Value replacement with equality check - skips update if values are equal
    /// Includes TypeId for runtime type checking when reconstructing equality check
    ValueIfChanged {
        /// The new value to set
        value: Box<dyn Any + Send>,
        /// TypeId of the value for runtime type checking
        type_id: std::any::TypeId,
    },
    /// Functional update with equality check - skips marking dirty if result equals current
    /// The TypeId is extracted from the updater's result when it's first called
    UpdaterIfChanged {
        /// The updater function wrapped in Arc<Mutex<Option<>>> for thread-safety
        updater: Arc<Mutex<Option<StateUpdaterFn>>>,
    },
}

// ============================================================================
// Thread-local batch types
// ============================================================================

/// Type alias for functional updater to reduce complexity
pub type StateUpdaterFn = Box<dyn FnOnce(&dyn Any) -> Box<dyn Any + Send> + Send>;

/// Type alias for equality check function
pub type EqualityCheckFn = Box<dyn FnOnce(&dyn Any, &dyn Any) -> bool + Send>;

/// A pending state update
pub struct StateUpdate {
    /// Index of the hook being updated
    pub hook_index: usize,
    /// The update to apply
    pub update: StateUpdateKind,
}

/// Kind of state update
pub enum StateUpdateKind {
    /// Direct value replacement
    Value(Box<dyn Any + Send>),
    /// Functional update that receives current state and returns new state
    Updater(StateUpdaterFn),
    /// Value replacement with equality check - skips update if values are equal
    ValueIfChanged {
        /// The new value to set
        value: Box<dyn Any + Send>,
        /// Function to check if old and new values are equal
        eq_check: EqualityCheckFn,
    },
    /// Functional update with equality check - skips marking dirty if result equals current
    UpdaterIfChanged {
        /// The updater function
        updater: StateUpdaterFn,
        /// Function to check if old and new values are equal
        eq_check: EqualityCheckFn,
    },
}

/// Tracks pending state updates for batching
///
/// State batching allows multiple state updates within the same event handler
/// to be combined into a single re-render, improving performance and ensuring
/// consistent state transitions.
pub struct StateBatch {
    /// Pending updates grouped by fiber
    updates: HashMap<FiberId, Vec<StateUpdate>>,
    /// Whether we're currently in a batch context
    batching: bool,
    /// Fibers that need re-render
    dirty_fibers: HashSet<FiberId>,
}

impl StateBatch {
    /// Create a new empty batch
    pub fn new() -> Self {
        Self {
            updates: HashMap::new(),
            batching: false,
            dirty_fibers: HashSet::new(),
        }
    }

    /// Begin a batch context
    ///
    /// While batching is active, state updates are queued rather than
    /// applied immediately. Call `end_batch` to apply all queued updates.
    pub fn begin_batch(&mut self) {
        self.batching = true;
    }

    /// End the batch context, apply all pending updates, and return dirty fibers
    ///
    /// This method:
    /// 1. Sets batching to false
    /// 2. Applies all pending state updates to the fiber tree
    /// 3. Returns the set of fibers that need re-rendering
    ///
    /// # Arguments
    ///
    /// * `tree` - The fiber tree to apply updates to
    ///
    /// # Returns
    ///
    /// A set of fiber IDs that have been modified and need re-rendering
    pub fn end_batch(&mut self, tree: &mut FiberTree) -> HashSet<FiberId> {
        self.batching = false;

        // Track which fibers actually had state changes
        let mut actually_dirty: HashSet<FiberId> = HashSet::new();

        // Apply all pending updates to fibers
        for (fiber_id, updates) in self.updates.drain() {
            if let Some(fiber) = tree.get_mut(fiber_id) {
                let mut fiber_changed = false;

                for update in updates {
                    // Ensure hooks vector is large enough
                    if update.hook_index >= fiber.hooks.len() {
                        fiber
                            .hooks
                            .resize_with(update.hook_index + 1, || Box::new(()));
                    }

                    match update.update {
                        StateUpdateKind::Value(value) => {
                            // Directly assign the boxed value
                            fiber.hooks[update.hook_index] = value;
                            fiber_changed = true;
                        }
                        StateUpdateKind::Updater(updater) => {
                            // Get current value, apply updater, set new value
                            let current = &*fiber.hooks[update.hook_index];
                            let new_value = updater(current);
                            fiber.hooks[update.hook_index] = new_value;
                            fiber_changed = true;
                        }
                        StateUpdateKind::ValueIfChanged { value, eq_check } => {
                            // Check if values are equal before updating
                            let current = &*fiber.hooks[update.hook_index];
                            if !eq_check(current, &*value) {
                                fiber.hooks[update.hook_index] = value;
                                fiber_changed = true;
                            }
                        }
                        StateUpdateKind::UpdaterIfChanged { updater, eq_check } => {
                            // Apply updater and check if result differs
                            let current = &*fiber.hooks[update.hook_index];
                            let new_value = updater(current);
                            if !eq_check(&*fiber.hooks[update.hook_index], &*new_value) {
                                fiber.hooks[update.hook_index] = new_value;
                                fiber_changed = true;
                            }
                        }
                    }
                }

                // Only mark fiber as dirty if state actually changed
                if fiber_changed {
                    fiber.dirty = true;
                    actually_dirty.insert(fiber_id);
                }
            }
        }

        // Clear the dirty_fibers set and return only actually dirty fibers
        self.dirty_fibers.clear();
        actually_dirty
    }

    /// Queue a state update
    ///
    /// The update will be applied when `end_batch` is called.
    /// The fiber is immediately marked as dirty.
    pub fn queue_update(&mut self, fiber_id: FiberId, update: StateUpdate) {
        self.updates.entry(fiber_id).or_default().push(update);
        self.dirty_fibers.insert(fiber_id);
    }

    /// Check if currently batching
    pub fn is_batching(&self) -> bool {
        self.batching
    }

    /// Take all pending updates for a fiber
    pub fn take_updates(&mut self, fiber_id: FiberId) -> Vec<StateUpdate> {
        self.updates.remove(&fiber_id).unwrap_or_default()
    }

    /// Check if there are pending updates
    pub fn has_pending_updates(&self) -> bool {
        !self.updates.is_empty()
    }

    /// Get the number of dirty fibers
    pub fn dirty_fiber_count(&self) -> usize {
        self.dirty_fibers.len()
    }

    /// Check if a specific fiber is dirty
    pub fn is_fiber_dirty(&self, fiber_id: FiberId) -> bool {
        self.dirty_fibers.contains(&fiber_id)
    }

    /// Clear all pending updates without applying them
    pub fn clear(&mut self) {
        self.updates.clear();
        self.dirty_fibers.clear();
        self.batching = false;
    }
}

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

// ============================================================================
// Cross-thread API functions
// ============================================================================

/// Initialize the main thread ID.
/// This should be called once at the start of the render loop.
/// After this is called, `is_main_thread()` will return true only on this thread.
pub fn init_main_thread() {
    if let Ok(mut guard) = MAIN_THREAD_ID.write() {
        *guard = Some(std::thread::current().id());
    }
}

/// Check if the current thread is the main render thread.
///
/// Returns `true` if:
/// - `init_main_thread()` has been called and we're on that thread, OR
/// - `init_main_thread()` has NOT been called (backward compatibility - assume main thread)
///
/// Returns `false` only if `init_main_thread()` was called on a different thread.
pub fn is_main_thread() -> bool {
    if let Ok(guard) = MAIN_THREAD_ID.read() {
        match *guard {
            Some(id) => id == std::thread::current().id(),
            None => true, // If not initialized, assume we're on main thread (backward compat)
        }
    } else {
        true // If lock is poisoned, assume main thread to avoid breaking things
    }
}

/// Reset the main thread ID (for testing purposes only).
/// This allows tests to re-initialize the main thread tracking.
#[cfg(test)]
pub fn reset_main_thread() {
    if let Ok(mut guard) = MAIN_THREAD_ID.write() {
        *guard = None;
    }
}

/// Queue a cross-thread update to the global queue.
/// This is called from background threads when they need to update state.
pub fn queue_cross_thread_update(update: CrossThreadUpdate) {
    if let Ok(mut queue) = CROSS_THREAD_UPDATES.lock() {
        queue.push(update);
    } else {
        // Mutex is poisoned - log error but don't panic
        tracing::error!("Cross-thread update queue mutex is poisoned, update dropped");
    }
}

/// Drain all cross-thread updates into the thread-local batch.
/// This should be called from the main render thread before `end_batch()`.
pub fn drain_cross_thread_updates() {
    if let Ok(mut queue) = CROSS_THREAD_UPDATES.lock() {
        for update in queue.drain(..) {
            // Convert CrossThreadUpdateKind to StateUpdateKind
            let state_update = StateUpdate {
                hook_index: update.hook_index,
                update: match update.update {
                    CrossThreadUpdateKind::Value(v) => StateUpdateKind::Value(v),
                    CrossThreadUpdateKind::Updater(arc_mutex) => {
                        // Extract the FnOnce from the Arc<Mutex<Option<>>>
                        StateUpdateKind::Updater(Box::new(move |any| {
                            if let Ok(mut guard) = arc_mutex.lock() {
                                if let Some(f) = guard.take() {
                                    f(any)
                                } else {
                                    // Updater already called - this shouldn't happen
                                    panic!("Cross-thread updater called more than once");
                                }
                            } else {
                                panic!("Cross-thread updater mutex poisoned");
                            }
                        }))
                    }
                    CrossThreadUpdateKind::ValueIfChanged { value, type_id } => {
                        // Reconstruct equality check using TypeId for runtime type checking
                        StateUpdateKind::ValueIfChanged {
                            value,
                            eq_check: Box::new(move |old, new| {
                                // Use TypeId to ensure we're comparing the right types
                                // This is a generic equality check that works for any PartialEq type
                                reconstruct_equality_check(old, new, type_id)
                            }),
                        }
                    }
                    CrossThreadUpdateKind::UpdaterIfChanged { updater } => {
                        // For UpdaterIfChanged, we need to extract the TypeId from the result
                        // We do this by wrapping the updater and extracting the type on first call
                        StateUpdateKind::UpdaterIfChanged {
                            updater: Box::new(move |any| {
                                if let Ok(mut guard) = updater.lock() {
                                    if let Some(f) = guard.take() {
                                        f(any)
                                    } else {
                                        panic!("Cross-thread updater called more than once");
                                    }
                                } else {
                                    panic!("Cross-thread updater mutex poisoned");
                                }
                            }),
                            eq_check: Box::new(move |old, new| {
                                // Extract TypeId from the values and use it for comparison
                                // Both old and new should have the same type
                                let type_id = old.type_id();
                                reconstruct_equality_check(old, new, type_id)
                            }),
                        }
                    }
                },
            };
            // Queue to thread-local batch (we're on main thread now)
            STATE_BATCH.with(|batch| {
                batch
                    .borrow_mut()
                    .queue_update(update.fiber_id, state_update);
            });
        }
    } else {
        tracing::error!("Cross-thread update queue mutex is poisoned, updates not drained");
    }
}

/// Helper function to reconstruct equality checks for cross-thread updates.
///
/// This function attempts to downcast the values to common types and compare them.
/// If the type is not recognized, it conservatively returns false (values are different).
///
/// # Arguments
///
/// * `old` - The old value
/// * `new` - The new value
/// * `type_id` - The TypeId of the values for runtime type checking
///
/// # Returns
///
/// `true` if the values are equal, `false` otherwise
fn reconstruct_equality_check(old: &dyn Any, new: &dyn Any, type_id: std::any::TypeId) -> bool {
    // Try common types that implement PartialEq
    // This is a best-effort approach - we can't reconstruct the exact equality check
    // but we can handle common cases

    // Check TypeId matches
    if old.type_id() != type_id || new.type_id() != type_id {
        return false;
    }

    // Try common integer types
    if type_id == std::any::TypeId::of::<i32>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<i32>(), new.downcast_ref::<i32>())
        {
            return old_val == new_val;
        }
    }
    if type_id == std::any::TypeId::of::<i64>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<i64>(), new.downcast_ref::<i64>())
        {
            return old_val == new_val;
        }
    }
    if type_id == std::any::TypeId::of::<u32>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<u32>(), new.downcast_ref::<u32>())
        {
            return old_val == new_val;
        }
    }
    if type_id == std::any::TypeId::of::<u64>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<u64>(), new.downcast_ref::<u64>())
        {
            return old_val == new_val;
        }
    }
    if type_id == std::any::TypeId::of::<usize>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<usize>(), new.downcast_ref::<usize>())
        {
            return old_val == new_val;
        }
    }

    // Try floating point types
    if type_id == std::any::TypeId::of::<f32>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<f32>(), new.downcast_ref::<f32>())
        {
            return old_val == new_val;
        }
    }
    if type_id == std::any::TypeId::of::<f64>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<f64>(), new.downcast_ref::<f64>())
        {
            return old_val == new_val;
        }
    }

    // Try boolean
    if type_id == std::any::TypeId::of::<bool>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<bool>(), new.downcast_ref::<bool>())
        {
            return old_val == new_val;
        }
    }

    // Try String
    if type_id == std::any::TypeId::of::<String>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<String>(), new.downcast_ref::<String>())
        {
            return old_val == new_val;
        }
    }

    // Try &str (though this is less common in state)
    if type_id == std::any::TypeId::of::<&str>() {
        if let (Some(old_val), Some(new_val)) =
            (old.downcast_ref::<&str>(), new.downcast_ref::<&str>())
        {
            return old_val == new_val;
        }
    }

    // For unknown types, conservatively return false (assume values are different)
    // This means the optimization is lost for custom types, but correctness is preserved
    false
}

/// Check if there are pending cross-thread updates.
pub fn has_cross_thread_updates() -> bool {
    CROSS_THREAD_UPDATES
        .lock()
        .map(|queue| !queue.is_empty())
        .unwrap_or(false)
}

/// Clear all cross-thread updates (for testing purposes).
#[cfg(test)]
pub fn clear_cross_thread_updates() {
    if let Ok(mut queue) = CROSS_THREAD_UPDATES.lock() {
        queue.clear();
    }
}

/// Test helper: Simulate a re-entrant update by holding STATE_BATCH borrow
/// while calling queue_update. This forces the update to go to the cross-thread queue.
#[cfg(test)]
pub fn test_simulate_reentrant_update(
    fiber_id: FiberId,
    hook_index: usize,
    value: Box<dyn Any + Send>,
) {
    STATE_BATCH.with(|batch| {
        let _guard = batch.borrow_mut(); // Hold the borrow

        // This should fall back to cross-thread queue
        queue_update(
            fiber_id,
            StateUpdate {
                hook_index,
                update: StateUpdateKind::Value(value),
            },
        );
    });
}

// ============================================================================
// Thread-local API functions
// ============================================================================

/// Begin a batch context on the thread-local state batch
///
/// While batching is active, state updates are queued rather than
/// applied immediately.
pub fn begin_batch() {
    STATE_BATCH.with(|batch| {
        batch.borrow_mut().begin_batch();
    });
}

/// End the batch context and apply all pending updates using a provided tree
///
/// # Arguments
///
/// * `tree` - The fiber tree to apply updates to
///
/// # Returns
///
/// A set of fiber IDs that have been modified and need re-rendering
pub fn end_batch_with_tree(tree: &mut FiberTree) -> HashSet<FiberId> {
    STATE_BATCH.with(|batch| batch.borrow_mut().end_batch(tree))
}

/// End the batch context and apply all pending updates using the thread-local fiber tree
///
/// # Returns
///
/// A set of fiber IDs that have been modified and need re-rendering
pub fn end_batch() -> HashSet<FiberId> {
    crate::fiber_tree::with_fiber_tree_mut(|tree| {
        STATE_BATCH.with(|batch| batch.borrow_mut().end_batch(tree))
    })
    .unwrap_or_default()
}

/// Queue a state update - automatically routes to correct queue based on thread.
///
/// If called from the main render thread (after `init_main_thread()`), the update
/// is queued to the thread-local batch for immediate batching.
///
/// If called from a background thread (e.g., from a tokio::spawn task in use_interval),
/// the update is queued to the global cross-thread queue, which will be drained
/// into the thread-local batch on the next render frame.
///
/// # Arguments
///
/// * `fiber_id` - The fiber to update
/// * `update` - The state update to queue
pub fn queue_update(fiber_id: FiberId, update: StateUpdate) {
    // Warn if state update is queued during render phase (development mode only)
    #[cfg(debug_assertions)]
    {
        if crate::runtime::is_in_render_phase() {
            tracing::warn!(
                fiber_id = ?fiber_id,
                hook_index = update.hook_index,
                "State update queued during render phase! State updates should be triggered by events or effects, not during render. \
                This can lead to infinite render loops and performance issues."
            );
        }
    }

    // First check if we're on the main thread
    if !is_main_thread() {
        // Definitely a background thread - use cross-thread queue
        queue_update_to_cross_thread(fiber_id, update);
        return;
    }

    // We're on the main thread, but we might be in a spawned task that's
    // running on the main thread (tokio work-stealing). Try to borrow
    // STATE_BATCH - if it fails, we're in a re-entrant situation and
    // should use the cross-thread queue instead.
    //
    // We use a Cell to pass the update out if try_borrow_mut fails.
    let fallback_update: std::cell::Cell<Option<StateUpdate>> = std::cell::Cell::new(None);

    let queued = STATE_BATCH.with(|batch| {
        match batch.try_borrow_mut() {
            Ok(mut b) => {
                b.queue_update(fiber_id, update);
                true
            }
            Err(_) => {
                // STATE_BATCH is already borrowed - we're in a re-entrant call
                // This can happen when a tokio task runs on the main thread
                // during drain_cross_thread_updates or end_batch
                fallback_update.set(Some(update));
                false
            }
        }
    });

    if !queued {
        // Couldn't borrow STATE_BATCH, use cross-thread queue
        if let Some(update) = fallback_update.take() {
            queue_update_to_cross_thread(fiber_id, update);
        }
    }
}

/// Internal function to queue an update to the cross-thread queue
fn queue_update_to_cross_thread(fiber_id: FiberId, update: StateUpdate) {
    let cross_update = CrossThreadUpdate {
        fiber_id,
        hook_index: update.hook_index,
        update: match update.update {
            StateUpdateKind::Value(v) => CrossThreadUpdateKind::Value(v),
            StateUpdateKind::Updater(f) => {
                // Wrap FnOnce in Arc<Mutex<Option<>>> for thread-safety
                CrossThreadUpdateKind::Updater(Arc::new(Mutex::new(Some(f))))
            }
            StateUpdateKind::ValueIfChanged { value, eq_check: _ } => {
                // Preserve type information for equality check reconstruction
                let type_id = (*value).type_id();
                CrossThreadUpdateKind::ValueIfChanged { value, type_id }
            }
            StateUpdateKind::UpdaterIfChanged {
                updater,
                eq_check: _,
            } => {
                // For UpdaterIfChanged, we can't extract the TypeId until the updater runs
                // The equality check will extract it from the result values at runtime
                CrossThreadUpdateKind::UpdaterIfChanged {
                    updater: Arc::new(Mutex::new(Some(updater))),
                }
            }
        },
    };
    queue_cross_thread_update(cross_update);
}

/// Check if currently batching on the thread-local state batch
pub fn is_batching() -> bool {
    STATE_BATCH.with(|batch| batch.borrow().is_batching())
}

/// Execute a closure with the thread-local state batch
pub fn with_state_batch<R, F: FnOnce(&StateBatch) -> R>(f: F) -> R {
    STATE_BATCH.with(|batch| f(&batch.borrow()))
}

/// Execute a closure with mutable access to the thread-local state batch
pub fn with_state_batch_mut<R, F: FnOnce(&mut StateBatch) -> R>(f: F) -> R {
    STATE_BATCH.with(|batch| f(&mut batch.borrow_mut()))
}

/// Clear the thread-local state batch
pub fn clear_state_batch() {
    STATE_BATCH.with(|batch| {
        batch.borrow_mut().clear();
    });
}

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

    #[test]
    fn test_state_batch_creation() {
        let batch = StateBatch::new();
        assert!(!batch.is_batching());
        assert!(!batch.has_pending_updates());
        assert_eq!(batch.dirty_fiber_count(), 0);
    }

    #[test]
    fn test_begin_and_end_batch() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();

        assert!(!batch.is_batching());

        batch.begin_batch();
        assert!(batch.is_batching());

        let dirty = batch.end_batch(&mut tree);
        assert!(!batch.is_batching());
        assert!(dirty.is_empty());
    }

    #[test]
    fn test_queue_update_marks_fiber_dirty() {
        let mut batch = StateBatch::new();
        let fiber_id = FiberId(1);

        assert!(!batch.is_fiber_dirty(fiber_id));

        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        assert!(batch.is_fiber_dirty(fiber_id));
        assert!(batch.has_pending_updates());
        assert_eq!(batch.dirty_fiber_count(), 1);
    }

    #[test]
    fn test_multiple_updates_same_fiber() {
        let mut batch = StateBatch::new();
        let fiber_id = FiberId(1);

        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(1i32)),
            },
        );
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(2i32)),
            },
        );
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 1,
                update: StateUpdateKind::Value(Box::new("hello".to_string())),
            },
        );

        // Still only one dirty fiber
        assert_eq!(batch.dirty_fiber_count(), 1);
        assert!(batch.has_pending_updates());
    }

    #[test]
    fn test_multiple_fibers_dirty() {
        let mut batch = StateBatch::new();
        let fiber1 = FiberId(1);
        let fiber2 = FiberId(2);
        let fiber3 = FiberId(3);

        batch.queue_update(
            fiber1,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(1i32)),
            },
        );
        batch.queue_update(
            fiber2,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(2i32)),
            },
        );
        batch.queue_update(
            fiber3,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(3i32)),
            },
        );

        assert_eq!(batch.dirty_fiber_count(), 3);
        assert!(batch.is_fiber_dirty(fiber1));
        assert!(batch.is_fiber_dirty(fiber2));
        assert!(batch.is_fiber_dirty(fiber3));
    }

    #[test]
    fn test_end_batch_applies_value_updates() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        let dirty = batch.end_batch(&mut tree);

        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(42));
    }

    #[test]
    fn test_end_batch_applies_functional_updates() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 10
        tree.get_mut(fiber_id).unwrap().set_hook(0, 10i32);

        batch.begin_batch();

        // Queue functional update that adds 5
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Updater(Box::new(|current| {
                    let val = current.downcast_ref::<i32>().unwrap();
                    Box::new(val + 5)
                })),
            },
        );

        let dirty = batch.end_batch(&mut tree);

        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(15));
    }

    #[test]
    fn test_chained_functional_updates() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 0
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        batch.begin_batch();

        // Queue multiple functional updates
        for _ in 0..5 {
            batch.queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Updater(Box::new(|current| {
                        let val = current.downcast_ref::<i32>().unwrap();
                        Box::new(val + 1)
                    })),
                },
            );
        }

        batch.end_batch(&mut tree);

        // All 5 updates should have been applied
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(5));
    }

    #[test]
    fn test_take_updates() {
        let mut batch = StateBatch::new();
        let fiber_id = FiberId(1);

        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(1i32)),
            },
        );
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 1,
                update: StateUpdateKind::Value(Box::new(2i32)),
            },
        );

        let updates = batch.take_updates(fiber_id);
        assert_eq!(updates.len(), 2);

        // Updates should be removed
        let updates_again = batch.take_updates(fiber_id);
        assert!(updates_again.is_empty());
    }

    #[test]
    fn test_clear_batch() {
        let mut batch = StateBatch::new();
        let fiber_id = FiberId(1);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        assert!(batch.is_batching());
        assert!(batch.has_pending_updates());

        batch.clear();

        assert!(!batch.is_batching());
        assert!(!batch.has_pending_updates());
        assert_eq!(batch.dirty_fiber_count(), 0);
    }

    #[test]
    fn test_thread_local_begin_batch() {
        // Clear any existing state
        clear_state_batch();

        assert!(!is_batching());

        begin_batch();
        assert!(is_batching());

        // Clean up
        clear_state_batch();
    }

    #[test]
    #[serial]
    fn test_thread_local_queue_and_end_batch() {
        clear_state_batch();
        clear_cross_thread_updates();
        reset_main_thread();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        begin_batch();

        // Use with_state_batch_mut to directly queue to local batch
        // This avoids the routing logic in queue_update
        with_state_batch_mut(|batch| {
            batch.queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Value(Box::new(100i32)),
                },
            );
        });

        let dirty = end_batch_with_tree(&mut tree);

        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(100));

        clear_state_batch();
    }

    #[test]
    #[serial]
    fn test_with_state_batch() {
        clear_state_batch();
        clear_cross_thread_updates();
        reset_main_thread();

        let fiber_id = FiberId(1);

        // Use with_state_batch_mut to directly queue to local batch
        with_state_batch_mut(|batch| {
            batch.queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Value(Box::new(42i32)),
                },
            );
        });

        let has_updates = with_state_batch(|batch| batch.has_pending_updates());
        assert!(has_updates);

        let is_dirty = with_state_batch(|batch| batch.is_fiber_dirty(fiber_id));
        assert!(is_dirty);

        clear_state_batch();
    }

    #[test]
    #[serial]
    fn test_with_state_batch_mut() {
        clear_state_batch();

        with_state_batch_mut(|batch| {
            batch.begin_batch();
        });

        assert!(is_batching());

        clear_state_batch();
    }

    #[test]
    fn test_end_batch_marks_fiber_dirty_in_tree() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Mark fiber as clean initially
        tree.mark_clean(fiber_id);
        assert!(!tree.get(fiber_id).unwrap().dirty);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        batch.end_batch(&mut tree);

        // Fiber should be marked dirty after state update
        assert!(tree.get(fiber_id).unwrap().dirty);
    }

    #[test]
    fn test_update_nonexistent_fiber() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let nonexistent_fiber = FiberId(999);

        batch.begin_batch();
        batch.queue_update(
            nonexistent_fiber,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        // Should not panic, just skip the update
        let dirty = batch.end_batch(&mut tree);

        // The fiber is NOT in dirty set because it doesn't exist in the tree
        assert!(!dirty.contains(&nonexistent_fiber));
    }

    #[test]
    fn test_default_impl() {
        let batch: StateBatch = Default::default();
        assert!(!batch.is_batching());
        assert!(!batch.has_pending_updates());
    }

    #[test]
    fn test_value_if_changed_skips_equal_values() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 42
        tree.get_mut(fiber_id).unwrap().set_hook(0, 42i32);
        tree.mark_clean(fiber_id);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::ValueIfChanged {
                    value: Box::new(42i32), // Same value
                    eq_check: Box::new(|old, new| {
                        let old = old.downcast_ref::<i32>().unwrap();
                        let new = new.downcast_ref::<i32>().unwrap();
                        old == new
                    }),
                },
            },
        );

        let dirty = batch.end_batch(&mut tree);

        // Fiber should NOT be dirty because value didn't change
        assert!(!dirty.contains(&fiber_id));
        assert!(!tree.get(fiber_id).unwrap().dirty);
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(42));
    }

    #[test]
    fn test_value_if_changed_updates_different_values() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 42
        tree.get_mut(fiber_id).unwrap().set_hook(0, 42i32);
        tree.mark_clean(fiber_id);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::ValueIfChanged {
                    value: Box::new(100i32), // Different value
                    eq_check: Box::new(|old, new| {
                        let old = old.downcast_ref::<i32>().unwrap();
                        let new = new.downcast_ref::<i32>().unwrap();
                        old == new
                    }),
                },
            },
        );

        let dirty = batch.end_batch(&mut tree);

        // Fiber SHOULD be dirty because value changed
        assert!(dirty.contains(&fiber_id));
        assert!(tree.get(fiber_id).unwrap().dirty);
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(100));
    }

    #[test]
    fn test_updater_if_changed_skips_equal_results() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 5
        tree.get_mut(fiber_id).unwrap().set_hook(0, 5i32);
        tree.mark_clean(fiber_id);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::UpdaterIfChanged {
                    updater: Box::new(|any| {
                        let n = any.downcast_ref::<i32>().unwrap();
                        Box::new((*n).max(3)) // 5.max(3) = 5, no change
                    }),
                    eq_check: Box::new(|old, new| {
                        let old = old.downcast_ref::<i32>().unwrap();
                        let new = new.downcast_ref::<i32>().unwrap();
                        old == new
                    }),
                },
            },
        );

        let dirty = batch.end_batch(&mut tree);

        // Fiber should NOT be dirty because result equals current
        assert!(!dirty.contains(&fiber_id));
        assert!(!tree.get(fiber_id).unwrap().dirty);
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(5));
    }

    #[test]
    fn test_updater_if_changed_updates_different_results() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 5
        tree.get_mut(fiber_id).unwrap().set_hook(0, 5i32);
        tree.mark_clean(fiber_id);

        batch.begin_batch();
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::UpdaterIfChanged {
                    updater: Box::new(|any| {
                        let n = any.downcast_ref::<i32>().unwrap();
                        Box::new((*n).max(10)) // 5.max(10) = 10, changed!
                    }),
                    eq_check: Box::new(|old, new| {
                        let old = old.downcast_ref::<i32>().unwrap();
                        let new = new.downcast_ref::<i32>().unwrap();
                        old == new
                    }),
                },
            },
        );

        let dirty = batch.end_batch(&mut tree);

        // Fiber SHOULD be dirty because result differs
        assert!(dirty.contains(&fiber_id));
        assert!(tree.get(fiber_id).unwrap().dirty);
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(10));
    }

    #[test]
    fn test_mixed_updates_with_equality_check() {
        let mut batch = StateBatch::new();
        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Initialize hook with value 10
        tree.get_mut(fiber_id).unwrap().set_hook(0, 10i32);
        tree.mark_clean(fiber_id);

        batch.begin_batch();

        // First: regular update (always marks dirty)
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(20i32)),
            },
        );

        // Second: equality-checked update with same value (should not add to dirty)
        batch.queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::ValueIfChanged {
                    value: Box::new(20i32), // Same as previous update
                    eq_check: Box::new(|old, new| {
                        let old = old.downcast_ref::<i32>().unwrap();
                        let new = new.downcast_ref::<i32>().unwrap();
                        old == new
                    }),
                },
            },
        );

        let dirty = batch.end_batch(&mut tree);

        // Fiber should be dirty because first update changed it
        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(20));
    }

    // ========================================================================
    // Cross-thread update tests
    // ========================================================================

    #[test]
    #[serial]
    fn test_is_main_thread_without_init() {
        // Reset to ensure clean state
        reset_main_thread();

        // Without init_main_thread(), is_main_thread() should return true
        // (backward compatibility - assume main thread if not explicitly set)
        assert!(is_main_thread());
    }

    #[test]
    #[serial]
    fn test_init_main_thread_and_is_main_thread() {
        // Reset to ensure clean state
        reset_main_thread();

        // Initialize main thread
        init_main_thread();

        // Should return true on the same thread
        assert!(is_main_thread());

        // Clean up
        reset_main_thread();
    }

    #[test]
    #[serial]
    fn test_queue_cross_thread_update_adds_to_queue() {
        reset_main_thread();
        clear_cross_thread_updates();

        let fiber_id = FiberId(42);
        let update = CrossThreadUpdate {
            fiber_id,
            hook_index: 0,
            update: CrossThreadUpdateKind::Value(Box::new(123i32)),
        };

        queue_cross_thread_update(update);

        assert!(has_cross_thread_updates());

        clear_cross_thread_updates();
    }

    #[test]
    #[serial]
    fn test_drain_cross_thread_updates_moves_to_local_batch() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let fiber_id = FiberId(42);

        // Queue a cross-thread update directly
        let update = CrossThreadUpdate {
            fiber_id,
            hook_index: 0,
            update: CrossThreadUpdateKind::Value(Box::new(999i32)),
        };
        queue_cross_thread_update(update);

        assert!(has_cross_thread_updates());

        // Drain to local batch
        drain_cross_thread_updates();

        // Cross-thread queue should be empty now
        assert!(!has_cross_thread_updates());

        // Local batch should have the update
        let has_updates = with_state_batch(|batch| batch.has_pending_updates());
        assert!(has_updates);

        let is_dirty = with_state_batch(|batch| batch.is_fiber_dirty(fiber_id));
        assert!(is_dirty);

        clear_state_batch();
    }

    #[test]
    fn test_drain_cross_thread_updates_applies_value() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // Queue a cross-thread value update
        let update = CrossThreadUpdate {
            fiber_id,
            hook_index: 0,
            update: CrossThreadUpdateKind::Value(Box::new(42i32)),
        };
        queue_cross_thread_update(update);

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(42));

        clear_state_batch();
    }

    #[test]
    fn test_drain_cross_thread_updates_applies_updater() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 10i32);

        // Queue a cross-thread functional update
        let updater: StateUpdaterFn = Box::new(|any| {
            let n = any.downcast_ref::<i32>().unwrap();
            Box::new(n + 5)
        });
        let update = CrossThreadUpdate {
            fiber_id,
            hook_index: 0,
            update: CrossThreadUpdateKind::Updater(Arc::new(Mutex::new(Some(updater)))),
        };
        queue_cross_thread_update(update);

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(15));

        clear_state_batch();
    }

    #[test]
    fn test_cross_thread_updates_preserve_order() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // Queue multiple updates in order
        for i in 1..=5 {
            let updater: StateUpdaterFn = Box::new(move |any| {
                let n = any.downcast_ref::<i32>().unwrap();
                Box::new(n + i)
            });
            let update = CrossThreadUpdate {
                fiber_id,
                hook_index: 0,
                update: CrossThreadUpdateKind::Updater(Arc::new(Mutex::new(Some(updater)))),
            };
            queue_cross_thread_update(update);
        }

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        end_batch_with_tree(&mut tree);

        // 0 + 1 + 2 + 3 + 4 + 5 = 15
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(15));

        clear_state_batch();
    }

    #[test]
    fn test_queue_update_routes_to_local_on_main_thread() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        // Since init_main_thread() may or may not have been called,
        // and is_main_thread() returns true by default, this should
        // route to the local batch
        let fiber_id = FiberId(1);
        queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        // Should be in local batch, not cross-thread queue
        let has_local = with_state_batch(|batch| batch.has_pending_updates());
        assert!(has_local);

        // Cross-thread queue should be empty
        assert!(!has_cross_thread_updates());

        clear_state_batch();
    }

    // ========================================================================
    // Re-entrancy and edge case tests
    // ========================================================================

    #[test]
    fn test_queue_update_fallback_to_cross_thread_on_reentrant_call() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let fiber_id = FiberId(1);

        // Simulate a re-entrant call by holding a borrow of STATE_BATCH
        // while calling queue_update
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut(); // Hold the borrow

            // Now call queue_update - it should fall back to cross-thread queue
            // because try_borrow_mut will fail
            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Value(Box::new(42i32)),
                },
            );

            // The update should be in the cross-thread queue, not local batch
            assert!(has_cross_thread_updates());
        });

        // After releasing the borrow, local batch should still be empty
        // (the update went to cross-thread queue)
        let has_local = with_state_batch(|batch| batch.has_pending_updates());
        assert!(!has_local);

        // Cross-thread queue should have the update
        assert!(has_cross_thread_updates());

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_queue_update_fallback_applies_correctly_after_drain() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // Simulate a re-entrant call that falls back to cross-thread queue
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut();

            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Value(Box::new(100i32)),
                },
            );
        });

        // Now drain and apply
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        // The update should have been applied
        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(100));

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_queue_update_fallback_with_functional_updater() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 10i32);

        // Simulate a re-entrant call with a functional updater
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut();

            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Updater(Box::new(|any| {
                        let n = any.downcast_ref::<i32>().unwrap();
                        Box::new(n * 2)
                    })),
                },
            );
        });

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        // The functional update should have been applied: 10 * 2 = 20
        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(20));

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_queue_update_fallback_preserves_order_with_multiple_updates() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // Simulate multiple re-entrant calls
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut();

            // Queue multiple updates that should be applied in order
            for i in 1..=3 {
                queue_update(
                    fiber_id,
                    StateUpdate {
                        hook_index: 0,
                        update: StateUpdateKind::Updater(Box::new(move |any| {
                            let n = any.downcast_ref::<i32>().unwrap();
                            Box::new(n + i)
                        })),
                    },
                );
            }
        });

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        end_batch_with_tree(&mut tree);

        // Updates should be applied in order: 0 + 1 + 2 + 3 = 6
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(6));

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_queue_update_mixed_local_and_fallback() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // First, queue a normal update (goes to local batch)
        queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(10i32)),
            },
        );

        // Then simulate a re-entrant call (goes to cross-thread queue)
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut();

            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Updater(Box::new(|any| {
                        let n = any.downcast_ref::<i32>().unwrap();
                        Box::new(n + 5)
                    })),
                },
            );
        });

        // Local batch should have the first update
        let has_local = with_state_batch(|batch| batch.has_pending_updates());
        assert!(has_local);

        // Cross-thread queue should have the second update
        assert!(has_cross_thread_updates());

        // Drain cross-thread updates into local batch
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        // Both updates should be applied: first 10, then 10 + 5 = 15
        assert!(dirty.contains(&fiber_id));
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(15));

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_queue_update_fallback_with_value_if_changed() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 42i32);
        tree.mark_clean(fiber_id);

        // Simulate a re-entrant call with ValueIfChanged
        // The equality check is now preserved when falling back to cross-thread queue
        STATE_BATCH.with(|batch| {
            let _guard = batch.borrow_mut();

            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::ValueIfChanged {
                        value: Box::new(42i32), // Same value
                        eq_check: Box::new(|old, new| {
                            let old = old.downcast_ref::<i32>().unwrap();
                            let new = new.downcast_ref::<i32>().unwrap();
                            old == new
                        }),
                    },
                },
            );
        });

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        let dirty = end_batch_with_tree(&mut tree);

        // The update should NOT be applied because values are equal
        // The equality check is now preserved in cross-thread updates
        assert!(!dirty.contains(&fiber_id));
        assert!(!tree.get(fiber_id).unwrap().dirty);
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(42));

        clear_state_batch();
        clear_cross_thread_updates();
    }

    #[test]
    fn test_try_borrow_mut_success_path() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        let fiber_id = FiberId(1);

        // Normal case: no existing borrow, should use local batch
        queue_update(
            fiber_id,
            StateUpdate {
                hook_index: 0,
                update: StateUpdateKind::Value(Box::new(42i32)),
            },
        );

        // Should be in local batch
        let has_local = with_state_batch(|batch| batch.has_pending_updates());
        assert!(has_local);

        // Cross-thread queue should be empty
        assert!(!has_cross_thread_updates());

        clear_state_batch();
    }

    #[test]
    fn test_background_thread_always_uses_cross_thread_queue() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        // Initialize main thread to current thread
        init_main_thread();

        // Spawn a background thread that queues an update
        let fiber_id = FiberId(1);
        let handle = std::thread::spawn(move || {
            queue_update(
                fiber_id,
                StateUpdate {
                    hook_index: 0,
                    update: StateUpdateKind::Value(Box::new(99i32)),
                },
            );
        });

        handle.join().unwrap();

        // The update should be in the cross-thread queue
        assert!(has_cross_thread_updates());

        // Local batch should be empty (update came from background thread)
        let has_local = with_state_batch(|batch| batch.has_pending_updates());
        assert!(!has_local);

        clear_state_batch();
        clear_cross_thread_updates();
        reset_main_thread();
    }

    #[test]
    fn test_multiple_background_threads_queue_updates() {
        reset_main_thread();
        clear_state_batch();
        clear_cross_thread_updates();

        // Initialize main thread
        init_main_thread();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);
        tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

        // Spawn multiple background threads
        let handles: Vec<_> = (1..=5)
            .map(|i| {
                std::thread::spawn(move || {
                    queue_update(
                        fiber_id,
                        StateUpdate {
                            hook_index: 0,
                            update: StateUpdateKind::Updater(Box::new(move |any| {
                                let n = any.downcast_ref::<i32>().unwrap();
                                Box::new(n + i)
                            })),
                        },
                    );
                })
            })
            .collect();

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // All updates should be in cross-thread queue
        assert!(has_cross_thread_updates());

        // Drain and apply
        begin_batch();
        drain_cross_thread_updates();
        end_batch_with_tree(&mut tree);

        // All updates should be applied: 0 + 1 + 2 + 3 + 4 + 5 = 15
        assert_eq!(tree.get(fiber_id).unwrap().get_hook::<i32>(0), Some(15));

        clear_state_batch();
        clear_cross_thread_updates();
        reset_main_thread();
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    // ========================================================================
    // Property tests for cross-thread state updates
    // ========================================================================

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// **Property 1: Cross-thread updates are applied after drain**
        /// **Validates: Requirements 1.1, 1.2**
        ///
        /// For any value queued from a background thread, after drain_cross_thread_updates()
        /// and end_batch(), the value should be present in the fiber tree.
        #[test]
        fn prop_cross_thread_updates_applied_after_drain(
            values in prop::collection::vec(any::<i32>(), 1..10)
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

            init_main_thread();

            // Use a barrier to ensure all threads start at the same time
            let barrier = Arc::new(std::sync::Barrier::new(values.len()));

            // Queue updates from background threads directly to cross-thread queue
            let handles: Vec<_> = values.iter().map(|&val| {
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    barrier.wait(); // Synchronize thread start
                    queue_cross_thread_update(CrossThreadUpdate {
                        fiber_id,
                        hook_index: 0,
                        update: CrossThreadUpdateKind::Value(Box::new(val)),
                    });
                })
            }).collect();

            for handle in handles {
                handle.join().unwrap();
            }

            // Property: Cross-thread queue should have updates
            prop_assert!(has_cross_thread_updates(),
                "Cross-thread queue should have updates after background thread queuing");

            // Drain and apply
            begin_batch();
            drain_cross_thread_updates();
            let dirty = end_batch_with_tree(&mut tree);

            // Property: Fiber should be dirty
            prop_assert!(dirty.contains(&fiber_id),
                "Fiber should be marked dirty after cross-thread updates");

            // Property: Cross-thread queue should be empty after drain
            prop_assert!(!has_cross_thread_updates(),
                "Cross-thread queue should be empty after drain");

            // Property: Some value should be applied (last one wins)
            let final_value = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
            prop_assert!(final_value.is_some(),
                "Fiber should have a value after updates");

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
            reset_main_thread();
        }

        /// **Property 2: Update ordering is preserved**
        /// **Validates: Requirements 1.3**
        ///
        /// For a sequence of functional updates queued in order, the final result
        /// should reflect all updates applied in order.
        #[test]
        fn prop_update_ordering_preserved(
            increments in prop::collection::vec(1i32..10, 1..20)
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

            // Queue updates directly to local batch to test ordering
            begin_batch();
            for inc in &increments {
                let inc_val = *inc;
                with_state_batch_mut(|batch| {
                    batch.queue_update(
                        fiber_id,
                        StateUpdate {
                            hook_index: 0,
                            update: StateUpdateKind::Updater(Box::new(move |any| {
                                let n = any.downcast_ref::<i32>().unwrap();
                                Box::new(n + inc_val)
                            })),
                        },
                    );
                });
            }
            let dirty = end_batch_with_tree(&mut tree);

            // Property: Fiber should be dirty
            prop_assert!(dirty.contains(&fiber_id),
                "Fiber should be marked dirty after updates");

            // Property: Final value should be sum of all increments
            let expected: i32 = increments.iter().sum();
            let actual = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
            prop_assert_eq!(actual, Some(expected),
                "Final value should be sum of all increments: expected {}, got {:?}", expected, actual);

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 3: Main thread uses thread-local batching**
        /// **Validates: Requirements 2.1, 2.2**
        ///
        /// Updates queued on the main thread should go to the thread-local batch,
        /// not the cross-thread queue.
        #[test]
        fn prop_main_thread_uses_local_batch(
            values in prop::collection::vec(any::<i32>(), 1..10)
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            // Don't initialize main thread - is_main_thread() returns true by default
            let fiber_id = FiberId(1);

            for &val in &values {
                queue_update(
                    fiber_id,
                    StateUpdate {
                        hook_index: 0,
                        update: StateUpdateKind::Value(Box::new(val)),
                    },
                );
            }

            // Property: Updates should be in local batch
            let has_local = with_state_batch(|batch| batch.has_pending_updates());
            prop_assert!(has_local,
                "Updates from main thread should be in local batch");

            // Property: Cross-thread queue should be empty
            prop_assert!(!has_cross_thread_updates(),
                "Cross-thread queue should be empty for main thread updates");

            // Property: Only one fiber should be dirty (batched)
            let dirty_count = with_state_batch(|batch| batch.dirty_fiber_count());
            prop_assert_eq!(dirty_count, 1,
                "Only one fiber should be dirty regardless of update count");

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 4: Concurrent cross-thread access is safe**
        /// **Validates: Requirements 5.2, 5.3**
        ///
        /// Multiple threads queuing updates concurrently should not cause panics
        /// or data races, and all updates should be applied.
        #[test]
        fn prop_concurrent_access_safe(
            thread_count in 2usize..10,
            updates_per_thread in 1usize..5
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

            init_main_thread();

            // Use a barrier to ensure all threads start at the same time
            let barrier = Arc::new(std::sync::Barrier::new(thread_count));

            // Spawn multiple threads that each queue multiple updates
            let handles: Vec<_> = (0..thread_count).map(|_| {
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    barrier.wait(); // Synchronize thread start
                    for _ in 0..updates_per_thread {
                        queue_cross_thread_update(CrossThreadUpdate {
                            fiber_id,
                            hook_index: 0,
                            update: CrossThreadUpdateKind::Updater(Arc::new(Mutex::new(Some(
                                Box::new(move |any| {
                                    let n = any.downcast_ref::<i32>().unwrap();
                                    Box::new(n + 1)
                                })
                            )))),
                        });
                    }
                })
            }).collect();

            // Wait for all threads - should not panic
            for handle in handles {
                handle.join().expect("Thread should not panic");
            }

            // Drain and apply
            begin_batch();
            drain_cross_thread_updates();
            let dirty = end_batch_with_tree(&mut tree);

            // Property: Fiber should be dirty
            prop_assert!(dirty.contains(&fiber_id),
                "Fiber should be marked dirty after concurrent updates");

            // Property: All updates should be applied
            let expected = (thread_count * updates_per_thread) as i32;
            let actual = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
            prop_assert_eq!(actual, Some(expected),
                "All {} updates should be applied, got {:?}", expected, actual);

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
            reset_main_thread();
        }

        /// **Property 4: State Batch Atomicity**
        /// **Validates: Requirements 3.1, 3.2, 3.3**
        ///
        /// For any sequence of state updates queued during a batch, all updates SHALL
        /// be applied atomically when end_batch is called, and the set of dirty fibers
        /// SHALL be returned.
        #[test]
        fn prop_state_batch_atomicity(
            fiber_count in 1usize..10,
            updates_per_fiber in 1usize..10
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_ids: Vec<_> = (0..fiber_count)
                .map(|_| {
                    let id = tree.mount(None, None);
                    tree.get_mut(id).unwrap().set_hook(0, 0i32);
                    id
                })
                .collect();

            // Begin batch
            begin_batch();

            // Queue multiple updates for each fiber directly to local batch
            for &fiber_id in &fiber_ids {
                for i in 0..updates_per_fiber {
                    with_state_batch_mut(|batch| {
                        batch.queue_update(
                            fiber_id,
                            StateUpdate {
                                hook_index: 0,
                                update: StateUpdateKind::Updater(Box::new(move |any| {
                                    let n = any.downcast_ref::<i32>().unwrap();
                                    Box::new(n + (i as i32 + 1))
                                })),
                            },
                        );
                    });
                }
            }

            // Property: Updates should be queued, not applied yet
            for &fiber_id in &fiber_ids {
                let value = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
                prop_assert_eq!(value, Some(0),
                    "Updates should not be applied until end_batch");
            }

            // End batch - apply all updates atomically
            let dirty = end_batch_with_tree(&mut tree);

            // Property: All fibers should be in the dirty set
            prop_assert_eq!(dirty.len(), fiber_count,
                "All {} fibers should be marked dirty", fiber_count);
            for &fiber_id in &fiber_ids {
                prop_assert!(dirty.contains(&fiber_id),
                    "Fiber {:?} should be in dirty set", fiber_id);
            }

            // Property: All updates should be applied
            let expected_sum: i32 = (1..=updates_per_fiber as i32).sum();
            for &fiber_id in &fiber_ids {
                let value = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
                prop_assert_eq!(value, Some(expected_sum),
                    "All updates should be applied atomically, expected {}, got {:?}",
                    expected_sum, value);
            }

            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 5: Functional Updater Chaining**
        /// **Validates: Requirements 3.5**
        ///
        /// For any sequence of functional updaters queued for the same hook, each updater
        /// SHALL receive the result of the previous updater, producing a correctly chained
        /// final value.
        #[test]
        fn prop_functional_updater_chaining(
            operations in prop::collection::vec((any::<bool>(), 1i32..10), 1..20)
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

            begin_batch();

            // Queue a sequence of functional updates
            // Each operation is (is_add, value): if true, add; if false, multiply
            for &(is_add, value) in &operations {
                queue_update(
                    fiber_id,
                    StateUpdate {
                        hook_index: 0,
                        update: StateUpdateKind::Updater(Box::new(move |any| {
                            let n = any.downcast_ref::<i32>().unwrap();
                            if is_add {
                                Box::new(n.saturating_add(value))
                            } else {
                                Box::new(n.saturating_mul(value))
                            }
                        })),
                    },
                );
            }

            end_batch_with_tree(&mut tree);

            // Property: Final value should reflect all operations applied in order
            let mut expected = 0i32;
            for &(is_add, value) in &operations {
                if is_add {
                    expected = expected.saturating_add(value);
                } else {
                    expected = expected.saturating_mul(value);
                }
            }

            let actual = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
            prop_assert_eq!(actual, Some(expected),
                "Functional updaters should chain correctly: expected {}, got {:?}",
                expected, actual);

            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 6: Equality Check Optimization**
        /// **Validates: Requirements 3.6**
        ///
        /// For any ValueIfChanged or UpdaterIfChanged update where the new value equals
        /// the current value, the fiber SHALL NOT be marked as dirty.
        #[test]
        fn prop_equality_check_optimization(
            initial_value in any::<i32>(),
            same_value_updates in 1usize..10,
            different_value in any::<i32>()
        ) {
            // Ensure different_value is actually different
            prop_assume!(initial_value != different_value);

            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, initial_value);
            tree.mark_clean(fiber_id);

            begin_batch();

            // Queue multiple ValueIfChanged updates with the same value directly to local batch
            for _ in 0..same_value_updates {
                with_state_batch_mut(|batch| {
                    batch.queue_update(
                        fiber_id,
                        StateUpdate {
                            hook_index: 0,
                            update: StateUpdateKind::ValueIfChanged {
                                value: Box::new(initial_value),
                                eq_check: Box::new(|old, new| {
                                    let old = old.downcast_ref::<i32>().unwrap();
                                    let new = new.downcast_ref::<i32>().unwrap();
                                    old == new
                                }),
                            },
                        },
                    );
                });
            }

            let dirty = end_batch_with_tree(&mut tree);

            // Property: Fiber should NOT be dirty (all values were equal)
            prop_assert!(!dirty.contains(&fiber_id),
                "Fiber should not be dirty when ValueIfChanged updates have equal values");
            prop_assert!(!tree.get(fiber_id).unwrap().dirty,
                "Fiber dirty flag should be false");

            // Now test with a different value
            tree.mark_clean(fiber_id);
            begin_batch();

            with_state_batch_mut(|batch| {
                batch.queue_update(
                    fiber_id,
                    StateUpdate {
                        hook_index: 0,
                        update: StateUpdateKind::ValueIfChanged {
                            value: Box::new(different_value),
                            eq_check: Box::new(|old, new| {
                                let old = old.downcast_ref::<i32>().unwrap();
                                let new = new.downcast_ref::<i32>().unwrap();
                                old == new
                            }),
                        },
                    },
                );
            });

            let dirty = end_batch_with_tree(&mut tree);

            // Property: Fiber SHOULD be dirty (value changed)
            prop_assert!(dirty.contains(&fiber_id),
                "Fiber should be dirty when ValueIfChanged has different value");
            prop_assert_eq!(
                tree.get(fiber_id).unwrap().get_hook::<i32>(0),
                Some(different_value),
                "Value should be updated to different_value"
            );

            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 5: Re-entrant calls fall back to cross-thread queue**
        /// **Validates: Requirements 5.2**
        ///
        /// When STATE_BATCH is already borrowed, queue_update should fall back
        /// to the cross-thread queue without panicking.
        #[test]
        fn prop_reentrant_fallback_safe(
            values in prop::collection::vec(any::<i32>(), 1..5)
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let fiber_id = FiberId(1);

            // Simulate re-entrant calls
            STATE_BATCH.with(|batch| {
                let _guard = batch.borrow_mut(); // Hold the borrow

                for &val in &values {
                    // This should fall back to cross-thread queue
                    queue_update(
                        fiber_id,
                        StateUpdate {
                            hook_index: 0,
                            update: StateUpdateKind::Value(Box::new(val)),
                        },
                    );
                }
            });

            // Property: All updates should be in cross-thread queue
            prop_assert!(has_cross_thread_updates(),
                "Re-entrant updates should fall back to cross-thread queue");

            // Property: Local batch should be empty (updates went to cross-thread)
            let has_local = with_state_batch(|batch| batch.has_pending_updates());
            prop_assert!(!has_local,
                "Local batch should be empty after re-entrant fallback");

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
        }

        /// **Property 14: Cross-Thread Update Delivery**
        /// **Validates: Requirements 3.7**
        ///
        /// For any state update queued from a background thread, the update SHALL be
        /// delivered to the main thread's batch and applied on the next frame.
        #[test]
        fn prop_cross_thread_update_delivery(
            update_count in 1usize..20,
            thread_count in 1usize..5
        ) {
            reset_main_thread();
            clear_state_batch();
            clear_cross_thread_updates();

            let mut tree = FiberTree::new();
            let fiber_id = tree.mount(None, None);
            tree.get_mut(fiber_id).unwrap().set_hook(0, 0i32);

            init_main_thread();

            // Use a barrier to ensure all threads start at the same time
            let barrier = Arc::new(std::sync::Barrier::new(thread_count));

            // Spawn background threads that queue updates directly to cross-thread queue
            let handles: Vec<_> = (0..thread_count).map(|_| {
                let barrier = Arc::clone(&barrier);
                std::thread::spawn(move || {
                    barrier.wait(); // Synchronize thread start
                    for _ in 0..update_count {
                        queue_cross_thread_update(CrossThreadUpdate {
                            fiber_id,
                            hook_index: 0,
                            update: CrossThreadUpdateKind::Updater(Arc::new(Mutex::new(Some(
                                Box::new(move |any| {
                                    let n = any.downcast_ref::<i32>().unwrap();
                                    Box::new(n + 1)
                                })
                            )))),
                        });
                    }
                })
            }).collect();

            // Wait for all background threads to complete
            for handle in handles {
                handle.join().expect("Background thread should not panic");
            }

            // Property: Cross-thread queue should have updates
            prop_assert!(has_cross_thread_updates(),
                "Cross-thread queue should have updates after background threads queue them");

            // Simulate main thread processing (next frame)
            begin_batch();
            drain_cross_thread_updates();
            let dirty = end_batch_with_tree(&mut tree);

            // Property: Updates SHALL be delivered to main thread's batch
            prop_assert!(dirty.contains(&fiber_id),
                "Fiber should be marked dirty after cross-thread updates are drained");

            // Property: Updates SHALL be applied on the next frame
            let expected = (update_count * thread_count) as i32;
            let actual = tree.get(fiber_id).unwrap().get_hook::<i32>(0);
            prop_assert_eq!(actual, Some(expected),
                "All {} updates should be applied after drain, got {:?}", expected, actual);

            // Property: Cross-thread queue should be empty after drain
            prop_assert!(!has_cross_thread_updates(),
                "Cross-thread queue should be empty after drain");

            // Clean up
            clear_state_batch();
            clear_cross_thread_updates();
            reset_main_thread();
        }
    }
}