blinc_app 0.5.1

Blinc application framework with clean layout and rendering API
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
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
//! Windowed application runner
//!
//! Provides a unified API for running windowed Blinc applications across
//! desktop and Android platforms.
//!
//! # Example
//!
//! ```ignore
//! use blinc_app::prelude::*;
//! use blinc_app::windowed::WindowedApp;
//!
//! fn main() -> Result<()> {
//!     WindowedApp::run(WindowConfig::default(), |ctx| {
//!         // Build your UI using reactive signals
//!         let count = ctx.use_signal(0);
//!         let doubled = ctx.use_derived(move |cx| cx.get(count).unwrap_or(0) * 2);
//!
//!         div().w_full().h_full()
//!             .flex_center()
//!             .child(text(&format!("Count: {}", ctx.get(count).unwrap_or(0))).size(48.0))
//!     })
//! }
//! ```

use std::hash::Hash;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};

use blinc_animation::{
    AnimatedTimeline, AnimatedValue, AnimationContext, AnimationScheduler, SchedulerHandle,
    SharedAnimatedTimeline, SharedAnimatedValue, SpringConfig,
};
use blinc_core::context_state::{BlincContextState, HookState, SharedHookState, StateKey};
use blinc_core::reactive::{Derived, ReactiveGraph, Signal, SignalId, State, StatefulDepsCallback};
use blinc_layout::overlay_state::{get_overlay_manager, OverlayContext};
use blinc_layout::prelude::*;
use blinc_layout::widgets::overlay::{overlay_manager, OverlayManager, OverlayManagerExt};
use blinc_platform::{
    ControlFlow, Event, EventLoop, InputEvent, Key, KeyState, LifecycleEvent, MouseEvent, Platform,
    TouchEvent, Window, WindowConfig, WindowEvent,
};

use crate::app::BlincApp;
use crate::error::{BlincError, Result};

/// Shared animation scheduler for the application (thread-safe)
pub type SharedAnimationScheduler = Arc<Mutex<AnimationScheduler>>;

// SharedAnimatedValue and SharedAnimatedTimeline are re-exported from blinc_animation

#[cfg(all(feature = "windowed", not(target_os = "android")))]
use blinc_platform_desktop::DesktopPlatform;

/// Shared dirty flag type for element refs
pub type RefDirtyFlag = Arc<AtomicBool>;

/// Shared reactive graph for the application (thread-safe)
pub type SharedReactiveGraph = Arc<Mutex<ReactiveGraph>>;

/// Shared element registry for query API (thread-safe)
pub type SharedElementRegistry = Arc<blinc_layout::selector::ElementRegistry>;

/// Callback type for on_ready handlers
pub type ReadyCallback = Box<dyn FnOnce() + Send + Sync>;

/// Shared storage for ready callbacks
pub type SharedReadyCallbacks = Arc<Mutex<Vec<ReadyCallback>>>;

/// UI builder function for a window. Called each frame to produce the UI tree.
/// Returns a `Div` (the root element type for all Blinc UIs).
pub type WindowBuilder = Box<dyn FnMut(&mut WindowedContext) -> Div + Send>;

/// Pending window request: config + optional UI builder
struct PendingWindowRequest {
    config: WindowConfig,
    builder: Option<WindowBuilder>,
}

/// Queue of pending window requests (builder closures waiting to be picked up
/// by the event loop after AppCommand::CreateWindow fires).
static PENDING_WINDOW_BUILDERS: std::sync::OnceLock<Mutex<Vec<PendingWindowRequest>>> =
    std::sync::OnceLock::new();

fn pending_builders() -> &'static Mutex<Vec<PendingWindowRequest>> {
    PENDING_WINDOW_BUILDERS.get_or_init(|| Mutex::new(Vec::new()))
}

/// Global callback for sending CreateWindow command to the event loop.
static OPEN_WINDOW_FN: std::sync::OnceLock<Arc<dyn Fn(WindowConfig) + Send + Sync>> =
    std::sync::OnceLock::new();

/// Global callback for initiating a window drag operation (custom title bars).
static DRAG_WINDOW_FN: std::sync::OnceLock<Arc<dyn Fn() + Send + Sync>> =
    std::sync::OnceLock::new();

/// Start a window drag operation (for custom title bars).
///
/// Call this from a mouse-down handler on a draggable element.
/// The OS takes over and the window follows the cursor until release.
pub fn drag_window() {
    if let Some(f) = DRAG_WINDOW_FN.get() {
        f();
    }
}

/// Open a new window with a UI builder from anywhere in the application.
///
/// The builder closure is called each frame to produce the window's UI.
///
/// # Example
/// ```ignore
/// use blinc_app::windowed::open_window_with;
///
/// open_window_with(
///     WindowConfig::new("Settings").size(400, 300),
///     |ctx| {
///         Box::new(div()
///             .w(ctx.width).h(ctx.height)
///             .bg(Color::rgb(0.1, 0.1, 0.15))
///             .child(text("Settings Window").size(24.0).color(Color::WHITE)))
///     },
/// );
/// ```
pub fn open_window_with<F>(config: WindowConfig, builder: F)
where
    F: FnMut(&mut WindowedContext) -> Div + Send + 'static,
{
    // Queue the builder so the event loop can pick it up
    pending_builders()
        .lock()
        .unwrap()
        .push(PendingWindowRequest {
            config: config.clone(),
            builder: Some(Box::new(builder)),
        });

    // Send the CreateWindow command to the event loop
    if let Some(f) = OPEN_WINDOW_FN.get() {
        f(config);
    } else {
        tracing::warn!("open_window_with() called before app initialization");
    }
}

/// Open a new window with a default blank UI.
///
/// For windows with custom UI, use `open_window_with()` instead.
pub fn open_window(config: WindowConfig) {
    // Queue without builder (uses default UI)
    pending_builders()
        .lock()
        .unwrap()
        .push(PendingWindowRequest {
            config: config.clone(),
            builder: None,
        });

    if let Some(f) = OPEN_WINDOW_FN.get() {
        f(config);
    } else {
        tracing::warn!("open_window() called before app initialization");
    }
}

/// Per-window state bundle.
///
/// Groups all state that is specific to a single window, extracted from the
/// monolithic event loop closure. This is the foundation for multi-window support.
#[cfg(all(feature = "windowed", not(target_os = "android")))]
pub(crate) struct WindowState {
    /// GPU app (renderer, device, queue)
    pub app: Option<BlincApp>,
    /// Window surface for rendering
    pub surface: Option<wgpu::Surface<'static>>,
    /// Surface configuration
    pub surface_config: Option<wgpu::SurfaceConfiguration>,
    /// UI context (dimensions, event router, shared handles)
    pub ctx: Option<WindowedContext>,
    /// Render tree (layout + render nodes)
    pub render_tree: Option<RenderTree>,
    /// Render state (cursor blink, animated values, motion)
    pub render_state: Option<blinc_layout::RenderState>,
    /// CSS animation/transition store
    pub css_anim_store: Arc<Mutex<blinc_layout::CssAnimationStore>>,
    /// Shared motion animation states
    pub shared_motion_states:
        Arc<std::sync::RwLock<std::collections::HashMap<String, blinc_core::MotionAnimationState>>>,
    /// Whether the UI tree needs rebuilding
    pub needs_rebuild: bool,
    /// Whether layout needs recomputing
    pub needs_relayout: bool,
    /// Last frame timestamp for CSS animation delta
    pub last_frame_time_ms: u64,
    /// Active touch point IDs
    pub active_touch_ids: std::collections::HashSet<u64>,
    /// UI builder for this window (None = default static UI)
    pub ui_builder: Option<WindowBuilder>,
}

#[cfg(all(feature = "windowed", not(target_os = "android")))]
impl WindowState {
    /// Create a new empty WindowState with shared resources
    pub fn new(
        css_anim_store: Arc<Mutex<blinc_layout::CssAnimationStore>>,
        shared_motion_states: Arc<
            std::sync::RwLock<std::collections::HashMap<String, blinc_core::MotionAnimationState>>,
        >,
    ) -> Self {
        Self {
            app: None,
            surface: None,
            surface_config: None,
            ctx: None,
            render_tree: None,
            render_state: None,
            css_anim_store,
            shared_motion_states,
            needs_rebuild: true,
            needs_relayout: false,
            last_frame_time_ms: 0,
            active_touch_ids: std::collections::HashSet::new(),
            ui_builder: None,
        }
    }
}

/// Context passed to the UI builder function
pub struct WindowedContext {
    /// Current window width in logical pixels (for UI layout)
    ///
    /// This is the width you should use when building UI. It automatically
    /// accounts for DPI scaling, so elements sized to `ctx.width` will
    /// fill the window regardless of display scale factor.
    pub width: f32,
    /// Current window height in logical pixels (for UI layout)
    pub height: f32,
    /// Current scale factor (physical / logical)
    pub scale_factor: f64,
    /// Safe area insets (top, right, bottom, left) in logical pixels.
    /// On mobile: notch, status bar, home indicator.
    /// On desktop: all zeros.
    pub safe_area: (f32, f32, f32, f32),
    /// Soft-keyboard inset, in **logical** pixels — height in pixels of
    /// the area at the bottom of the screen currently obscured by an
    /// on-screen keyboard. Zero when the keyboard is hidden.
    ///
    /// Updated by the platform runner from native keyboard events:
    ///
    ///   - iOS: parsed from
    ///     `UIKeyboardWillChangeFrameNotification.userInfo[UIKeyboardFrameEndUserInfoKey]`
    ///     in `BlincKeyboardHelper`, pushed via the
    ///     `blinc_ios_set_keyboard_inset` FFI export.
    ///   - Android: read from
    ///     `WindowInsets.Type.ime().bottom` in
    ///     `BlincNativeBridge.kt`, dispatched into Rust through the
    ///     `keyboard.set_inset` native-bridge handler.
    ///   - Desktop / web / Fuchsia: always zero.
    ///
    /// The text-input refocus path consumes this to scroll the focused
    /// input above the keyboard when it appears, mirroring the iOS UIKit
    /// `UIScrollView.contentInset` adjustment dance.
    pub keyboard_inset: f32,
    /// Physical window width (for internal use)
    pub(crate) physical_width: f32,
    /// Physical window height (for internal use)
    pub(crate) physical_height: f32,
    /// Whether the window is focused
    pub focused: bool,
    /// Number of completed UI rebuilds (0 = first build in progress)
    ///
    /// Use `is_ready()` to check if the UI has been built at least once.
    /// This is useful for triggering animations after motion bindings are registered.
    pub rebuild_count: u32,
    /// Event router for input event handling
    pub event_router: EventRouter,
    /// Animation scheduler for spring/keyframe animations
    pub animations: SharedAnimationScheduler,
    /// Shared dirty flag for element refs - when set, triggers UI rebuild
    ref_dirty_flag: RefDirtyFlag,
    /// Reactive graph for signal-based state management
    reactive: SharedReactiveGraph,
    /// Hook state for call-order based signal persistence
    hooks: SharedHookState,
    /// Overlay manager for modals, dialogs, toasts, etc.
    pub(crate) overlay_manager: OverlayManager,
    /// Whether overlays were visible last frame (for triggering rebuilds)
    pub(crate) had_visible_overlays: bool,
    /// Element registry for query API (shared with RenderTree)
    element_registry: SharedElementRegistry,
    /// Callbacks to run after UI is ready (motion bindings registered)
    ready_callbacks: SharedReadyCallbacks,
    /// CSS stylesheet for automatic style application (hover, animations, base styles)
    /// Multiple stylesheets cascade — later rules override earlier ones.
    pub stylesheet: Option<Arc<blinc_layout::css_parser::Stylesheet>>,
    /// Raw CSS source strings, preserved for reparsing on theme changes.
    /// Each entry corresponds to one `add_css()` call, in order.
    css_sources: Vec<String>,
    /// Continuous pointer query state (per-element pointer tracking)
    pub pointer_query: blinc_layout::pointer_query::PointerQueryState,
    /// Callback to request opening a new window (set by desktop runner)
    open_window_fn: Option<Arc<dyn Fn(WindowConfig) + Send + Sync>>,
    /// Per-window close callback (sends CloseWindow command for THIS window)
    close_fn: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Per-window drag callback (starts OS drag for THIS window)
    drag_fn: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Per-window minimize callback
    minimize_fn: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Per-window maximize callback
    maximize_fn: Option<Arc<dyn Fn() + Send + Sync>>,
}

impl WindowedContext {
    #[allow(clippy::too_many_arguments)]
    fn from_window<W: Window>(
        window: &W,
        event_router: EventRouter,
        animations: SharedAnimationScheduler,
        ref_dirty_flag: RefDirtyFlag,
        reactive: SharedReactiveGraph,
        hooks: SharedHookState,
        overlay_mgr: OverlayManager,
        element_registry: SharedElementRegistry,
        ready_callbacks: SharedReadyCallbacks,
    ) -> Self {
        // Get physical size (actual surface pixels) and scale factor
        let (physical_width, physical_height) = window.size();
        let scale_factor = window.scale_factor();

        // Compute logical size (what users work with in their UI code)
        // This ensures elements sized with ctx.width/height fill the window
        // regardless of DPI, and font sizes appear consistent across displays
        let logical_width = physical_width as f32 / scale_factor as f32;
        let logical_height = physical_height as f32 / scale_factor as f32;

        Self {
            width: logical_width,
            height: logical_height,
            scale_factor,
            safe_area: window.safe_area_insets(),
            keyboard_inset: 0.0,
            physical_width: physical_width as f32,
            physical_height: physical_height as f32,
            focused: window.is_focused(),
            rebuild_count: 0,
            event_router,
            animations,
            ref_dirty_flag,
            reactive,
            hooks,
            overlay_manager: overlay_mgr,
            had_visible_overlays: false,
            element_registry,
            ready_callbacks,
            stylesheet: None,
            css_sources: Vec::new(),
            pointer_query: blinc_layout::pointer_query::PointerQueryState::new(),
            open_window_fn: None,
            close_fn: None,
            drag_fn: None,
            minimize_fn: None,
            maximize_fn: None,
        }
    }

