blinc_layout 0.5.1

Blinc layout engine - Flexbox layout powered by Taffy
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
//! Ready-to-use TextInput widget
//!
//! Single-line text input with:
//! - Visual states: idle, hovered, focused (via FSM-driven Stateful)
//! - Cursor blinking via AnimatedValue + Canvas (no rebuilds)
//! - Incremental updates: prop updates for visuals, subtree rebuilds for content
//! - No full UI rebuilds - uses queue_prop_update and queue_subtree_rebuild
//!
//! # Example
//!
//! ```ignore
//! let input_data = text_input_data_with_placeholder("Enter username");
//! text_input(&input_data)
//!     .w(280.0)
//!     .rounded(12.0)
//! ```

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};

use blinc_core::Color;
use blinc_theme::{ColorToken, ThemeState};

use crate::canvas::canvas;
use crate::css_parser::{active_stylesheet, ElementState, Stylesheet};
use crate::div::{div, Div, ElementBuilder};
use crate::element::RenderProps;
use crate::stateful::{
    refresh_stateful, SharedState, StateTransitions, Stateful, StatefulInner, TextFieldState,
};
use crate::text::text;
use crate::text_selection::{clear_selection, set_selection, SelectionSource};
use crate::tree::{LayoutNodeId, LayoutTree};
use crate::widgets::cursor::{cursor_state, CursorAnimation, SharedCursorState};

/// Get elapsed time in milliseconds since app start (for cursor blinking)
pub fn elapsed_ms() -> u64 {
    static START_TIME: OnceLock<web_time::Instant> = OnceLock::new();
    let start = START_TIME.get_or_init(web_time::Instant::now);
    start.elapsed().as_millis() as u64
}

/// Standard cursor blink interval in milliseconds
pub const CURSOR_BLINK_INTERVAL_MS: u64 = 400;

// =============================================================================
// Global focus tracking
// =============================================================================

static GLOBAL_FOCUS_COUNT: AtomicU64 = AtomicU64::new(0);

/// Generation counter that increments on every text-input tap, regardless
/// of whether the tap actually transitions focus state. Polled by mobile
/// runners (`blinc_app::android` / `blinc_app::ios`) to detect "user tapped
/// a text input again" events that `take_keyboard_state_change` misses,
/// because that flag only fires on `0 → 1` / `1 → 0` focus-count
/// transitions.
///
/// Re-tapping the same input (or a different input while the keyboard is
/// already up) does NOT cross those transitions, so the runner has no
/// other way to know the user wanted to re-engage the keyboard. This
/// counter gives it that signal: bump on every tap that lands on a text
/// input handler, runner stores the last value it saw, and runs
/// scroll-into-view whenever the value advances.
///
/// Used by [`focus_tap_generation`] / bumped by the `text_input`,
/// `text_area`, `code_editor`, and `rich_text_editor` widgets'
/// `on_mouse_down` handlers.
static FOCUS_TAP_GENERATION: AtomicU64 = AtomicU64::new(0);

/// Layout node ID of the currently focused text-editable widget, encoded as
/// the raw `u64` from `LayoutNodeId::to_raw()`. `0` is the sentinel for
/// "nothing focused" since taffy never assigns id `0`.
///
/// `text_input` and `text_area` track their focus through dedicated
/// `FOCUSED_TEXT_INPUT` / `FOCUSED_TEXT_AREA` mutexes (which carry the
/// full widget data), but other text-editable widgets (`code_editor`,
/// `rich_text_editor`) don't share that data layout — they have their
/// own state types that the global trackers can't store. This atomic is
/// the lowest-common-denominator pointer-back: every editable widget can
/// register its own LayoutNodeId here on focus, and the
/// `scroll_focused_text_input_above_keyboard` helper consults this
/// generic ID when the typed lookups (`focused_text_input_node_id` /
/// `focused_text_area_node_id`) come up empty.
///
/// Bumped by [`set_focused_editable_node`] / cleared by
/// [`clear_focused_editable_node`]. Read by [`focused_editable_node_id`].
static FOCUSED_EDITABLE_NODE_ID: AtomicU64 = AtomicU64::new(0);

/// Companion to `FOCUSED_EDITABLE_NODE_ID` — an opaque blur callback
/// that the focused widget registers alongside its node id, so
/// [`blur_all_text_inputs`] can dismiss the editor when the user taps
/// outside it. The dedicated trackers (`FOCUSED_TEXT_INPUT` /
/// `FOCUSED_TEXT_AREA`) carry typed widget data and can call into the
/// widget's blur path directly; widgets that don't fit those types
/// (`code_editor`, `rich_text_editor`) instead pass a closure here so
/// the global blur path remains a single call.
///
/// `Box<dyn Fn() + Send + Sync>` rather than `FnOnce` because the
/// closure is invoked at most once but `take()` and replace would race
/// with the writer that just registered it. The closure typically
/// captures an `Arc<Mutex<...>>` to the widget state so it can flip
/// the local `focused` flag, decrement the global focus count, and
/// release any cursor-tick callbacks the widget held.
#[allow(clippy::type_complexity)]
static FOCUSED_EDITABLE_BLUR_CALLBACK: Mutex<Option<Box<dyn Fn() + Send + Sync>>> =
    Mutex::new(None);

/// Whether the most recent pointer event came from a touchscreen rather
/// than a mouse / trackpad.
///
/// Set to `true` from the iOS / Android runners on every
/// `TouchPhase::Began` (and reset to `false` from the desktop / web
/// runners on `mouse_down`). Editable widgets read this on
/// `on_mouse_down` / `on_drag` to switch between desktop semantics
/// (drag = extend selection) and mobile semantics (drag = move cursor
/// with haptic feedback, double-tap = native context menu).
///
/// Polled by [`is_touch_input`]. Updated by
/// [`set_touch_input`]. The flag is *sticky* — it stays set until a
/// non-touch input event flips it back, so re-rendering between
/// touch frames doesn't lose the bit.
static INPUT_SOURCE_IS_TOUCH: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// Long-press timer state for editable widgets.
///
/// When a user begins a touch on a focused text-editable widget, the
/// widget calls [`arm_long_press_timer`] to record the start time +
/// anchor position + bounds where the menu should pop. The platform
/// runner's frame loop polls [`fire_long_press_timer_if_due`] every
/// tick, and when 500 ms have elapsed without a cancel-via-drag or
/// cancel-via-release, the helper fires `show_edit_menu` with the
/// PASTE bit set so the user can paste from the clipboard the same
/// way native iOS UITextField / Android EditText do.
///
/// The timer is cancelled by [`cancel_long_press_timer`], called
/// from `on_drag` (when the finger moves too far) and from
/// `on_mouse_up`.
///
/// Stored as a `Mutex<Option<...>>` rather than separate atomics
/// because the four fields must be read atomically together — a
/// torn read between deadline and anchor would dispatch the menu
/// at the wrong location.
struct LongPressArm {
    /// Deadline in milliseconds since app start
    /// (`text_input::elapsed_ms`). When `elapsed_ms()` >= this,
    /// the timer fires.
    deadline_ms: u64,
    /// Anchor position in window-space logical pixels — passed
    /// straight through to `show_edit_menu`'s anchor_x / anchor_y.
    anchor_x: f32,
    anchor_y: f32,
    /// Original press position used for movement-cancel check.
    start_x: f32,
    start_y: f32,
    /// Selection rect height (used as the menu's vertical extent
    /// hint). The width is intentionally 0 because the menu hugs
    /// the anchor point, not a real selection rect.
    bounds_height: f32,
    /// Optional pre-show callback. Fired immediately before
    /// `show_edit_menu` when the long-press deadline elapses, so
    /// the focused widget can update its selection state to match
    /// the iOS UITextField / Android EditText UX of selecting the
    /// word under the finger on a long press (mirroring the
    /// double-tap behavior). Captured at arm time with an `Arc` to
    /// the widget's data state and the cursor position computed
    /// from the press location, so the callback runs entirely
    /// against state owned by the widget and doesn't need to walk
    /// any registries at fire time.
    on_fire: Option<Box<dyn Fn() + Send + Sync>>,
}

#[allow(clippy::type_complexity)]
static LONG_PRESS_ARM: Mutex<Option<LongPressArm>> = Mutex::new(None);

/// Long-press deadline relative to the press start time (ms). 500ms
/// matches iOS UITextField / Android EditText long-press timing.
const LONG_PRESS_DURATION_MS: u64 = 500;

/// Maximum movement (in logical pixels) allowed before the long-press
/// is cancelled. Mirrors the existing `widgets::gesture` constant.
const LONG_PRESS_MAX_DRIFT_PX: f32 = 10.0;

/// Arm the long-press timer at the given position. Called from a
/// text-editable widget's `on_mouse_down` handler when
/// `is_touch_input()` returns true.
///
/// The runner's frame poll calls [`fire_long_press_timer_if_due`]
/// each tick to check whether the deadline has elapsed.
///
/// `on_fire` is an optional pre-show callback that runs when the
/// deadline elapses, immediately before the edit menu is shown.
/// Editable widgets pass a closure here that selects the word
/// under the press position so a long-press behaves the same as a
/// double-tap (matches iOS UITextField / Android EditText UX). The
/// closure should capture an `Arc` to the widget's data state and
/// any state needed to update the selection (cursor position,
/// stateful refresh handle).
///
/// Calling this overwrites any previously armed timer — only the
/// most recent press counts, mirroring the iOS UITextField behavior
/// where re-tapping during a press cancels the previous long-press.
pub fn arm_long_press_timer(
    anchor_x: f32,
    anchor_y: f32,
    bounds_height: f32,
    on_fire: Option<Box<dyn Fn() + Send + Sync>>,
) {
    if let Ok(mut slot) = LONG_PRESS_ARM.lock() {
        *slot = Some(LongPressArm {
            deadline_ms: elapsed_ms() + LONG_PRESS_DURATION_MS,
            anchor_x,
            anchor_y,
            start_x: anchor_x,
            start_y: anchor_y,
            bounds_height,
            on_fire,
        });
    }
}

/// Cancel any armed long-press timer.
///
/// Called from a text-editable widget's `on_mouse_up` handler and
/// from `on_drag` when the finger moves more than
/// `LONG_PRESS_MAX_DRIFT_PX` from the original position. Idempotent
/// — clearing an already-empty slot is a no-op.
pub fn cancel_long_press_timer() {
    if let Ok(mut slot) = LONG_PRESS_ARM.lock() {
        *slot = None;
    }
}

/// Returns `true` if a long-press timer is currently armed and waiting
/// to fire. Used by `IOSRenderContext::needs_render` to keep the frame
/// loop ticking while the user holds a text input — without this, no
/// events would come in during the hold and the deadline poll would
/// never run.
pub fn is_long_press_armed() -> bool {
    LONG_PRESS_ARM
        .lock()
        .map(|slot| slot.is_some())
        .unwrap_or(false)
}

/// Check whether an active drag has exceeded the movement budget for
/// the armed long-press, cancelling it if so. Called from `on_drag`
/// before the cursor-move logic so a small finger jitter doesn't
/// kill a still-valid long press.
pub fn check_long_press_drift(current_x: f32, current_y: f32) {
    if let Ok(mut slot) = LONG_PRESS_ARM.lock() {
        if let Some(arm) = slot.as_ref() {
            let dx = (current_x - arm.start_x).abs();
            let dy = (current_y - arm.start_y).abs();
            if dx > LONG_PRESS_MAX_DRIFT_PX || dy > LONG_PRESS_MAX_DRIFT_PX {
                *slot = None;
            }
        }
    }
}

/// Poll: if a long-press is armed and the deadline has elapsed, fire
/// `show_edit_menu` with the PASTE bit set and clear the timer.
///
/// Returns `true` if the timer fired (so the runner can request a
/// redraw), `false` otherwise. Called from the platform runner's
/// frame loop on every tick — for iOS this lives in
/// `blinc_build_frame`, for Android it lives in the `android_main`
/// poll loop.
pub fn fire_long_press_timer_if_due() -> bool {
    let arm = if let Ok(mut slot) = LONG_PRESS_ARM.lock() {
        if let Some(arm) = slot.as_ref() {
            if elapsed_ms() >= arm.deadline_ms {
                slot.take()
            } else {
                None
            }
        } else {
            None
        }
    } else {
        None
    };

    if let Some(arm) = arm {
        // Long press fired. Run the widget-supplied pre-show
        // callback first so the focused editable can update its
        // selection state to match the iOS UITextField /
        // Android EditText UX of selecting the word under the
        // finger on a long press (mirroring double-tap). The
        // callback is registered at arm time and captures an
        // `Arc` to the widget's data + a stateful refresh handle.
        if let Some(cb) = arm.on_fire.as_ref() {
            cb();
        }
        // Then show the paste menu. We expose CUT / COPY too so
        // the user can still cut/copy the just-selected word.
        // SELECT_ALL is also useful from a long press. The bridge
        // will dim items the field reports as unavailable.
        use crate::widgets::text_edit::edit_menu_actions;
        crate::widgets::text_edit::haptic_impact_light();
        crate::widgets::text_edit::show_edit_menu(
            arm.anchor_x,
            arm.anchor_y,
            arm.anchor_x,
            arm.anchor_y,
            0.0,
            arm.bounds_height,
            edit_menu_actions::PASTE
                | edit_menu_actions::SELECT_ALL
                | edit_menu_actions::COPY
                | edit_menu_actions::CUT,
        );
        true
    } else {
        false
    }
}

static NEEDS_REBUILD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static NEEDS_RELAYOUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static NEEDS_CSS_REPARSE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static NEEDS_CONTINUOUS_REDRAW: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);
static FOCUSED_TEXT_INPUT: Mutex<Option<Weak<Mutex<TextInputData>>>> = Mutex::new(None);
static FOCUSED_TEXT_AREA: Mutex<Option<Weak<Mutex<crate::widgets::text_area::TextAreaState>>>> =
    Mutex::new(None);

/// Callback for setting continuous redraw on the animation scheduler
/// This is set by the windowed app to bridge text widgets with the animation system
#[allow(clippy::type_complexity)]
static CONTINUOUS_REDRAW_CALLBACK: Mutex<Option<Box<dyn Fn(bool) + Send + Sync>>> =
    Mutex::new(None);

/// Tracks whether the soft keyboard should be visible on mobile platforms.
/// Set to `true` when the first text widget gains focus, `false` when all lose focus.
/// Polled by the platform runner (android.rs / ios.rs) in the frame loop.
static KEYBOARD_SHOULD_SHOW: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);
/// Set when keyboard visibility state changes and needs platform action.
static KEYBOARD_STATE_CHANGED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// Set the callback for continuous redraw requests
///
/// This should be called once during app initialization to connect
/// text widget focus tracking with the animation scheduler.
pub fn set_continuous_redraw_callback<F>(callback: F)
where
    F: Fn(bool) + Send + Sync + 'static,
{
    let mut guard = CONTINUOUS_REDRAW_CALLBACK.lock().unwrap();
    *guard = Some(Box::new(callback));
}

/// Internal function to notify animation scheduler about cursor animation needs
fn notify_continuous_redraw(enabled: bool) {
    if let Ok(guard) = CONTINUOUS_REDRAW_CALLBACK.lock() {
        if let Some(ref callback) = *guard {
            callback(enabled);
        }
    }
}

/// Internal function to flag that the soft keyboard visibility should change.
/// The platform runner polls this via `take_keyboard_state_change()`.
fn notify_keyboard_visibility(show: bool) {
    KEYBOARD_SHOULD_SHOW.store(show, Ordering::SeqCst);
    KEYBOARD_STATE_CHANGED.store(true, Ordering::SeqCst);
}

/// Check if the keyboard visibility state changed and needs platform action.
/// Returns `Some(true)` = show keyboard, `Some(false)` = hide keyboard, `None` = no change.
/// The flag is consumed (cleared) on read.
pub fn take_keyboard_state_change() -> Option<bool> {
    if KEYBOARD_STATE_CHANGED.swap(false, Ordering::SeqCst) {
        Some(KEYBOARD_SHOULD_SHOW.load(Ordering::SeqCst))
    } else {
        None
    }
}

pub fn has_focused_text_input() -> bool {
    GLOBAL_FOCUS_COUNT.load(Ordering::Relaxed) > 0
}

/// Get the current text-input tap generation counter.
///
/// Increments on every tap that lands on a text input or text area
/// `on_mouse_down` handler, regardless of whether the focus state
/// actually transitioned. Mobile platform runners use this as a more
/// reliable "user just tapped an input" signal than
/// [`take_keyboard_state_change`], which only fires on transitions
/// of the global focus count and misses re-taps of an already-focused
/// input.
///
/// The runner pattern is:
/// ```ignore
/// let gen = focus_tap_generation();
/// if gen != last_seen_gen {
///     last_seen_gen = gen;
///     tree.scroll_focused_text_input_above_keyboard(viewport_h, inset);
/// }
/// ```
pub fn focus_tap_generation() -> u64 {
    FOCUS_TAP_GENERATION.load(Ordering::Relaxed)
}

/// Bump the tap generation counter.
///
/// Called by text-editable widgets (`text_input`, `text_area`,
/// `code_editor`, `rich_text_editor`) from their `on_mouse_down`
/// handlers, after they've confirmed the tap landed on the widget
/// (passes the disabled / pointer_events check). Mobile runners poll
/// this via [`focus_tap_generation`] to drive scroll-into-view on
/// re-taps and cross-input focus swaps.
pub fn bump_focus_tap_generation() {
    FOCUS_TAP_GENERATION.fetch_add(1, Ordering::Relaxed);
}

/// Register a text-editable widget's `LayoutNodeId` as the currently
/// focused editable, optionally with a blur callback.
///
/// Called by widgets that don't fit the dedicated `text_input` /
/// `text_area` focus trackers (`code_editor`, `rich_text_editor`).
/// Pass `node_id` from the widget's `on_mouse_down` handler so the
/// scroll-into-view helper knows which node to keep above the
/// soft keyboard.
///
/// `blur_callback`, if `Some`, is invoked from
/// [`blur_all_text_inputs`] when the user taps outside any editable
/// widget. It should clear the widget's local `focused` flag, call
/// [`decrement_focus_count`] (so the soft keyboard hides), and
/// release any cursor-tick callbacks the widget held. Widgets that
/// have their own `on_event(BLUR)` handling can pass `None` and
/// rely on that path instead.
pub fn set_focused_editable_node(
    node_id: LayoutNodeId,
    blur_callback: Option<Box<dyn Fn() + Send + Sync>>,
) {
    FOCUSED_EDITABLE_NODE_ID.store(node_id.to_raw(), Ordering::Relaxed);
    if let Ok(mut slot) = FOCUSED_EDITABLE_BLUR_CALLBACK.lock() {
        *slot = blur_callback;
    }
}

/// Clear the focused-editable node id and drop any registered blur
/// callback. See [`set_focused_editable_node`].
///
/// Also dismisses any open native edit menu (Cut / Copy / Paste /
/// Select All) and cancels any armed long-press timer. The edit
/// menu is anchored to the focused widget — leaving it visible
/// after focus moves away would let the user pick Cut / Copy / etc.
/// against the wrong (now-unfocused) input. Cancelling the
/// long-press is the same logic: a timer that fires while no
/// editable is focused would pop a menu against a stale anchor.
pub fn clear_focused_editable_node() {
    FOCUSED_EDITABLE_NODE_ID.store(0, Ordering::Relaxed);
    if let Ok(mut slot) = FOCUSED_EDITABLE_BLUR_CALLBACK.lock() {
        *slot = None;
    }
    crate::widgets::text_edit::hide_edit_menu();
    cancel_long_press_timer();
}

/// Get the LayoutNodeId of the currently focused generic editable widget,
/// if any. Used by the mobile-runner scroll-into-view helper as a fallback
/// when the typed `focused_text_input_node_id` / `focused_text_area_node_id`
/// lookups return `None` (e.g. for `code_editor` and `rich_text_editor`).
pub fn focused_editable_node_id() -> Option<LayoutNodeId> {
    let raw = FOCUSED_EDITABLE_NODE_ID.load(Ordering::Relaxed);
    if raw == 0 {
        None
    } else {
        Some(LayoutNodeId::from_raw(raw))
    }
}

/// Set whether the most recent pointer input came from a touchscreen.
///
/// Called by platform runners on every input event so editable widgets
/// can branch on input source: mouse drags extend selections, touch
/// drags move the cursor with haptic feedback. Pass `true` from
/// `TouchPhase::Began` / `MotionAction::Down` (mobile), and `false`
/// from desktop / web `mouse_down` paths.
///
/// The flag is sticky between events — calling once per input event
/// is enough; the widget consults it during the same frame's event
/// dispatch.
pub fn set_touch_input(is_touch: bool) {
    INPUT_SOURCE_IS_TOUCH.store(is_touch, Ordering::Relaxed);
}

/// Returns true if the most recent pointer event came from a
/// touchscreen. See [`set_touch_input`] for the contract.
pub fn is_touch_input() -> bool {
    INPUT_SOURCE_IS_TOUCH.load(Ordering::Relaxed)
}

pub fn take_needs_continuous_redraw() -> bool {
    NEEDS_CONTINUOUS_REDRAW.swap(false, Ordering::SeqCst)
}

fn request_continuous_redraw() {
    if has_focused_text_input() {
        NEEDS_CONTINUOUS_REDRAW.store(true, Ordering::SeqCst);
    }
}

pub fn request_continuous_redraw_pub() {
    request_continuous_redraw();
}

pub fn take_needs_rebuild() -> bool {
    NEEDS_REBUILD.swap(false, Ordering::SeqCst)
}

pub fn request_rebuild() {
    NEEDS_REBUILD.store(true, Ordering::SeqCst);
}

/// Check and clear the relayout flag
pub fn take_needs_relayout() -> bool {
    NEEDS_RELAYOUT.swap(false, Ordering::SeqCst)
}

/// Request a full rebuild with relayout
///
/// This triggers all three phases:
/// 1. Tree rebuild - UI tree is reconstructed from builder functions
/// 2. Layout recompute - Flexbox layout is recalculated
/// 3. Visual redraw - Frame is rendered
///
/// Use this for theme changes or other global state that affects the entire UI.
pub fn request_full_rebuild() {
    NEEDS_REBUILD.store(true, Ordering::SeqCst);
    NEEDS_RELAYOUT.store(true, Ordering::SeqCst);
    // Also trigger stateful redraw to ensure visual updates
    crate::stateful::request_redraw();
}

/// Check and clear the CSS reparse flag
pub fn take_needs_css_reparse() -> bool {
    NEEDS_CSS_REPARSE.swap(false, Ordering::SeqCst)
}

/// Request CSS stylesheet reparsing (e.g., after theme color scheme change)
pub fn request_css_reparse() {
    NEEDS_CSS_REPARSE.store(true, Ordering::SeqCst);
}

pub fn increment_focus_count() {
    let prev = GLOBAL_FOCUS_COUNT.fetch_add(1, Ordering::Relaxed);
    // If this is the first focused text widget, enable continuous redraw for cursor animation
    // and show the soft keyboard on mobile platforms
    if prev == 0 {
        notify_continuous_redraw(true);
        notify_keyboard_visibility(true);
    }
}

pub fn decrement_focus_count() {
    let prev = GLOBAL_FOCUS_COUNT.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
        Some(v.saturating_sub(1))
    });
    // If no more focused text widgets, disable continuous redraw
    // and hide the soft keyboard on mobile platforms
    if let Ok(prev_val) = prev {
        if prev_val == 1 {
            notify_continuous_redraw(false);
            notify_keyboard_visibility(false);
        }
    }
}

pub(crate) fn set_focused_text_input(state: &SharedTextInputData) {
    use blinc_core::events::event_types;

    let mut focused = FOCUSED_TEXT_INPUT.lock().unwrap();

    if let Some(weak) = focused.take() {
        if let Some(prev_state) = weak.upgrade() {
            if !Arc::ptr_eq(&prev_state, state) {
                if let Ok(mut s) = prev_state.lock() {
                    if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                        s.visual = new_state;
                        decrement_focus_count();
                    }
                }
            }
        }
    }

    blur_focused_text_area();
    *focused = Some(Arc::downgrade(state));
}

pub(crate) fn clear_focused_text_input(state: &SharedTextInputData) {
    let mut focused = FOCUSED_TEXT_INPUT.lock().unwrap();
    if let Some(weak) = focused.as_ref() {
        if let Some(prev_state) = weak.upgrade() {
            if Arc::ptr_eq(&prev_state, state) {
                *focused = None;
            }
        }
    }
}