    /// Create a WindowedContext for Android
    ///
    /// This is used by the Android runner since it doesn't have a Window trait implementation.
    #[cfg(all(feature = "android", target_os = "android"))]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new_android(
        logical_width: f32,
        logical_height: f32,
        scale_factor: f64,
        physical_width: f32,
        physical_height: f32,
        focused: bool,
        safe_area: (f32, f32, f32, f32),
        animations: SharedAnimationScheduler,
        ref_dirty_flag: RefDirtyFlag,
        reactive: SharedReactiveGraph,
        hooks: SharedHookState,
        overlay_mgr: OverlayManager,
        element_registry: SharedElementRegistry,
        ready_callbacks: SharedReadyCallbacks,
    ) -> Self {
        Self {
            width: logical_width,
            height: logical_height,
            scale_factor,
            safe_area,
            keyboard_inset: 0.0,
            physical_width,
            physical_height,
            focused,
            rebuild_count: 0,
            event_router: EventRouter::new(),
            animations,
            ref_dirty_flag,
            reactive,
            hooks,
            overlay_manager: overlay_mgr,
            had_visible_overlays: false,
            element_registry,
            ready_callbacks,
            stylesheet: None,
            css_sources: Vec::new(),
            pointer_query: blinc_layout::pointer_query::PointerQueryState::new(),
            open_window_fn: None,
            close_fn: None,
            drag_fn: None,
            minimize_fn: None,
            maximize_fn: None,
        }
    }

    /// Create a WindowedContext for iOS
    ///
    /// This is used by the iOS runner since it doesn't have a Window trait implementation.
    #[cfg(all(feature = "ios", target_os = "ios"))]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new_ios(
        logical_width: f32,
        logical_height: f32,
        scale_factor: f64,
        physical_width: f32,
        physical_height: f32,
        focused: bool,
        safe_area: (f32, f32, f32, f32),
        animations: SharedAnimationScheduler,
        ref_dirty_flag: RefDirtyFlag,
        reactive: SharedReactiveGraph,
        hooks: SharedHookState,
        overlay_mgr: OverlayManager,
        element_registry: SharedElementRegistry,
        ready_callbacks: SharedReadyCallbacks,
    ) -> Self {
        Self {
            width: logical_width,
            height: logical_height,
            scale_factor,
            safe_area,
            keyboard_inset: 0.0,
            physical_width,
            physical_height,
            focused,
            rebuild_count: 0,
            event_router: EventRouter::new(),
            animations,
            ref_dirty_flag,
            reactive,
            hooks,
            overlay_manager: overlay_mgr,
            had_visible_overlays: false,
            element_registry,
            ready_callbacks,
            stylesheet: None,
            css_sources: Vec::new(),
            pointer_query: blinc_layout::pointer_query::PointerQueryState::new(),
            open_window_fn: None,
            close_fn: None,
            drag_fn: None,
            minimize_fn: None,
            maximize_fn: None,
        }
    }

    /// Create a WindowedContext for the web target.
    ///
    /// Mirrors [`Self::new_android`] / [`Self::new_ios`] / [`Self::new_fuchsia`]:
    /// the web runner extracts canvas dimensions and `devicePixelRatio`
    /// from the browser before calling, instead of going through the
    /// `Window` trait (which requires `raw-window-handle` types that
    /// `HtmlCanvasElement` doesn't implement).
    ///
    /// Wired into the `web` feature so this constructor is invisible to
    /// non-wasm builds. The shared / animation / overlay parameters are
    /// the same as the other `new_*` constructors so the wasm runner
    /// can build the same `WindowedContext` shape every other platform
    /// gets.
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new_web(
        logical_width: f32,
        logical_height: f32,
        scale_factor: f64,
        physical_width: f32,
        physical_height: f32,
        focused: bool,
        animations: SharedAnimationScheduler,
        ref_dirty_flag: RefDirtyFlag,
        reactive: SharedReactiveGraph,
        hooks: SharedHookState,
        overlay_mgr: OverlayManager,
        element_registry: SharedElementRegistry,
        ready_callbacks: SharedReadyCallbacks,
    ) -> Self {
        Self {
            width: logical_width,
            height: logical_height,
            scale_factor,
            safe_area: (0.0, 0.0, 0.0, 0.0),
            keyboard_inset: 0.0,
            physical_width,
            physical_height,
            focused,
            rebuild_count: 0,
            event_router: EventRouter::new(),
            animations,
            ref_dirty_flag,
            reactive,
            hooks,
            overlay_manager: overlay_mgr,
            had_visible_overlays: false,
            element_registry,
            ready_callbacks,
            stylesheet: None,
            css_sources: Vec::new(),
            pointer_query: blinc_layout::pointer_query::PointerQueryState::new(),
            open_window_fn: None,
            close_fn: None,
            drag_fn: None,
            minimize_fn: None,
            maximize_fn: None,
        }
    }

    /// Create a WindowedContext for Fuchsia
    ///
    /// This is used by the Fuchsia runner since it doesn't have a Window trait implementation.
    #[cfg(all(feature = "fuchsia", target_os = "fuchsia"))]
    pub(crate) fn new_fuchsia(
        logical_width: f32,
        logical_height: f32,
        scale_factor: f64,
        physical_width: f32,
        physical_height: f32,
        focused: bool,
        animations: SharedAnimationScheduler,
        ref_dirty_flag: RefDirtyFlag,
        reactive: SharedReactiveGraph,
        hooks: SharedHookState,
        overlay_mgr: OverlayManager,
        element_registry: SharedElementRegistry,
        ready_callbacks: SharedReadyCallbacks,
    ) -> Self {
        Self {
            width: logical_width,
            height: logical_height,
            scale_factor,
            safe_area: (0.0, 0.0, 0.0, 0.0),
            keyboard_inset: 0.0,
            physical_width,
            physical_height,
            focused,
            rebuild_count: 0,
            event_router: EventRouter::new(),
            animations,
            ref_dirty_flag,
            reactive,
            hooks,
            overlay_manager: overlay_mgr,
            had_visible_overlays: false,
            element_registry,
            ready_callbacks,
            stylesheet: None,
            css_sources: Vec::new(),
            pointer_query: blinc_layout::pointer_query::PointerQueryState::new(),
            open_window_fn: None,
            close_fn: None,
            drag_fn: None,
            minimize_fn: None,
            maximize_fn: None,
        }
    }

    /// Update context from window (preserving event router, dirty flag, and reactive graph)
    fn update_from_window<W: Window>(&mut self, window: &W) {
        let (physical_width, physical_height) = window.size();
        let scale_factor = window.scale_factor();

        self.physical_width = physical_width as f32;
        self.physical_height = physical_height as f32;
        self.width = physical_width as f32 / scale_factor as f32;
        self.height = physical_height as f32 / scale_factor as f32;
        self.scale_factor = scale_factor;
        self.focused = window.is_focused();
    }

    // =========================================================================
    // DPI-Related Helpers
    // =========================================================================

    /// Get the physical window width (for advanced use cases)
    ///
    /// Most users should use `ctx.width` which is in logical pixels.
    /// Physical dimensions are only needed when directly interfacing
    /// with GPU surfaces or platform-specific code.
    pub fn physical_width(&self) -> f32 {
        self.physical_width
    }

    /// Get the physical window height (for advanced use cases)
    pub fn physical_height(&self) -> f32 {
        self.physical_height
    }

    /// Check if the UI is ready (has completed at least one rebuild)
    ///
    /// This is useful for triggering animations after the first UI build,
    /// when motion bindings have been registered with the renderer.
    ///
    /// # Example
    ///
    /// ```ignore
    /// fn my_component(ctx: &WindowedContext) -> impl ElementBuilder {
    ///     let progress = ctx.use_animated_value_for("progress", 0.0, SpringConfig::gentle());
    ///
    ///     // Only trigger animation after UI is ready
    ///     let triggered = ctx.use_state_keyed("triggered", || false);
    ///     if ctx.is_ready() && !triggered.get() {
    ///         triggered.set(true);
    ///         progress.lock().unwrap().set_target(100.0);
    ///     }
    ///
    ///     // ... build UI ...
    /// }
    /// ```
    pub fn is_ready(&self) -> bool {
        self.rebuild_count > 0
    }

    /// Safe area inset from the top (status bar, notch)
    pub fn safe_top(&self) -> f32 {
        self.safe_area.0
    }

    /// Safe area inset from the right
    pub fn safe_right(&self) -> f32 {
        self.safe_area.1
    }

    /// Safe area inset from the bottom (home indicator)
    pub fn safe_bottom(&self) -> f32 {
        self.safe_area.2
    }

    /// Safe area inset from the left
    pub fn safe_left(&self) -> f32 {
        self.safe_area.3
    }

    /// Content width excluding safe area insets
    pub fn safe_width(&self) -> f32 {
        self.width - self.safe_area.1 - self.safe_area.3
    }

    /// Content height excluding safe area insets
    pub fn safe_height(&self) -> f32 {
        self.height - self.safe_area.0 - self.safe_area.2
    }

    /// Open a new window with the given configuration.
    ///
    /// The window is created asynchronously on the next event loop tick.
    /// Only available on desktop platforms.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.open_window(WindowConfig::new("Settings").size(400, 300));
    /// ```
    pub fn open_window(&self, config: WindowConfig) {
        if let Some(ref open_fn) = self.open_window_fn {
            open_fn(config);
        } else {
            tracing::warn!(
                "open_window() called but no window creation callback is set (not on desktop?)"
            );
        }
    }

    /// Set the callback for opening new windows (called by the desktop runner)
    pub(crate) fn set_open_window_fn(&mut self, f: Arc<dyn Fn(WindowConfig) + Send + Sync>) {
        self.open_window_fn = Some(f);
    }

    /// Set per-window action callbacks (called by the desktop runner)
    pub(crate) fn set_window_actions(
        &mut self,
        close: Arc<dyn Fn() + Send + Sync>,
        drag: Arc<dyn Fn() + Send + Sync>,
        minimize: Arc<dyn Fn() + Send + Sync>,
        maximize: Arc<dyn Fn() + Send + Sync>,
    ) {
        self.close_fn = Some(close);
        self.drag_fn = Some(drag);
        self.minimize_fn = Some(minimize);
        self.maximize_fn = Some(maximize);
    }

    /// Close THIS window. Safe to call from any click handler.
    pub fn close(&self) {
        if let Some(ref f) = self.close_fn {
            f();
        }
    }

    /// Start dragging THIS window (for custom title bars).
    pub fn drag(&self) {
        if let Some(ref f) = self.drag_fn {
            f();
        }
    }

    /// Minimize THIS window.
    pub fn minimize(&self) {
        if let Some(ref f) = self.minimize_fn {
            f();
        }
    }

    /// Maximize/restore THIS window.
    pub fn maximize(&self) {
        if let Some(ref f) = self.maximize_fn {
            f();
        }
    }

    /// Get a cloneable close callback for THIS window.
    /// Use this to capture the close action in event handler closures.
    pub fn close_callback(&self) -> Arc<dyn Fn() + Send + Sync> {
        self.close_fn.clone().unwrap_or_else(|| Arc::new(|| {}))
    }

    /// Get a cloneable drag callback for THIS window.
    pub fn drag_callback(&self) -> Arc<dyn Fn() + Send + Sync> {
        self.drag_fn.clone().unwrap_or_else(|| Arc::new(|| {}))
    }

    /// Get a cloneable minimize callback for THIS window.
    pub fn minimize_callback(&self) -> Arc<dyn Fn() + Send + Sync> {
        self.minimize_fn.clone().unwrap_or_else(|| Arc::new(|| {}))
    }

    /// Get a cloneable maximize callback for THIS window.
    pub fn maximize_callback(&self) -> Arc<dyn Fn() + Send + Sync> {
        self.maximize_fn.clone().unwrap_or_else(|| Arc::new(|| {}))
    }

    /// Register a callback to run once after the UI is ready
    ///
    /// The callback will be executed after the first UI rebuild completes,
    /// when motion bindings have been registered with the renderer.
    /// This is the recommended way to trigger initial animations.
    ///
    /// Callbacks are executed once and then discarded. If `is_ready()` is
    /// already true, the callback will run on the next frame.
    ///
    /// # Example
    ///
    /// ```ignore
    /// fn my_component(ctx: &WindowedContext) -> impl ElementBuilder {
    ///     let progress = ctx.use_animated_value_for("progress", 0.0, SpringConfig::gentle());
    ///
    ///     // Register animation to trigger when UI is ready
    ///     let progress_clone = progress.clone();
    ///     ctx.on_ready(move || {
    ///         if let Ok(mut value) = progress_clone.lock() {
    ///             value.set_target(100.0);
    ///         }
    ///     });
    ///
    ///     // ... build UI ...
    /// }
    /// ```
    /// Register a callback to run once when the UI is ready (context-level).
    ///
    /// **Note:** For element-specific callbacks, prefer using the query API:
    /// ```ignore
    /// ctx.query_element("my-element").on_ready(|bounds| {
    ///     // Triggered once after element is laid out
    /// });
    /// ```
    /// The query-based approach uses stable string IDs that survive tree rebuilds.
    ///
    /// This context-level callback runs after the first rebuild completes.
    /// If called after the UI is already ready, executes immediately.
    pub fn on_ready<F>(&self, callback: F)
    where
        F: FnOnce() + Send + Sync + 'static,
    {
        // If already ready, execute immediately
        if self.rebuild_count > 0 {
            callback();
            return;
        }
        // Otherwise queue for execution after first rebuild
        if let Ok(mut callbacks) = self.ready_callbacks.lock() {
            callbacks.push(Box::new(callback));
        }
    }

    // =========================================================================
    // Reactive Signal API
    // =========================================================================

    /// Create a persistent state value that survives across UI rebuilds (keyed)
    ///
    /// This creates component-level state identified by a unique string key.
    /// Returns a `State<T>` with direct `.get()` and `.set()` methods.
    ///
    /// For stateful UI elements with `StateTransitions`, prefer `use_state(initial)`
    /// which auto-keys by source location.
    ///
    /// # Example
    ///
    /// ```ignore
    /// fn my_button(ctx: &WindowedContext, id: &str) -> impl ElementBuilder {
    ///     // Each button gets its own hover state, keyed by id
    ///     let hovered = ctx.use_state_keyed(id, || false);
    ///
    ///     div()
    ///         .bg(if hovered.get() { Color::RED } else { Color::BLUE })
    ///         .on_hover_enter({
    ///             let hovered = hovered.clone();
    ///             move |_| hovered.set(true)
    ///         })
    ///         .on_hover_leave({
    ///             let hovered = hovered.clone();
    ///             move |_| hovered.set(false)
    ///         })
    /// }
    /// ```
    pub fn use_state_keyed<T, F>(&self, key: &str, init: F) -> State<T>
    where
        T: Clone + Send + 'static,
        F: FnOnce() -> T,
    {
        use blinc_core::reactive::SignalId;

        let state_key = StateKey::from_string::<T>(key);
        let mut hooks = self.hooks.lock().unwrap();

        // Check if we have an existing signal with this key
        let signal = if let Some(raw_id) = hooks.get(&state_key) {
            // Reconstruct the signal from stored ID
            let signal_id = SignalId::from_raw(raw_id);
            Signal::from_id(signal_id)
        } else {
            // First time - create a new signal and store it
            let signal = self.reactive.lock().unwrap().create_signal(init());
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            signal
        };

        // Create callback for stateful deps notification
        let callback: StatefulDepsCallback = Arc::new(|signal_ids| {
            blinc_layout::check_stateful_deps(signal_ids);
        });

        State::with_stateful_callback(
            signal,
            Arc::clone(&self.reactive),
            Arc::clone(&self.ref_dirty_flag),
            callback,
        )
    }

    /// Create a persistent signal that survives across UI rebuilds (keyed)
    ///
    /// Unlike `use_signal()` which creates a new signal each call, this method
    /// persists the signal using a unique string key. Use this for simple
    /// reactive values that need to survive rebuilds.
    ///
    /// For FSM-based state with `StateTransitions`, use `use_state_keyed()` instead.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let current_index = ctx.use_signal_keyed("current_index", || 0usize);
    ///
    /// // Read the value
    /// let index = ctx.get(current_index).unwrap_or(0);
    ///
    /// // Set the value (in an event handler)
    /// ctx.set(current_index, 1);
    /// ```
    pub fn use_signal_keyed<T, F>(&self, key: &str, init: F) -> Signal<T>
    where
        T: Clone + Send + 'static,
        F: FnOnce() -> T,
    {
        use blinc_core::reactive::SignalId;

        let state_key = StateKey::from_string::<T>(key);
        let mut hooks = self.hooks.lock().unwrap();

        // Check if we have an existing signal with this key
        if let Some(raw_id) = hooks.get(&state_key) {
            // Reconstruct the signal from stored ID
            let signal_id = SignalId::from_raw(raw_id);
            Signal::from_id(signal_id)
        } else {
            // First time - create a new signal and store it
            let signal = self.reactive.lock().unwrap().create_signal(init());
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            signal
        }
    }

    /// Create a persistent ScrollRef for programmatic scroll control
    ///
    /// This creates a ScrollRef that survives across UI rebuilds. Use `.bind()`
    /// on a scroll widget to connect it, then call methods like `.scroll_to()`
    /// to programmatically control scrolling.
    ///
    /// # Example
    ///
    /// ```ignore
    /// fn build_ui(ctx: &WindowedContext) -> impl ElementBuilder {
    ///     let scroll_ref = ctx.use_scroll_ref("my_scroll");
    ///
    ///     div()
    ///         .child(
    ///             scroll()
    ///                 .bind(&scroll_ref)
    ///                 .child(items.iter().map(|i| div().id(format!("item-{}", i.id))))
    ///         )
    ///         .child(
    ///             button("Scroll to item 5").on_click({
    ///                 let scroll_ref = scroll_ref.clone();
    ///                 move |_| scroll_ref.scroll_to("item-5")
    ///             })
    ///         )
    /// }
    /// ```
    pub fn use_scroll_ref(&self, key: &str) -> blinc_layout::selector::ScrollRef {
        use blinc_core::reactive::SignalId;
        use blinc_layout::selector::{ScrollRef, SharedScrollRefInner, TriggerCallback};

        // Create a unique key for the scroll ref's inner state
        let state_key =
            StateKey::from_string::<SharedScrollRefInner>(&format!("scroll_ref:{}", key));
        let mut hooks = self.hooks.lock().unwrap();

        // Check if we have an existing signal with this key
        let (signal_id, inner) = if let Some(raw_id) = hooks.get(&state_key) {
            // Reconstruct the signal ID and get the inner state from the reactive graph
            let signal_id = SignalId::from_raw(raw_id);
            let inner = self
                .reactive
                .lock()
                .unwrap()
                .get_untracked(Signal::<SharedScrollRefInner>::from_id(signal_id))
                .unwrap_or_else(ScrollRef::new_inner);
            (signal_id, inner)
        } else {
            // First time - create a new inner state and store it in the reactive graph
            let new_inner = ScrollRef::new_inner();
            let signal = self
                .reactive
                .lock()
                .unwrap()
                .create_signal(Arc::clone(&new_inner));
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            (signal.id(), new_inner)
        };

        drop(hooks);

        // ScrollRef doesn't need to trigger rebuilds - scroll operations are processed
        // every frame by process_pending_scroll_refs()
        let noop_trigger: TriggerCallback = Arc::new(|| {});

        ScrollRef::with_inner(inner, signal_id, noop_trigger)
    }

    /// Create a new reactive signal with an initial value (low-level API)
    ///
    /// **Note**: Prefer `use_state` in most cases, as it automatically
    /// persists signals across rebuilds.
    ///
    /// This method always creates a new signal. Use this for advanced
    /// cases where you manage signal lifecycle manually.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = ctx.use_signal(0);
    ///
    /// // In an event handler:
    /// ctx.set(count, ctx.get(count).unwrap_or(0) + 1);
    /// ```
    pub fn use_signal<T: Send + 'static>(&self, initial: T) -> Signal<T> {
        self.reactive.lock().unwrap().create_signal(initial)
    }

    /// Get the current value of a signal
    ///
    /// This automatically tracks the signal as a dependency when called
    /// within a derived computation or effect.
    pub fn get<T: Clone + 'static>(&self, signal: Signal<T>) -> Option<T> {
        self.reactive.lock().unwrap().get(signal)
    }

    /// Set the value of a signal, triggering reactive updates
    ///
    /// This will automatically trigger a UI rebuild.
    pub fn set<T: Send + 'static>(&self, signal: Signal<T>, value: T) {
        self.reactive.lock().unwrap().set(signal, value);
        // Mark dirty to trigger rebuild
        self.ref_dirty_flag.store(true, Ordering::SeqCst);
    }

    /// Update a signal using a function
    ///
    /// This is useful for incrementing counters or modifying state based
    /// on the current value.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.update(count, |n| n + 1);
    /// ```
    pub fn update<T: Clone + Send + 'static, F: FnOnce(T) -> T>(&self, signal: Signal<T>, f: F) {
        self.reactive.lock().unwrap().update(signal, f);
        self.ref_dirty_flag.store(true, Ordering::SeqCst);
    }

    /// Create a derived (computed) value
    ///
    /// Derived values are lazily computed and cached. They automatically
    /// track their signal dependencies and recompute when those signals change.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = ctx.use_signal(5);
    /// let doubled = ctx.use_derived(move |cx| cx.get(count).unwrap_or(0) * 2);
    ///
    /// assert_eq!(ctx.get_derived(doubled), Some(10));
    /// ```
    pub fn use_derived<T, F>(&self, compute: F) -> Derived<T>
    where
        T: Clone + Send + 'static,
        F: Fn(&ReactiveGraph) -> T + Send + 'static,
    {
        self.reactive.lock().unwrap().create_derived(compute)
    }

    /// Get the value of a derived computation
    pub fn get_derived<T: Clone + 'static>(&self, derived: Derived<T>) -> Option<T> {
        self.reactive.lock().unwrap().get_derived(derived)
    }

    /// Create an effect that runs when its dependencies change
    ///
    /// Effects are useful for side effects like logging, network requests,
    /// or syncing state with external systems.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = ctx.use_signal(0);
    ///
    /// ctx.use_effect(move |cx| {
    ///     let value = cx.get(count).unwrap_or(0);
    ///     println!("Count changed to: {}", value);
    /// });
    /// ```
    pub fn use_effect<F>(&self, run: F) -> blinc_core::reactive::Effect
    where
        F: FnMut(&ReactiveGraph) + Send + 'static,
    {
        self.reactive.lock().unwrap().create_effect(run)
    }

    /// Batch multiple signal updates into a single reactive update
    ///
    /// This is useful when updating multiple signals at once to avoid
    /// redundant recomputations.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.batch(|g| {
    ///     g.set(x, 10);
    ///     g.set(y, 20);
    ///     g.set(z, 30);
    /// });
    /// // Only one UI rebuild triggered
    /// ```
    pub fn batch<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut ReactiveGraph) -> R,
    {
        let result = self.reactive.lock().unwrap().batch(f);
        self.ref_dirty_flag.store(true, Ordering::SeqCst);
        result
    }

    /// Get the shared reactive graph for advanced usage
    ///
    /// This is useful when you need to pass the graph to closures or
    /// store it for later use.
    pub fn reactive(&self) -> SharedReactiveGraph {
        Arc::clone(&self.reactive)
    }

    /// Create a new DivRef that will trigger rebuilds when modified
    ///
    /// Use this to create refs that can be mutated in event handlers.
    /// When you call `.borrow_mut()` or `.with_mut()` on the returned ref,
    /// the UI will automatically rebuild when the mutation completes.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let card_ref = ctx.create_ref::<Div>();
    ///
    /// div()
    ///     .child(
    ///         div()
    ///             .bind(&card_ref)
    ///             .on_hover_enter({
    ///                 let r = card_ref.clone();
    ///                 move |_| {
    ///                     // This automatically triggers a rebuild
    ///                     r.with_mut(|d| *d = d.swap().bg(Color::RED));
    ///                 }
    ///             })
    ///     )
    /// ```
    pub fn create_ref<T>(&self) -> ElementRef<T> {
        ElementRef::with_dirty_flag(Arc::clone(&self.ref_dirty_flag))
    }

    /// Create a new DivRef (convenience method)
    pub fn div_ref(&self) -> DivRef {
        self.create_ref::<Div>()
    }

    /// Get the shared dirty flag for manual state management
    ///
    /// Use this when you want to create your own state types that trigger
    /// UI rebuilds when modified. When you modify state, set this flag to true.
    ///
    /// # Example
    ///
    /// ```ignore
    /// struct MyState {
    ///     value: i32,
    ///     dirty_flag: RefDirtyFlag,
    /// }
    ///
    /// impl MyState {
    ///     fn set_value(&mut self, v: i32) {
    ///         self.value = v;
    ///         self.dirty_flag.store(true, Ordering::SeqCst);
    ///     }
    /// }
    /// ```
    pub fn dirty_flag(&self) -> RefDirtyFlag {
        Arc::clone(&self.ref_dirty_flag)
    }

    /// Get a handle to the animation scheduler for creating animated values
    ///
    /// Components use this handle to create `AnimatedValue`s that automatically
    /// register with the scheduler. The scheduler ticks all animations each frame
    /// and triggers UI rebuilds while animations are active.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_animation::{AnimatedValue, SpringConfig};
    ///
    /// let opacity = AnimatedValue::new(ctx.animations(), 1.0, SpringConfig::stiff());
    /// opacity.set_target(0.5); // Auto-registers and animates
    /// let current = opacity.get(); // Get interpolated value
    /// ```
    pub fn animation_handle(&self) -> SchedulerHandle {
        self.animations.lock().unwrap().handle()
    }

    /// Get the overlay manager for showing modals, dialogs, toasts, etc.
    ///
    /// The overlay manager provides a fluent API for creating overlays that
    /// render in a separate pass after the main UI tree, ensuring they always
    /// appear on top.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_layout::prelude::*;
    ///
    /// fn my_ui(ctx: &WindowedContext) -> impl ElementBuilder {
    ///     let overlay_mgr = ctx.overlay_manager();
    ///
    ///     div()
    ///         .child(
    ///             button("Show Modal").on_click({
    ///                 let mgr = overlay_mgr.clone();
    ///                 move |_| {
    ///                     mgr.modal()
    ///                         .content(|| {
    ///                             div().p(20.0).bg(Color::WHITE)
    ///                                 .child(text("Hello from modal!"))
    ///                         })
    ///                         .show();
    ///                 }
    ///             })
    ///         )
    /// }
    /// ```
    pub fn overlay_manager(&self) -> OverlayManager {
        Arc::clone(&self.overlay_manager)
    }

    // =========================================================================
    // Query API
    // =========================================================================

    /// Query an element by ID and get an ElementHandle for programmatic manipulation
    ///
    /// Returns an `ElementHandle` for interacting with the element. The handle
    /// provides methods like `scroll_into_view()`, `focus()`, `click()`, `on_ready()`,
    /// and tree traversal.
    ///
    /// The handle works even if the element doesn't exist yet - operations like
    /// `on_ready()` will queue until the element is laid out. Use `handle.exists()`
    /// to check if the element currently exists.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Register on_ready callback (works before element exists):
    /// ctx.query("progress-bar").on_ready(|bounds| {
    ///     progress_anim.lock().unwrap().set_target(bounds.width * 0.75);
    /// });
    ///
    /// // In UI builder:
    /// div().id("progress-bar").child(...)
    ///
    /// // Later, interact with existing element:
    /// let handle = ctx.query("my-element");
    /// if handle.exists() {
    ///     handle.scroll_into_view();
    ///     handle.focus();
    /// }
    /// ```
    pub fn query(&self, id: &str) -> blinc_layout::selector::ElementHandle<()> {
        blinc_layout::selector::ElementHandle::new(id, self.element_registry.clone())
    }

    /// Get the shared element registry
    ///
    /// This provides access to the element registry for advanced query operations.
    pub fn element_registry(&self) -> &SharedElementRegistry {
        &self.element_registry
    }

    /// Create a persistent state for stateful UI elements
    ///
    /// This creates a `SharedState<S>` that survives across UI rebuilds.
    /// State is keyed automatically by source location using `#[track_caller]`.
    ///
    /// Use with `stateful()` for the cleanest API:
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_layout::prelude::*;
    ///
    /// fn my_button(ctx: &WindowedContext) -> impl ElementBuilder {
    ///     let handle = ctx.use_state(ButtonState::Idle);
    ///
    ///     stateful(handle)
    ///         .on_state(|state, div| {
    ///             match state {
    ///                 ButtonState::Hovered => { *div = div.swap().bg(Color::RED); }
    ///                 _ => { *div = div.swap().bg(Color::BLUE); }
    ///             }
    ///         })
    /// }
    /// ```
    #[track_caller]
    pub fn use_state<S>(&self, initial: S) -> blinc_layout::SharedState<S>
    where
        S: blinc_layout::StateTransitions + Clone + Send + 'static,
    {
        // Use caller location as the key
        let location = std::panic::Location::caller();
        let key = format!(
            "{}:{}:{}",
            location.file(),
            location.line(),
            location.column()
        );
        self.use_state_for(&key, initial)
    }

    /// Create a persistent state with an explicit key
    ///
    /// Use this for reusable components that are called multiple times
    /// from the same location (e.g., in a loop or when the same component
    /// function is called multiple times with different props).
    ///
    /// The key can be any type that implements `Hash` (strings, numbers, etc).
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Reusable component - string key
    /// fn feature_card(ctx: &WindowedContext, id: &str) -> impl ElementBuilder {
    ///     let handle = ctx.use_state_for(id, ButtonState::Idle);
    ///     stateful(handle).on_state(|state, div| { ... })
    /// }
    ///
    /// // Or with numeric key in a loop
    /// for i in 0..3 {
    ///     let handle = ctx.use_state_for(i, ButtonState::Idle);
    ///     // ...
    /// }
    /// ```
    pub fn use_state_for<K, S>(&self, key: K, initial: S) -> blinc_layout::SharedState<S>
    where
        K: Hash,
        S: blinc_layout::StateTransitions + Clone + Send + 'static,
    {
        use blinc_core::reactive::SignalId;
        use blinc_layout::stateful::StatefulInner;

        // We store the SharedState<S> as a signal value
        let state_key = StateKey::new::<blinc_layout::SharedState<S>, _>(&key);
        let mut hooks = self.hooks.lock().unwrap();

        if let Some(raw_id) = hooks.get(&state_key) {
            // Existing state - get the SharedState from the signal
            let signal_id = SignalId::from_raw(raw_id);
            let signal: Signal<blinc_layout::SharedState<S>> = Signal::from_id(signal_id);
            self.reactive.lock().unwrap().get(signal).unwrap()
        } else {
            // New state - create SharedState and store in signal
            let shared_state: blinc_layout::SharedState<S> =
                Arc::new(Mutex::new(StatefulInner::new(initial)));
            let signal = self
                .reactive
                .lock()
                .unwrap()
                .create_signal(shared_state.clone());
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            shared_state
        }
    }

    /// Create a persistent animated value using caller location as key
    ///
    /// The animated value survives UI rebuilds, preserving its current value
    /// and active spring animations. This is essential for continuous animations
    /// driven by state changes.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Animated value persists across rebuilds
    /// let offset_y = ctx.use_animated_value(0.0, SpringConfig::wobbly());
    ///
    /// // Can be used in motion bindings
    /// motion().translate_y(offset_y.clone()).child(content)
    /// ```
    #[track_caller]
    pub fn use_animated_value(&self, initial: f32, config: SpringConfig) -> SharedAnimatedValue {
        let location = std::panic::Location::caller();
        let key = format!(
            "{}:{}:{}",
            location.file(),
            location.line(),
            location.column()
        );
        self.use_animated_value_for(&key, initial, config)
    }

    /// Create a persistent animated value with an explicit key
    ///
    /// Use this for reusable components or when creating multiple animated
    /// values at the same source location (e.g., in a loop).
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Multiple animated values with unique keys
    /// for i in 0..3 {
    ///     let scale = ctx.use_animated_value_for(
    ///         format!("item_{}_scale", i),
    ///         1.0,
    ///         SpringConfig::snappy(),
    ///     );
    /// }
    /// ```
    pub fn use_animated_value_for<K: Hash>(
        &self,
        key: K,
        initial: f32,
        config: SpringConfig,
    ) -> SharedAnimatedValue {
        use blinc_core::reactive::SignalId;

        // Use a type marker for SharedAnimatedValue
        let state_key = StateKey::new::<SharedAnimatedValue, _>(&key);
        let mut hooks = self.hooks.lock().unwrap();

        if let Some(raw_id) = hooks.get(&state_key) {
            // Existing animated value - retrieve from signal
            let signal_id = SignalId::from_raw(raw_id);
            let signal: Signal<SharedAnimatedValue> = Signal::from_id(signal_id);
            self.reactive.lock().unwrap().get(signal).unwrap()
        } else {
            // New animated value - create and store in signal
            let animated_value: SharedAnimatedValue = Arc::new(Mutex::new(AnimatedValue::new(
                self.animation_handle(),
                initial,
                config,
            )));
            let signal = self
                .reactive
                .lock()
                .unwrap()
                .create_signal(animated_value.clone());
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            animated_value
        }
    }

    /// Create or retrieve a persistent animated timeline
    ///
    /// AnimatedTimeline provides keyframe-based animations that persist across
    /// UI rebuilds. Use this for timeline animations that need to survive
    /// layout changes and window resizes.
    ///
    /// The returned timeline is empty on first call - add keyframes using
    /// `timeline.add()` then call `start()`. Use `has_entries()` to check
    /// if the timeline needs configuration.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let timeline = ctx.use_animated_timeline();
    /// let entry_id = {
    ///     let mut t = timeline.lock().unwrap();
    ///     if !t.has_entries() {
    ///         let id = t.add(0, 2000, 0.0, 1.0);
    ///         t.start();
    ///         id
    ///     } else {
    ///         t.entry_ids().first().copied().unwrap()
    ///     }
    /// };
    /// ```
    #[track_caller]
    pub fn use_animated_timeline(&self) -> SharedAnimatedTimeline {
        let location = std::panic::Location::caller();
        let key = format!(
            "{}:{}:{}",
            location.file(),
            location.line(),
            location.column()
        );
        self.use_animated_timeline_for(&key)
    }

    /// Create or retrieve a persistent animated timeline with an explicit key
    ///
    /// Use this for reusable components or when creating multiple timelines
    /// at the same source location (e.g., in a loop).
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Multiple timelines with unique keys
    /// for i in 0..3 {
    ///     let timeline = ctx.use_animated_timeline_for(format!("dot_{}", i));
    ///     // ...
    /// }
    /// ```
    pub fn use_animated_timeline_for<K: Hash>(&self, key: K) -> SharedAnimatedTimeline {
        use blinc_core::reactive::SignalId;

        // Use a type marker for SharedAnimatedTimeline
        let state_key = StateKey::new::<SharedAnimatedTimeline, _>(&key);
        let mut hooks = self.hooks.lock().unwrap();

        if let Some(raw_id) = hooks.get(&state_key) {
            // Existing timeline - retrieve from signal
            let signal_id = SignalId::from_raw(raw_id);
            let signal: Signal<SharedAnimatedTimeline> = Signal::from_id(signal_id);
            self.reactive.lock().unwrap().get(signal).unwrap()
        } else {
            // New timeline - create and store in signal
            let timeline: SharedAnimatedTimeline =
                Arc::new(Mutex::new(AnimatedTimeline::new(self.animation_handle())));
            let signal = self
                .reactive
                .lock()
                .unwrap()
                .create_signal(timeline.clone());
            let raw_id = signal.id().to_raw();
            hooks.insert(state_key, raw_id);
            timeline
        }
    }

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

    /// Register a callback that runs each frame in the animation scheduler
    ///
    /// This creates a persistent tick callback keyed by source location.
    /// The callback receives delta time in seconds and runs on the animation
    /// scheduler's background thread at 120fps.
    ///
    /// Use this for ECS systems, physics, or any per-frame updates.
    /// The callback is registered once and persists across UI rebuilds.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Create ECS world (persisted via use_state)
    /// let world = ctx.use_state_keyed("world", || Arc::new(Mutex::new(World::new())));
    ///
    /// // Register tick callback to run ECS systems
    /// ctx.use_tick_callback({
    ///     let world = world.get();
    ///     move |dt| {
    ///         let mut w = world.lock().unwrap();
    ///         // Run ECS systems with delta time
    ///         w.run_systems(dt);
    ///     }
    /// });
    /// ```
    #[track_caller]
    pub fn use_tick_callback<F>(&self, callback: F) -> blinc_animation::TickCallbackId
    where
        F: FnMut(f32) + Send + Sync + 'static,
    {
        let location = std::panic::Location::caller();
        let key = format!(
            "tick_{}:{}:{}",
            location.file(),
            location.line(),
            location.column()
        );
        self.use_tick_callback_for(&key, callback)
    }

    /// Register a tick callback with an explicit key
    ///
    /// Use this when you need to create multiple tick callbacks at the same
    /// source location (e.g., in a loop) or in reusable components.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Multiple tick callbacks with unique keys
    /// for i in 0..3 {
    ///     ctx.use_tick_callback_for(format!("system_{}", i), move |dt| {
    ///         // Per-frame update
    ///     });
    /// }
    /// ```
    pub fn use_tick_callback_for<K: Hash, F>(
        &self,
        key: K,
        callback: F,
    ) -> blinc_animation::TickCallbackId
    where
        F: FnMut(f32) + Send + Sync + 'static,
    {
        // Marker type for TickCallbackId storage
        struct TickCallbackMarker;

        let state_key = StateKey::new::<TickCallbackMarker, _>(&key);
        let mut hooks = self.hooks.lock().unwrap();

        if let Some(raw_id) = hooks.get(&state_key) {
            // Already registered - return existing ID
            blinc_animation::TickCallbackId::from_raw(raw_id)
        } else {
            // First time - register the callback with the scheduler
            let id = self
                .animation_handle()
                .register_tick_callback(callback)
                .expect("Animation scheduler should be alive");
            hooks.insert(state_key, id.to_raw());
            id
        }
    }

    // =========================================================================
    // Theme API
    // =========================================================================

    /// Get the current color scheme (light or dark)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let scheme = ctx.color_scheme();
    /// match scheme {
    ///     ColorScheme::Light => println!("Light mode"),
    ///     ColorScheme::Dark => println!("Dark mode"),
    /// }
    /// ```
    pub fn color_scheme(&self) -> blinc_theme::ColorScheme {
        blinc_theme::ThemeState::get().scheme()
    }

    /// Set the color scheme (triggers smooth theme transition)
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.set_color_scheme(ColorScheme::Dark);
    /// ```
    pub fn set_color_scheme(&self, scheme: blinc_theme::ColorScheme) {
        blinc_theme::ThemeState::get().set_scheme(scheme);
    }

    /// Toggle between light and dark mode
    ///
    /// # Example
    ///
    /// ```ignore
    /// button("Toggle Theme").on_click(|ctx| {
    ///     ctx.toggle_color_scheme();
    /// })
    /// ```
    pub fn toggle_color_scheme(&self) {
        blinc_theme::ThemeState::get().toggle_scheme();
    }

    /// Get a color from the current theme
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_theme::ColorToken;
    ///
    /// let primary = ctx.theme_color(ColorToken::Primary);
    /// let bg = ctx.theme_color(ColorToken::Background);
    /// ```
    pub fn theme_color(&self, token: blinc_theme::ColorToken) -> blinc_core::Color {
        blinc_theme::ThemeState::get().color(token)
    }

    /// Get spacing from the current theme
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_theme::SpacingToken;
    ///
    /// let padding = ctx.theme_spacing(SpacingToken::Space4); // 16px
    /// ```
    pub fn theme_spacing(&self, token: blinc_theme::SpacingToken) -> f32 {
        blinc_theme::ThemeState::get().spacing_value(token)
    }

    /// Get border radius from the current theme
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_theme::RadiusToken;
    ///
    /// let radius = ctx.theme_radius(RadiusToken::Lg); // 8px
    /// ```
    pub fn theme_radius(&self, token: blinc_theme::RadiusToken) -> f32 {
        blinc_theme::ThemeState::get().radius(token)
    }

    // =========================================================================
    // CSS Stylesheet API
    // =========================================================================

    /// Add inline CSS to the application stylesheet.
    ///
    /// Multiple calls cascade — later rules override earlier ones.
    /// Stylesheets are visual-only: they update render props on existing nodes
    /// and trigger redraws. They never cause tree rebuilds.
    pub fn add_css(&mut self, css: &str) {
        // Store raw CSS for reparsing on theme changes
        self.css_sources.push(css.to_string());

        // Seed parser with theme variables + any previously defined CSS variables
        let mut external_vars = blinc_theme::ThemeState::try_get()
            .map(|t| t.to_css_variable_map())
            .unwrap_or_default();
        if let Some(existing) = &self.stylesheet {
            for (k, v) in existing.variables() {
                external_vars.insert(k.clone(), v.clone());
            }
        }
        match blinc_layout::css_parser::Stylesheet::parse_with_variables(css, &external_vars) {
            Ok(sheet) => self.add_stylesheet(sheet),
            Err(e) => {
                tracing::warn!("Failed to parse CSS: {}", e);
            }
        }
    }

    /// Load and add a `.css` file to the application stylesheet.
    ///
    /// Multiple calls cascade — later rules override earlier ones.
    pub fn load_css(&mut self, path: &str) {
        match std::fs::read_to_string(path) {
            Ok(css) => self.add_css(&css),
            Err(e) => {
                tracing::warn!("Failed to load CSS file '{}': {}", path, e);
            }
        }
    }

    /// Add a pre-parsed stylesheet to the application.
    ///
    /// Multiple calls cascade — later rules override earlier ones.
    pub fn add_stylesheet(&mut self, sheet: blinc_layout::css_parser::Stylesheet) {
        match self.stylesheet.as_mut() {
            Some(existing) => {
                // Cascade: merge into existing (Arc::make_mut for COW)
                Arc::make_mut(existing).merge(sheet);
            }
            None => {
                self.stylesheet = Some(Arc::new(sheet));
            }
        }
        // Publish to global so stateful widgets (buttons, etc.) can read CSS
        // overrides during tree construction, before set_stylesheet_arc() runs
        if let Some(ref stylesheet) = self.stylesheet {
            blinc_layout::css_parser::set_active_stylesheet(std::sync::Arc::clone(stylesheet));
        }
    }

    /// Reparse all stored CSS sources with fresh theme variables.
    ///
    /// Called automatically when the theme color scheme changes to ensure
    /// CSS `var()` and `theme()` references resolve to the new colors.
    pub fn reparse_css(&mut self) {
        if self.css_sources.is_empty() {
            return;
        }

        tracing::debug!(
            "Reparsing {} CSS sources with updated theme variables",
            self.css_sources.len()
        );

        // Clear existing stylesheet
        self.stylesheet = None;

        // Reparse each CSS source with fresh theme variables
        for css in self.css_sources.clone() {
            let mut external_vars = blinc_theme::ThemeState::try_get()
                .map(|t| t.to_css_variable_map())
                .unwrap_or_default();
            if let Some(existing) = &self.stylesheet {
                for (k, v) in existing.variables() {
                    external_vars.insert(k.clone(), v.clone());
                }
            }
            match blinc_layout::css_parser::Stylesheet::parse_with_variables(&css, &external_vars) {
                Ok(sheet) => self.add_stylesheet(sheet),
                Err(e) => {
                    tracing::warn!("Failed to reparse CSS on theme change: {}", e);
                }
            }
        }
    }

    /// Set a style for an element by ID.
    ///
    /// This is the Rust-native alternative to `add_css()`. Use with `css!` or `style!`
    /// macros to define styles in Rust syntax that are applied automatically to matching
    /// elements — just like CSS stylesheets.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ctx.set_style("card", css! {
    ///     background: Color::BLUE;
    ///     border-radius: 12.0;
    ///     box-shadow: md;
    /// });
    ///
    /// // Then just give the element an ID:
    /// div().id("card").w(200.0).h(100.0)
    /// ```
    pub fn set_style(&mut self, id: &str, style: blinc_layout::element_style::ElementStyle) {
        match self.stylesheet.as_mut() {
            Some(existing) => {
                Arc::make_mut(existing).insert(id, style);
            }
            None => {
                let mut sheet = blinc_layout::css_parser::Stylesheet::new();
                sheet.insert(id, style);
                self.stylesheet = Some(Arc::new(sheet));
            }
        }
    }

    /// Set a state-specific style for an element by ID.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use blinc_layout::css_parser::ElementState;
    ///
    /// ctx.set_style("button", style! { bg: Color::BLUE, rounded: 8.0 });
    /// ctx.set_state_style("button", ElementState::Hover, style! {
    ///     bg: Color::from_hex(0x2563EB),
    ///     shadow_md,
    /// });
    /// ```
    pub fn set_state_style(
        &mut self,
        id: &str,
        state: blinc_layout::css_parser::ElementState,
        style: blinc_layout::element_style::ElementStyle,
    ) {
        match self.stylesheet.as_mut() {
            Some(existing) => {
                Arc::make_mut(existing).insert_with_state(id, state, style);
            }
            None => {
                let mut sheet = blinc_layout::css_parser::Stylesheet::new();
                sheet.insert_with_state(id, state, style);
                self.stylesheet = Some(Arc::new(sheet));
            }
        }
    }
}

// =============================================================================
// BlincContext Implementation
// =============================================================================

impl blinc_core::BlincContext for WindowedContext {
    fn use_state_keyed<T, F>(&self, key: &str, init: F) -> State<T>
    where
        T: Clone + Send + 'static,
        F: FnOnce() -> T,
    {
        // Delegate to the existing method
        WindowedContext::use_state_keyed(self, key, init)
    }

    fn use_signal_keyed<T, F>(&self, key: &str, init: F) -> Signal<T>
    where
        T: Clone + Send + 'static,
        F: FnOnce() -> T,
    {
        WindowedContext::use_signal_keyed(self, key, init)
    }

    fn use_signal<T: Send + 'static>(&self, initial: T) -> Signal<T> {
        WindowedContext::use_signal(self, initial)
    }

    fn get<T: Clone + 'static>(&self, signal: Signal<T>) -> Option<T> {
        WindowedContext::get(self, signal)
    }

    fn set<T: Send + 'static>(&self, signal: Signal<T>, value: T) {
        WindowedContext::set(self, signal, value)
    }

    fn update<T: Clone + Send + 'static, F: FnOnce(T) -> T>(&self, signal: Signal<T>, f: F) {
        WindowedContext::update(self, signal, f)
    }

    fn use_derived<T, F>(&self, compute: F) -> Derived<T>
    where
        T: Clone + Send + 'static,
        F: Fn(&ReactiveGraph) -> T + Send + 'static,
    {
        WindowedContext::use_derived(self, compute)
    }

    fn get_derived<T: Clone + 'static>(&self, derived: Derived<T>) -> Option<T> {
        WindowedContext::get_derived(self, derived)
    }

    fn batch<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut ReactiveGraph) -> R,
    {
        WindowedContext::batch(self, f)
    }

    fn dirty_flag(&self) -> blinc_core::DirtyFlag {
        WindowedContext::dirty_flag(self)
    }

    fn request_rebuild(&self) {
        self.ref_dirty_flag.store(true, Ordering::SeqCst);
    }

    fn width(&self) -> f32 {
        self.width
    }

    fn height(&self) -> f32 {
        self.height
    }

    fn scale_factor(&self) -> f64 {
        self.scale_factor
    }
}