pub(crate) fn set_focused_text_area(state: &crate::widgets::text_area::SharedTextAreaState) {
    use blinc_core::events::event_types;

    {
        let mut focused = FOCUSED_TEXT_INPUT.lock().unwrap();
        if let Some(weak) = focused.take() {
            if let Some(prev_state) = weak.upgrade() {
                if let Ok(mut s) = prev_state.lock() {
                    if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                        s.visual = new_state;
                        decrement_focus_count();
                    }
                }
            }
        }
    }

    {
        let mut focused = FOCUSED_TEXT_AREA.lock().unwrap();
        if let Some(weak) = focused.take() {
            if let Some(prev_state) = weak.upgrade() {
                if !Arc::ptr_eq(&prev_state, state) {
                    if let Ok(mut s) = prev_state.lock() {
                        if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                            s.visual = new_state;
                            decrement_focus_count();
                        }
                    }
                }
            }
        }
        *focused = Some(Arc::downgrade(state));
    }
}

pub(crate) fn clear_focused_text_area(state: &crate::widgets::text_area::SharedTextAreaState) {
    let mut focused = FOCUSED_TEXT_AREA.lock().unwrap();
    if let Some(weak) = focused.as_ref() {
        if let Some(prev_state) = weak.upgrade() {
            if Arc::ptr_eq(&prev_state, state) {
                *focused = None;
            }
        }
    }
}

fn blur_focused_text_area() {
    use blinc_core::events::event_types;

    let mut focused = FOCUSED_TEXT_AREA.lock().unwrap();
    if let Some(weak) = focused.take() {
        if let Some(prev_state) = weak.upgrade() {
            if let Ok(mut s) = prev_state.lock() {
                if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                    s.visual = new_state;
                    decrement_focus_count();
                }
            }
        }
    }
}

/// Blur all focused text inputs and text areas.
/// Called when clicking outside any text element.
pub fn blur_all_text_inputs() {
    use crate::stateful::refresh_stateful;
    use blinc_core::events::event_types;

    // Run any registered generic-editable blur callback first so
    // widgets that don't fit the typed `text_input` / `text_area`
    // trackers (`code_editor`, `rich_text_editor`) get their local
    // `focused = false` and matching `decrement_focus_count` call
    // when the user taps outside. The callback is taken out of the
    // slot before invocation so a re-entrant blur can't run it
    // twice. After running, `clear_focused_editable_node` zeroes the
    // node id so the scroll-into-view helper doesn't reach for a
    // stale entry on the next frame.
    let editable_blur = {
        if let Ok(mut slot) = FOCUSED_EDITABLE_BLUR_CALLBACK.lock() {
            slot.take()
        } else {
            None
        }
    };
    if let Some(cb) = editable_blur {
        cb();
    }
    clear_focused_editable_node();

    // Blur focused TextInput
    {
        let mut focused = FOCUSED_TEXT_INPUT.lock().unwrap();
        if let Some(weak) = focused.take() {
            if let Some(state) = weak.upgrade() {
                if let Ok(mut s) = state.lock() {
                    if s.visual.is_focused() {
                        if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                            s.visual = new_state;
                            decrement_focus_count();
                        }
                        // Also update the FSM state to keep in sync
                        let stateful_ref = s.stateful_state.clone();
                        if let Some(ref stateful) = stateful_ref {
                            if let Ok(mut shared) = stateful.lock() {
                                if let Some(new_fsm) = shared.state.on_event(event_types::BLUR) {
                                    shared.state = new_fsm;
                                    shared.needs_visual_update = true;
                                }
                            }
                        }
                        // Trigger visual refresh after releasing the data lock
                        drop(s);
                        if let Some(ref stateful) = stateful_ref {
                            refresh_stateful(stateful);
                        }
                    }
                }
            }
        }
    }

    // Blur focused TextArea
    {
        let mut focused = FOCUSED_TEXT_AREA.lock().unwrap();
        if let Some(weak) = focused.take() {
            if let Some(state) = weak.upgrade() {
                if let Ok(mut s) = state.lock() {
                    if s.visual.is_focused() {
                        if let Some(new_state) = s.visual.on_event(event_types::BLUR) {
                            s.visual = new_state;
                            decrement_focus_count();
                        }
                        // Also update the FSM state to keep in sync
                        let stateful_ref = s.stateful_state.clone();
                        if let Some(ref stateful) = stateful_ref {
                            if let Ok(mut shared) = stateful.lock() {
                                if let Some(new_fsm) = shared.state.on_event(event_types::BLUR) {
                                    shared.state = new_fsm;
                                    shared.needs_visual_update = true;
                                }
                            }
                        }
                        // Trigger visual refresh after releasing the data lock
                        drop(s);
                        if let Some(ref stateful) = stateful_ref {
                            refresh_stateful(stateful);
                        }
                    }
                }
            }
        }
    }
}

/// Get the layout node ID of the currently focused TextInput, if any.
///
/// This allows the CSS styling system to bridge TextInput focus state
/// to the EventRouter, enabling `:focus` pseudo-class matching.
pub fn focused_text_input_node_id() -> Option<LayoutNodeId> {
    let focused = FOCUSED_TEXT_INPUT.lock().ok()?;
    let weak = focused.as_ref()?;
    let data = weak.upgrade()?;
    let guard = data.lock().ok()?;
    let stateful = guard.stateful_state.as_ref()?;
    let shared = stateful.lock().ok()?;
    shared.node_id
}

/// Get the layout node ID of the currently focused TextArea, if any.
///
/// This allows the CSS styling system to bridge TextArea focus state
/// to the EventRouter, enabling `:focus` pseudo-class matching.
pub fn focused_text_area_node_id() -> Option<LayoutNodeId> {
    let focused = FOCUSED_TEXT_AREA.lock().ok()?;
    let weak = focused.as_ref()?;
    let data = weak.upgrade()?;
    let guard = data.lock().ok()?;
    let stateful = guard.stateful_state.as_ref()?;
    let shared = stateful.lock().ok()?;
    shared.node_id
}

// =============================================================================
// Input Types and Validation
// =============================================================================

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InputType {
    #[default]
    Text,
    Number,
    Integer,
    Email,
    Password,
    Url,
    Tel,
    Search,
}

#[derive(Clone, Debug, Default)]
pub struct InputConstraints {
    pub min_length: Option<usize>,
    pub max_length: Option<usize>,
    pub min_value: Option<f64>,
    pub max_value: Option<f64>,
    pub pattern: Option<String>,
    pub required: bool,
}

impl InputConstraints {
    pub fn max_length(max: usize) -> Self {
        Self {
            max_length: Some(max),
            ..Default::default()
        }
    }

    pub fn required() -> Self {
        Self {
            required: true,
            ..Default::default()
        }
    }

    pub fn number_range(min: f64, max: f64) -> Self {
        Self {
            min_value: Some(min),
            max_value: Some(max),
            ..Default::default()
        }
    }
}

// =============================================================================
// TextInputData - the external state that persists across rebuilds
// =============================================================================

/// Shared text input data handle
pub type SharedTextInputData = Arc<Mutex<TextInputData>>;

/// Text input data (content, cursor, validation)
///
/// This is the EXTERNAL state that persists across rebuilds.
/// Visual state (hover/focus) is managed by the Stateful FSM.
#[derive(Clone)]
pub struct TextInputData {
    pub value: String,
    pub cursor: usize,
    pub selection_start: Option<usize>,
    pub placeholder: String,
    pub input_type: InputType,
    pub constraints: InputConstraints,
    pub disabled: bool,
    pub masked: bool,
    pub is_valid: bool,
    pub visual: TextFieldState,
    pub focus_time_ms: u64,
    pub cursor_state: SharedCursorState,
    /// Horizontal scroll offset for text that exceeds the input width
    pub scroll_offset_x: f32,
    /// Computed width of the text input (set after layout, used for scroll calculations)
    /// This is updated when the layout is computed and allows proper scroll behavior
    /// even when `use_full_width` is true.
    pub computed_width: Option<f32>,
    /// Layout bounds storage - updated after each layout computation
    /// Used to get the actual computed width for proper scroll behavior
    pub layout_bounds_storage: crate::renderer::LayoutBoundsStorage,
    /// Reference to the Stateful's shared state for triggering incremental updates
    pub(crate) stateful_state: Option<SharedState<TextFieldState>>,
    /// Callback invoked when text value changes
    pub(crate) on_change_callback: Option<OnChangeCallback>,
    /// CSS element ID for stylesheet matching (set via TextInput::id())
    pub(crate) css_element_id: Option<String>,
    /// CSS class names for stylesheet matching (set via TextInput::class())
    pub(crate) css_classes: Vec<String>,
    /// Last click timestamp for double-click detection
    pub(crate) last_click_time: Option<web_time::Instant>,
    /// Anchor position for drag-to-select
    pub(crate) drag_select_anchor: Option<usize>,
    /// Undo history. Each entry snapshots `(value, cursor, selection_start)`
    /// captured immediately BEFORE a text-mutating operation runs (insert,
    /// delete_*). Cmd+Z pops from this stack onto the redo stack and
    /// restores the popped entry. Capped at [`UNDO_HISTORY_MAX`] entries
    /// — older entries are dropped from the front when the cap is hit.
    pub(crate) undo_stack: Vec<UndoEntry>,
    /// Redo history. Populated by [`Self::undo`] (and cleared by any new
    /// edit since a fresh edit starts a new branch in the history). Cmd+Shift+Z
    /// (or Cmd+Y) pops from this stack onto the undo stack.
    pub(crate) redo_stack: Vec<UndoEntry>,
}

/// One snapshot in the undo / redo history. Stores the full pre-edit
/// state of the text input. We snapshot the entire `value` rather than
/// a diff because the typical input field is short enough that the
/// memory cost is negligible (a 100-entry stack of 80-char strings is
/// ~8 KB).
#[derive(Clone, Debug)]
pub struct UndoEntry {
    pub value: String,
    pub cursor: usize,
    pub selection_start: Option<usize>,
}

/// Maximum number of entries kept in the undo / redo stacks. Once
/// exceeded, the oldest entry is dropped from the front to make room.
const UNDO_HISTORY_MAX: usize = 100;

impl std::fmt::Debug for TextInputData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextInputData")
            .field("value", &self.value)
            .field("cursor", &self.cursor)
            .field("selection_start", &self.selection_start)
            .field("placeholder", &self.placeholder)
            .field("input_type", &self.input_type)
            .field("constraints", &self.constraints)
            .field("disabled", &self.disabled)
            .field("masked", &self.masked)
            .field("is_valid", &self.is_valid)
            .field("visual", &self.visual)
            .field("focus_time_ms", &self.focus_time_ms)
            // Skip stateful_state since StatefulInner doesn't implement Debug
            .finish()
    }
}

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

impl TextInputData {
    pub fn new() -> Self {
        Self {
            value: String::new(),
            cursor: 0,
            selection_start: None,
            placeholder: String::new(),
            input_type: InputType::Text,
            constraints: InputConstraints::default(),
            disabled: false,
            masked: false,
            is_valid: true,
            visual: TextFieldState::Idle,
            focus_time_ms: 0,
            cursor_state: cursor_state(),
            scroll_offset_x: 0.0,
            computed_width: None,
            layout_bounds_storage: Arc::new(Mutex::new(None)),
            stateful_state: None,
            on_change_callback: None,
            css_element_id: None,
            css_classes: Vec::new(),
            last_click_time: None,
            drag_select_anchor: None,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
        }
    }

    /// Snapshot the current `(value, cursor, selection_start)` triple
    /// onto the undo stack and clear the redo stack. Called from inside
    /// the text-mutating helpers BEFORE they apply their change so the
    /// snapshot represents the pre-edit state.
    ///
    /// New edits invalidate the redo branch — once you type something
    /// after an undo, the path you undid is no longer reachable.
    pub(crate) fn push_undo(&mut self) {
        self.undo_stack.push(UndoEntry {
            value: self.value.clone(),
            cursor: self.cursor,
            selection_start: self.selection_start,
        });
        if self.undo_stack.len() > UNDO_HISTORY_MAX {
            self.undo_stack.remove(0);
        }
        self.redo_stack.clear();
    }

    /// Pop the most recent undo entry, push the current state onto the
    /// redo stack, and restore the popped state. Returns `true` if any
    /// state was actually restored (i.e. the undo stack was non-empty).
    pub fn undo(&mut self) -> bool {
        let Some(entry) = self.undo_stack.pop() else {
            return false;
        };
        self.redo_stack.push(UndoEntry {
            value: self.value.clone(),
            cursor: self.cursor,
            selection_start: self.selection_start,
        });
        if self.redo_stack.len() > UNDO_HISTORY_MAX {
            self.redo_stack.remove(0);
        }
        self.value = entry.value;
        self.cursor = entry.cursor;
        self.selection_start = entry.selection_start;
        true
    }

    /// Symmetric inverse of [`Self::undo`]. Returns `true` when the
    /// redo stack had something to apply.
    pub fn redo(&mut self) -> bool {
        let Some(entry) = self.redo_stack.pop() else {
            return false;
        };
        self.undo_stack.push(UndoEntry {
            value: self.value.clone(),
            cursor: self.cursor,
            selection_start: self.selection_start,
        });
        if self.undo_stack.len() > UNDO_HISTORY_MAX {
            self.undo_stack.remove(0);
        }
        self.value = entry.value;
        self.cursor = entry.cursor;
        self.selection_start = entry.selection_start;
        true
    }

    pub fn with_placeholder(placeholder: impl Into<String>) -> Self {
        Self {
            placeholder: placeholder.into(),
            ..Self::new()
        }
    }

    pub fn with_value(value: impl Into<String>) -> Self {
        let v: String = value.into();
        let cursor = v.chars().count();
        Self {
            value: v,
            cursor,
            ..Self::new()
        }
    }

    /// Get display text (masked for password, or actual value)
    pub fn display_text(&self) -> String {
        if self.masked {
            "•".repeat(self.value.chars().count())
        } else {
            self.value.clone()
        }
    }

    /// Insert text at cursor, respecting input type constraints
    pub fn insert(&mut self, text: &str) {
        // Snapshot for undo BEFORE the mutation. We snapshot
        // unconditionally even if the eventual `filtered` text turns
        // out empty (e.g. typing a non-digit into an InputType::Number)
        // because the cost is one no-op undo entry, and the
        // alternative — snapshotting after filtering — would mean the
        // undo history conflates "I typed nothing" with "I typed
        // something that got dropped", which is the wrong UX.
        self.push_undo();
        // Delete selection first if any
        if let Some(start) = self.selection_start {
            let (from, to) = if start < self.cursor {
                (start, self.cursor)
            } else {
                (self.cursor, start)
            };
            let before: String = self.value.chars().take(from).collect();
            let after: String = self.value.chars().skip(to).collect();
            self.value = before + &after;
            self.cursor = from;
            self.selection_start = None;
        }

        // Filter based on input type
        let filtered: String = match self.input_type {
            InputType::Number => text
                .chars()
                .filter(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
                .collect(),
            InputType::Integer => text
                .chars()
                .filter(|c| c.is_ascii_digit() || *c == '-')
                .collect(),
            InputType::Tel => text
                .chars()
                .filter(|c| c.is_ascii_digit() || *c == '+' || *c == '-' || *c == ' ')
                .collect(),
            _ => text.to_string(),
        };

        if filtered.is_empty() {
            return;
        }

        // Check max length
        if let Some(max) = self.constraints.max_length {
            if self.value.chars().count() + filtered.chars().count() > max {
                return;
            }
        }

        // Insert at cursor
        let before: String = self.value.chars().take(self.cursor).collect();
        let after: String = self.value.chars().skip(self.cursor).collect();
        self.value = before + &filtered + &after;
        self.cursor += filtered.chars().count();

        self.validate();
        // NOTE: Don't call trigger_content_refresh() here - caller must do it
        // after releasing the lock to avoid deadlock
    }

    pub fn delete_backward(&mut self) {
        // Snapshot for undo BEFORE the mutation. We always snapshot
        // even when there's nothing to delete (cursor at 0, no
        // selection) — the resulting no-op undo entry is harmless
        // and keeps the call sites simple.
        self.push_undo();
        if let Some(start) = self.selection_start {
            let (from, to) = if start < self.cursor {
                (start, self.cursor)
            } else {
                (self.cursor, start)
            };
            let before: String = self.value.chars().take(from).collect();
            let after: String = self.value.chars().skip(to).collect();
            self.value = before + &after;
            self.cursor = from;
            self.selection_start = None;
        } else if self.cursor > 0 {
            let before: String = self.value.chars().take(self.cursor - 1).collect();
            let after: String = self.value.chars().skip(self.cursor).collect();
            self.value = before + &after;
            self.cursor -= 1;
        }
        self.validate();
        // NOTE: Don't call trigger_content_refresh() here - caller must do it
        // after releasing the lock to avoid deadlock
    }

    pub fn delete_forward(&mut self) {
        self.push_undo();
        if let Some(start) = self.selection_start {
            let (from, to) = if start < self.cursor {
                (start, self.cursor)
            } else {
                (self.cursor, start)
            };
            let before: String = self.value.chars().take(from).collect();
            let after: String = self.value.chars().skip(to).collect();
            self.value = before + &after;
            self.cursor = from;
            self.selection_start = None;
        } else if self.cursor < self.value.chars().count() {
            let before: String = self.value.chars().take(self.cursor).collect();
            let after: String = self.value.chars().skip(self.cursor + 1).collect();
            self.value = before + &after;
        }
        self.validate();
        // NOTE: Don't call trigger_content_refresh() here - caller must do it
        // after releasing the lock to avoid deadlock
    }

    pub fn move_left(&mut self, shift: bool) {
        if shift {
            if self.selection_start.is_none() {
                self.selection_start = Some(self.cursor);
            }
        } else {
            self.selection_start = None;
        }
        if self.cursor > 0 {
            self.cursor -= 1;
        }
    }

    pub fn move_right(&mut self, shift: bool) {
        if shift {
            if self.selection_start.is_none() {
                self.selection_start = Some(self.cursor);
            }
        } else {
            self.selection_start = None;
        }
        if self.cursor < self.value.chars().count() {
            self.cursor += 1;
        }
    }

    pub fn move_to_start(&mut self, shift: bool) {
        if shift {
            if self.selection_start.is_none() {
                self.selection_start = Some(self.cursor);
            }
        } else {
            self.selection_start = None;
        }
        self.cursor = 0;
    }

    pub fn move_to_end(&mut self, shift: bool) {
        if shift {
            if self.selection_start.is_none() {
                self.selection_start = Some(self.cursor);
            }
        } else {
            self.selection_start = None;
        }
        self.cursor = self.value.chars().count();
    }

    pub fn select_all(&mut self) {
        self.selection_start = Some(0);
        self.cursor = self.value.chars().count();
    }

    pub fn selected_text(&self) -> Option<String> {
        self.selection_start.map(|start| {
            let (from, to) = if start < self.cursor {
                (start, self.cursor)
            } else {
                (self.cursor, start)
            };
            self.value.chars().skip(from).take(to - from).collect()
        })
    }

    /// Move cursor to the previous word boundary
    pub fn move_word_left(&mut self, shift: bool) {
        if shift && self.selection_start.is_none() {
            self.selection_start = Some(self.cursor);
        } else if !shift {
            self.selection_start = None;
        }
        self.cursor = crate::widgets::text_edit::word_boundary_left(&self.value, self.cursor);
    }

    /// Move cursor to the next word boundary
    pub fn move_word_right(&mut self, shift: bool) {
        if shift && self.selection_start.is_none() {
            self.selection_start = Some(self.cursor);
        } else if !shift {
            self.selection_start = None;
        }
        self.cursor = crate::widgets::text_edit::word_boundary_right(&self.value, self.cursor);
    }

    /// Delete from cursor to the previous word boundary
    pub fn delete_word_backward(&mut self) {
        // Push BEFORE the early-return delete_selection branch so we
        // don't end up with the selection-delete branch double-pushing
        // (delete_selection also pushes its own undo). Take the
        // selection-delete fast path WITHOUT pushing here, then bail.
        if self.selection_start.is_some() {
            self.delete_selection();
            return;
        }
        self.push_undo();
        let target = crate::widgets::text_edit::word_boundary_left(&self.value, self.cursor);
        if target < self.cursor {
            let byte_start = self
                .value
                .char_indices()
                .nth(target)
                .map(|(i, _)| i)
                .unwrap_or(0);
            let byte_end = self
                .value
                .char_indices()
                .nth(self.cursor)
                .map(|(i, _)| i)
                .unwrap_or(self.value.len());
            self.value = format!("{}{}", &self.value[..byte_start], &self.value[byte_end..]);
            self.cursor = target;
        }
    }

    /// Delete from cursor to the next word boundary
    pub fn delete_word_forward(&mut self) {
        if self.selection_start.is_some() {
            self.delete_selection();
            return;
        }
        self.push_undo();
        let target = crate::widgets::text_edit::word_boundary_right(&self.value, self.cursor);
        if target > self.cursor {
            let byte_start = self
                .value
                .char_indices()
                .nth(self.cursor)
                .map(|(i, _)| i)
                .unwrap_or(self.value.len());
            let byte_end = self
                .value
                .char_indices()
                .nth(target)
                .map(|(i, _)| i)
                .unwrap_or(self.value.len());
            self.value = format!("{}{}", &self.value[..byte_start], &self.value[byte_end..]);
        }
    }

    /// Delete the current selection, returning true if text changed
    pub fn delete_selection(&mut self) -> bool {
        if self.selection_start.is_none() {
            return false;
        }
        // Snapshot before mutating, but only if there's actually a
        // selection to delete. Calling `push_undo` for a no-op delete
        // would otherwise pollute the history with empty entries.
        self.push_undo();
        let start = self.selection_start.take().expect("checked above");
        let (from, to) = if start < self.cursor {
            (start, self.cursor)
        } else {
            (self.cursor, start)
        };
        let byte_from = self
            .value
            .char_indices()
            .nth(from)
            .map(|(i, _)| i)
            .unwrap_or(0);
        let byte_to = self
            .value
            .char_indices()
            .nth(to)
            .map(|(i, _)| i)
            .unwrap_or(self.value.len());
        self.value = format!("{}{}", &self.value[..byte_from], &self.value[byte_to..]);
        self.cursor = from;
        true
    }

    pub fn validate(&mut self) {
        self.is_valid = match self.input_type {
            InputType::Email => {
                self.value.is_empty() || (self.value.contains('@') && self.value.contains('.'))
            }
            InputType::Number => self.value.is_empty() || self.value.parse::<f64>().is_ok(),
            InputType::Integer => self.value.is_empty() || self.value.parse::<i64>().is_ok(),
            InputType::Url => {
                self.value.is_empty()
                    || self.value.starts_with("http://")
                    || self.value.starts_with("https://")
            }
            _ => true,
        };

        if self.constraints.required && self.value.is_empty() {
            self.is_valid = false;
        }

        if let Some(min) = self.constraints.min_length {
            if self.value.len() < min {
                self.is_valid = false;
            }
        }
    }

    pub fn reset_cursor_blink(&mut self) {
        if let Ok(mut cs) = self.cursor_state.lock() {
            cs.reset_blink();
        }
    }

    pub fn sync_global_selection(&self) {
        if let Some(start) = self.selection_start {
            if start != self.cursor {
                let (from, to) = if start < self.cursor {
                    (start, self.cursor)
                } else {
                    (self.cursor, start)
                };
                let selected: String = self.value.chars().skip(from).take(to - from).collect();
                set_selection(selected, SelectionSource::TextInput, true);
            } else {
                clear_selection();
            }
        } else {
            clear_selection();
        }
    }

    /// Calculate cursor position from x coordinate (relative to text content area)
    ///
    /// This is used for click-to-position cursor functionality.
    /// The x coordinate should be relative to the start of the text content (after padding).
    pub fn cursor_position_from_x(&self, x: f32, font_size: f32) -> usize {
        let display = self.display_text();
        if display.is_empty() {
            return 0;
        }

        // Account for scroll offset - the click x is in viewport space,
        // so add scroll_offset to get position in text space
        let text_x = x + self.scroll_offset_x;

        // Binary search would be more efficient, but for typical text input lengths,
        // linear search is fast enough
        let char_count = display.chars().count();
        let mut best_pos = 0;
        let mut min_dist = f32::MAX;

        // Check position before each character and after the last
        for i in 0..=char_count {
            let prefix: String = display.chars().take(i).collect();
            let prefix_width = crate::text_measure::measure_text(&prefix, font_size).width;

            let dist = (prefix_width - text_x).abs();
            if dist < min_dist {
                min_dist = dist;
                best_pos = i;
            }
        }

        best_pos
    }

    /// Ensure the cursor is visible by adjusting horizontal scroll offset.
    /// This implements HTML-like behavior where text scrolls left when typing
    /// extends beyond the visible width.
    pub fn ensure_cursor_visible(&mut self, config: &TextInputConfig) {
        // Try to get computed width from layout bounds storage first
        // This is updated after each layout computation
        let layout_width = self
            .layout_bounds_storage
            .lock()
            .ok()
            .and_then(|guard| guard.as_ref().map(|b| b.width));

        // Use layout width if available, otherwise fall back to stored computed_width
        let effective_computed_width = layout_width.or(self.computed_width);

        // For full-width inputs without computed bounds yet, don't scroll
        // This prevents incorrect scrolling before we have the real container width
        if config.use_full_width && effective_computed_width.is_none() {
            self.scroll_offset_x = 0.0;
            return;
        }

        // Calculate total text width
        let display = self.display_text();
        let total_text_width = if !display.is_empty() {
            crate::text_measure::measure_text(&display, config.font_size).width
        } else {
            0.0
        };

        // Calculate cursor x position (where cursor is in the full text)
        let cursor_x = if self.cursor > 0 && !display.is_empty() {
            let text_before: String = display.chars().take(self.cursor).collect();
            crate::text_measure::measure_text(&text_before, config.font_size).width
        } else {
            0.0
        };

        // Calculate available width for text (the visible viewport)
        // Use computed_width if available (set after layout), otherwise fall back to config.width
        // Account for padding on both sides and border
        let base_width = effective_computed_width.unwrap_or(config.width);
        let available_width = base_width - config.padding_x * 2.0 - config.border_width * 2.0;

        // Simple approach: measure if text exceeds viewport
        // If cursor is past the visible right edge, scroll to show cursor
        let visible_right = self.scroll_offset_x + available_width;
        let cursor_margin = 4.0; // Small margin so cursor isn't at the very edge

        if cursor_x > visible_right - cursor_margin {
            // Cursor is past the right edge - scroll right to show it
            self.scroll_offset_x = cursor_x - available_width + cursor_margin;
        } else if cursor_x < self.scroll_offset_x {
            // Cursor is past the left edge - scroll left to show it
            self.scroll_offset_x = cursor_x;
        }

        // Clamp: can't scroll past start, and don't scroll more than necessary
        self.scroll_offset_x = self.scroll_offset_x.max(0.0);

        // Also clamp max scroll so we don't scroll past the end of text
        let max_scroll = (total_text_width - available_width + cursor_margin).max(0.0);
        self.scroll_offset_x = self.scroll_offset_x.min(max_scroll);
    }
}

/// Create a shared text input data
pub fn text_input_data() -> SharedTextInputData {
    Arc::new(Mutex::new(TextInputData::new()))
}

/// Create a shared text input data with placeholder
pub fn text_input_data_with_placeholder(placeholder: impl Into<String>) -> SharedTextInputData {
    Arc::new(Mutex::new(TextInputData::with_placeholder(placeholder)))
}

// Backwards compatibility aliases
pub type TextInputState = TextInputData;
pub type SharedTextInputState = SharedTextInputData;

pub fn text_input_state() -> SharedTextInputData {
    text_input_data()
}

pub fn text_input_state_with_placeholder(placeholder: impl Into<String>) -> SharedTextInputData {
    text_input_data_with_placeholder(placeholder)
}

// =============================================================================
// CSS Override Resolution
// =============================================================================

/// Apply CSS stylesheet overrides to a TextInputConfig.
///
/// Resolves base styles, state-specific styles (:hover/:focus/:disabled),
/// and ::placeholder styles from the active stylesheet, then mutates the
/// config with any CSS-specified values.
fn apply_css_overrides(
    cfg: &mut TextInputConfig,
    stylesheet: &Stylesheet,
    element_id: Option<&str>,
    css_classes: &[String],
    visual: &TextFieldState,
) {
    // Determine the element state for state-specific lookups
    let state = match visual {
        TextFieldState::Hovered | TextFieldState::FocusedHovered => Some(ElementState::Hover),
        TextFieldState::Focused => Some(ElementState::Focus),
        TextFieldState::Disabled => Some(ElementState::Disabled),
        TextFieldState::Idle => None,
    };

    // 1. Apply class-based styles (lowest priority — overridden by ID)
    for class in css_classes {
        if let Some(base) = stylesheet.get_class(class) {
            apply_style_to_config(cfg, base, visual);
        }
        // For FocusedHovered, apply both :focus and :hover
        if matches!(visual, TextFieldState::FocusedHovered) {
            if let Some(s) = stylesheet.get_class_with_state(class, ElementState::Focus) {
                apply_style_to_config(cfg, s, visual);
            }
        }
        if let Some(s) = state {
            if let Some(state_style) = stylesheet.get_class_with_state(class, s) {
                apply_style_to_config(cfg, state_style, visual);
            }
        }
    }

    // 2. Apply ID-based styles (higher priority — overrides class)
    if let Some(element_id) = element_id {
        if let Some(base) = stylesheet.get(element_id) {
            apply_style_to_config(cfg, base, visual);
        }
        if matches!(visual, TextFieldState::FocusedHovered) {
            if let Some(focus_style) = stylesheet.get_with_state(element_id, ElementState::Focus) {
                apply_style_to_config(cfg, focus_style, visual);
            }
        }
        if let Some(s) = state {
            if let Some(state_style) = stylesheet.get_with_state(element_id, s) {
                apply_style_to_config(cfg, state_style, visual);
            }
        }

        // 3. Apply ::placeholder style (ID-only)
        if let Some(placeholder_style) = stylesheet.get_placeholder_style(element_id) {
            if let Some(color) = placeholder_style.text_color {
                cfg.placeholder_color = color;
            }
            if let Some(color) = placeholder_style.placeholder_color {
                cfg.placeholder_color = color;
            }
        }
    }
}

/// Apply an ElementStyle to a TextInputConfig (CSS properties override config values)
fn apply_style_to_config(
    cfg: &mut TextInputConfig,
    style: &crate::element_style::ElementStyle,
    visual: &TextFieldState,
) {
    // Background → applies to current state's bg color
    if let Some(ref bg) = style.background {
        let color = match bg {
            blinc_core::Brush::Solid(c) => *c,
            _ => return, // Gradients not supported for input bg
        };
        match visual {
            TextFieldState::Idle => cfg.bg_color = color,
            TextFieldState::Hovered => cfg.hover_bg_color = color,
            TextFieldState::Focused | TextFieldState::FocusedHovered => {
                cfg.focused_bg_color = color;
            }
            TextFieldState::Disabled => {} // Disabled bg is hardcoded
        }
    }

    // Border color
    if let Some(color) = style.border_color {
        match visual {
            TextFieldState::Idle => cfg.border_color = color,
            TextFieldState::Hovered => cfg.hover_border_color = color,
            TextFieldState::Focused | TextFieldState::FocusedHovered => {
                cfg.focused_border_color = color;
            }
            TextFieldState::Disabled => {}
        }
    }

    // Border width
    if let Some(w) = style.border_width {
        cfg.border_width = w;
    }

    // Corner radius
    if let Some(cr) = style.corner_radius {
        cfg.corner_radius = cr.top_left; // Use uniform radius
    }

    // Text color
    if let Some(color) = style.text_color {
        cfg.text_color = color;
    }

    // Font size
    if let Some(size) = style.font_size {
        cfg.font_size = size;
    }

    // Caret (cursor) color
    if let Some(color) = style.caret_color {
        cfg.cursor_color = color;
    }

    // Selection color
    if let Some(color) = style.selection_color {
        cfg.selection_color = color;
    }

    // Placeholder color
    if let Some(color) = style.placeholder_color {
        cfg.placeholder_color = color;
    }
}

/// Extract outline properties from stylesheet for the current state.
/// Returns (width, color, offset) if any outline is specified.
fn extract_outline_from_stylesheet(
    stylesheet: &Stylesheet,
    element_id: &str,
    visual: &TextFieldState,
) -> Option<(f32, Color, f32)> {
    let mut width = None;
    let mut color = None;
    let mut offset = None;

    // Check base style
    if let Some(base) = stylesheet.get(element_id) {
        if let Some(w) = base.outline_width {
            width = Some(w);
        }
        if let Some(c) = base.outline_color {
            color = Some(c);
        }
        if let Some(o) = base.outline_offset {
            offset = Some(o);
        }
    }

    // Layer state-specific style
    let state = match visual {
        TextFieldState::Hovered | TextFieldState::FocusedHovered => Some(ElementState::Hover),
        TextFieldState::Focused => Some(ElementState::Focus),
        TextFieldState::Disabled => Some(ElementState::Disabled),
        TextFieldState::Idle => None,
    };
    if matches!(visual, TextFieldState::FocusedHovered) {
        if let Some(focus_style) = stylesheet.get_with_state(element_id, ElementState::Focus) {
            if let Some(w) = focus_style.outline_width {
                width = Some(w);
            }
            if let Some(c) = focus_style.outline_color {
                color = Some(c);
            }
            if let Some(o) = focus_style.outline_offset {
                offset = Some(o);
            }
        }
    }
    if let Some(s) = state {
        if let Some(state_style) = stylesheet.get_with_state(element_id, s) {
            if let Some(w) = state_style.outline_width {
                width = Some(w);
            }
            if let Some(c) = state_style.outline_color {
                color = Some(c);
            }
            if let Some(o) = state_style.outline_offset {
                offset = Some(o);
            }
        }
    }

    // Only return if at least width is specified
    width.map(|w| {
        (
            w,
            color.unwrap_or(Color::rgba(0.23, 0.51, 0.97, 0.5)),
            offset.unwrap_or(0.0),
        )
    })
}

// =============================================================================
// TextInputConfig - visual configuration
// =============================================================================

#[derive(Clone, Debug)]
pub struct TextInputConfig {
    pub width: f32,
    pub height: f32,
    pub use_full_width: bool,
    pub font_size: f32,
    pub text_color: Color,
    pub placeholder_color: Color,
    pub bg_color: Color,
    pub hover_bg_color: Color,
    pub focused_bg_color: Color,
    pub border_color: Color,
    pub hover_border_color: Color,
    pub focused_border_color: Color,
    pub error_border_color: Color,
    pub cursor_color: Color,
    pub selection_color: Color,
    pub corner_radius: f32,
    pub border_width: f32,
    pub padding_x: f32,
    pub placeholder: String,
}

impl Default for TextInputConfig {
    fn default() -> Self {
        let theme = ThemeState::get();
        Self {
            width: 200.0,
            height: 44.0,
            use_full_width: false,
            font_size: 16.0,
            text_color: theme.color(ColorToken::TextPrimary),
            placeholder_color: theme.color(ColorToken::TextTertiary),
            bg_color: theme.color(ColorToken::InputBg),
            hover_bg_color: theme.color(ColorToken::InputBgHover),
            focused_bg_color: theme.color(ColorToken::InputBgFocus),
            border_color: theme.color(ColorToken::BorderSecondary),
            hover_border_color: theme.color(ColorToken::BorderHover),
            focused_border_color: theme.color(ColorToken::BorderFocus),
            error_border_color: theme.color(ColorToken::BorderError),
            cursor_color: theme.color(ColorToken::Accent),
            selection_color: theme.color(ColorToken::Selection),
            corner_radius: 8.0,
            border_width: 1.5,
            padding_x: 12.0,
            placeholder: String::new(),
        }
    }
}

// =============================================================================
// TextInput Widget
// =============================================================================

/// Callback type for on_change events
pub type OnChangeCallback = Arc<dyn Fn(&str) + Send + Sync>;

/// TextInput widget using FSM-driven Stateful for incremental updates
pub struct TextInput {
    inner: Stateful<TextFieldState>,
    data: SharedTextInputData,
    config: Arc<Mutex<TextInputConfig>>,
    /// Reference to the Stateful's shared state for wiring up to TextInputData
    stateful_state: SharedState<TextFieldState>,
    /// Callback invoked when text value changes
    on_change_callback: Option<OnChangeCallback>,
}

impl TextInput {
    /// Create a text input with externally-managed data state
    pub fn new(data: SharedTextInputData) -> Self {
        let config = Arc::new(Mutex::new(TextInputConfig::default()));

        // Get initial visual state and existing stateful_state from data
        let (initial_visual, existing_stateful_state) = {
            let d = data.lock().unwrap();
            (d.visual, d.stateful_state.clone())
        };

        // Reuse existing stateful_state if available, otherwise create new one
        // This ensures state persists across rebuilds (e.g., window resize)
        let stateful_state: SharedState<TextFieldState> =
            existing_stateful_state.unwrap_or_else(|| {
                let new_state = Arc::new(Mutex::new(StatefulInner::new(initial_visual)));
                // Store reference in TextInputData for triggering refreshes
                if let Ok(mut d) = data.lock() {
                    d.stateful_state = Some(Arc::clone(&new_state));
                }
                new_state
            });

        // Clear stale node_id from previous tree builds
        // During full rebuild (e.g., window resize), the old node_id points to
        // nodes in the old tree. Clearing it ensures the new node_id gets assigned
        // when this element is added to the new tree.
        {
            let mut shared = stateful_state.lock().unwrap();
            shared.node_id = None;
        }

        // Create inner Stateful with text input event handlers
        let mut inner = Self::create_inner_with_handlers(
            Arc::clone(&stateful_state),
            Arc::clone(&data),
            Arc::clone(&config),
        );

        // Set default width and height from config on the outer Stateful
        // This ensures proper layout constraints even without explicit .w() call
        // Also set overflow_clip to ensure children never visually exceed parent bounds
        //
        // HTML input behavior in flex layouts:
        // 1. Inputs stretch to fill parent width in flex-col (align-items: stretch)
        // 2. min-width: 0 - allows shrinking below content size in flex containers
        // 3. flex-shrink: 1 - allows shrinking when container is constrained
        {
            let cfg = config.lock().unwrap();
            // By default, use w_full() to stretch like HTML inputs do in flex containers.
            // The config.width serves as a fallback/minimum, not a fixed constraint.
            // Users can override with .w(px) for fixed width behavior.
            if cfg.use_full_width {
                inner = inner.w_full();
            }
            // Note: When neither w() nor w_full() is called, the element uses auto width
            // which allows it to stretch in flex containers (align-items: stretch default)

            // Apply HTML input-like flex behavior:
            // - min_w(0.0) allows the input to shrink below its content size
            // - flex_shrink (default 1) allows shrinking in flex containers
            // Note: Don't use overflow_clip() here - the inner clip_container handles clipping.
            // Using overflow_clip on the outer container with rounded corners causes
            // the clip to interfere with border rendering at the corners.
            inner = inner.h(cfg.height).min_w(0.0);
        }

        // Register callback immediately so it's available for incremental diff
        // The diff system calls children_builders() before build(), so the callback
        // must be registered here, not in build()
        {
            let config_for_callback = Arc::clone(&config);
            let data_for_callback = Arc::clone(&data);
            let mut shared = stateful_state.lock().unwrap();

            shared.state_callback = Some(Arc::new(
                move |visual: &TextFieldState, container: &mut Div| {
                    let mut cfg = config_for_callback.lock().unwrap().clone();
                    let mut data_guard = data_for_callback.lock().unwrap();

                    // Apply CSS stylesheet overrides (class-based and/or ID-based)
                    let has_css_target =
                        data_guard.css_element_id.is_some() || !data_guard.css_classes.is_empty();
                    let css_outline = if has_css_target {
                        if let Some(stylesheet) = active_stylesheet() {
                            apply_css_overrides(
                                &mut cfg,
                                &stylesheet,
                                data_guard.css_element_id.as_deref(),
                                &data_guard.css_classes,
                                visual,
                            );
                            // Extract outline properties for the inner div
                            if let Some(ref element_id) = data_guard.css_element_id {
                                extract_outline_from_stylesheet(&stylesheet, element_id, visual)
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    };

                    // Update scroll offset to keep cursor visible
                    let old_scroll = data_guard.scroll_offset_x;
                    data_guard.ensure_cursor_visible(&cfg);
                    if data_guard.scroll_offset_x != old_scroll {
                        tracing::debug!(
                            "TextInput scroll changed: {} -> {} (cursor={}, text_len={})",
                            old_scroll,
                            data_guard.scroll_offset_x,
                            data_guard.cursor,
                            data_guard.value.len()
                        );
                    }

                    // Determine colors based on visual state
                    let (bg, border_color) = match visual {
                        TextFieldState::Idle => (cfg.bg_color, cfg.border_color),
                        TextFieldState::Hovered => (cfg.hover_bg_color, cfg.hover_border_color),
                        TextFieldState::Focused | TextFieldState::FocusedHovered => {
                            (cfg.focused_bg_color, cfg.focused_border_color)
                        }
                        TextFieldState::Disabled => (
                            Color::rgba(0.12, 0.12, 0.15, 0.5),
                            Color::rgba(0.25, 0.25, 0.3, 0.5),
                        ),
                    };

                    // Apply error state border if invalid
                    let border_color = if !data_guard.is_valid && !data_guard.value.is_empty() {
                        cfg.error_border_color
                    } else {
                        border_color
                    };

                    // Apply visual styling directly to the container (preserves fixed dimensions)
                    // This is the key fix: use set_* methods instead of merge() to avoid
                    // overwriting layout properties like width set on the outer Stateful
                    let mut inner = div()
                        .w_full()
                        .bg(bg)
                        .border(cfg.border_width, border_color)
                        .rounded(cfg.corner_radius);

                    // Apply CSS outline if specified
                    if let Some((width, color, offset)) = css_outline {
                        inner = inner
                            .outline_width(width)
                            .outline_color(color)
                            .outline_offset(offset);
                    }

                    // Build and set content as a child (not merge)
                    let content = TextInput::build_content(*visual, &data_guard, &cfg);
                    container.merge(inner.child(content));
                },
            ));

            shared.needs_visual_update = true;
        }

        // Ensure state handlers (hover/press) are registered immediately
        // so they're available for incremental diff
        inner.ensure_state_handlers_registered();

        Self {
            inner,
            data,
            config,
            stateful_state,
            on_change_callback: None,
        }
    }

    /// Create the inner Stateful element with all event handlers registered
    fn create_inner_with_handlers(
        stateful_state: SharedState<TextFieldState>,
        data: SharedTextInputData,
        config: Arc<Mutex<TextInputConfig>>,
    ) -> Stateful<TextFieldState> {
        use blinc_core::events::event_types;

        let data_for_click = Arc::clone(&data);
        let data_for_drag = Arc::clone(&data);
        let config_for_drag = Arc::clone(&config);
        let stateful_for_drag = Arc::clone(&stateful_state);
        let data_for_text = Arc::clone(&data);
        let data_for_key = Arc::clone(&data);
        let config_for_click = Arc::clone(&config);
        let stateful_for_click = Arc::clone(&stateful_state);
        let stateful_for_text = Arc::clone(&stateful_state);
        let stateful_for_key = Arc::clone(&stateful_state);

        Stateful::with_shared_state(stateful_state)
            .w_full()
            // Handle mouse down to focus and position cursor
            .on_mouse_down(move |ctx| {
                let needs_refresh = {
                    let mut d = match data_for_click.lock() {
                        Ok(d) => d,
                        Err(_) => return,
                    };

                    if d.disabled {
                        return;
                    }

                    // Bump the focus-tap generation counter so the
                    // mobile runner picks this up as a "user tapped a
                    // text input" event, even if the input was already
                    // focused. This drives scroll-into-view on re-taps
                    // — see `focus_tap_generation` for the rationale
                    // and `blinc_app::android::android_main` /
                    // `blinc_app::ios::blinc_build_frame` for the
                    // consumers.
                    bump_focus_tap_generation();

                    // Register this node id as the generic
                    // focused-editable. The scroll-into-view helper
                    // consults this when the typed
                    // `focused_text_input_node_id` lookup is empty
                    // (e.g. for code_editor / rich_text_editor); we
                    // populate it here too so a single lookup site
                    // covers every editable widget.
                    //
                    // No blur callback because text_input has its own
                    // dedicated `FOCUSED_TEXT_INPUT` tracker that
                    // `blur_all_text_inputs` walks via the typed path
                    // — passing a callback here would cause double
                    // blur.
                    set_focused_editable_node(ctx.node_id, None);

                    // Get font size + the horizontal offset of the
                    // text content area inside the widget bounds.
                    // The widget renders a `padding_x`-wide spacer
                    // before the clip container that holds the text
                    // (see [`build_text_input_inner`]), and the
                    // border on the parent stateful adds another
                    // `border_width` on the left edge — so the very
                    // first glyph sits at
                    // `local_x = padding_x + border_width`, NOT at
                    // `local_x = 0`. Without subtracting this offset
                    // before calling `cursor_position_from_x`, every
                    // click is shifted right by ~13.5px and the very
                    // first character is unreachable: clicking on the
                    // "H" of "Hello World" lands a cursor position
                    // PAST the H, so a drag-select that starts there
                    // misses the first character.
                    let (font_size, text_origin_x) = {
                        let cfg = config_for_click.lock().unwrap();
                        (cfg.font_size, cfg.padding_x + cfg.border_width)
                    };

                    // Update FSM state
                    {
                        let mut shared = stateful_for_click.lock().unwrap();
                        if !shared.state.is_focused() {
                            if let Some(new_state) = shared
                                .state
                                .on_event(event_types::POINTER_DOWN)
                                .or_else(|| shared.state.on_event(event_types::FOCUS))
                            {
                                shared.state = new_state;
                                shared.needs_visual_update = true;
                            }
                        }
                    }

                    // Update data state
                    if !d.visual.is_focused() {
                        d.visual = TextFieldState::Focused;
                        d.focus_time_ms = elapsed_ms();
                        d.reset_cursor_blink();
                        increment_focus_count();
                        set_focused_text_input(&data_for_click);
                        request_continuous_redraw();
                    }

                    // Store computed width from layout bounds for scroll calculations
                    // This allows ensure_cursor_visible to work correctly with w_full() inputs
                    if ctx.bounds_width > 0.0 {
                        d.computed_width = Some(ctx.bounds_width);
                    }

                    // Calculate cursor position from click x position.
                    // Translate widget-local x into text-content x by
                    // subtracting the left padding + border, then clamp
                    // to >= 0 so clicks in the padding gutter snap to
                    // the start of the text instead of going negative.
                    let text_x = (ctx.local_x - text_origin_x).max(0.0);
                    let cursor_pos = d.cursor_position_from_x(text_x, font_size);

                    // Double-click detection (select word)
                    let now = web_time::Instant::now();
                    let is_double_click = d
                        .last_click_time
                        .map(|t| now.duration_since(t).as_millis() < 400)
                        .unwrap_or(false);
                    d.last_click_time = Some(now);

                    let touch = is_touch_input();

                    if is_double_click {
                        // Select word at cursor — same on touch and
                        // mouse. On touch we additionally fire an
                        // impact haptic and ask the platform to show
                        // the native edit menu (Cut / Copy / Paste /
                        // Select All) anchored at the tap position.
                        let (start, end) =
                            crate::widgets::text_edit::word_at_position(&d.value, cursor_pos);
                        d.selection_start = Some(start);
                        d.cursor = end;
                        if touch {
                            crate::widgets::text_edit::haptic_impact_light();
                            // Show edit menu — actions reflect the
                            // current state. There IS a selection
                            // (the just-selected word) so Cut / Copy
                            // are available; SELECT_ALL is always
                            // valid; PASTE depends on clipboard
                            // contents but we let the native side
                            // figure that out (it'll dim the menu
                            // item if the system clipboard is empty).
                            use crate::widgets::text_edit::edit_menu_actions;
                            crate::widgets::text_edit::show_edit_menu(
                                ctx.bounds_x + text_x,
                                ctx.bounds_y,
                                ctx.bounds_x + text_x,
                                ctx.bounds_y,
                                0.0,
                                ctx.bounds_height,
                                edit_menu_actions::CUT
                                    | edit_menu_actions::COPY
                                    | edit_menu_actions::PASTE
                                    | edit_menu_actions::SELECT_ALL,
                            );
                        }
                    } else {
                        // Single click: position cursor. On touch, we
                        // do NOT start a drag-select anchor — touch
                        // drag is repurposed for cursor movement (see
                        // the on_drag handler below). On mouse,
                        // single-click + drag extends selection just
                        // like the desktop UX expects.
                        d.cursor = cursor_pos;
                        d.selection_start = None;
                        if touch {
                            d.drag_select_anchor = None;
                            // Subtle haptic on single-tap focus, mirroring
                            // iOS UITextField's selection feedback.
                            crate::widgets::text_edit::haptic_selection();
                            // Hide any leftover edit menu from a
                            // previous double-tap so the user gets a
                            // clean re-engagement.
                            crate::widgets::text_edit::hide_edit_menu();
                            // Arm the long-press timer. The platform
                            // runner's frame loop polls
                            // `fire_long_press_timer_if_due` each
                            // tick, and after 500 ms (cancelled by
                            // any drift past 10 px or by mouse_up)
                            // it shows the edit menu with PASTE
                            // available — matching the iOS
                            // UITextField / Android EditText
                            // long-press-to-paste UX.
                            // Capture clones of the data + stateful
                            // refresh handle for the long-press
                            // callback. The closure runs at
                            // deadline-fire time and selects the
                            // word at the captured cursor position,
                            // matching the double-tap UX.
                            let data_for_long_press = std::sync::Arc::clone(&data_for_click);
                            let stateful_for_long_press =
                                std::sync::Arc::clone(&stateful_for_click);
                            let captured_cursor = cursor_pos;
                            arm_long_press_timer(
                                ctx.bounds_x + text_x,
                                ctx.bounds_y,
                                ctx.bounds_height,
                                Some(Box::new(move || {
                                    let did_update = {
                                        let mut d = match data_for_long_press.lock() {
                                            Ok(d) => d,
                                            Err(_) => return,
                                        };
                                        if !d.visual.is_focused() {
                                            return;
                                        }
                                        let (start, end) =
                                            crate::widgets::text_edit::word_at_position(
                                                &d.value,
                                                captured_cursor,
                                            );
                                        if start == end {
                                            return;
                                        }
                                        d.selection_start = Some(start);
                                        d.cursor = end;
                                        true
                                    };
                                    if did_update {
                                        refresh_stateful(&stateful_for_long_press);
                                    }
                                })),
                            );
                        } else {
                            d.drag_select_anchor = Some(cursor_pos);
                        }
                    }
                    d.reset_cursor_blink();

                    true
                };

                if needs_refresh {
                    refresh_stateful(&stateful_for_click);
                }
            })
            // Mouse drag to extend selection
            .on_drag({
                move |ctx| {
                    let needs_refresh = {
                        let mut d = match data_for_drag.lock() {
                            Ok(d) => d,
                            Err(_) => return,
                        };
                        if !d.visual.is_focused() {
                            return;
                        }

                        // Mirror the offset translation in
                        // on_mouse_down: convert widget-local x into
                        // text-content x by subtracting the left
                        // padding + border before mapping to a
                        // character index. Without this, the drag
                        // would cover one character less than the
                        // mouse-down anchor on the very first
                        // character.
                        let (font_size, text_origin_x) = {
                            let cfg = config_for_drag.lock().unwrap();
                            (cfg.font_size, cfg.padding_x + cfg.border_width)
                        };
                        let text_x = (ctx.local_x - text_origin_x).max(0.0);
                        let new_pos = d.cursor_position_from_x(text_x, font_size);

                        // Touch input branches its drag semantics:
                        //
                        //   * Mouse drag (desktop / web) — extends
                        //     selection from the anchor recorded by
                        //     `on_mouse_down`. Same behavior as
                        //     `text_input` has always had.
                        //
                        //   * Touch drag (mobile) — moves the caret
                        //     to wherever the finger is, without
                        //     starting a selection. Each character
                        //     boundary crossed gets a subtle
                        //     selection-changed haptic, mirroring the
                        //     UITextField / Android EditText cursor-
                        //     drag UX. Selection is reserved for
                        //     double-tap and the native edit menu.
                        //
                        // The branch is gated on
                        // `text_input::is_touch_input()`, which the
                        // platform runners flip on every touch /
                        // mouse event.
                        if is_touch_input() {
                            // Cancel any armed long-press as soon as
                            // the finger drifts past the threshold —
                            // a real drag should not also fire the
                            // paste menu mid-gesture.
                            check_long_press_drift(ctx.mouse_x, ctx.mouse_y);
                            if new_pos != d.cursor {
                                d.cursor = new_pos;
                                d.selection_start = None;
                                crate::widgets::text_edit::haptic_selection();
                            }
                        } else if let Some(anchor) = d.drag_select_anchor {
                            if new_pos != anchor {
                                d.selection_start = Some(anchor);
                                d.cursor = new_pos;
                            }
                        }
                        true
                    };
                    if needs_refresh {
                        refresh_stateful(&stateful_for_drag);
                    }
                }
            })
            // Handle text input
            .on_event(event_types::TEXT_INPUT, move |ctx| {
                let (needs_refresh, callback_info) = {
                    let mut d = match data_for_text.lock() {
                        Ok(d) => d,
                        Err(_) => return,
                    };

                    if d.disabled || !d.visual.is_focused() {
                        return;
                    }

                    if let Some(c) = ctx.key_char {
                        d.insert(&c.to_string());
                        d.reset_cursor_blink();
                        tracing::debug!("TextInput received char: {:?}, value: {}", c, d.value);
                        // Extract callback and value for calling after lock release
                        let cb_info = d
                            .on_change_callback
                            .as_ref()
                            .map(|cb| (Arc::clone(cb), d.value.clone()));
                        (true, cb_info)
                    } else {
                        (false, None)
                    }
                }; // Lock released here

                // Trigger incremental refresh AFTER releasing the data lock
                if needs_refresh {
                    refresh_stateful(&stateful_for_text);
                }

                // Call on_change callback after lock is released
                if let Some((callback, new_value)) = callback_info {
                    callback(&new_value);
                }
            })
            // Handle key down for navigation and deletion
            .on_key_down(move |ctx| {
                let (needs_refresh, callback_info) = {
                    let mut d = match data_for_key.lock() {
                        Ok(d) => d,
                        Err(_) => return,
                    };

                    if d.disabled || !d.visual.is_focused() {
                        return;
                    }

                    let mut changed = true;
                    let mut should_blur = false;
                    let mut value_changed = false;
                    let mod_key = ctx.meta || ctx.ctrl;

                    match ctx.key_code {
                        8 if mod_key => {
                            // Cmd+Backspace: delete word backward
                            d.delete_word_backward();
                            value_changed = true;
                        }
                        8 => {
                            // Backspace
                            if d.selection_start.is_some() {
                                d.delete_selection();
                            } else {
                                d.delete_backward();
                            }
                            value_changed = true;
                        }
                        127 if mod_key => {
                            // Cmd+Delete: delete word forward
                            d.delete_word_forward();
                            value_changed = true;
                        }
                        127 => {
                            // Delete
                            if d.selection_start.is_some() {
                                d.delete_selection();
                            } else {
                                d.delete_forward();
                            }
                            value_changed = true;
                        }
                        37 if mod_key => d.move_word_left(ctx.shift), // Cmd+Left
                        39 if mod_key => d.move_word_right(ctx.shift), // Cmd+Right
                        37 => d.move_left(ctx.shift),                 // Left
                        39 => d.move_right(ctx.shift),                // Right
                        36 => d.move_to_start(ctx.shift),             // Home
                        35 => d.move_to_end(ctx.shift),               // End
                        27 => {
                            should_blur = true;
                        }
                        _ if mod_key => {
                            match ctx.key_code {
                                // Cmd+A: select all
                                65 => d.select_all(),
                                // Cmd+C: copy
                                67 => {
                                    if let Some(text) = d.selected_text() {
                                        crate::widgets::text_edit::clipboard_write(&text);
                                    }
                                    changed = true;
                                }
                                // Cmd+X: cut
                                88 => {
                                    if let Some(text) = d.selected_text() {
                                        crate::widgets::text_edit::clipboard_write(&text);
                                        d.delete_selection();
                                        value_changed = true;
                                    }
                                }
                                // Cmd+V: paste
                                86 => {
                                    if let Some(clip) = crate::widgets::text_edit::clipboard_read()
                                    {
                                        // Remove newlines for single-line input
                                        let clean: String = clip
                                            .chars()
                                            .filter(|c| *c != '\n' && *c != '\r')
                                            .collect();
                                        if !clean.is_empty() {
                                            if d.selection_start.is_some() {
                                                d.delete_selection();
                                            }
                                            d.insert(&clean);
                                            value_changed = true;
                                        }
                                    }
                                }
                                // Cmd+Z: undo. Cmd+Shift+Z and Cmd+Y
                                // are both treated as redo (the two
                                // are mutually exclusive convention-
                                // wise on macOS vs Windows, so we
                                // accept both — single-source-of-
                                // truth: the user pressed something
                                // that means "redo").
                                90 if ctx.shift => {
                                    if d.redo() {
                                        value_changed = true;
                                    }
                                }
                                90 => {
                                    if d.undo() {
                                        value_changed = true;
                                    }
                                }
                                89 => {
                                    if d.redo() {
                                        value_changed = true;
                                    }
                                }
                                _ => changed = false,
                            }
                        }
                        _ => changed = false,
                    }

                    if changed && !should_blur {
                        d.reset_cursor_blink();
                        d.sync_global_selection();
                    }

                    // Extract callback info if value changed
                    let cb_info = if value_changed {
                        d.on_change_callback
                            .as_ref()
                            .map(|cb| (Arc::clone(cb), d.value.clone()))
                    } else {
                        None
                    };

                    ((changed, should_blur), cb_info)
                }; // Lock released here

                // Handle blur (Escape key)
                if needs_refresh.1 {
                    blur_all_text_inputs();
                } else if needs_refresh.0 {
                    // Trigger incremental refresh AFTER releasing the data lock
                    refresh_stateful(&stateful_for_key);
                }

                // Call on_change callback after lock is released
                if let Some((callback, new_value)) = callback_info {
                    callback(&new_value);
                }
            })
            // Set text cursor (I-beam) for text input
            .cursor_text()
    }

    /// Build the content div based on current visual state and data
    ///
    /// Note: Visual styling (bg, border, rounded) is now applied directly to the
    /// container in the callback via set_* methods. This function only builds
    /// the inner content structure (padding spacers, clip container, text, cursor).
    fn build_content(
        visual: TextFieldState,
        data: &TextInputData,
        config: &TextInputConfig,
    ) -> Div {
        let display = if data.value.is_empty() {
            if !data.placeholder.is_empty() {
                data.placeholder.clone()
            } else {
                config.placeholder.clone()
            }
        } else {
            data.display_text()
        };

        let text_color = if data.value.is_empty() {
            config.placeholder_color
        } else if data.disabled {
            Color::rgba(0.4, 0.4, 0.4, 1.0)
        } else {
            config.text_color
        };

        let is_focused = visual.is_focused();
        let cursor_color = config.cursor_color;
        let selection_color = config.selection_color;
        let cursor_pos = data.cursor;
        let cursor_height = config.font_size * 1.2;
        let scroll_offset = data.scroll_offset_x;

        let selection_range: Option<(usize, usize)> = data.selection_start.map(|start| {
            if start < cursor_pos {
                (start, cursor_pos)
            } else {
                (cursor_pos, start)
            }
        });

        let cursor_state_for_canvas = Arc::clone(&data.cursor_state);

        let cursor_x = if cursor_pos > 0 && !display.is_empty() {
            let text_before: String = display.chars().take(cursor_pos).collect();
            crate::text_measure::measure_text(&text_before, config.font_size).width
        } else {
            0.0
        };

        // Calculate dimensions - inner height accounts for border
        let inner_height = config.height - config.border_width * 2.0;

        // Build main content container - NO visual styling here (handled by callback)
        // Always use w_full() so content fills the parent Stateful element.
        // The parent's width is controlled by:
        // - auto (default): stretches in flex containers via align-items: stretch
        // - w_full(): explicitly fills parent width
        // - w(px): user-specified fixed width
        let mut main_content = div().h_full().w_full().relative().flex_row().items_center();

        // Left padding spacer
        main_content =
            main_content.child(div().w(config.padding_x).h(inner_height).flex_shrink_0());

        // Clip container - use flex_1 to fill available space
        // This works for both full-width and fixed-width cases because:
        // - The parent (main_content) already has the width constraint
        // - flex_1 allows the clip container to fill remaining space after padding spacers
        // - min_w(0) allows shrinking below content size (HTML input behavior)
        let mut clip_container = div()
            .h(inner_height)
            .relative()
            .overflow_clip()
            .flex_1()
            .min_w(0.0);

        // Text wrapper with absolute positioning
        // Using left() with negative scroll offset to scroll content
        let mut text_wrapper = div()
            .absolute()
            .left(-scroll_offset)
            .top(0.0)
            .h(inner_height)
            .flex_row()
            .items_center();

        if !display.is_empty() {
            if let Some((sel_start, sel_end)) = selection_range {
                let mut text_container = div().flex_row().items_center();

                let before_sel: String = display.chars().take(sel_start).collect();
                if !before_sel.is_empty() {
                    text_container = text_container.child(
                        text(&before_sel)
                            .size(config.font_size)
                            .color(text_color)
                            .text_left()
                            .no_wrap()
                            .v_center(),
                    );
                }

                let selected: String = display
                    .chars()
                    .skip(sel_start)
                    .take(sel_end - sel_start)
                    .collect();
                if !selected.is_empty() {
                    text_container = text_container.child(
                        div()
                            .bg(selection_color)
                            .rounded(config.corner_radius)
                            .child(
                                text(&selected)
                                    .size(config.font_size)
                                    .color(text_color)
                                    .text_left()
                                    .no_wrap()
                                    .v_center(),
                            ),
                    );
                }

                let after_sel: String = display.chars().skip(sel_end).collect();
                if !after_sel.is_empty() {
                    text_container = text_container.child(
                        text(&after_sel)
                            .size(config.font_size)
                            .color(text_color)
                            .text_left()
                            .no_wrap()
                            .v_center(),
                    );
                }

                text_wrapper = text_wrapper.child(text_container);
            } else {
                text_wrapper = text_wrapper.child(
                    text(&display)
                        .size(config.font_size)
                        .color(text_color)
                        .text_left()
                        .no_wrap()
                        .v_center(),
                );
            }
        }

        // Add text wrapper to clip container
        clip_container = clip_container.child(text_wrapper);

        // Add cursor via canvas as a sibling to text_wrapper, also in clip_container
        // The cursor position is adjusted for scroll offset since it's not inside text_wrapper
        if is_focused && selection_range.is_none() {
            let cursor_left = cursor_x - scroll_offset;
            // Calculate proper vertical margins to center cursor (inner_height already defined above)
            let cursor_margin = (inner_height - cursor_height) / 2.0;

            {
                if let Ok(mut cs) = cursor_state_for_canvas.lock() {
                    cs.visible = true;
                    cs.color = cursor_color;
                    cs.x = cursor_left;
                    cs.animation = CursorAnimation::SmoothFade;
                }
            }

            let cursor_state_clone = Arc::clone(&cursor_state_for_canvas);
            let cursor_canvas = canvas(
                move |ctx: &mut dyn blinc_core::DrawContext,
                      bounds: crate::canvas::CanvasBounds| {
                    let cs = cursor_state_clone.lock().unwrap();
                    if !cs.visible {
                        return;
                    }

                    let opacity = cs.current_opacity();
                    if opacity < 0.01 {
                        return;
                    }

                    let color = blinc_core::Color::rgba(
                        cs.color.r,
                        cs.color.g,
                        cs.color.b,
                        cs.color.a * opacity,
                    );
                    // Draw cursor centered within the bounds
                    ctx.fill_rect(
                        blinc_core::Rect::new(0.0, 0.0, cs.width, bounds.height),
                        blinc_core::CornerRadius::default(),
                        blinc_core::Brush::Solid(color),
                    );
                },
            )
            .absolute()
            .left(cursor_left)
            .top(cursor_margin)
            .w(2.0)
            .h(cursor_height);

            // Add cursor to clip_container (sibling to text_wrapper, doesn't scroll)
            clip_container = clip_container.child(cursor_canvas);
        } else if let Ok(mut cs) = cursor_state_for_canvas.lock() {
            cs.visible = false;
        }

        // Add clip container to main content
        main_content = main_content.child(clip_container);

        // Right padding spacer
        main_content =
            main_content.child(div().w(config.padding_x).h(inner_height).flex_shrink_0());

        // Return the main container with proper border
        main_content
    }

    // Builder methods that forward to inner Stateful
    pub fn w(mut self, px: f32) -> Self {
        {
            let mut cfg = self.config.lock().unwrap();
            cfg.width = px;
        }
        self.inner = std::mem::take(&mut self.inner).w(px);
        self
    }

    pub fn w_full(mut self) -> Self {
        self.config.lock().unwrap().use_full_width = true;
        self.inner = std::mem::take(&mut self.inner).w_full();
        self
    }

    pub fn min_w(mut self, px: f32) -> Self {
        self.inner = std::mem::take(&mut self.inner).min_w(px);
        self
    }

    pub fn h(mut self, px: f32) -> Self {
        {
            let mut cfg = self.config.lock().unwrap();
            cfg.height = px;
        }
        self.inner = std::mem::take(&mut self.inner).h(px);
        self
    }

    pub fn placeholder(self, text: impl Into<String>) -> Self {
        let placeholder = text.into();
        self.config.lock().unwrap().placeholder = placeholder.clone();
        if let Ok(mut d) = self.data.lock() {
            d.placeholder = placeholder;
        }
        self
    }

    pub fn input_type(self, input_type: InputType) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.input_type = input_type;
        }
        self
    }