// =============================================================================
// AnimationContext Implementation
// =============================================================================

impl AnimationContext for WindowedContext {
    fn animation_handle(&self) -> SchedulerHandle {
        WindowedContext::animation_handle(self)
    }

    fn use_animated_value_for<K: Hash>(
        &self,
        key: K,
        initial: f32,
        config: SpringConfig,
    ) -> SharedAnimatedValue {
        WindowedContext::use_animated_value_for(self, key, initial, config)
    }

    fn use_animated_timeline_for<K: Hash>(&self, key: K) -> SharedAnimatedTimeline {
        WindowedContext::use_animated_timeline_for(self, key)
    }
}

/// Windowed application runner
///
/// Provides a simple way to run a Blinc application in a window
/// with automatic event handling and rendering.
pub struct WindowedApp;

impl WindowedApp {
    /// Initialize the platform asset loader
    ///
    /// On desktop, this sets up a filesystem-based loader.
    /// On Android, this would use the NDK AssetManager.
    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    fn init_asset_loader() {
        use blinc_platform::assets::{set_global_asset_loader, FilesystemAssetLoader};

        // Create a filesystem loader (uses current directory as base)
        let loader = FilesystemAssetLoader::new();

        // Try to set the global loader (ignore error if already set)
        let _ = set_global_asset_loader(Box::new(loader));
    }

    /// Initialize the theme system with platform detection
    ///
    /// This sets up the global ThemeState with:
    /// - Platform-appropriate theme bundle (macOS, Windows, Linux, etc.)
    /// - System color scheme detection (light/dark mode)
    /// - Redraw callback to trigger UI updates on theme changes
    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    fn init_theme() {
        use blinc_theme::{
            detect_system_color_scheme, platform_theme_bundle, set_redraw_callback, ThemeState,
        };

        // Only initialize if not already initialized
        if ThemeState::try_get().is_none() {
            let bundle = platform_theme_bundle();
            let scheme = detect_system_color_scheme();
            ThemeState::init(bundle, scheme);
        }

        // Set up the redraw callback to trigger full UI rebuilds when theme changes
        // We use request_full_rebuild() to trigger all three phases:
        // 1. Tree rebuild - reconstruct UI with new theme values
        // 2. Layout recompute - recalculate flexbox layout
        // 3. Visual redraw - render the frame
        set_redraw_callback(|| {
            tracing::debug!("Theme changed - requesting full rebuild + CSS reparse");
            blinc_layout::widgets::request_css_reparse();
            blinc_layout::widgets::request_full_rebuild();
        });
    }

    /// Run a windowed Blinc application on desktop platforms
    ///
    /// This is the main entry point for desktop applications. It creates
    /// a window, sets up GPU rendering, and runs the event loop.
    ///
    /// # Arguments
    ///
    /// * `config` - Window configuration (title, size, etc.)
    /// * `ui_builder` - Function that builds the UI tree given the window context
    ///
    /// # Example
    ///
    /// ```ignore
    /// WindowedApp::run(WindowConfig::default(), |ctx| {
    ///     div()
    ///         .w(ctx.width).h(ctx.height)
    ///         .bg([0.1, 0.1, 0.15, 1.0])
    ///         .flex_center()
    ///         .child(
    ///             div().glass().rounded(16.0).p(24.0)
    ///                 .child(text("Hello Blinc!").size(32.0))
    ///         )
    /// })
    /// ```
    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    pub fn run<F, E>(config: WindowConfig, ui_builder: F) -> Result<()>
    where
        F: FnMut(&mut WindowedContext) -> E + 'static,
        E: ElementBuilder + 'static,
    {
        Self::run_desktop(config, ui_builder)
    }

    /// Create per-window action closures (close, drag, minimize, maximize).
    /// Returns (close, drag, minimize, maximize) Arcs.
    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    #[allow(clippy::type_complexity)]
    fn make_window_actions(
        win: std::sync::Arc<winit::window::Window>,
        wake: blinc_platform_desktop::WakeProxy,
    ) -> (
        Arc<dyn Fn() + Send + Sync>,
        Arc<dyn Fn() + Send + Sync>,
        Arc<dyn Fn() + Send + Sync>,
        Arc<dyn Fn() + Send + Sync>,
    ) {
        let d = Arc::downgrade(&win);
        let mi = Arc::downgrade(&win);
        let ma = Arc::downgrade(&win);
        let cl = Arc::downgrade(&win);
        let wake_for_close = wake;
        (
            Arc::new(move || {
                if let Some(w) = cl.upgrade() {
                    use std::hash::{Hash, Hasher};
                    let mut hasher = std::collections::hash_map::DefaultHasher::new();
                    w.id().hash(&mut hasher);
                    wake_for_close.close_window(blinc_platform::WindowId(hasher.finish()));
                }
            }),
            Arc::new(move || {
                if let Some(w) = d.upgrade() {
                    let _ = w.drag_window();
                }
            }),
            Arc::new(move || {
                if let Some(w) = mi.upgrade() {
                    w.set_minimized(true);
                }
            }),
            Arc::new(move || {
                if let Some(w) = ma.upgrade() {
                    w.set_maximized(!w.is_maximized());
                }
            }),
        )
    }

    /// Register global window action callbacks (for drag_region() on Div).
    /// Called for both primary and secondary windows, and on focus changes.
    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    fn register_window_actions_static(
        win: std::sync::Arc<winit::window::Window>,
        wake: blinc_platform_desktop::WakeProxy,
    ) {
        let d = win.clone();
        let mi = win.clone();
        let ma = win.clone();
        let cl = win;
        blinc_layout::window_actions::set_active_window_actions(
            move || {
                let _ = d.drag_window();
            },
            move || mi.set_minimized(true),
            move || ma.set_maximized(!ma.is_maximized()),
            move || {
                use std::hash::{Hash, Hasher};
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                cl.id().hash(&mut hasher);
                wake.close_window(blinc_platform::WindowId(hasher.finish()));
            },
        );
    }