    pub fn disabled(self, disabled: bool) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.disabled = disabled;
            if disabled {
                d.visual = TextFieldState::Disabled;
            }
        }
        self
    }

    pub fn masked(self, masked: bool) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.masked = masked;
        }
        self
    }

    pub fn max_length(self, max: usize) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.constraints.max_length = Some(max);
        }
        self
    }

    /// Set the font size for the text input (default: 16.0)
    pub fn text_size(self, size: f32) -> Self {
        self.config.lock().unwrap().font_size = size;
        self
    }

    pub fn rounded(mut self, radius: f32) -> Self {
        self.config.lock().unwrap().corner_radius = radius;
        self.inner = std::mem::take(&mut self.inner).rounded(radius);
        self
    }

    pub fn border(mut self, width: f32, color: blinc_core::Color) -> Self {
        self.inner = std::mem::take(&mut self.inner).border(width, color);
        self
    }

    pub fn border_color(mut self, color: blinc_core::Color) -> Self {
        self.inner = std::mem::take(&mut self.inner).border_color(color);
        self
    }

    pub fn border_width(mut self, width: f32) -> Self {
        self.inner = std::mem::take(&mut self.inner).border_width(width);
        self
    }

    pub fn shadow_sm(mut self) -> Self {
        self.inner = std::mem::take(&mut self.inner).shadow_sm();
        self
    }

    pub fn shadow_md(mut self) -> Self {
        self.inner = std::mem::take(&mut self.inner).shadow_md();
        self
    }

    pub fn flex_grow(mut self) -> Self {
        self.inner = std::mem::take(&mut self.inner).flex_grow();
        self
    }

    /// Set the CSS element ID for stylesheet matching
    ///
    /// When set, the TextInput will query the active stylesheet for
    /// styles matching `#id`, `#id:hover`, `#id:focus`, `#id:disabled`,
    /// and `#id::placeholder`.
    pub fn id(mut self, id: &str) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.css_element_id = Some(id.to_string());
        }
        self.inner = std::mem::take(&mut self.inner).id(id);
        self
    }

    /// Add a CSS class name for selector matching
    pub fn class(mut self, name: &str) -> Self {
        if let Ok(mut d) = self.data.lock() {
            d.css_classes.push(name.to_string());
        }
        self.inner = std::mem::take(&mut self.inner).class(name);
        self
    }

    // ========== Border Color Configuration ==========

    /// Set the idle border color (when not hovered or focused)
    pub fn idle_border_color(self, color: Color) -> Self {
        self.config.lock().unwrap().border_color = color;
        self
    }

    /// Set the hover border color
    pub fn hover_border_color(self, color: Color) -> Self {
        self.config.lock().unwrap().hover_border_color = color;
        self
    }

    /// Set the focused border color
    pub fn focused_border_color(self, color: Color) -> Self {
        self.config.lock().unwrap().focused_border_color = color;
        self
    }

    /// Set the error border color (shown when is_valid is false)
    pub fn error_border_color(self, color: Color) -> Self {
        self.config.lock().unwrap().error_border_color = color;
        self
    }

    /// Set all border colors at once for consistent theming
    pub fn border_colors(self, idle: Color, hover: Color, focused: Color, error: Color) -> Self {
        let mut cfg = self.config.lock().unwrap();
        cfg.border_color = idle;
        cfg.hover_border_color = hover;
        cfg.focused_border_color = focused;
        cfg.error_border_color = error;
        drop(cfg);
        self
    }

    // ========== Background Color Configuration ==========

    /// Set the idle background color
    pub fn idle_bg_color(self, color: Color) -> Self {
        self.config.lock().unwrap().bg_color = color;
        self
    }

    /// Set the hover background color
    pub fn hover_bg_color(self, color: Color) -> Self {
        self.config.lock().unwrap().hover_bg_color = color;
        self
    }

    /// Set the focused background color
    pub fn focused_bg_color(self, color: Color) -> Self {
        self.config.lock().unwrap().focused_bg_color = color;
        self
    }

    /// Set all background colors at once
    pub fn bg_colors(self, idle: Color, hover: Color, focused: Color) -> Self {
        let mut cfg = self.config.lock().unwrap();
        cfg.bg_color = idle;
        cfg.hover_bg_color = hover;
        cfg.focused_bg_color = focused;
        drop(cfg);
        self
    }

    // ========== Text Color Configuration ==========

    /// Set the text color
    pub fn text_color(self, color: Color) -> Self {
        self.config.lock().unwrap().text_color = color;
        self
    }

    /// Set the placeholder text color
    pub fn placeholder_color(self, color: Color) -> Self {
        self.config.lock().unwrap().placeholder_color = color;
        self
    }

    /// Set the cursor color
    pub fn cursor_color(self, color: Color) -> Self {
        self.config.lock().unwrap().cursor_color = color;
        self
    }

    /// Set the selection highlight color
    pub fn selection_color(self, color: Color) -> Self {
        self.config.lock().unwrap().selection_color = color;
        self
    }

    /// Set the callback to be invoked when the text value changes
    ///
    /// The callback receives the new text value as a string slice.
    /// This is called after insert or delete operations modify the text.
    ///
    /// # Example
    ///
    /// ```ignore
    /// text_input(&data)
    ///     .on_change(|new_value| {
    ///         println!("Text changed to: {}", new_value);
    ///     })
    /// ```
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        let cb: OnChangeCallback = Arc::new(callback);
        self.on_change_callback = Some(Arc::clone(&cb));
        // Store in TextInputData so it can be accessed in event handlers
        if let Ok(mut d) = self.data.lock() {
            d.on_change_callback = Some(cb);
        }
        self
    }
}