    #[cfg(all(feature = "windowed", not(target_os = "android")))]
    fn run_desktop<F, E>(config: WindowConfig, mut ui_builder: F) -> Result<()>
    where
        F: FnMut(&mut WindowedContext) -> E + 'static,
        E: ElementBuilder + 'static,
    {
        // Initialize the platform asset loader for cross-platform asset loading
        Self::init_asset_loader();

        // Initialize the text measurer for accurate text layout
        crate::text_measurer::init_text_measurer();

        // Initialize the theme system with platform detection
        Self::init_theme();

        let platform = DesktopPlatform::new().map_err(|e| BlincError::Platform(e.to_string()))?;
        let event_loop = platform
            .create_event_loop_with_config(config)
            .map_err(|e| BlincError::Platform(e.to_string()))?;

        // Get a wake proxy to allow the animation thread to wake up the event loop
        let wake_proxy = event_loop.wake_proxy();
        // Clone for the open_window callback
        let wake_proxy_for_windows = event_loop.wake_proxy();

        // Shared dirty flag for element refs
        let ref_dirty_flag: RefDirtyFlag = Arc::new(AtomicBool::new(false));
        // Shared reactive graph for signal-based state management
        let reactive: SharedReactiveGraph = Arc::new(Mutex::new(ReactiveGraph::new()));
        // Shared hook state for use_state persistence
        let hooks: SharedHookState = Arc::new(Mutex::new(HookState::new()));

        // Initialize global context state singleton (if not already initialized)
        // This allows components to create internal state without context parameters
        if !BlincContextState::is_initialized() {
            #[allow(clippy::type_complexity)]
            let stateful_callback: std::sync::Arc<dyn Fn(&[SignalId]) + Send + Sync> =
                Arc::new(|signal_ids| {
                    blinc_layout::check_stateful_deps(signal_ids);
                });
            BlincContextState::init_with_callback(
                Arc::clone(&reactive),
                Arc::clone(&hooks),
                Arc::clone(&ref_dirty_flag),
                stateful_callback,
            );
        }

        // Shared animation scheduler for spring/keyframe animations
        // Runs on background thread so animations continue even when window loses focus
        let mut scheduler = AnimationScheduler::new();
        // Set up wake callback so animation thread can wake the event loop
        scheduler.set_wake_callback(move || wake_proxy.wake());
        scheduler.start_background();
        let animations: SharedAnimationScheduler = Arc::new(Mutex::new(scheduler));

        // Set global scheduler handle for StateContext and component access
        {
            let scheduler_handle = animations.lock().unwrap().handle();
            blinc_animation::set_global_scheduler(scheduler_handle);
        }

        // Shared CSS animation/transition store
        // The scheduler's background thread keeps the redraw loop alive at 120fps
        // via the tick callback below (acts as keep-alive signal). Actual ticking
        // happens synchronously on the main thread to avoid phase jitter between
        // the bg thread's tick timing and the frame's render timing.
        let css_anim_store = Arc::new(Mutex::new(blinc_layout::CssAnimationStore::new()));
        {
            animations
                .lock()
                .unwrap()
                .add_tick_callback(move |_dt_secs| {
                    // Keep-alive no-op: the callback's existence ensures the scheduler
                    // considers tick_callbacks as "active", triggering wake_callback()
                    // at 120fps so the main thread gets continuous frame requests
                    // while CSS animations are running.
                    // Actual ticking happens on the main thread to avoid phase jitter.
                });
        }

        // Shared element registry for query API
        let element_registry: SharedElementRegistry =
            Arc::new(blinc_layout::selector::ElementRegistry::new());

        // Set up query callback in BlincContextState so components can query elements globally
        {
            let registry_for_query = Arc::clone(&element_registry);
            let query_callback: blinc_core::QueryCallback = Arc::new(move |id: &str| {
                registry_for_query.get(id).map(|node_id| node_id.to_raw())
            });
            BlincContextState::get().set_query_callback(query_callback);
        }

        // Set up bounds callback for ElementHandle.bounds()
        {
            let registry_for_bounds = Arc::clone(&element_registry);
            let bounds_callback: blinc_core::BoundsCallback =
                Arc::new(move |id: &str| registry_for_bounds.get_bounds(id));
            BlincContextState::get().set_bounds_callback(bounds_callback);
        }

        // Store element registry in BlincContextState for global query() function
        // Cast to Arc<dyn Any + Send + Sync> for type-erased storage
        BlincContextState::get()
            .set_element_registry(Arc::clone(&element_registry) as blinc_core::AnyElementRegistry);

        // Shared storage for on_ready callbacks
        let ready_callbacks: SharedReadyCallbacks = Arc::new(Mutex::new(Vec::new()));

        // Set up continuous redraw callback for text widget cursor animation
        // This bridges text widgets (which track focus) with the animation scheduler (which drives redraws)
        {
            let animations_for_callback = Arc::clone(&animations);
            blinc_layout::widgets::set_continuous_redraw_callback(move |enabled| {
                if let Ok(scheduler) = animations_for_callback.lock() {
                    scheduler.set_continuous_redraw(enabled);
                }
            });
        }

        // Connect theme animation to the animation scheduler
        // This enables smooth color transitions when switching between light/dark mode
        blinc_theme::ThemeState::get().set_scheduler(&animations);

        // Render state: dynamic properties that update every frame without tree rebuild
        // This includes cursor blink, animated colors, hover states, etc.
        let mut render_state: Option<blinc_layout::RenderState> = None;

        // Shared motion states for query API access
        // This allows components to query motion animation state via query_motion()
        let shared_motion_states = blinc_layout::create_shared_motion_states();

        // Set up motion state callback in BlincContextState
        {
            let motion_states_for_callback = Arc::clone(&shared_motion_states);
            let motion_callback: blinc_core::MotionStateCallback = Arc::new(move |key: &str| {
                motion_states_for_callback
                    .read()
                    .ok()
                    .and_then(|states| states.get(key).copied())
                    .unwrap_or(blinc_core::MotionAnimationState::NotFound)
            });
            BlincContextState::get().set_motion_state_callback(motion_callback);
        }

        // Overlay manager for modals, dialogs, toasts, etc.
        let overlays: OverlayManager = overlay_manager();

        // Initialize overlay context singleton for component access
        if !OverlayContext::is_initialized() {
            OverlayContext::init(Arc::clone(&overlays));
        }

        // Primary window state
        let mut ws = WindowState::new(
            Arc::clone(&css_anim_store),
            Arc::clone(&shared_motion_states),
        );
        // Track primary window ID once known
        let mut primary_wid: Option<blinc_platform::WindowId> = None;
        // Secondary windows (opened via ctx.open_window())
        let mut secondary_windows: std::collections::HashMap<
            blinc_platform::WindowId,
            WindowState,
        > = std::collections::HashMap::new();
        // UI builders for secondary windows (queued via open_window)
        // For now secondary windows get a blank UI — full UI builder support is future work

        event_loop
            .run(move |event, window| {
                // Check if this event is for a secondary window
                let event_wid = match &event {
                    Event::Window(wid, _) | Event::Input(wid, _) | Event::Frame(wid) => Some(*wid),
                    _ => None,
                };
                let is_secondary = event_wid
                    .map(|wid| primary_wid.is_some_and(|p| wid != p))
                    .unwrap_or(false);

                // Handle secondary window events
                if is_secondary {
                    let wid = event_wid.unwrap();
                    match event {
                        Event::Window(_, WindowEvent::Resized { width, height }) => {
                            if let Some(sws) = secondary_windows.get_mut(&wid) {
                                if let (Some(ref surf), Some(ref mut config)) =
                                    (&sws.surface, &mut sws.surface_config)
                                {
                                    if width > 0 && height > 0 {
                                        config.width = width;
                                        config.height = height;
                                        if let Some(ref blinc_app) = ws.app {
                                            surf.configure(blinc_app.device(), config);
                                        }
                                        sws.needs_rebuild = true;
                                        if let Some(ref mut ctx) = sws.ctx {
                                            let sf = window.scale_factor();
                                            ctx.width = width as f32 / sf as f32;
                                            ctx.height = height as f32 / sf as f32;
                                            ctx.physical_width = width as f32;
                                            ctx.physical_height = height as f32;
                                            ctx.scale_factor = sf;
                                        }
                                    }
                                }
                            }
                        }
                        Event::Window(_, WindowEvent::CloseRequested) => {
                            secondary_windows.remove(&wid);
                            tracing::info!("Secondary window closed (wid={:?})", wid);
                        }
                        Event::Window(_, WindowEvent::Focused(_focused)) => {}
                        Event::Input(_, ref input_event) => {

                            if let Some(sws) = secondary_windows.get_mut(&wid) {
                                if let (Some(ref mut ctx), Some(ref mut tree)) =
                                    (&mut sws.ctx, &mut sws.render_tree)
                                {
                                    let sf = ctx.scale_factor as f32;

                                    // Collect events from the router
                                    let mut pending: Vec<(blinc_layout::tree::LayoutNodeId, u32)> =
                                        Vec::new();
                                    ctx.event_router.set_event_callback({
                                        let events =
                                            &mut pending as *mut Vec<(blinc_layout::tree::LayoutNodeId, u32)>;
                                        move |node, event_type| unsafe {
                                            (*events).push((node, event_type));
                                        }
                                    });

                                    let convert_button =
                                        |b: &blinc_platform::MouseButton| match b {
                                            blinc_platform::MouseButton::Left => {
                                                blinc_layout::prelude::MouseButton::Left
                                            }
                                            blinc_platform::MouseButton::Right => {
                                                blinc_layout::prelude::MouseButton::Right
                                            }
                                            blinc_platform::MouseButton::Middle => {
                                                blinc_layout::prelude::MouseButton::Middle
                                            }
                                            _ => blinc_layout::prelude::MouseButton::Left,
                                        };

                                    match input_event {
                                        InputEvent::Mouse(MouseEvent::Moved { x, y }) => {
                                            ctx.event_router
                                                .on_mouse_move(tree, *x / sf, *y / sf);
                                        }
                                        InputEvent::Mouse(MouseEvent::ButtonPressed {
                                            button,
                                            x,
                                            y,
                                        }) => {
                                            // Mark this event as mouse (not
                                            // touch) input so editable widgets
                                            // restore desktop semantics
                                            // (drag = extend selection). The
                                            // flag is sticky between events
                                            // and gets flipped back to true
                                            // by the touch path on
                                            // touchscreens — desktop runners
                                            // don't see touch events at all,
                                            // but a docked tablet running
                                            // the desktop runner could mix
                                            // both, so we set this on every
                                            // mouse press to be safe.
                                            blinc_layout::widgets::text_input::set_touch_input(false);
                                            ctx.event_router.on_mouse_down(
                                                tree,
                                                *x / sf,
                                                *y / sf,
                                                convert_button(button),
                                            );
                                        }
                                        InputEvent::Mouse(MouseEvent::ButtonReleased {
                                            button,
                                            x,
                                            y,
                                        }) => {
                                            ctx.event_router.on_mouse_up(
                                                tree,
                                                *x / sf,
                                                *y / sf,
                                                convert_button(button),
                                            );
                                        }
                                        _ => {}
                                    }

                                    ctx.event_router.clear_event_callback();

                                    // Dispatch collected events through render tree handlers
                                    for (node_id, event_type) in &pending {
                                        tree.dispatch_event(
                                            *node_id,
                                            *event_type,
                                            ctx.event_router.mouse_position().0,
                                            ctx.event_router.mouse_position().1,
                                        );
                                    }
                                }
                            }
                        }
                        Event::Frame(_) => {
                            if let Some(sws) = secondary_windows.get_mut(&wid) {

                                if let (Some(ref mut blinc_app), Some(ref surf), Some(ref config)) =
                                    (&mut ws.app, &sws.surface, &sws.surface_config)
                                {
                                    // Build render tree on first frame or after resize
                                    if sws.render_tree.is_none() || sws.needs_rebuild {
                                        let (w, h) = sws.ctx.as_ref()
                                            .map(|c| (c.width, c.height))
                                            .unwrap_or((400.0, 300.0));

                                        let ui: Div =
                                            if let Some(ref mut builder) = sws.ui_builder {
                                                if let Some(ref mut sctx) = sws.ctx {
                                                    builder(sctx)
                                                } else {
                                                    div().w(w).h(h)
                                                }
                                            } else {
                                                let title = window.winit_window().title();
                                                div()
                                                    .w(w)
                                                    .h(h)
                                                    .bg(blinc_core::Color::rgba(
                                                        0.06, 0.06, 0.09, 1.0,
                                                    ))
                                                    .flex_col()
                                                    .justify_center()
                                                    .items_center()
                                                    .gap_px(12.0)
                                                    .child(
                                                        text(&title)
                                                            .size(24.0)
                                                            .color(blinc_core::Color::WHITE)
                                                            .bold(),
                                                    )
                                                    .child(
                                                        text(format!("{:.0} x {:.0}", w, h))
                                                            .size(14.0)
                                                            .color(blinc_core::Color::rgba(
                                                                0.5, 0.5, 0.6, 1.0,
                                                            )),
                                                    )
                                            };

                                        let sf = sws
                                            .ctx
                                            .as_ref()
                                            .map(|c| c.scale_factor as f32)
                                            .unwrap_or(1.0);
                                        let mut tree = RenderTree::from_element(&ui);
                                        tree.set_scale_factor(sf);
                                        tree.compute_layout(w, h);
                                        sws.render_tree = Some(tree);
                                        sws.needs_rebuild = false;
                                    }

                                    // Render the tree (skip if minimized / zero size)
                                    if config.width > 0 && config.height > 0 {
                                        if let (Some(ref tree), Some(ref rs)) =
                                            (&sws.render_tree, &sws.render_state)
                                        {
                                            match surf.get_current_texture() {
                                                Ok(frame) => {
                                                    let view = frame.texture.create_view(
                                                        &wgpu::TextureViewDescriptor::default(),
                                                    );
                                                    let _ = blinc_app.render_tree_with_motion(
                                                        tree,
                                                        rs,
                                                        &view,
                                                        config.width,
                                                        config.height,
                                                    );
                                                    frame.present();
                                                }
                                                Err(
                                                    wgpu::SurfaceError::Lost
                                                    | wgpu::SurfaceError::Outdated,
                                                ) => {
                                                    surf.configure(blinc_app.device(), config);
                                                }
                                                Err(_) => {}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                    return ControlFlow::Continue;
                }

                match event {
                    Event::Lifecycle(LifecycleEvent::Resumed) => {
                        let wid = window.id();
                        // Initialize GPU if not already done (primary window)
                        if ws.app.is_none() {
                            primary_wid = Some(wid);
                            let winit_window = window.winit_window_arc();

                            match BlincApp::with_window(winit_window, None) {
                                Ok((blinc_app, surf)) => {
                                    let (width, height) = window.size();
                                    // Use the same texture format that the renderer's pipelines use
                                    let format = blinc_app.texture_format();
                                    let config = wgpu::SurfaceConfiguration {
                                        usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                                            | wgpu::TextureUsages::COPY_SRC,
                                        format,
                                        width,
                                        height,
                                        present_mode: wgpu::PresentMode::AutoVsync,
                                        alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                                        view_formats: vec![],
                                        desired_maximum_frame_latency: 2,
                                    };
                                    surf.configure(blinc_app.device(), &config);

                                    // Update text measurer with shared font registry for accurate measurement
                                    crate::text_measurer::init_text_measurer_with_registry(
                                        blinc_app.font_registry(),
                                    );

                                    ws.surface = Some(surf);
                                    ws.surface_config = Some(config);
                                    ws.app = Some(blinc_app);

                                    // Initialize context with event router, animations, dirty flag, reactive graph, hooks, overlay manager, registry, and ready callbacks
                                    ws.ctx = Some(WindowedContext::from_window(
                                        window,
                                        EventRouter::new(),
                                        Arc::clone(&animations),
                                        Arc::clone(&ref_dirty_flag),
                                        Arc::clone(&reactive),
                                        Arc::clone(&hooks),
                                        Arc::clone(&overlays),
                                        Arc::clone(&element_registry),
                                        Arc::clone(&ready_callbacks),
                                    ));

                                    // Wire open_window callback using the event loop's wake proxy
                                    let wp_for_ctx = wake_proxy_for_windows.clone();
                                    let open_fn: Arc<dyn Fn(WindowConfig) + Send + Sync> =
                                        Arc::new(move |config| {
                                            wp_for_ctx.create_window(config);
                                        });
                                    if let Some(ref mut windowed_ctx) = ws.ctx {
                                        windowed_ctx.set_open_window_fn(Arc::clone(&open_fn));
                                        // Per-window action callbacks
                                        let win_actions = Self::make_window_actions(
                                            window.winit_window_arc(),
                                            wake_proxy_for_windows.clone(),
                                        );
                                        windowed_ctx.set_window_actions(
                                            win_actions.0,
                                            win_actions.1,
                                            win_actions.2,
                                            win_actions.3,
                                        );
                                    }
                                    // Register globally so open_window() works from anywhere
                                    let _ = OPEN_WINDOW_FN.set(open_fn);

                                    // Register global window action callbacks (for drag_region() on Div)
                                    Self::register_window_actions_static(window.winit_window_arc(), wake_proxy_for_windows.clone());

                                    // Set initial viewport size in BlincContextState
                                    if let Some(ref windowed_ctx) = ws.ctx {
                                        BlincContextState::get().set_viewport_size(windowed_ctx.width, windowed_ctx.height);
                                    }

                                    // Initialize render state with the shared animation scheduler
                                    // RenderState handles dynamic properties (cursor blink, animations)
                                    // independently from tree structure changes
                                    let mut rs = blinc_layout::RenderState::new(Arc::clone(&animations));
                                    rs.set_shared_motion_states(Arc::clone(&shared_motion_states));
                                    ws.render_state = Some(rs);

                                    tracing::debug!("Blinc windowed ws.app initialized");
                                }
                                Err(e) => {
                                    tracing::error!("Failed to initialize Blinc: {}", e);
                                    return ControlFlow::Exit;
                                }
                            }
                        } else {
                            // Resumed for a secondary window
                            let wid = window.id();
                            #[allow(clippy::map_entry)]
                            if !secondary_windows.contains_key(&wid) {
                                if let Some(ref blinc_app) = ws.app {
                                    let winit_window = window.winit_window_arc();
                                    match blinc_app.create_surface_for_window(winit_window) {
                                        Ok(surf) => {
                                            let (w, h) = window.size();
                                            let format = blinc_app.texture_format();
                                            let config = wgpu::SurfaceConfiguration {
                                                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                                                    | wgpu::TextureUsages::COPY_SRC,
                                                format,
                                                width: w,
                                                height: h,
                                                present_mode: wgpu::PresentMode::AutoVsync,
                                                alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                                                view_formats: vec![],
                                                desired_maximum_frame_latency: 2,
                                            };
                                            surf.configure(blinc_app.device(), &config);

                                            let mut sws = WindowState::new(
                                                Arc::clone(&css_anim_store),
                                                Arc::clone(&shared_motion_states),
                                            );
                                            sws.surface = Some(surf);
                                            sws.surface_config = Some(config);

                                            sws.ctx = Some(WindowedContext::from_window(
                                                window,
                                                EventRouter::new(),
                                                Arc::clone(&animations),
                                                Arc::clone(&ref_dirty_flag),
                                                Arc::clone(&reactive),
                                                Arc::clone(&hooks),
                                                Arc::clone(&overlays),
                                                Arc::clone(&element_registry),
                                                Arc::clone(&ready_callbacks),
                                            ));

                                            if let Some(ref mut ctx) = sws.ctx {
                                                let wp = wake_proxy_for_windows.clone();
                                                ctx.set_open_window_fn(Arc::new(move |c| {
                                                    wp.create_window(c);
                                                }));
                                                // Per-window actions
                                                let win_actions = Self::make_window_actions(
                                                    window.winit_window_arc(),
                                                    wake_proxy_for_windows.clone(),
                                                );
                                                ctx.set_window_actions(
                                                    win_actions.0,
                                                    win_actions.1,
                                                    win_actions.2,
                                                    win_actions.3,
                                                );
                                            }

                                            let mut rs = blinc_layout::RenderState::new(
                                                Arc::clone(&animations),
                                            );
                                            rs.set_shared_motion_states(
                                                Arc::clone(&shared_motion_states),
                                            );
                                            sws.render_state = Some(rs);

                                            // Pop the UI builder from the pending queue
                                            if let Ok(mut pending) =
                                                pending_builders().lock()
                                            {
                                                // Find matching request by config title
                                                let title =
                                                    window.winit_window().title();
                                                if let Some(idx) = pending.iter().position(|r| {
                                                    r.config.title == title
                                                }) {
                                                    let req = pending.remove(idx);
                                                    sws.ui_builder = req.builder;
                                                }
                                            }

                                            // Per-window callbacks are set via set_window_actions above.
                                            // Global window_actions is NOT set — secondary windows
                                            // use ctx.close_callback() etc. instead.

                                            secondary_windows.insert(wid, sws);
                                            tracing::info!(
                                                "Secondary window initialized (wid={:?})",
                                                wid
                                            );
                                        }
                                        Err(e) => {
                                            tracing::error!(
                                                "Failed to create surface for window: {}",
                                                e
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Event::Window(_, WindowEvent::Resized { width, height }) => {
                        if let (Some(ref blinc_app), Some(ref surf), Some(ref mut config)) =
                            (&ws.app, &ws.surface, &mut ws.surface_config)
                        {
                            if width > 0 && height > 0 {
                                config.width = width;
                                config.height = height;
                                surf.configure(blinc_app.device(), config);
                                ws.needs_rebuild = true;
                                ws.needs_relayout = true;

                                // Dispatch RESIZE event to elements (use logical dimensions)
                                if let (Some(ref mut windowed_ctx), Some(ref tree)) =
                                    (&mut ws.ctx, &ws.render_tree)
                                {
                                    let logical_width = width as f32 / windowed_ctx.scale_factor as f32;
                                    let logical_height = height as f32 / windowed_ctx.scale_factor as f32;

                                    // Update windowed context dimensions - CRITICAL for layout computation
                                    // Without this, compute_layout uses stale dimensions
                                    windowed_ctx.width = logical_width;
                                    windowed_ctx.height = logical_height;
                                    windowed_ctx.physical_width = width as f32;
                                    windowed_ctx.physical_height = height as f32;

                                    // Update viewport size in BlincContextState for ElementHandle.is_visible()
                                    BlincContextState::get().set_viewport_size(logical_width, logical_height);

                                    windowed_ctx
                                        .event_router
                                        .on_window_resize(tree, logical_width, logical_height);

                                    // Clear layout bounds storages to force fresh calculations
                                    // This prevents stale cached bounds from influencing the new layout
                                    tree.clear_layout_bounds_storages();
                                }

                                // Request redraw to trigger relayout with new dimensions
                                window.request_redraw();
                            }
                        }
                    }

                    Event::Window(_, WindowEvent::Focused(focused)) => {
                        // Update context focus state
                        if let Some(ref mut windowed_ctx) = ws.ctx {
                            windowed_ctx.focused = focused;
                            windowed_ctx.event_router.on_window_focus(focused);

                            if !focused {
                                blinc_layout::widgets::blur_all_text_inputs();
                            }
                        }
                    }

                    Event::Window(_, WindowEvent::CloseRequested) => {
                        return ControlFlow::Exit;
                    }

                    // File drop events — dispatch to drop handler and render tree
                    Event::Window(_, WindowEvent::DroppedFile { paths }) => {
                        crate::dnd::dispatch_drop_event(crate::dnd::DropEvent::Dropped(paths));
                    }
                    Event::Window(_, WindowEvent::DroppedFileHovered { paths }) => {
                        crate::dnd::dispatch_drop_event(crate::dnd::DropEvent::Hovered(paths));
                    }
                    Event::Window(_, WindowEvent::DroppedFileCancelled) => {
                        crate::dnd::dispatch_drop_event(crate::dnd::DropEvent::Cancelled);
                    }

                    // Handle input events
                    Event::Input(_, input_event) => {
                        // Pending event structure for deferred dispatch
                        #[derive(Clone)]
                        struct PendingEvent {
                            node_id: LayoutNodeId,
                            event_type: u32,
                            mouse_x: f32,
                            mouse_y: f32,
                            /// Local coordinates relative to element bounds
                            local_x: f32,
                            local_y: f32,
                            /// Absolute position of element bounds (top-left corner)
                            bounds_x: f32,
                            bounds_y: f32,
                            /// Computed bounds dimensions of the element
                            bounds_width: f32,
                            bounds_height: f32,
                            scroll_delta_x: f32,
                            scroll_delta_y: f32,
                            /// Drag delta for DRAG/DRAG_END events
                            drag_delta_x: f32,
                            drag_delta_y: f32,
                            key_char: Option<char>,
                            key_code: u32,
                            shift: bool,
                            ctrl: bool,
                            alt: bool,
                            meta: bool,
                            /// Pinch scale or rotation delta
                            pinch_scale: f32,
                        }

                        impl Default for PendingEvent {
                            fn default() -> Self {
                                Self {
                                    node_id: LayoutNodeId::default(),
                                    event_type: 0,
                                    mouse_x: 0.0,
                                    mouse_y: 0.0,
                                    local_x: 0.0,
                                    local_y: 0.0,
                                    bounds_x: 0.0,
                                    bounds_y: 0.0,
                                    bounds_width: 0.0,
                                    bounds_height: 0.0,
                                    scroll_delta_x: 0.0,
                                    scroll_delta_y: 0.0,
                                    drag_delta_x: 0.0,
                                    drag_delta_y: 0.0,
                                    key_char: None,
                                    key_code: 0,
                                    shift: false,
                                    ctrl: false,
                                    alt: false,
                                    meta: false,
                                    pinch_scale: 1.0,
                                }
                            }
                        }

                        // First phase: collect events using immutable borrow
                        let (pending_events, keyboard_events, scroll_ended, gesture_ended, scroll_info) = if let (Some(ref mut windowed_ctx), Some(ref tree)) =
                            (&mut ws.ctx, &ws.render_tree)
                        {
                            let router = &mut windowed_ctx.event_router;

                            // Collect events from router
                            let mut pending_events: Vec<PendingEvent> = Vec::new();
                            // Separate collection for keyboard events (TEXT_INPUT)
                            let mut keyboard_events: Vec<PendingEvent> = Vec::new();
                            // Track if scroll ended (momentum finished)
                            let mut scroll_ended = false;
                            // Track if gesture ended (finger lifted - may still have momentum)
                            let mut gesture_ended = false;
                            // Track scroll info for nested scroll dispatch (mouse_x, mouse_y, delta_x, delta_y)
                            let mut scroll_info: Option<(f32, f32, f32, f32)> = None;

                            // Set up callback to collect events
                            router.set_event_callback({
                                let events = &mut pending_events as *mut Vec<PendingEvent>;
                                move |node, event_type| {
                                    // SAFETY: This callback is only used within this scope
                                    unsafe {
                                        (*events).push(PendingEvent {
                                            node_id: node,
                                            event_type,
                                            ..Default::default()
                                        });
                                    }
                                }
                            });

                            // Note: Overlays are now part of the main tree, so all events
                            // are routed through the single main event router.

                            // Convert physical coordinates to logical for hit testing
                            let scale = windowed_ctx.scale_factor as f32;

                            match input_event {
                                InputEvent::Mouse(mouse_event) => match mouse_event {
                                    MouseEvent::Moved { x, y } => {
                                        // Convert physical to logical coordinates
                                        let lx = x / scale;
                                        let ly = y / scale;

                                        // Get overlay bounds and layer ID for occlusion-aware hit testing
                                        // This prevents background elements from receiving hover events
                                        // when they are visually occluded by overlay content
                                        let overlay_bounds = windowed_ctx.overlay_manager.get_visible_overlay_bounds();
                                        let overlay_layer_id = tree.query_by_id(
                                            blinc_layout::widgets::overlay::OVERLAY_LAYER_ID
                                        );

                                        // Route mouse move through main tree with overlay occlusion awareness
                                        router.on_mouse_move_with_occlusion(
                                            tree,
                                            lx,
                                            ly,
                                            &overlay_bounds,
                                            overlay_layer_id,
                                        );

                                        // Get drag delta from router (for DRAG events)
                                        let (drag_dx, drag_dy) = router.drag_delta();

                                        // Populate bounds for each event from the router's hit test results
                                        // This is needed for POINTER_ENTER/POINTER_LEAVE/POINTER_MOVE events
                                        for event in pending_events.iter_mut() {
                                            event.mouse_x = lx;
                                            event.mouse_y = ly;
                                            // Populate drag delta for DRAG events
                                            if event.event_type == blinc_core::events::event_types::DRAG
                                                || event.event_type == blinc_core::events::event_types::DRAG_END
                                            {
                                                event.drag_delta_x = drag_dx;
                                                event.drag_delta_y = drag_dy;
                                            }
                                            // Populate bounds from hit test results (stored in router)
                                            if let Some((bx, by, bw, bh)) = router.get_node_bounds(event.node_id) {
                                                event.bounds_x = bx;
                                                event.bounds_y = by;
                                                event.bounds_width = bw;
                                                event.bounds_height = bh;
                                                event.local_x = lx - bx;
                                                event.local_y = ly - by;
                                            }
                                        }

                                        // Update cursor based on hovered element
                                        let cursor = tree
                                            .get_cursor_at(router, lx, ly)
                                            .unwrap_or(CursorStyle::Default);
                                        window.set_cursor(convert_cursor_style(cursor));
                                    }
                                    MouseEvent::ButtonPressed { button, x, y } => {
                                        let lx = x / scale;
                                        let ly = y / scale;
                                        let btn = convert_mouse_button(button);
                                        windowed_ctx.pointer_query.set_pressure(1.0);

                                        // Check for backdrop clicks (dismisses overlays)
                                        // This still needs special handling because backdrop clicks should
                                        // not propagate to elements behind the overlay
                                        let overlay_dismissed = if windowed_ctx.overlay_manager.has_blocking_overlay()
                                            || windowed_ctx.overlay_manager.has_dismissable_overlay()
                                        {
                                            windowed_ctx.overlay_manager.handle_click_at(lx, ly)
                                        } else {
                                            false
                                        };

                                        // If overlay was dismissed by backdrop click, don't process further
                                        if !overlay_dismissed {
                                            // Blur any focused text inputs BEFORE processing mouse down
                                            // This mimics HTML behavior where clicking anywhere blurs inputs,
                                            // and clicking on an input then re-focuses it via its own handler
                                            blinc_layout::widgets::blur_all_text_inputs();

                                            // Route through main tree (includes overlay content)
                                            let _events = router.on_mouse_down(tree, lx, ly, btn);

                                            let (local_x, local_y) = router.last_hit_local();
                                            let (bounds_x, bounds_y) = router.last_hit_bounds_pos();
                                            let (bounds_width, bounds_height) = router.last_hit_bounds();
                                            for event in pending_events.iter_mut() {
                                                event.mouse_x = lx;
                                                event.mouse_y = ly;
                                                event.local_x = local_x;
                                                event.local_y = local_y;
                                                event.bounds_x = bounds_x;
                                                event.bounds_y = bounds_y;
                                                event.bounds_width = bounds_width;
                                                event.bounds_height = bounds_height;
                                            }
                                        }
                                    }
                                    MouseEvent::ButtonReleased { button, x, y } => {
                                        let lx = x / scale;
                                        let ly = y / scale;
                                        let btn = convert_mouse_button(button);
                                        windowed_ctx.pointer_query.set_pressure(0.0);

                                        // Route through main tree (includes overlay content)
                                        router.on_mouse_up(tree, lx, ly, btn);
                                        // Use the local coordinates from when the press started
                                        // (stored by on_mouse_down via last_hit_local)
                                        let (local_x, local_y) = router.last_hit_local();
                                        let (bounds_x, bounds_y) = router.last_hit_bounds_pos();
                                        let (bounds_width, bounds_height) = router.last_hit_bounds();
                                        for event in pending_events.iter_mut() {
                                            event.mouse_x = lx;
                                            event.mouse_y = ly;
                                            event.local_x = local_x;
                                            event.local_y = local_y;
                                            event.bounds_x = bounds_x;
                                            event.bounds_y = bounds_y;
                                            event.bounds_width = bounds_width;
                                            event.bounds_height = bounds_height;
                                        }
                                    }
                                    MouseEvent::Left => {
                                        // on_mouse_leave now emits POINTER_UP if there was a pressed target
                                        // This handles the case where mouse leaves window while dragging
                                        router.on_mouse_leave();
                                        // Reset cursor to default when mouse leaves window
                                        window.set_cursor(blinc_platform::Cursor::Default);
                                        // Events are collected via the callback set above
                                    }
                                    MouseEvent::Entered => {
                                        let (mx, my) = router.mouse_position();

                                        // Use occlusion-aware hit testing when mouse enters window
                                        let overlay_bounds = windowed_ctx.overlay_manager.get_visible_overlay_bounds();
                                        let overlay_layer_id = tree.query_by_id(
                                            blinc_layout::widgets::overlay::OVERLAY_LAYER_ID
                                        );
                                        router.on_mouse_move_with_occlusion(
                                            tree,
                                            mx,
                                            my,
                                            &overlay_bounds,
                                            overlay_layer_id,
                                        );

                                        for event in pending_events.iter_mut() {
                                            event.mouse_x = mx;
                                            event.mouse_y = my;
                                        }

                                        // Update cursor based on hovered element
                                        let cursor = tree
                                            .get_cursor_at(router, mx, my)
                                            .unwrap_or(CursorStyle::Default);
                                        window.set_cursor(convert_cursor_style(cursor));
                                    }
                                },
                                InputEvent::Keyboard(kb_event) => {
                                    let mods = &kb_event.modifiers;

                                    // Extract character from key if applicable
                                    let key_char = match &kb_event.key {
                                        Key::Char(c) => Some(*c),
                                        Key::Space => Some(' '),
                                        Key::A => Some(if mods.shift { 'A' } else { 'a' }),
                                        Key::B => Some(if mods.shift { 'B' } else { 'b' }),
                                        Key::C => Some(if mods.shift { 'C' } else { 'c' }),
                                        Key::D => Some(if mods.shift { 'D' } else { 'd' }),
                                        Key::E => Some(if mods.shift { 'E' } else { 'e' }),
                                        Key::F => Some(if mods.shift { 'F' } else { 'f' }),
                                        Key::G => Some(if mods.shift { 'G' } else { 'g' }),
                                        Key::H => Some(if mods.shift { 'H' } else { 'h' }),
                                        Key::I => Some(if mods.shift { 'I' } else { 'i' }),
                                        Key::J => Some(if mods.shift { 'J' } else { 'j' }),
                                        Key::K => Some(if mods.shift { 'K' } else { 'k' }),
                                        Key::L => Some(if mods.shift { 'L' } else { 'l' }),
                                        Key::M => Some(if mods.shift { 'M' } else { 'm' }),
                                        Key::N => Some(if mods.shift { 'N' } else { 'n' }),
                                        Key::O => Some(if mods.shift { 'O' } else { 'o' }),
                                        Key::P => Some(if mods.shift { 'P' } else { 'p' }),
                                        Key::Q => Some(if mods.shift { 'Q' } else { 'q' }),
                                        Key::R => Some(if mods.shift { 'R' } else { 'r' }),
                                        Key::S => Some(if mods.shift { 'S' } else { 's' }),
                                        Key::T => Some(if mods.shift { 'T' } else { 't' }),
                                        Key::U => Some(if mods.shift { 'U' } else { 'u' }),
                                        Key::V => Some(if mods.shift { 'V' } else { 'v' }),
                                        Key::W => Some(if mods.shift { 'W' } else { 'w' }),
                                        Key::X => Some(if mods.shift { 'X' } else { 'x' }),
                                        Key::Y => Some(if mods.shift { 'Y' } else { 'y' }),
                                        Key::Z => Some(if mods.shift { 'Z' } else { 'z' }),
                                        Key::Num0 => Some(if mods.shift { ')' } else { '0' }),
                                        Key::Num1 => Some(if mods.shift { '!' } else { '1' }),
                                        Key::Num2 => Some(if mods.shift { '@' } else { '2' }),
                                        Key::Num3 => Some(if mods.shift { '#' } else { '3' }),
                                        Key::Num4 => Some(if mods.shift { '$' } else { '4' }),
                                        Key::Num5 => Some(if mods.shift { '%' } else { '5' }),
                                        Key::Num6 => Some(if mods.shift { '^' } else { '6' }),
                                        Key::Num7 => Some(if mods.shift { '&' } else { '7' }),
                                        Key::Num8 => Some(if mods.shift { '*' } else { '8' }),
                                        Key::Num9 => Some(if mods.shift { '(' } else { '9' }),
                                        Key::Minus => Some(if mods.shift { '_' } else { '-' }),
                                        Key::Equals => Some(if mods.shift { '+' } else { '=' }),
                                        Key::LeftBracket => Some(if mods.shift { '{' } else { '[' }),
                                        Key::RightBracket => Some(if mods.shift { '}' } else { ']' }),
                                        Key::Backslash => Some(if mods.shift { '|' } else { '\\' }),
                                        Key::Semicolon => Some(if mods.shift { ':' } else { ';' }),
                                        Key::Quote => Some(if mods.shift { '"' } else { '\'' }),
                                        Key::Comma => Some(if mods.shift { '<' } else { ',' }),
                                        Key::Period => Some(if mods.shift { '>' } else { '.' }),
                                        Key::Slash => Some(if mods.shift { '?' } else { '/' }),
                                        Key::Grave => Some(if mods.shift { '~' } else { '`' }),
                                        _ => None,
                                    };

                                    // Key code for special key handling (backspace, arrows, etc)
                                    // Letter keys use ASCII uppercase (65=A, 90=Z) for Cmd+key shortcuts
                                    let key_code = match &kb_event.key {
                                        Key::Backspace => 8,
                                        Key::Delete => 127,
                                        Key::Enter => 13,
                                        Key::Tab => 9,
                                        Key::Escape => 27,
                                        Key::Left => 37,
                                        Key::Right => 39,
                                        Key::Up => 38,
                                        Key::Down => 40,
                                        Key::Home => 36,
                                        Key::End => 35,
                                        // Map letter keys to ASCII uppercase for Cmd+key shortcuts
                                        Key::A => 65, Key::B => 66, Key::C => 67,
                                        Key::D => 68, Key::E => 69, Key::F => 70,
                                        Key::G => 71, Key::H => 72, Key::I => 73,
                                        Key::J => 74, Key::K => 75, Key::L => 76,
                                        Key::M => 77, Key::N => 78, Key::O => 79,
                                        Key::P => 80, Key::Q => 81, Key::R => 82,
                                        Key::S => 83, Key::T => 84, Key::U => 85,
                                        Key::V => 86, Key::W => 87, Key::X => 88,
                                        Key::Y => 89, Key::Z => 90,
                                        Key::Back => {
                                            // System back button — dispatch through back handler
                                            if blinc_layout::back_handler::dispatch_back() {
                                                return ControlFlow::Continue;
                                            }
                                            // Not consumed — let default handling proceed
                                            0
                                        }
                                        _ => 0,
                                    };

                                    match kb_event.state {
                                        KeyState::Pressed => {
                                            // Handle Escape key for overlays first
                                            // If an overlay handles it, don't propagate further
                                            if kb_event.key == Key::Escape
                                                && windowed_ctx.overlay_manager.handle_escape()
                                            {
                                                // Escape was consumed by overlay, skip further processing
                                                // (but continue collecting events for non-overlay targets)
                                            }

                                            // Dispatch KEY_DOWN for all keys
                                            router.on_key_down(key_code);

                                            // For character-producing keys, dispatch TEXT_INPUT
                                            // We use broadcast dispatch so any focused text input can receive it
                                            if let Some(c) = key_char {
                                                // Don't send text input if ctrl/cmd is held (shortcuts)
                                                if !mods.ctrl && !mods.meta {
                                                    keyboard_events.push(PendingEvent {
                                                        event_type: blinc_core::events::event_types::TEXT_INPUT,
                                                        key_char: Some(c),
                                                        key_code,
                                                        shift: mods.shift,
                                                        ctrl: mods.ctrl,
                                                        alt: mods.alt,
                                                        meta: mods.meta,
                                                        ..Default::default()
                                                    });
                                                }
                                            }

                                            // For KEY_DOWN events with special keys (backspace, arrows)
                                            if key_code != 0 {
                                                keyboard_events.push(PendingEvent {
                                                    event_type: blinc_core::events::event_types::KEY_DOWN,
                                                    key_char: None,
                                                    key_code,
                                                    shift: mods.shift,
                                                    ctrl: mods.ctrl,
                                                    alt: mods.alt,
                                                    meta: mods.meta,
                                                    ..Default::default()
                                                });
                                            }
                                        }
                                        KeyState::Released => {
                                            router.on_key_up(key_code);
                                        }
                                    }
                                },
                                InputEvent::Touch(touch_event) => {
                                    // Track active touch IDs for touch count
                                    match &touch_event {
                                        TouchEvent::Started { .. } => {
                                            ws.active_touch_ids.insert(touch_event.id());
                                            windowed_ctx.pointer_query.set_touch_count(ws.active_touch_ids.len() as u32);
                                        }
                                        TouchEvent::Ended { .. } => {
                                            ws.active_touch_ids.remove(&touch_event.id());
                                            windowed_ctx.pointer_query.set_touch_count(ws.active_touch_ids.len() as u32);
                                        }
                                        TouchEvent::Cancelled { .. } => {
                                            ws.active_touch_ids.remove(&touch_event.id());
                                            windowed_ctx.pointer_query.set_touch_count(ws.active_touch_ids.len() as u32);
                                        }
                                        _ => {}
                                    }
                                    match touch_event {
                                        TouchEvent::Started { x, y, pressure, .. } => {
                                            let lx = x / scale;
                                            let ly = y / scale;
                                            windowed_ctx.pointer_query.set_pressure(pressure);
                                            router.on_mouse_down(tree, lx, ly, MouseButton::Left);
                                            let (local_x, local_y) = router.last_hit_local();
                                            let (bounds_x, bounds_y) = router.last_hit_bounds_pos();
                                            let (bounds_width, bounds_height) = router.last_hit_bounds();
                                            for event in pending_events.iter_mut() {
                                                event.mouse_x = lx;
                                                event.mouse_y = ly;
                                                event.local_x = local_x;
                                                event.local_y = local_y;
                                                event.bounds_x = bounds_x;
                                                event.bounds_y = bounds_y;
                                                event.bounds_width = bounds_width;
                                                event.bounds_height = bounds_height;
                                            }
                                        }
                                        TouchEvent::Moved { x, y, pressure, .. } => {
                                            let lx = x / scale;
                                            let ly = y / scale;
                                            windowed_ctx.pointer_query.set_pressure(pressure);

                                            // Use occlusion-aware hit testing for touch move as well
                                            let overlay_bounds = windowed_ctx.overlay_manager.get_visible_overlay_bounds();
                                            let overlay_layer_id = tree.query_by_id(
                                                blinc_layout::widgets::overlay::OVERLAY_LAYER_ID
                                            );
                                            router.on_mouse_move_with_occlusion(
                                                tree,
                                                lx,
                                                ly,
                                                &overlay_bounds,
                                                overlay_layer_id,
                                            );

                                            for event in pending_events.iter_mut() {
                                                event.mouse_x = lx;
                                                event.mouse_y = ly;
                                            }
                                        }
                                        TouchEvent::Ended { x, y, .. } => {
                                            let lx = x / scale;
                                            let ly = y / scale;
                                            windowed_ctx.pointer_query.set_pressure(0.0);
                                            router.on_mouse_up(tree, lx, ly, MouseButton::Left);
                                            for event in pending_events.iter_mut() {
                                                event.mouse_x = lx;
                                                event.mouse_y = ly;
                                            }
                                        }
                                        TouchEvent::Cancelled { .. } => {
                                            // Touch cancelled - treat like mouse leave
                                            // This will emit POINTER_UP if there was a pressed target
                                            windowed_ctx.pointer_query.set_pressure(0.0);
                                            windowed_ctx.pointer_query.set_touch_count(0);
                                            router.on_mouse_leave();
                                        }
                                    }
                                }
                                InputEvent::Scroll { delta_x, delta_y, phase } => {
                                    let (mx, my) = router.mouse_position();
                                    // Scroll deltas are also in physical pixels, convert to logical
                                    let ldx = delta_x;
                                    let ldy = delta_y;

                                    tracing::trace!(
                                        "InputEvent::Scroll received: pos=({:.1}, {:.1}) delta=({:.1}, {:.1}) phase={:?}",
                                        mx, my, ldx, ldy, phase
                                    );

                                    // Check if gesture ended (finger lifted from trackpad)
                                    // This happens before momentum ends
                                    if phase == blinc_platform::ScrollPhase::Ended {
                                        gesture_ended = true;
                                    }

                                    // Use nested scroll support - get hit result for smart dispatch
                                    // Store mouse position and delta for dispatch phase
                                    // We'll re-do hit test in dispatch phase since we need mutable borrow
                                    scroll_info = Some((mx, my, ldx, ldy));
                                }
                                InputEvent::ScrollEnd => {
                                    // Scroll momentum ended - full stop
                                    scroll_ended = true;
                                }
                                InputEvent::Pinch { scale, .. } => {
                                    let (mx, my) = router.mouse_position();
                                    pending_events.push(PendingEvent {
                                        event_type: blinc_core::events::event_types::PINCH,
                                        mouse_x: mx,
                                        mouse_y: my,
                                        pinch_scale: scale,
                                        ..Default::default()
                                    });
                                }
                                InputEvent::Rotation { angle, .. } => {
                                    let (mx, my) = router.mouse_position();
                                    pending_events.push(PendingEvent {
                                        event_type: blinc_core::events::event_types::ROTATE,
                                        mouse_x: mx,
                                        mouse_y: my,
                                        pinch_scale: angle,
                                        ..Default::default()
                                    });
                                }
                            }

                            router.clear_event_callback();
                            (pending_events, keyboard_events, scroll_ended, gesture_ended, scroll_info)
                        } else {
                            (Vec::new(), Vec::new(), false, false, None)
                        };

                        // Second phase: dispatch events with mutable borrow
                        // This automatically marks the tree dirty when handlers fire
                        if let Some(ref mut tree) = ws.render_tree {
                            // IMPORTANT: Process gesture_ended BEFORE scroll delta dispatch
                            // When gesture ends while overscrolling, we start bounce which
                            // sets state to Bouncing. Then apply_scroll_delta will early-return
                            // and ignore the momentum delta that came with this same event.
                            if gesture_ended {
                                tree.on_gesture_end();
                                // Request redraw to animate bounce-back
                                window.request_redraw();
                            }

                            // Handle scroll with nested scroll support
                            // Skip scroll delta entirely if gesture just ended - the delta
                            // from the same event as gesture_ended is the last finger movement,
                            // not momentum, but we still want to ignore it for instant snap-back
                            //
                            // Also skip scroll when an overlay with an actual backdrop is open to prevent
                            // background content from scrolling while dropdown/modal is visible.
                            // Note: We only check has_blocking_overlay(), not has_dismissable_overlay(),
                            // because overlays with dismiss_on_click_outside (like popovers) should allow
                            // scroll events to pass through to content behind them.
                            let has_overlay_backdrop = ws.ctx
                                .as_ref()
                                .map(|c| c.overlay_manager.has_blocking_overlay())
                                .unwrap_or(false);

                            if let Some((mouse_x, mouse_y, delta_x, delta_y)) = scroll_info {
                                // Skip if gesture ended in this same event - go straight to bounce
                                if gesture_ended {
                                    tracing::trace!("Skipping scroll delta - gesture ended, bouncing");
                                } else if has_overlay_backdrop {
                                    // Skip scroll when overlay is visible to prevent background scrolling
                                    tracing::trace!("Skipping scroll delta - overlay with backdrop is visible");
                                } else {
                                    tracing::trace!(
                                        "Scroll dispatch: pos=({:.1}, {:.1}) delta=({:.1}, {:.1})",
                                        mouse_x, mouse_y, delta_x, delta_y
                                    );

                                    // Update overlay positions for overlays with follows_scroll enabled
                                    // Use the singleton overlay manager since components use get_overlay_manager()
                                    if OverlayContext::is_initialized() {
                                        let mgr = get_overlay_manager();
                                        if mgr.handle_scroll(delta_y) {
                                            // Apply scroll offsets to render tree for visual movement
                                            for (element_id, offset_y) in mgr.get_scroll_offsets() {
                                                if let Some(node_id) = tree.query_by_id(&element_id) {
                                                    tree.set_scroll_offset(node_id, 0.0, offset_y);
                                                }
                                            }
                                            window.request_redraw();
                                        }
                                    }

                                    // Re-do hit test with mutable borrow to get ancestor chain
                                    // Then use dispatch_scroll_chain for proper nested scroll handling
                                    if let Some(ref mut windowed_ctx) = ws.ctx {
                                        let router = &mut windowed_ctx.event_router;
                                        if let Some(hit) = router.hit_test(tree, mouse_x, mouse_y) {
                                            tree.dispatch_scroll_chain(
                                                hit.node,
                                                &hit.ancestors,
                                                mouse_x,
                                                mouse_y,
                                                delta_x,
                                                delta_y,
                                            );
                                        }
                                    }
                                }
                            }

                            // Dispatch mouse/touch events (scroll is handled above with nested support)
                            if let Some(ref mut windowed_ctx) = ws.ctx {
                                let router = &windowed_ctx.event_router;
                                for mut event in pending_events {
                                    // Skip scroll events - already handled with nested scroll support
                                    if event.event_type == blinc_core::events::event_types::SCROLL {
                                        continue;
                                    }
                                    // Gesture events (PINCH/ROTATE) need hit testing since
                                    // they were collected without a node target
                                    if (event.event_type == blinc_core::events::event_types::PINCH
                                        || event.event_type
                                            == blinc_core::events::event_types::ROTATE)
                                        && event.node_id == LayoutNodeId::default()
                                    {
                                        if let Some(hit) =
                                            router.hit_test(tree, event.mouse_x, event.mouse_y)
                                        {
                                            event.node_id = hit.node;
                                            event.local_x = hit.local_x;
                                            event.local_y = hit.local_y;
                                            event.bounds_x = hit.bounds_x;
                                            event.bounds_y = hit.bounds_y;
                                            event.bounds_width = hit.bounds_width;
                                            event.bounds_height = hit.bounds_height;
                                        } else {
                                            continue; // No element under cursor
                                        }
                                    }
                                    // Look up the correct bounds for this specific node.
                                    // When events bubble from a child to a parent handler,
                                    // we need the parent's bounds, not the original hit target's bounds.
                                    let (bounds_x, bounds_y, bounds_width, bounds_height) =
                                        router.get_node_bounds(event.node_id).unwrap_or((
                                            event.bounds_x,
                                            event.bounds_y,
                                            event.bounds_width,
                                            event.bounds_height,
                                        ));
                                    let local_x = event.mouse_x - bounds_x;
                                    let local_y = event.mouse_y - bounds_y;
                                    tree.dispatch_event_full(
                                        event.node_id,
                                        event.event_type,
                                        event.mouse_x,
                                        event.mouse_y,
                                        local_x,
                                        local_y,
                                        bounds_x,
                                        bounds_y,
                                        bounds_width,
                                        bounds_height,
                                        event.drag_delta_x,
                                        event.drag_delta_y,
                                        event.pinch_scale,
                                    );
                                }
                            }

                            // Note: Overlay events are now dispatched through the main tree
                            // since overlays are composed into the main tree via build_overlay_layer()

                            // Dispatch keyboard events
                            // Use broadcast instead of bubbling to handle focus correctly after tree rebuilds.
                            // Text inputs track their own focus state internally via `s.visual.is_focused()`,
                            // so broadcasting to all handlers is safe - only the focused one will process.
                            for event in keyboard_events {
                                if event.event_type == blinc_core::events::event_types::TEXT_INPUT {
                                    if let Some(c) = event.key_char {
                                        // Broadcast to all text input handlers
                                        // Each handler checks its own focus state internally
                                        tree.broadcast_text_input_event(
                                            c,
                                            event.shift,
                                            event.ctrl,
                                            event.alt,
                                            event.meta,
                                        );
                                    }
                                } else {
                                    // Broadcast KEY_DOWN to all key handlers
                                    tree.broadcast_key_event(
                                        event.event_type,
                                        event.key_code,
                                        event.shift,
                                        event.ctrl,
                                        event.alt,
                                        event.meta,
                                    );
                                }
                            }

                            // If scroll momentum ended, notify scroll physics
                            if scroll_ended {
                                tree.on_scroll_end();
                                // Request redraw to animate bounce-back
                                window.request_redraw();
                            }
                        }
                    }

                    Event::Frame(_) => {
                        if let (
                            Some(ref mut blinc_app),
                            Some(ref surf),
                            Some(ref config),
                            Some(ref mut windowed_ctx),
                            Some(ref mut rs),
                        ) = (&mut ws.app, &ws.surface, &ws.surface_config, &mut ws.ctx, &mut ws.render_state)
                        {
                            // Get current frame
                            let frame = match surf.get_current_texture() {
                                Ok(f) => f,
                                Err(wgpu::SurfaceError::Lost) => {
                                    surf.configure(blinc_app.device(), config);
                                    return ControlFlow::Continue;
                                }
                                Err(wgpu::SurfaceError::OutOfMemory) => {
                                    tracing::error!("Out of GPU memory");
                                    return ControlFlow::Exit;
                                }
                                Err(e) => {
                                    tracing::warn!("Surface error: {:?}", e);
                                    return ControlFlow::Continue;
                                }
                            };

                            let view = frame
                                .texture
                                .create_view(&wgpu::TextureViewDescriptor::default());

                            // Update context from window
                            windowed_ctx.update_from_window(window);

                            // Update viewport for lazy loading visibility checks
                            // Uses logical pixels (width/height) as that's what layout uses
                            rs.set_viewport_size(windowed_ctx.width, windowed_ctx.height);

                            // Get current time for animation updates (used in multiple phases)
                            let current_time = elapsed_ms();

                            // Clear overlays from previous frame (cursor, selection, focus ring)
                            // These are re-added during rendering if still active
                            rs.clear_overlays();

                            // Tick scroll physics and sync ScrollRef state BEFORE any rebuilds
                            // This ensures ScrollRef has up-to-date values when stateful components
                            // query scroll position during rebuild
                            let scroll_animating = if let Some(ref mut tree) = ws.render_tree {
                                let animating = tree.tick_scroll_physics(current_time);
                                tree.process_pending_scroll_refs();
                                animating
                            } else {
                                false
                            };

                            // =========================================================
                            // PHASE 1: Check if tree structure needs rebuild
                            // Only structural changes require tree rebuild
                            // =========================================================

                            // Check if event handlers marked anything dirty (auto-rebuild)
                            if let Some(ref tree) = ws.render_tree {
                                if tree.needs_rebuild() {
                                    tracing::debug!("Rebuild triggered by: dirty_tracker");
                                    ws.needs_rebuild = true;
                                }
                            }

                            // Check if element refs were modified (triggers rebuild)
                            if ref_dirty_flag.swap(false, Ordering::SeqCst) {
                                tracing::debug!("Rebuild triggered by: ref_dirty_flag (State::set)");
                                ws.needs_rebuild = true;
                            }

                            // Check if text widgets requested a rebuild (focus/text changes)
                            if blinc_layout::widgets::take_needs_rebuild() {
                                tracing::debug!("Rebuild triggered by: text widget state change");
                                ws.needs_rebuild = true;
                            }

                            // Check if a full relayout was requested (e.g., theme changes)
                            if blinc_layout::widgets::take_needs_relayout() {
                                tracing::debug!("Relayout triggered by: theme or global state change");
                                ws.needs_relayout = true;
                            }

                            // Check if CSS stylesheets need reparsing (e.g., theme color scheme changed)
                            // This must happen before tree rebuild so the new stylesheet is available
                            if blinc_layout::widgets::take_needs_css_reparse() {
                                tracing::debug!("Reparsing CSS stylesheets due to theme change");
                                windowed_ctx.reparse_css();
                            }

                            // Process pending motion exit starts BEFORE overlay update
                            // This is critical: when an overlay closes, it queues a motion exit via
                            // query_motion(key).exit(). The overlay's update() method then checks
                            // if the motion is done animating. If we don't process the exit queue
                            // first, the motion won't be in Exiting state yet, and update() will
                            // incorrectly think the exit animation is complete.
                            rs.process_global_motion_exit_starts();
                            rs.process_global_motion_exit_cancels();
                            // Process suspended motion starts queued via query_motion(key).start()
                            rs.process_global_motion_starts();

                            // Sync motion states to shared store so overlay can query them
                            // This must happen after processing exits but before overlay update
                            rs.sync_shared_motion_states();

                            // Update overlay manager viewport and state for subtree rebuilds
                            // This must happen BEFORE checking is_dirty() so build_overlay_layer() works correctly
                            windowed_ctx.overlay_manager.set_viewport_with_scale(
                                windowed_ctx.width,
                                windowed_ctx.height,
                                windowed_ctx.scale_factor as f32,
                            );
                            windowed_ctx.overlay_manager.update(current_time);

                            // Check if overlay content changed (new overlay opened/closed)
                            // NOTE: We only rebuild on actual content changes, NOT during animations.
                            // Animation visual updates (backdrop opacity, motion transforms) are handled
                            // by the motion system and render-time interpolation, not content rebuilds.
                            // Rebuilding during animation breaks event handlers because node IDs change.
                            let overlay_content_dirty = windowed_ctx.overlay_manager.is_dirty();

                            if overlay_content_dirty {
                                tracing::debug!(
                                    "Overlay rebuild: dirty={}, has_visible={}",
                                    overlay_content_dirty,
                                    windowed_ctx.overlay_manager.has_visible_overlays()
                                );
                                // Look up the overlay layer node by its element ID
                                if let Some(overlay_node_id) = element_registry.get(
                                    blinc_layout::widgets::overlay::OVERLAY_LAYER_ID
                                ) {
                                    tracing::debug!("Overlay changed - queueing subtree rebuild for node {:?}", overlay_node_id);
                                    // Build the new overlay content and queue the subtree rebuild
                                    let overlay_content = windowed_ctx.overlay_manager.build_overlay_layer();
                                    blinc_layout::queue_subtree_rebuild(overlay_node_id, overlay_content);
                                } else {
                                    tracing::warn!("Overlay changed but node '{}' not found in registry - will rebuild on next frame",
                                        blinc_layout::widgets::overlay::OVERLAY_LAYER_ID);
                                }
                                // Consume the dirty flag
                                windowed_ctx.overlay_manager.take_dirty();
                            }

                            // Check if stateful elements requested a redraw (hover/press changes)
                            // Apply incremental prop updates without full rebuild
                            let has_stateful_updates = blinc_layout::take_needs_redraw();
                            let has_pending_rebuilds = blinc_layout::has_pending_subtree_rebuilds();

                            if has_stateful_updates || has_pending_rebuilds {
                                if has_stateful_updates {
                                    tracing::debug!("Redraw requested by: stateful state change");
                                }

                                // Get all pending prop updates
                                let prop_updates = blinc_layout::take_pending_prop_updates();
                                let had_prop_updates = !prop_updates.is_empty();

                                // Apply prop updates to the main tree
                                // (Overlays are now part of the main tree, so all nodes are here)
                                if let Some(ref mut tree) = ws.render_tree {
                                    for (node_id, props) in &prop_updates {
                                        tree.update_render_props(*node_id, |p| *p = props.clone());
                                    }
                                }

                                // Process subtree rebuilds (from stateful changes OR overlay changes)
                                let mut needs_layout = false;
                                if let Some(ref mut tree) = ws.render_tree {
                                    needs_layout = tree.process_pending_subtree_rebuilds();
                                }

                                if needs_layout {
                                    if let Some(ref mut tree) = ws.render_tree {
                                        tracing::debug!("Subtree rebuilds processed, recomputing layout");
                                        tree.apply_stylesheet_layout_overrides();
                                        tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                        // FLIP: detect position changes and start CSS transitions
                                        tree.apply_flip_transitions();
                                        // Update FLIP bounds cache for next rebuild
                                        tree.update_flip_bounds();
                                        // Begin/end motion frame to track which motions are still in tree
                                        rs.begin_stable_motion_frame();
                                        tree.initialize_motion_animations(rs);
                                        rs.end_stable_motion_frame();
                                        rs.process_global_motion_replays();
                                        // Start CSS animations for elements with animation properties
                                        tree.start_all_css_animations();
                                    }
                                }
                                if had_prop_updates && !needs_layout {
                                    tracing::trace!("Visual-only prop updates, skipping layout");
                                }

                                // Request window redraw without rebuild
                                window.request_redraw();
                            }

                            // =========================================================
                            // PHASE 2: Build/rebuild tree only for structural changes
                            // This must happen BEFORE tick() so motion animations are available
                            // =========================================================

                            // Begin stable motion frame tracking
                            // This clears the "used" set so we can detect which motions are no longer in the tree
                            rs.begin_stable_motion_frame();

                            if ws.needs_rebuild || ws.render_tree.is_none() {
                                // Reset call counters for stable key generation
                                reset_call_counters();
                                // Clear stale Stateful base_render_props updaters
                                blinc_layout::clear_stateful_base_updaters();
                                blinc_layout::click_outside::clear_click_outside_handlers();

                                // Reset stable motions so they replay on full rebuild
                                // This ensures motion animations play when UI is reconstructed
                                rs.reset_stable_motions_for_rebuild();

                                // Note: Viewport and overlay state are already updated in PHASE 1
                                // so build_overlay_layer() has correct dimensions

                                // Build UI element tree
                                let user_ui = ui_builder(windowed_ctx);

                                // Compose user UI with overlay layer using a regular Div container
                                // We use position:relative with the overlay absolutely positioned on top.
                                let overlay_layer = windowed_ctx.overlay_manager.build_overlay_layer();
                                let ui = div()
                                    .w(windowed_ctx.width)
                                    .h(windowed_ctx.height)
                                    .relative() // positioning context for overlay
                                    .child(user_ui)
                                    .child(overlay_layer);

                                // Use incremental update if we have an existing tree
                                // BUT: Skip incremental update during resize - do full rebuild instead
                                // This ensures parent constraints properly propagate to all children
                                if let Some(ref mut existing_tree) = ws.render_tree {
                                    if ws.needs_relayout {
                                        // Window resize: bypass incremental update, do full rebuild
                                        // This ensures proper constraint propagation from parents to children
                                        tracing::debug!("Window resize: full tree rebuild (bypassing incremental update)");

                                        // Clear layout bounds storages before rebuild
                                        existing_tree.clear_layout_bounds_storages();

                                        // Full rebuild: create new tree from element with shared registry
                                        // Pass registry to from_element_with_registry so IDs are registered during build
                                        let mut tree = RenderTree::from_element_with_registry(
                                            &ui,
                                            Arc::clone(&element_registry),
                                        );

                                        // Set animation scheduler for scroll bounce springs
                                        tree.set_animations(&windowed_ctx.animations);

                                        // Share the CSS animation store (ticked by scheduler thread)
                                        tree.set_css_anim_store(Arc::clone(&css_anim_store));

                                        // Set DPI scale factor for HiDPI rendering
                                        tree.set_scale_factor(windowed_ctx.scale_factor as f32);

                                        // Set CSS stylesheet for automatic style application
                                        if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                            tree.set_stylesheet_arc(stylesheet.clone());
                                        }
                                        // Apply CSS visual + layout styles in a single optimized pass
                                        // (builds class index once, iterates rules once)
                                        tree.apply_all_stylesheet_styles();

                                        // Register pointer-space elements from stylesheet
                                        if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                            windowed_ctx.pointer_query.register_from_stylesheet(stylesheet);
                                        }

                                        // Compute layout with new viewport dimensions
                                        tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                        tree.update_flip_bounds();

                                        // Initialize motion animations for any nodes wrapped in motion() containers
                                        tree.initialize_motion_animations(rs);
                                        // End motion frame to detect unmounted motions and trigger exit animations
                                        rs.end_stable_motion_frame();
                                        // Process any motion replay requests queued during tree building
                                        rs.process_global_motion_replays();
                                        // Start CSS animations for elements with animation properties
                                        tree.start_all_css_animations();

                                        // Replace existing tree with fresh one
                                        *existing_tree = tree;

                                        // Clear relayout flag after full rebuild
                                        ws.needs_relayout = false;
                                    } else {
                                        // Normal incremental update (no resize)
                                        use blinc_layout::UpdateResult;

                                        // Update stylesheet in case it changed between frames
                                        if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                            existing_tree.set_stylesheet_arc(stylesheet.clone());
                                        }

                                        let update_result = existing_tree.incremental_update(&ui);

                                        match update_result {
                                            UpdateResult::NoChanges => {
                                                tracing::debug!("Incremental update: NoChanges - skipping rebuild");
                                            }
                                            UpdateResult::VisualOnly => {
                                                tracing::debug!("Incremental update: VisualOnly - skipping layout");
                                                // Props already updated in-place by incremental_update
                                            }
                                            UpdateResult::LayoutChanged => {
                                                // Layout changed - recompute layout
                                                tracing::debug!("Incremental update: LayoutChanged - recomputing layout");
                                                existing_tree.apply_stylesheet_layout_overrides();
                                                existing_tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                                existing_tree.update_flip_bounds();
                                            }
                                            UpdateResult::ChildrenChanged => {
                                                // Children changed - subtrees were rebuilt in place
                                                tracing::debug!("Incremental update: ChildrenChanged - subtrees rebuilt");

                                                // Apply CSS styles to new nodes from rebuilt subtrees
                                                // (collect_render_props only applies ID-based CSS;
                                                // class selectors need apply_stylesheet_base_styles)
                                                existing_tree.apply_stylesheet_base_styles();
                                                // Recompute layout since structure changed
                                                existing_tree.apply_stylesheet_layout_overrides();
                                                existing_tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                                // FLIP: detect position changes and start CSS transitions
                                                existing_tree.apply_flip_transitions();
                                                existing_tree.update_flip_bounds();

                                                // Re-register pointer-space elements (new elements may have pointer-space)
                                                if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                                    windowed_ctx.pointer_query.register_from_stylesheet(stylesheet);
                                                }

                                                // Initialize motion animations for any new nodes wrapped in motion() containers
                                                existing_tree.initialize_motion_animations(rs);
                                                // End motion frame to detect unmounted motions and trigger exit animations
                                                rs.end_stable_motion_frame();

                                                // Process any global motion replays that were queued during tree building
                                                rs.process_global_motion_replays();
                                                // Start CSS animations for elements with animation properties
                                                existing_tree.start_all_css_animations();
                                            }
                                        }
                                    }
                                } else {
                                    // No existing tree - create new with shared registry
                                    let mut tree = RenderTree::from_element_with_registry(
                                        &ui,
                                        Arc::clone(&element_registry),
                                    );

                                    // Set animation scheduler for scroll bounce springs
                                    tree.set_animations(&windowed_ctx.animations);

                                    // Share the CSS animation store (ticked by scheduler thread)
                                    tree.set_css_anim_store(Arc::clone(&css_anim_store));

                                    // Set DPI scale factor for HiDPI rendering
                                    tree.set_scale_factor(windowed_ctx.scale_factor as f32);

                                    // Set CSS stylesheet for automatic style application
                                    if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                        tree.set_stylesheet_arc(stylesheet.clone());
                                    }
                                    // Apply CSS visual + layout styles in a single optimized pass
                                    tree.apply_all_stylesheet_styles();

                                    // Register pointer-space elements from stylesheet
                                    if let Some(ref stylesheet) = windowed_ctx.stylesheet {
                                        windowed_ctx.pointer_query.register_from_stylesheet(stylesheet);
                                    }

                                    // Compute layout in logical pixels
                                    tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                    tree.update_flip_bounds();

                                    // Initialize motion animations for any nodes wrapped in motion() containers
                                    tree.initialize_motion_animations(rs);
                                    // End motion frame to detect unmounted motions and trigger exit animations
                                    rs.end_stable_motion_frame();

                                    // Process any global motion replays that were queued during tree building
                                    rs.process_global_motion_replays();
                                    // Start CSS animations for elements with animation properties
                                    tree.start_all_css_animations();

                                    ws.render_tree = Some(tree);
                                }

                                ws.needs_rebuild = false;
                                let was_first_rebuild = windowed_ctx.rebuild_count == 0;
                                windowed_ctx.rebuild_count = windowed_ctx.rebuild_count.saturating_add(1);

                                // Execute on_ready callbacks after first rebuild
                                if was_first_rebuild {
                                    if let Ok(mut callbacks) = ready_callbacks.lock() {
                                        for callback in callbacks.drain(..) {
                                            callback();
                                        }
                                    }
                                }
                            } else {
                                // No rebuild needed - still need to end the motion frame
                                // If an existing tree exists, initialize motions to mark them as used
                                if let Some(ref tree) = ws.render_tree {
                                    tree.initialize_motion_animations(rs);
                                }
                                rs.end_stable_motion_frame();
                            }

                            // Note: on_ready callbacks are only executed after the FIRST rebuild
                            // (in the was_first_rebuild block above). Callbacks registered
                            // after the first rebuild are executed immediately since the UI
                            // is already ready at that point.

                            // =========================================================
                            // PHASE 3: Tick animations and dynamic render state
                            // This must happen AFTER tree rebuild so motions are initialized
                            // =========================================================

                            // Process any pending motion exit cancellations
                            // This must happen before tick() so cancelled motions don't continue exiting
                            rs.process_global_motion_exit_cancels();

                            // Process any pending motion exit starts (explicit exit triggers)
                            rs.process_global_motion_exit_starts();

                            // Process suspended motion starts queued via query_motion(key).start()
                            rs.process_global_motion_starts();

                            // Tick render state (handles cursor blink, color animations, etc.)
                            // This updates dynamic properties without touching tree structure
                            let _animations_active = rs.tick(current_time);

                            // Tick CSS animations/transitions synchronously on the main thread.
                            // The scheduler's bg thread drives 120fps redraws via wake_callback,
                            // but actual ticking is done here to stay in phase with rendering.
                            let dt_ms = if ws.last_frame_time_ms > 0 {
                                (current_time - ws.last_frame_time_ms) as f32
                            } else {
                                16.0
                            };
                            let css_active = if let Some(ref mut tree) = ws.render_tree {
                                let store = tree.css_anim_store();
                                let mut s = store.lock().unwrap();
                                let (anim, trans) = s.tick(dt_ms);
                                drop(s);
                                let flip = tree.tick_flip_animations(dt_ms);
                                anim || trans || flip || tree.css_has_active()
                            } else {
                                false
                            };
                            ws.last_frame_time_ms = current_time;

                            // Sync motion states to shared store for query_motion API
                            rs.sync_shared_motion_states();

                            // Tick theme animation (handles color interpolation during theme transitions)
                            let theme_animating = blinc_theme::ThemeState::get().tick();

                            // Note: scroll physics tick moved to before PHASE 1 (before any rebuilds)
                            // so that ScrollRef has up-to-date values when stateful components rebuild

                            // =========================================================
                            // PHASE 4: Render
                            // Combines stable tree structure with dynamic render state
                            // =========================================================

                            // Sync text input/textarea focus to EventRouter so CSS :focus matching works
                            {
                                let text_focus = blinc_layout::widgets::text_input::focused_text_input_node_id()
                                    .or_else(blinc_layout::widgets::text_input::focused_text_area_node_id);
                                let current_focus = windowed_ctx.event_router.focused();
                                if text_focus != current_focus {
                                    windowed_ctx.event_router.set_focus(text_focus);
                                }
                            }

                            // Apply CSS state styles (:hover, :active, :focus) from stylesheet
                            // This also detects property changes and starts new transitions
                            if let Some(ref mut tree) = ws.render_tree {
                                if tree.stylesheet().is_some() {
                                    let state_changed = tree.apply_stylesheet_state_styles(&windowed_ctx.event_router);
                                    // Recompute layout if state styles affected layout properties
                                    // (e.g. visibility: hidden → display: none, or height changes on hover)
                                    if state_changed {
                                        tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                        tree.update_flip_bounds();
                                    }
                                }
                            }

                            // Apply CSS animation/transition values AFTER state styles
                            // (state styles reset to base, animations must override)
                            if css_active || !ws.render_tree.as_ref().map_or(true, |t| t.css_transitions_empty()) {
                                if let Some(ref mut tree) = ws.render_tree {
                                    tree.apply_all_css_animation_props();
                                    tree.apply_all_css_transition_props();
                                    tree.apply_flip_animation_props();
                                    if tree.apply_animated_layout_props() {
                                        tree.compute_layout(windowed_ctx.width, windowed_ctx.height);
                                        tree.update_flip_bounds();
                                    }
                                }
                            }

                            // Update continuous pointer query state
                            if !windowed_ctx.pointer_query.is_empty() {
                                let (mx, my) = windowed_ctx.event_router.mouse_position();
                                let is_pressed = windowed_ctx.event_router.pressed_target().is_some();
                                let dt_sec = dt_ms / 1000.0;
                                let time_sec = current_time as f64 / 1000.0;
                                // Use event router's hit test results for hover detection.
                                // The router already handles scroll offsets, transforms, and occlusion
                                // correctly, so bounds from get_node_bounds match the rendering pipeline.
                                windowed_ctx.pointer_query.update(
                                    mx, my, is_pressed, dt_sec, time_sec,
                                    |id| {
                                        let node = element_registry.get(id)?;
                                        if windowed_ctx.event_router.is_hovered(node) {
                                            windowed_ctx.event_router.get_node_bounds(node)
                                        } else {
                                            None
                                        }
                                    },
                                );
                                // Evaluate dynamic calc(env(...)) properties with current pointer state
                                if let Some(ref mut tree) = ws.render_tree {
                                    tree.apply_pointer_styles(
                                        &windowed_ctx.pointer_query,
                                        &windowed_ctx.event_router,
                                    );
                                }
                            }

                            if let Some(ref tree) = ws.render_tree {
                                // Set blend target for mix-blend-mode support
                                blinc_app.set_blend_target(&frame.texture);

                                // Pass cursor position for @flow pointer input
                                let (mx, my) = windowed_ctx.event_router.mouse_position();
                                let sf = windowed_ctx.scale_factor as f32;
                                blinc_app.set_cursor_position(mx * sf, my * sf);

                                // Drain any custom passes queued via BlincContextState
                                // (e.g. SceneKit3D registering a GridPass from a closure)
                                {
                                    let ctx_state = blinc_core::BlincContextState::get();
                                    for pass in ctx_state.drain_custom_passes() {
                                        if let Ok(typed) = pass.downcast::<Box<dyn blinc_gpu::custom_pass::CustomRenderPass>>() {
                                            blinc_app.context().register_custom_pass(*typed);
                                        }
                                    }
                                }

                                // Render with motion animations
                                // Use physical pixel dimensions for the render surface
                                let result = blinc_app.render_tree_with_motion(
                                    tree,
                                    rs,
                                    &view,
                                    windowed_ctx.physical_width as u32,
                                    windowed_ctx.physical_height as u32,
                                );
                                if let Err(e) = result {
                                    tracing::error!("Render error: {}", e);
                                }

                                blinc_app.clear_blend_target();
                            }

                            // =========================================================
                            // PHASE 4b: Overlay state management (overlays now in main tree)
                            // Overlays are composed into the main tree via build_overlay_layer()
                            // so they share the same event routing and incremental update path.
                            // =========================================================

                            // Clear dirty flags for overlays (they've been processed in tree build)
                            let _content_dirty = windowed_ctx.overlay_manager.take_dirty();
                            let _animation_dirty = windowed_ctx.overlay_manager.take_animation_dirty();

                            // Track overlay visibility for triggering rebuilds
                            let has_visible_overlays = windowed_ctx.overlay_manager.has_visible_overlays();
                            windowed_ctx.had_visible_overlays = has_visible_overlays;

                            frame.present();

                            // =========================================================
                            // PHASE 5: Request next frame if animations are active
                            // This ensures smooth animation without waiting for events
                            // =========================================================

                            // Check if background animation thread signaled that redraw is needed
                            // The background thread runs at 120fps and sets this flag when
                            // there are active animations (springs, keyframes, timelines)
                            let scheduler = windowed_ctx.animations.lock().unwrap();
                            let needs_animation_redraw = scheduler.take_needs_redraw();
                            drop(scheduler); // Release lock before request_redraw

                            // Check if stateful elements have active spring animations
                            // If so, re-run their callbacks to get updated animation values
                            if needs_animation_redraw && blinc_layout::has_animating_statefuls() {
                                blinc_layout::check_stateful_animations();
                            }

                            // Check if text widgets need continuous redraws (cursor blink)
                            let needs_cursor_redraw = blinc_layout::widgets::take_needs_continuous_redraw();

                            // Check if motion animations are active (enter/exit animations)
                            let needs_motion_redraw = if let Some(ref rs) = ws.render_state {
                                rs.has_active_motions()
                            } else {
                                false
                            };

                            // Check if overlays changed (modal opened/closed, toast appeared, etc.)
                            let needs_overlay_redraw = {
                                let mgr = windowed_ctx.overlay_manager.lock().unwrap();
                                mgr.take_dirty() || mgr.has_visible_overlays()
                            };

                            // Check if CSS animations/transitions/FLIP need continued redraws
                            // (includes transitions created during apply_complex_selector_styles)
                            let css_needs_redraw = css_active
                                || !ws.render_tree
                                    .as_ref()
                                    .map_or(true, |t| t.css_transitions_empty())
                                || ws.render_tree
                                    .as_ref()
                                    .is_some_and(|t| t.has_active_flip_animations());

                            // Check if pointer query elements need continuous redraws
                            let pointer_query_active = !windowed_ctx.pointer_query.is_empty();

                            // @flow shaders using time/animation builtins need continuous redraws
                            let flow_needs_redraw = blinc_app.has_active_flows();

                            if needs_animation_redraw || needs_cursor_redraw || needs_motion_redraw || scroll_animating || needs_overlay_redraw || theme_animating || css_needs_redraw || pointer_query_active || flow_needs_redraw {
                                // Request another frame to render updated animation values
                                // For cursor blink, also re-request continuous redraw for next frame
                                if needs_cursor_redraw {
                                    // Keep requesting redraws as long as a text input is focused
                                    if blinc_layout::widgets::has_focused_text_input() {
                                        blinc_layout::widgets::text_input::request_continuous_redraw_pub();
                                    }
                                }
                                window.request_redraw();
                            }
                        }
                    }

                    _ => {}
                }

                ControlFlow::Continue
            })
            .map_err(|e| BlincError::Platform(e.to_string()))?;

        Ok(())
    }

    /// Placeholder for non-windowed builds
    #[cfg(not(feature = "windowed"))]
    pub fn run<F, E>(_config: WindowConfig, _ui_builder: F) -> Result<()>
    where
        F: FnMut(&mut WindowedContext) -> E + 'static,
        E: ElementBuilder + 'static,
    {
        Err(BlincError::Platform(
            "Windowed feature not enabled. Add 'windowed' feature to blinc_app".to_string(),
        ))
    }
}

/// Convert platform mouse button to layout mouse button
#[cfg(all(feature = "windowed", not(target_os = "android")))]
fn convert_mouse_button(button: blinc_platform::MouseButton) -> MouseButton {
    match button {
        blinc_platform::MouseButton::Left => MouseButton::Left,
        blinc_platform::MouseButton::Right => MouseButton::Right,
        blinc_platform::MouseButton::Middle => MouseButton::Middle,
        blinc_platform::MouseButton::Back => MouseButton::Back,
        blinc_platform::MouseButton::Forward => MouseButton::Forward,
        blinc_platform::MouseButton::Other(n) => MouseButton::Other(n),
    }
}

/// Convert layout cursor style to platform cursor
#[cfg(all(feature = "windowed", not(target_os = "android")))]
fn convert_cursor_style(cursor: CursorStyle) -> blinc_platform::Cursor {
    match cursor {
        CursorStyle::Default => blinc_platform::Cursor::Default,
        CursorStyle::Pointer => blinc_platform::Cursor::Pointer,
        CursorStyle::Text => blinc_platform::Cursor::Text,
        CursorStyle::Crosshair => blinc_platform::Cursor::Crosshair,
        CursorStyle::Move => blinc_platform::Cursor::Move,
        CursorStyle::NotAllowed => blinc_platform::Cursor::NotAllowed,
        CursorStyle::ResizeNS => blinc_platform::Cursor::ResizeNS,
        CursorStyle::ResizeEW => blinc_platform::Cursor::ResizeEW,
        CursorStyle::ResizeNESW => blinc_platform::Cursor::ResizeNESW,
        CursorStyle::ResizeNWSE => blinc_platform::Cursor::ResizeNWSE,
        CursorStyle::Grab => blinc_platform::Cursor::Grab,
        CursorStyle::Grabbing => blinc_platform::Cursor::Grabbing,
        CursorStyle::Wait => blinc_platform::Cursor::Wait,
        CursorStyle::Progress => blinc_platform::Cursor::Progress,
        CursorStyle::None => blinc_platform::Cursor::None,
    }
}

/// Convenience function to run a windowed ws.app with default configuration
#[cfg(all(feature = "windowed", not(target_os = "android")))]
pub fn run_windowed<F, E>(ui_builder: F) -> Result<()>
where
    F: FnMut(&mut WindowedContext) -> E + 'static,
    E: ElementBuilder + 'static,
{
    WindowedApp::run(WindowConfig::default(), ui_builder)
}

/// Convenience function to run a windowed ws.app with a title
#[cfg(all(feature = "windowed", not(target_os = "android")))]
pub fn run_windowed_with_title<F, E>(title: &str, ui_builder: F) -> Result<()>
where
    F: FnMut(&mut WindowedContext) -> E + 'static,
    E: ElementBuilder + 'static,
{
    let config = WindowConfig {
        title: title.to_string(),
        ..Default::default()
    };
    WindowedApp::run(config, ui_builder)
}