/// Create a text input widget
/// By default, uses the config's default width (200px).
/// Use .w_full() to fill parent width, or .w() to set explicit width.
pub fn text_input(data: &SharedTextInputData) -> TextInput {
    // TextInput::new() sets default width from config (200px)
    TextInput::new(Arc::clone(data))
}

impl ElementBuilder for TextInput {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        // Set base render props and layout style for incremental updates
        // Note: callback and handlers are registered in new() so they're available for incremental diff
        // base_style must be updated here because on_state() captures it before .w()/.h() are applied
        {
            let mut shared = self.stateful_state.lock().unwrap();
            shared.base_render_props = Some(self.inner.inner_render_props());
            shared.base_style = self.inner.inner_layout_style();
        }

        self.inner.build(tree)
    }

    fn render_props(&self) -> RenderProps {
        self.inner.render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.inner.children_builders()
    }

    fn element_type_id(&self) -> crate::div::ElementTypeId {
        crate::div::ElementTypeId::Div
    }

    fn semantic_type_name(&self) -> Option<&'static str> {
        Some("input")
    }

    fn event_handlers(&self) -> Option<&crate::event_handler::EventHandlers> {
        self.inner.event_handlers()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.inner.layout_style()
    }

    fn layout_bounds_storage(&self) -> Option<crate::renderer::LayoutBoundsStorage> {
        // Return the layout bounds storage from the data so it gets updated after layout
        if let Ok(data) = self.data.lock() {
            Some(Arc::clone(&data.layout_bounds_storage))
        } else {
            None
        }
    }

    fn layout_bounds_callback(&self) -> Option<crate::renderer::LayoutBoundsCallback> {
        // When layout bounds change, trigger a refresh so the TextInput can
        // recalculate scroll offset with the new width
        let stateful_state = Arc::clone(&self.stateful_state);
        Some(Arc::new(move |_bounds| {
            // Trigger a visual update so ensure_cursor_visible runs with new bounds
            refresh_stateful(&stateful_state);
        }))
    }
}

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

    #[test]
    fn test_text_input_data_insert() {
        let mut data = TextInputData::new();
        data.stateful_state = None; // No refresh in tests

        data.insert("hello");
        assert_eq!(data.value, "hello");
        assert_eq!(data.cursor, 5);

        data.cursor = 0;
        data.insert("world ");
        assert_eq!(data.value, "world hello");
    }

    #[test]
    fn test_text_input_data_delete() {
        let mut data = TextInputData::with_value("hello");
        data.stateful_state = None;

        data.cursor = 5;
        data.delete_backward();
        assert_eq!(data.value, "hell");

        data.cursor = 0;
        data.delete_forward();
        assert_eq!(data.value, "ell");
    }

    #[test]
    fn test_input_type_filtering() {
        let mut data = TextInputData::new();
        data.stateful_state = None;
        data.input_type = InputType::Number;

        data.insert("123.45");
        assert_eq!(data.value, "123.45");

        data.value.clear();
        data.cursor = 0;
        data.insert("abc123");
        assert_eq!(data.value, "123");
    }
}