azul-core 0.0.8

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
//! Event and callback filtering module

#[cfg(not(feature = "std"))]
use alloc::string::{String, ToString};
use alloc::{
    boxed::Box,
    collections::{btree_map::BTreeMap, btree_set::BTreeSet},
    vec::Vec,
};

use azul_css::AzString;

use crate::{
    callbacks::Update,
    dom::{DomId, DomNodeId, On},
    geom::{LogicalPosition, LogicalRect},
    hit_test::{FullHitTest, HitTestItem},
    id::NodeId,
    styled_dom::{ChangedCssProperty, NodeHierarchyItemId},
    task::Instant,
    OrderedMap,
};

/// Easing functions for smooth scroll animations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EasingFunction {
    Linear,
    EaseInOut,
    EaseOut,
}

pub type RestyleNodes = BTreeMap<NodeId, Vec<ChangedCssProperty>>;
pub type RelayoutNodes = BTreeMap<NodeId, Vec<ChangedCssProperty>>;
pub type RelayoutWords = BTreeMap<NodeId, AzString>;

#[derive(Debug, Clone, PartialEq)]
pub struct FocusChange {
    pub old: Option<DomNodeId>,
    pub new: Option<DomNodeId>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CallbackToCall {
    pub node_id: NodeId,
    pub hit_test_item: Option<HitTestItem>,
    pub event_filter: EventFilter,
}

impl CallbackToCall {
    pub fn new(
        node_id: NodeId,
        hit_test_item: Option<HitTestItem>,
        event_filter: EventFilter,
    ) -> Self {
        Self { node_id, hit_test_item, event_filter }
    }

    /// Build a list of `CallbackToCall` entries for every node hit by the
    /// given hit test under the given DOM, tagged with `event_filter`.
    /// Returns an empty `Vec` when there is no hit test data for the DOM.
    pub fn from_hit_test(
        hit_test: &FullHitTest,
        dom_id: DomId,
        event_filter: EventFilter,
    ) -> Vec<CallbackToCall> {
        let Some(hit) = hit_test.hovered_nodes.get(&dom_id) else {
            return Vec::new();
        };
        hit.regular_hit_test_nodes
            .iter()
            .map(|(node_id, item)| CallbackToCall {
                node_id: *node_id,
                hit_test_item: Some(item.clone()),
                event_filter: event_filter.clone(),
            })
            .collect()
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use = "ProcessEventResult must be used to determine if relayout/repaint is needed"]
pub enum ProcessEventResult {
    DoNothing = 0,
    ShouldReRenderCurrentWindow = 1,
    ShouldUpdateDisplayListCurrentWindow = 2,
    // GPU transforms changed: do another hit-test and recurse
    // until nothing has changed anymore
    UpdateHitTesterAndProcessAgain = 3,
    // Restyle or runtime edit changed layout-affecting properties:
    // re-run layout on the EXISTING StyledDom (no DOM rebuild).
    ShouldIncrementalRelayout = 4,
    // Full DOM rebuild via user's layout_callback()
    ShouldRegenerateDomCurrentWindow = 5,
    ShouldRegenerateDomAllWindows = 6,
}

impl ProcessEventResult {
    pub fn order(&self) -> usize {
        use self::ProcessEventResult::*;
        match self {
            DoNothing => 0,
            ShouldReRenderCurrentWindow => 1,
            ShouldUpdateDisplayListCurrentWindow => 2,
            UpdateHitTesterAndProcessAgain => 3,
            ShouldIncrementalRelayout => 4,
            ShouldRegenerateDomCurrentWindow => 5,
            ShouldRegenerateDomAllWindows => 6,
        }
    }
}

impl PartialOrd for ProcessEventResult {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        self.order().partial_cmp(&other.order())
    }
}

impl Ord for ProcessEventResult {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.order().cmp(&other.order())
    }
}

impl ProcessEventResult {
    pub fn max_self(self, other: Self) -> Self {
        self.max(other)
    }
}

/// Tracks the origin of an event for proper handling.
///
/// This allows the system to distinguish between user input, programmatic
/// changes, and synthetic events generated by UI components.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum EventSource {
    /// Direct user input (mouse, keyboard, touch, gamepad)
    User,
    /// API call (programmatic scroll, focus change, etc.)
    Programmatic,
    /// Generated from UI interaction (scrollbar drag, synthetic events)
    Synthetic,
    /// Generated from lifecycle hooks (mount, unmount, resize)
    Lifecycle,
}

/// Event propagation phase (similar to DOM Level 2 Events).
///
/// Events can be intercepted at different phases:
/// - **Capture**: Event travels from root down to target (rarely used)
/// - **Target**: Event is at the target element
/// - **Bubble**: Event travels from target back up to root (most common)
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum EventPhase {
    /// Event travels from root down to target
    Capture,
    /// Event is at the target element
    Target,
    /// Event bubbles from target back up to root
    Bubble,
}

impl Default for EventPhase {
    fn default() -> Self {
        EventPhase::Bubble
    }
}

/// Mouse button identifier for mouse events.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum MouseButton {
    Left,
    Middle,
    Right,
    Other(u8),
}

/// Scroll delta mode (how scroll deltas should be interpreted).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum ScrollDeltaMode {
    /// Delta is in pixels
    Pixel,
    /// Delta is in lines (e.g., 3 lines of text)
    Line,
    /// Delta is in pages
    Page,
}

/// Scroll direction for conditional event filtering.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum ScrollDirection {
    Up,
    Down,
    Left,
    Right,
}

// ============================================================================
// W3C CSSOM View Module - Scroll Into View Types
// ============================================================================

/// W3C-compliant scroll-into-view options
///
/// These options control how an element is scrolled into view, following
/// the CSSOM View Module specification.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ScrollIntoViewOptions {
    /// Vertical alignment: start, center, end, nearest (default: nearest)
    pub block: ScrollLogicalPosition,
    /// Horizontal alignment: start, center, end, nearest (default: nearest)
    /// Note: Named `inline_axis` to avoid conflict with C keyword `inline`
    pub inline_axis: ScrollLogicalPosition,
    /// Animation behavior: auto, instant, smooth (default: auto)
    pub behavior: ScrollIntoViewBehavior,
}

impl ScrollIntoViewOptions {
    /// Create options with "nearest" alignment for both axes
    pub fn nearest() -> Self {
        Self {
            block: ScrollLogicalPosition::Nearest,
            inline_axis: ScrollLogicalPosition::Nearest,
            behavior: ScrollIntoViewBehavior::Auto,
        }
    }
    
    /// Create options with "center" alignment for both axes
    pub fn center() -> Self {
        Self {
            block: ScrollLogicalPosition::Center,
            inline_axis: ScrollLogicalPosition::Center,
            behavior: ScrollIntoViewBehavior::Auto,
        }
    }
    
    /// Create options with "start" alignment for both axes
    pub fn start() -> Self {
        Self {
            block: ScrollLogicalPosition::Start,
            inline_axis: ScrollLogicalPosition::Start,
            behavior: ScrollIntoViewBehavior::Auto,
        }
    }
    
    /// Create options to align the end of the target with the end of the viewport
    pub fn end() -> Self {
        Self {
            block: ScrollLogicalPosition::End,
            inline_axis: ScrollLogicalPosition::End,
            behavior: ScrollIntoViewBehavior::Auto,
        }
    }
    
    /// Set instant scroll behavior
    pub fn with_instant(mut self) -> Self {
        self.behavior = ScrollIntoViewBehavior::Instant;
        self
    }
    
    /// Set smooth scroll behavior
    pub fn with_smooth(mut self) -> Self {
        self.behavior = ScrollIntoViewBehavior::Smooth;
        self
    }
}

/// Scroll alignment for vertical (block) or horizontal (inline) axis
///
/// Determines where the target element should be positioned within
/// the scroll container's visible area.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum ScrollLogicalPosition {
    /// Align target's start edge with container's start edge
    Start,
    /// Center target within container
    Center,
    /// Align target's end edge with container's end edge
    End,
    /// Minimum scroll distance to make target fully visible (default)
    #[default]
    Nearest,
}

/// Scroll animation behavior for scrollIntoView API
///
/// This is distinct from the CSS `scroll-behavior` property, as it also
/// supports the `Instant` option which CSS does not have.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum ScrollIntoViewBehavior {
    /// Respect CSS scroll-behavior property (default)
    #[default]
    Auto,
    /// Immediate jump without animation
    Instant,
    /// Animated smooth scroll
    Smooth,
}

/// Reason why a lifecycle event was triggered.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum LifecycleReason {
    /// First appearance in DOM
    InitialMount,
    /// Removed and re-added to DOM
    Remount,
    /// Layout bounds changed
    Resize,
    /// Props or state changed
    Update,
    /// Node was removed from DOM
    Unmount,
}

/// Keyboard modifier keys state.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
#[repr(C)]
pub struct KeyModifiers {
    pub shift: bool,
    pub ctrl: bool,
    pub alt: bool,
    pub meta: bool,
}

impl KeyModifiers {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_shift(mut self) -> Self {
        self.shift = true;
        self
    }

    pub fn with_ctrl(mut self) -> Self {
        self.ctrl = true;
        self
    }

    pub fn with_alt(mut self) -> Self {
        self.alt = true;
        self
    }

    pub fn with_meta(mut self) -> Self {
        self.meta = true;
        self
    }

    pub fn is_empty(&self) -> bool {
        !self.shift && !self.ctrl && !self.alt && !self.meta
    }
}

/// Type-specific event data for mouse events.
#[derive(Debug, Clone, PartialEq)]
pub struct MouseEventData {
    /// Position of the mouse cursor
    pub position: LogicalPosition,
    /// Which button was pressed/released
    pub button: MouseButton,
    /// Bitmask of currently pressed buttons
    pub buttons: u8,
    /// Modifier keys state
    pub modifiers: KeyModifiers,
}

/// Type-specific event data for keyboard events.
#[derive(Debug, Clone, PartialEq)]
pub struct KeyboardEventData {
    /// The virtual key code
    pub key_code: u32,
    /// The character produced (if any)
    pub char_code: Option<char>,
    /// Modifier keys state
    pub modifiers: KeyModifiers,
    /// Whether this is a repeat event
    pub repeat: bool,
}

/// Type-specific event data for scroll events.
#[derive(Debug, Clone, PartialEq)]
pub struct ScrollEventData {
    /// Scroll delta (dx, dy)
    pub delta: LogicalPosition,
    /// How the delta should be interpreted
    pub delta_mode: ScrollDeltaMode,
}

/// Type-specific event data for touch events.
#[derive(Debug, Clone, PartialEq)]
pub struct TouchEventData {
    /// Touch identifier
    pub id: u64,
    /// Touch position
    pub position: LogicalPosition,
    /// Touch force/pressure (0.0 - 1.0)
    pub force: f32,
}

/// Type-specific event data for clipboard events.
#[derive(Debug, Clone, PartialEq)]
pub struct ClipboardEventData {
    /// The clipboard content (for paste events)
    pub content: Option<String>,
}

/// Type-specific event data for lifecycle events.
#[derive(Debug, Clone, PartialEq)]
pub struct LifecycleEventData {
    /// Why this lifecycle event was triggered
    pub reason: LifecycleReason,
    /// Previous layout bounds (for resize events)
    pub previous_bounds: Option<LogicalRect>,
    /// Current layout bounds
    pub current_bounds: LogicalRect,
}

/// Type-specific event data for window events.
#[derive(Debug, Clone, PartialEq)]
pub struct WindowEventData {
    /// Window size (for resize events)
    pub size: Option<LogicalRect>,
    /// Window position (for move events)
    pub position: Option<LogicalPosition>,
}

/// Union of all possible event data types.
#[derive(Debug, Clone, PartialEq)]
pub enum EventData {
    /// Mouse event data
    Mouse(MouseEventData),
    /// Keyboard event data
    Keyboard(KeyboardEventData),
    /// Scroll event data
    Scroll(ScrollEventData),
    /// Touch event data
    Touch(TouchEventData),
    /// Clipboard event data
    Clipboard(ClipboardEventData),
    /// Lifecycle event data
    Lifecycle(LifecycleEventData),
    /// Window event data
    Window(WindowEventData),
    /// No additional data
    None,
}

/// High-level event type classification.
///
/// This enum categorizes all possible events that can occur in the UI.
/// It extends the existing event system with new event types for
/// lifecycle, clipboard, media, and form handling.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum EventType {
    // Mouse Events
    /// Mouse cursor is over the element
    MouseOver,
    /// Mouse cursor entered the element
    MouseEnter,
    /// Mouse cursor left the element
    MouseLeave,
    /// Mouse left the element OR moved to a child element (W3C `mouseout`, bubbles)
    MouseOut,
    /// Mouse button pressed
    MouseDown,
    /// Mouse button released
    MouseUp,
    /// Mouse click (down + up on same element)
    Click,
    /// Mouse double-click
    DoubleClick,
    /// Right-click / context menu
    ContextMenu,

    // Keyboard Events
    /// Key pressed down
    KeyDown,
    /// Key released
    KeyUp,
    /// Character input (respects locale/keyboard layout)
    KeyPress,

    // IME Composition Events
    /// IME composition started
    CompositionStart,
    /// IME composition updated (intermediate text changed)
    CompositionUpdate,
    /// IME composition ended (final text committed)
    CompositionEnd,

    // Focus Events
    /// Element received focus
    Focus,
    /// Element lost focus
    Blur,
    /// Focus entered element or its children
    FocusIn,
    /// Focus left element and its children
    FocusOut,

    // Input Events
    /// Input value is being changed (fires on every keystroke)
    Input,
    /// Input value has changed (fires after editing complete)
    Change,
    /// Form submitted
    Submit,
    /// Form reset
    Reset,
    /// Form validation failed
    Invalid,

    // Scroll Events
    /// Element is being scrolled
    Scroll,
    /// Scroll started
    ScrollStart,
    /// Scroll ended
    ScrollEnd,

    // Drag Events
    /// Drag operation started
    DragStart,
    /// Element is being dragged
    Drag,
    /// Drag operation ended
    DragEnd,
    /// Dragged element entered drop target
    DragEnter,
    /// Dragged element is over drop target
    DragOver,
    /// Dragged element left drop target
    DragLeave,
    /// Element was dropped
    Drop,

    // Touch Events
    /// Touch started
    TouchStart,
    /// Touch moved
    TouchMove,
    /// Touch ended
    TouchEnd,
    /// Touch cancelled
    TouchCancel,

    // Pen / Stylus Events (W3C PointerEvent, pointerType "pen")
    /// Pen tip made contact (or pen entered while down)
    PenDown,
    /// Pen moved (in contact or hovering in range)
    PenMove,
    /// Pen tip lifted
    PenUp,
    /// Pen entered hover/sensing range (proximity in)
    PenEnter,
    /// Pen left hover/sensing range (proximity out)
    PenLeave,

    // Gesture Events
    /// Long press detected (touch or mouse held down)
    LongPress,
    /// Swipe gesture to the left
    SwipeLeft,
    /// Swipe gesture to the right
    SwipeRight,
    /// Swipe gesture upward
    SwipeUp,
    /// Swipe gesture downward
    SwipeDown,
    /// Pinch-in gesture (zoom out)
    PinchIn,
    /// Pinch-out gesture (zoom in)
    PinchOut,
    /// Clockwise rotation gesture
    RotateClockwise,
    /// Counter-clockwise rotation gesture
    RotateCounterClockwise,

    // Clipboard Events
    /// Content copied to clipboard
    Copy,
    /// Content cut to clipboard
    Cut,
    /// Content pasted from clipboard
    Paste,

    // Media Events
    /// Media playback started
    Play,
    /// Media playback paused
    Pause,
    /// Media playback ended
    Ended,
    /// Media time updated
    TimeUpdate,
    /// Media volume changed
    VolumeChange,
    /// Media error occurred
    MediaError,

    // Lifecycle Events
    /// Component was mounted to the DOM
    Mount,
    /// Component will be unmounted from the DOM
    Unmount,
    /// Component was updated
    Update,
    /// Component layout bounds changed
    Resize,

    // Window Events
    /// Window resized
    WindowResize,
    /// Window moved
    WindowMove,
    /// Window close requested
    WindowClose,
    /// Window received focus
    WindowFocusIn,
    /// Window lost focus
    WindowFocusOut,
    /// System theme changed
    ThemeChange,
    /// Window DPI/scale factor changed (moved to different monitor)
    WindowDpiChanged,
    /// Window moved to a different monitor
    WindowMonitorChanged,

    // Application Events
    /// A monitor/display was connected
    MonitorConnected,
    /// A monitor/display was disconnected
    MonitorDisconnected,

    // File Events
    /// File is being hovered
    FileHover,
    /// File was dropped
    FileDrop,
    /// File hover cancelled
    FileHoverCancel,

    // Hardware input-device Events (P6 sensors / gamepad)
    /// A motion-sensor reading (accelerometer / gyroscope / magnetometer)
    /// changed. Read the value with `CallbackInfo::get_sensor_reading`.
    SensorChanged,
    /// A gamepad's buttons / axes changed, or one was (dis)connected. Read it
    /// with `CallbackInfo::get_primary_gamepad` / `get_gamepad_state`.
    GamepadInput,
}

/// Unified event wrapper (similar to React's SyntheticEvent).
///
/// All events in the system are wrapped in this structure, providing
/// a consistent interface and enabling event propagation control.
#[derive(Debug, Clone, PartialEq)]
pub struct SyntheticEvent {
    /// The type of event
    pub event_type: EventType,

    /// Where the event came from
    pub source: EventSource,

    /// Current propagation phase
    pub phase: EventPhase,

    /// Target node that the event was dispatched to
    pub target: DomNodeId,

    /// Current node in the propagation path
    pub current_target: DomNodeId,

    /// Timestamp when event was created
    pub timestamp: Instant,

    /// Type-specific event data
    pub data: EventData,

    /// Whether propagation has been stopped
    pub stopped: bool,

    /// Whether immediate propagation has been stopped
    pub stopped_immediate: bool,

    /// Whether default action has been prevented
    pub prevented_default: bool,
}

impl SyntheticEvent {
    /// Create a new synthetic event.
    ///
    /// # Parameters
    /// - `timestamp`: Current time from `(system_callbacks.get_system_time_fn.cb)()`
    pub fn new(
        event_type: EventType,
        source: EventSource,
        target: DomNodeId,
        timestamp: Instant,
        data: EventData,
    ) -> Self {
        Self {
            event_type,
            source,
            phase: EventPhase::Target,
            target,
            current_target: target,
            timestamp,
            data,
            stopped: false,
            stopped_immediate: false,
            prevented_default: false,
        }
    }

    /// Stop event propagation after the current phase completes.
    ///
    /// This prevents the event from reaching handlers in subsequent phases
    /// (e.g., stopping during capture prevents bubble phase).
    pub fn stop_propagation(&mut self) {
        self.stopped = true;
    }

    /// Stop event propagation immediately.
    ///
    /// This prevents any further handlers from being called, even on the
    /// current target element.
    pub fn stop_immediate_propagation(&mut self) {
        self.stopped_immediate = true;
        self.stopped = true;
    }

    /// Prevent the default action associated with this event.
    ///
    /// For example, prevents form submission on Enter key, or prevents
    /// text selection on drag.
    pub fn prevent_default(&mut self) {
        self.prevented_default = true;
    }

    /// Check if propagation was stopped.
    pub fn is_propagation_stopped(&self) -> bool {
        self.stopped
    }

    /// Check if immediate propagation was stopped.
    pub fn is_immediate_propagation_stopped(&self) -> bool {
        self.stopped_immediate
    }

    /// Check if default action was prevented.
    pub fn is_default_prevented(&self) -> bool {
        self.prevented_default
    }
}

/// Result of event propagation through DOM tree.
#[derive(Debug, Clone)]
pub struct PropagationResult {
    /// Callbacks that should be invoked, in order
    pub callbacks_to_invoke: Vec<(NodeId, EventFilter)>,
    /// Whether default action should be prevented
    pub default_prevented: bool,
}

/// Get the path from root to target node in the DOM tree.
///
/// This is used for event propagation - we need to know which nodes
/// are ancestors of the target to implement capture/bubble phases.
///
/// Returns nodes in order from root to target (inclusive).
pub fn get_dom_path(
    node_hierarchy: &crate::id::NodeHierarchy,
    target_node: NodeHierarchyItemId,
) -> Vec<NodeId> {
    let mut path = Vec::new();
    let target_node_id = match target_node.into_crate_internal() {
        Some(id) => id,
        None => return path,
    };

    let hier_ref = node_hierarchy.as_ref();

    // Build path from target to root
    let mut current = Some(target_node_id);
    while let Some(node_id) = current {
        path.push(node_id);
        current = hier_ref.get(node_id).and_then(|node| node.parent);
    }

    // Reverse to get root → target order
    path.reverse();
    path
}

/// Propagate event through DOM tree with capture and bubble phases.
///
/// This implements DOM Level 2 event propagation:
/// 1. **Capture Phase**: Event travels from root down to target
/// 2. **Target Phase**: Event is at the target element
/// 3. **Bubble Phase**: Event travels from target back up to root
///
/// The event can be stopped at any point via `stopPropagation()` or
/// `stopImmediatePropagation()`.
pub fn propagate_event(
    event: &mut SyntheticEvent,
    node_hierarchy: &crate::id::NodeHierarchy,
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
) -> PropagationResult {
    let path = get_dom_path(node_hierarchy, event.target.node);
    if path.is_empty() {
        return PropagationResult::default();
    }

    let ancestors = &path[..path.len().saturating_sub(1)];
    let target_node_id = *path.last().unwrap();

    let mut result = PropagationResult::default();

    // Phase 1: Capture (root → target)
    propagate_phase(
        event,
        ancestors.iter().copied(),
        EventPhase::Capture,
        callbacks,
        &mut result,
    );

    // Phase 2: Target
    if !event.stopped {
        propagate_target_phase(event, target_node_id, callbacks, &mut result);
    }

    // Phase 3: Bubble (target → root)
    if !event.stopped {
        propagate_phase(
            event,
            ancestors.iter().rev().copied(),
            EventPhase::Bubble,
            callbacks,
            &mut result,
        );
    }

    result.default_prevented = event.prevented_default;
    result
}

/// Process a single propagation phase (Capture or Bubble)
fn propagate_phase(
    event: &mut SyntheticEvent,
    nodes: impl Iterator<Item = NodeId>,
    phase: EventPhase,
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
    result: &mut PropagationResult,
) {
    event.phase = phase;

    for node_id in nodes {
        if event.stopped_immediate || event.stopped {
            return;
        }

        event.current_target = DomNodeId {
            dom: event.target.dom,
            node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
        };

        collect_matching_callbacks(event, node_id, phase, callbacks, result);
    }
}

/// Process the target phase
fn propagate_target_phase(
    event: &mut SyntheticEvent,
    target_node_id: NodeId,
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
    result: &mut PropagationResult,
) {
    event.phase = EventPhase::Target;
    event.current_target = event.target;

    collect_matching_callbacks(event, target_node_id, EventPhase::Target, callbacks, result);
}

/// Collect callbacks that match the current phase for a node
fn collect_matching_callbacks(
    event: &SyntheticEvent,
    node_id: NodeId,
    phase: EventPhase,
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
    result: &mut PropagationResult,
) {
    let Some(node_callbacks) = callbacks.get(&node_id) else {
        return;
    };

    let matching = node_callbacks
        .iter()
        .take_while(|_| !event.stopped_immediate)
        .filter(|filter| matches_filter_phase(filter, event, phase))
        .map(|filter| (node_id, *filter));

    result.callbacks_to_invoke.extend(matching);
}

impl Default for PropagationResult {
    fn default() -> Self {
        Self {
            callbacks_to_invoke: Vec::new(),
            default_prevented: false,
        }
    }
}

// =============================================================================
// DEFAULT ACTIONS (W3C UI Events / HTML5 Activation Behavior)
// =============================================================================

/// Default actions are built-in behaviors that occur in response to events.
///
/// Per W3C DOM Event specification:
/// > A default action is an action that the implementation is expected to take
/// > in response to an event, unless that action is cancelled by the script.
///
/// Examples:
/// - Tab key → move focus to next focusable element
/// - Enter/Space on button → activate (click) the button
/// - Escape → clear focus or close modal
/// - Arrow keys in listbox → move selection
///
/// Default actions are processed AFTER all event callbacks have been invoked,
/// and only if `event.prevent_default()` was NOT called.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[repr(C, u8)]
pub enum DefaultAction {
    /// Move focus to the next focusable element (Tab key)
    FocusNext,
    /// Move focus to the previous focusable element (Shift+Tab)
    FocusPrevious,
    /// Move focus to the first focusable element
    FocusFirst,
    /// Move focus to the last focusable element
    FocusLast,
    /// Clear focus from the currently focused element (Escape key)
    ClearFocus,
    /// Activate the focused element (Enter/Space on activatable elements)
    /// This generates a synthetic Click event on the target
    ActivateFocusedElement {
        target: DomNodeId,
    },
    /// Submit the form containing the focused element (Enter in form input)
    SubmitForm {
        form_node: DomNodeId,
    },
    /// Close the current modal/dialog (Escape key when modal is open)
    CloseModal {
        modal_node: DomNodeId,
    },
    /// Scroll the focused scrollable container
    ScrollFocusedContainer {
        direction: ScrollDirection,
        amount: ScrollAmount,
    },
    /// Select all text in the focused text input (Ctrl+A / Cmd+A)
    SelectAllText,
    /// No default action for this event
    None,
}

/// Amount to scroll for keyboard-based scrolling
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum ScrollAmount {
    /// Scroll by one line (arrow keys)
    Line,
    /// Scroll by one page (Page Up/Down)
    Page,
    /// Scroll to start/end (Home/End)
    Document,
}

/// Result of determining what default action should occur for an event.
///
/// This is computed AFTER event dispatch, based on:
/// 1. The event type
/// 2. The target element's type/role
/// 3. Whether `prevent_default()` was called
#[derive(Debug, Clone)]
#[repr(C)]
pub struct DefaultActionResult {
    /// The default action to perform (if any)
    pub action: DefaultAction,
    /// Whether the action was prevented by a callback
    pub prevented: bool,
}

impl Default for DefaultActionResult {
    fn default() -> Self {
        Self {
            action: DefaultAction::None,
            prevented: false,
        }
    }
}

impl DefaultActionResult {
    /// Create a new result with a specific action
    pub fn new(action: DefaultAction) -> Self {
        Self {
            action,
            prevented: false,
        }
    }

    /// Create a prevented result (callback called prevent_default)
    pub fn prevented() -> Self {
        Self {
            action: DefaultAction::None,
            prevented: true,
        }
    }

    /// Check if there's an action to perform
    pub fn has_action(&self) -> bool {
        !self.prevented && !matches!(self.action, DefaultAction::None)
    }
}

/// Trait for elements that have activation behavior (can be "clicked" via keyboard).
///
/// Per HTML5 spec, elements with activation behavior include:
/// - `<button>` elements
/// - `<input type="submit">`, `<input type="button">`, `<input type="reset">`
/// - `<a>` elements with href
/// - `<area>` elements with href
/// - Any element with a click handler (implicit activation)
///
/// When an element with activation behavior is focused and the user presses
/// Enter or Space, a synthetic click event is generated.
pub trait ActivationBehavior {
    /// Returns true if this element can be activated via keyboard (Enter/Space)
    fn has_activation_behavior(&self) -> bool;

    /// Returns true if this element is currently activatable
    /// (e.g., not disabled, not aria-disabled="true")
    fn is_activatable(&self) -> bool;
}

/// Trait to query if a node is focusable for tab navigation
pub trait Focusable {
    /// Returns the tabindex value for this element (-1, 0, or positive)
    fn get_tabindex(&self) -> Option<i32>;

    /// Returns true if this element can receive focus
    fn is_focusable(&self) -> bool;

    /// Returns true if this element should be in the tab order
    fn is_in_tab_order(&self) -> bool {
        match self.get_tabindex() {
            None => self.is_naturally_focusable(),
            Some(i) => i >= 0,
        }
    }

    /// Returns true if this element type is naturally focusable
    /// (button, input, select, textarea, a[href])
    fn is_naturally_focusable(&self) -> bool;
}

/// Check if an event filter matches the given event in the current phase.
///
/// This is used during event propagation to determine which callbacks
/// should be invoked at each phase.
fn matches_filter_phase(
    filter: &EventFilter,
    event: &SyntheticEvent,
    current_phase: EventPhase,
) -> bool {
    // For now, we match based on the filter type
    // In the future, this will also check EventPhase and EventConditions

    match filter {
        EventFilter::Hover(hover_filter) => {
            matches_hover_filter(hover_filter, event, current_phase)
        }
        EventFilter::Focus(focus_filter) => {
            matches_focus_filter(focus_filter, event, current_phase)
        }
        EventFilter::Window(window_filter) => {
            matches_window_filter(window_filter, event, current_phase)
        }
        EventFilter::Component(component_filter) => {
            matches_component_filter(component_filter, event, current_phase)
        }
        EventFilter::Application(_) => {
            // Application events - will be implemented in future
            false
        }
    }
}

/// Check if a component (lifecycle) filter matches the event.
///
/// Lifecycle events produced by `diff::reconcile_dom` carry the target node in
/// `SyntheticEvent.target`, so dispatchers that bypass `propagate_event` and
/// invoke the target directly also need a way to compare. This predicate is
/// the single source of truth for that comparison; changing it without
/// updating `event_type_to_filters` will de-sync dispatch.
fn matches_component_filter(
    filter: &ComponentEventFilter,
    event: &SyntheticEvent,
    _phase: EventPhase,
) -> bool {
    matches!(
        (filter, &event.event_type),
        (ComponentEventFilter::AfterMount, EventType::Mount)
            | (ComponentEventFilter::BeforeUnmount, EventType::Unmount)
            | (ComponentEventFilter::Updated, EventType::Update)
            | (ComponentEventFilter::NodeResized, EventType::Resize)
    )
}

/// Check if the event data contains a mouse event with the expected button.
fn check_mouse_button(data: &EventData, expected: MouseButton) -> bool {
    if let EventData::Mouse(mouse_data) = data {
        mouse_data.button == expected
    } else {
        false
    }
}

/// Check if a hover filter matches the event.
fn matches_hover_filter(
    filter: &HoverEventFilter,
    event: &SyntheticEvent,
    _phase: EventPhase,
) -> bool {
    use HoverEventFilter::*;

    match (filter, &event.event_type) {
        (MouseOver, EventType::MouseOver) => true,
        (MouseDown, EventType::MouseDown) => true,
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Middle)
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
        (MouseEnter, EventType::MouseEnter) => true,
        (MouseLeave, EventType::MouseLeave) => true,
        (Scroll, EventType::Scroll) => true,
        (ScrollStart, EventType::ScrollStart) => true,
        (ScrollEnd, EventType::ScrollEnd) => true,
        (TextInput, EventType::Input) => true,
        (VirtualKeyDown, EventType::KeyDown) => true,
        (VirtualKeyUp, EventType::KeyUp) => true,
        (HoveredFile, EventType::FileHover) => true,
        (DroppedFile, EventType::FileDrop) => true,
        (HoveredFileCancelled, EventType::FileHoverCancel) => true,
        (TouchStart, EventType::TouchStart) => true,
        (TouchMove, EventType::TouchMove) => true,
        (TouchEnd, EventType::TouchEnd) => true,
        (TouchCancel, EventType::TouchCancel) => true,
        (PenDown, EventType::PenDown) => true,
        (PenMove, EventType::PenMove) => true,
        (PenUp, EventType::PenUp) => true,
        (PenEnter, EventType::PenEnter) => true,
        (PenLeave, EventType::PenLeave) => true,
        (DragStart, EventType::DragStart) => true,
        (Drag, EventType::Drag) => true,
        (DragEnd, EventType::DragEnd) => true,
        (DragEnter, EventType::DragEnter) => true,
        (DragOver, EventType::DragOver) => true,
        (DragLeave, EventType::DragLeave) => true,
        (Drop, EventType::Drop) => true,
        (DoubleClick, EventType::DoubleClick) => true,
        (SensorChanged, EventType::SensorChanged) => true,
        (GamepadInput, EventType::GamepadInput) => true,
        _ => false,
    }
}

/// Check if a focus filter matches the event.
fn matches_focus_filter(
    filter: &FocusEventFilter,
    event: &SyntheticEvent,
    _phase: EventPhase,
) -> bool {
    use FocusEventFilter::*;

    match (filter, &event.event_type) {
        (MouseOver, EventType::MouseOver) => true,
        (MouseDown, EventType::MouseDown) => true,
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Middle)
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
        (MouseEnter, EventType::MouseEnter) => true,
        (MouseLeave, EventType::MouseLeave) => true,
        (Scroll, EventType::Scroll) => true,
        (ScrollStart, EventType::ScrollStart) => true,
        (ScrollEnd, EventType::ScrollEnd) => true,
        (TextInput, EventType::Input) => true,
        (VirtualKeyDown, EventType::KeyDown) => true,
        (VirtualKeyUp, EventType::KeyUp) => true,
        (FocusReceived, EventType::Focus) => true,
        (FocusLost, EventType::Blur) => true,
        (DragStart, EventType::DragStart) => true,
        (Drag, EventType::Drag) => true,
        (DragEnd, EventType::DragEnd) => true,
        (DragEnter, EventType::DragEnter) => true,
        (DragOver, EventType::DragOver) => true,
        (DragLeave, EventType::DragLeave) => true,
        (Drop, EventType::Drop) => true,
        _ => false,
    }
}

/// Check if a window filter matches the event.
fn matches_window_filter(
    filter: &WindowEventFilter,
    event: &SyntheticEvent,
    _phase: EventPhase,
) -> bool {
    use WindowEventFilter::*;

    match (filter, &event.event_type) {
        (MouseOver, EventType::MouseOver) => true,
        (MouseDown, EventType::MouseDown) => true,
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Middle)
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
        (MouseEnter, EventType::MouseEnter) => true,
        (MouseLeave, EventType::MouseLeave) => true,
        (Scroll, EventType::Scroll) => true,
        (ScrollStart, EventType::ScrollStart) => true,
        (ScrollEnd, EventType::ScrollEnd) => true,
        (TextInput, EventType::Input) => true,
        (VirtualKeyDown, EventType::KeyDown) => true,
        (VirtualKeyUp, EventType::KeyUp) => true,
        (HoveredFile, EventType::FileHover) => true,
        (DroppedFile, EventType::FileDrop) => true,
        (HoveredFileCancelled, EventType::FileHoverCancel) => true,
        (Resized, EventType::WindowResize) => true,
        (Moved, EventType::WindowMove) => true,
        (TouchStart, EventType::TouchStart) => true,
        (TouchMove, EventType::TouchMove) => true,
        (TouchEnd, EventType::TouchEnd) => true,
        (TouchCancel, EventType::TouchCancel) => true,
        (PenDown, EventType::PenDown) => true,
        (PenMove, EventType::PenMove) => true,
        (PenUp, EventType::PenUp) => true,
        (PenEnter, EventType::PenEnter) => true,
        (PenLeave, EventType::PenLeave) => true,
        (FocusReceived, EventType::Focus) => true,
        (FocusLost, EventType::Blur) => true,
        (CloseRequested, EventType::WindowClose) => true,
        (ThemeChanged, EventType::ThemeChange) => true,
        (WindowFocusReceived, EventType::WindowFocusIn) => true,
        (WindowFocusLost, EventType::WindowFocusOut) => true,
        (SensorChanged, EventType::SensorChanged) => true,
        (GamepadInput, EventType::GamepadInput) => true,
        (DragStart, EventType::DragStart) => true,
        (Drag, EventType::Drag) => true,
        (DragEnd, EventType::DragEnd) => true,
        (DragEnter, EventType::DragEnter) => true,
        (DragOver, EventType::DragOver) => true,
        (DragLeave, EventType::DragLeave) => true,
        (Drop, EventType::Drop) => true,
        _ => false,
    }
}

/// Detect lifecycle events by comparing old and new DOM state.
///
/// This is the simple, index-based lifecycle detection that doesn't account for
/// node reordering. For more sophisticated reconciliation that can detect moves,
/// use `detect_lifecycle_events_with_reconciliation`.
///
/// Generates Mount, Unmount, and Resize events by comparing DOM hierarchies.
pub fn detect_lifecycle_events(
    old_dom_id: DomId,
    new_dom_id: DomId,
    old_hierarchy: Option<&crate::id::NodeHierarchy>,
    new_hierarchy: Option<&crate::id::NodeHierarchy>,
    old_layout: Option<&BTreeMap<NodeId, LogicalRect>>,
    new_layout: Option<&BTreeMap<NodeId, LogicalRect>>,
    timestamp: Instant,
) -> Vec<SyntheticEvent> {
    let old_nodes = collect_node_ids(old_hierarchy);
    let new_nodes = collect_node_ids(new_hierarchy);

    let mut events = Vec::new();

    // Mount events: nodes in new but not in old
    if let Some(layout) = new_layout {
        for &node_id in new_nodes.difference(&old_nodes) {
            events.push(create_mount_event(node_id, new_dom_id, layout, &timestamp));
        }
    }

    // Unmount events: nodes in old but not in new
    if let Some(layout) = old_layout {
        for &node_id in old_nodes.difference(&new_nodes) {
            events.push(create_unmount_event(
                node_id, old_dom_id, layout, &timestamp,
            ));
        }
    }

    // Resize events: nodes in both with changed bounds
    if let (Some(old_l), Some(new_l)) = (old_layout, new_layout) {
        for &node_id in old_nodes.intersection(&new_nodes) {
            if let Some(ev) = create_resize_event(node_id, new_dom_id, old_l, new_l, &timestamp) {
                events.push(ev);
            }
        }
    }

    events
}

fn collect_node_ids(hierarchy: Option<&crate::id::NodeHierarchy>) -> BTreeSet<NodeId> {
    hierarchy
        .map(|h| h.as_ref().linear_iter().collect())
        .unwrap_or_default()
}

fn create_lifecycle_event(
    event_type: EventType,
    node_id: NodeId,
    dom_id: DomId,
    timestamp: &Instant,
    data: LifecycleEventData,
) -> SyntheticEvent {
    let dom_node_id = DomNodeId {
        dom: dom_id,
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
    };
    SyntheticEvent {
        event_type,
        source: EventSource::Lifecycle,
        phase: EventPhase::Target,
        target: dom_node_id,
        current_target: dom_node_id,
        timestamp: timestamp.clone(),
        data: EventData::Lifecycle(data),
        stopped: false,
        stopped_immediate: false,
        prevented_default: false,
    }
}

fn create_mount_event(
    node_id: NodeId,
    dom_id: DomId,
    layout: &BTreeMap<NodeId, LogicalRect>,
    timestamp: &Instant,
) -> SyntheticEvent {
    let current_bounds = layout.get(&node_id).copied().unwrap_or(LogicalRect::zero());
    create_lifecycle_event(
        EventType::Mount,
        node_id,
        dom_id,
        timestamp,
        LifecycleEventData {
            reason: LifecycleReason::InitialMount,
            previous_bounds: None,
            current_bounds,
        },
    )
}

fn create_unmount_event(
    node_id: NodeId,
    dom_id: DomId,
    layout: &BTreeMap<NodeId, LogicalRect>,
    timestamp: &Instant,
) -> SyntheticEvent {
    let previous_bounds = layout.get(&node_id).copied().unwrap_or(LogicalRect::zero());
    create_lifecycle_event(
        EventType::Unmount,
        node_id,
        dom_id,
        timestamp,
        LifecycleEventData {
            reason: LifecycleReason::Unmount,
            previous_bounds: Some(previous_bounds),
            current_bounds: LogicalRect::zero(),
        },
    )
}

fn create_resize_event(
    node_id: NodeId,
    dom_id: DomId,
    old_layout: &BTreeMap<NodeId, LogicalRect>,
    new_layout: &BTreeMap<NodeId, LogicalRect>,
    timestamp: &Instant,
) -> Option<SyntheticEvent> {
    let old_bounds = *old_layout.get(&node_id)?;
    let new_bounds = *new_layout.get(&node_id)?;

    if old_bounds.size == new_bounds.size {
        return None;
    }

    Some(create_lifecycle_event(
        EventType::Resize,
        node_id,
        dom_id,
        timestamp,
        LifecycleEventData {
            reason: LifecycleReason::Resize,
            previous_bounds: Some(old_bounds),
            current_bounds: new_bounds,
        },
    ))
}

/// Result of lifecycle event detection with reconciliation.
///
/// Contains both the generated lifecycle events and a mapping from old to new
/// node IDs for state migration (focus, scroll, etc.).
#[derive(Debug, Clone, Default)]
pub struct LifecycleEventResult {
    /// Lifecycle events (Mount, Unmount, Resize, Update)
    pub events: Vec<SyntheticEvent>,
    /// Maps old NodeId -> new NodeId for matched nodes.
    /// Use this to migrate focus, scroll state, and other node-specific state.
    pub node_id_mapping: crate::OrderedMap<NodeId, NodeId>,
}

/// Detect lifecycle events using reconciliation with stable keys and content hashing.
///
/// This is the advanced lifecycle detection that can correctly identify:
/// - **Moves**: When a node changes position but keeps its identity (via key or hash)
/// - **Mounts**: When a new node appears
/// - **Unmounts**: When an existing node disappears
/// - **Resizes**: When a node's layout bounds change
/// - **Updates**: When a keyed node's content changes
///
/// The reconciliation strategy is:
/// 1. **Stable Key Match:** Nodes with `.with_reconciliation_key()` are matched by key (O(1))
/// 2. **Hash Match:** Nodes without keys are matched by content hash (enables reorder detection)
/// 3. **Fallback:** Unmatched nodes generate Mount/Unmount events
///
/// # Arguments
/// * `dom_id` - The DOM identifier
/// * `old_node_data` - Node data from the previous frame
/// * `new_node_data` - Node data from the current frame
/// * `old_layout` - Layout bounds from the previous frame
/// * `new_layout` - Layout bounds from the current frame
/// * `timestamp` - Current timestamp for events
///
/// # Returns
/// A `LifecycleEventResult` containing:
/// - `events`: Lifecycle events to dispatch
/// - `node_id_mapping`: Mapping from old to new NodeIds for state migration
///
/// # Example
/// ```rust,ignore
/// let result = detect_lifecycle_events_with_reconciliation(
///     dom_id,
///     &old_node_data,
///     &new_node_data,
///     &old_layout,
///     &new_layout,
///     timestamp,
/// );
///
/// // Dispatch lifecycle events
/// for event in result.events {
///     dispatch_event(event);
/// }
///
/// // Migrate focus to new node ID
/// if let Some(focused) = focus_manager.focused_node {
///     if let Some(&new_id) = result.node_id_mapping.get(&focused) {
///         focus_manager.focused_node = Some(new_id);
///     } else {
///         // Focused node was unmounted
///         focus_manager.focused_node = None;
///     }
/// }
/// ```
pub fn detect_lifecycle_events_with_reconciliation(
    dom_id: DomId,
    old_node_data: &[crate::dom::NodeData],
    new_node_data: &[crate::dom::NodeData],
    old_hierarchy: &[crate::styled_dom::NodeHierarchyItem],
    new_hierarchy: &[crate::styled_dom::NodeHierarchyItem],
    old_layout: &crate::OrderedMap<NodeId, LogicalRect>,
    new_layout: &crate::OrderedMap<NodeId, LogicalRect>,
    timestamp: Instant,
) -> LifecycleEventResult {
    let diff_result = crate::diff::reconcile_dom(
        old_node_data,
        new_node_data,
        old_hierarchy,
        new_hierarchy,
        old_layout,
        new_layout,
        dom_id,
        timestamp,
    );

    LifecycleEventResult {
        events: diff_result.events,
        node_id_mapping: crate::diff::create_migration_map(&diff_result.node_moves),
    }
}

/// Event filter that only fires when an element is hovered over.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum HoverEventFilter {
    /// Mouse moved over the hovered element
    MouseOver,
    /// Any mouse button pressed on the hovered element
    MouseDown,
    /// Left mouse button pressed on the hovered element
    LeftMouseDown,
    /// Right mouse button pressed on the hovered element
    RightMouseDown,
    /// Middle mouse button pressed on the hovered element
    MiddleMouseDown,
    /// Any mouse button released on the hovered element
    MouseUp,
    /// Left mouse button released on the hovered element
    LeftMouseUp,
    /// Right mouse button released on the hovered element
    RightMouseUp,
    /// Middle mouse button released on the hovered element
    MiddleMouseUp,
    /// Mouse entered the hovered element bounds
    MouseEnter,
    /// Mouse left the hovered element bounds
    MouseLeave,
    /// Scroll event on the hovered element
    Scroll,
    /// Scroll started on the hovered element
    ScrollStart,
    /// Scroll ended on the hovered element
    ScrollEnd,
    /// Text input received while element is hovered
    TextInput,
    /// Virtual key pressed while element is hovered
    VirtualKeyDown,
    /// Virtual key released while element is hovered
    VirtualKeyUp,
    /// File is being hovered over the element
    HoveredFile,
    /// File was dropped onto the element
    DroppedFile,
    /// File hover was cancelled
    HoveredFileCancelled,
    /// Touch started on the hovered element
    TouchStart,
    /// Touch moved on the hovered element
    TouchMove,
    /// Touch ended on the hovered element
    TouchEnd,
    /// Touch was cancelled on the hovered element
    TouchCancel,
    /// Pen/stylus made contact on the hovered element
    PenDown,
    /// Pen/stylus moved while in contact on the hovered element
    PenMove,
    /// Pen/stylus lifted from the hovered element
    PenUp,
    /// Pen/stylus entered proximity of the hovered element
    PenEnter,
    /// Pen/stylus left proximity of the hovered element
    PenLeave,
    /// Apple Pencil 2 / Surface Slim Pen 2 barrel squeeze on the hovered
    /// element. Fires once per squeeze. The matching W3C primitive is the
    /// `PointerEvent` with `pointerType: "pen"` and a transient
    /// `tangentialPressure` spike — most apps tie a tool-switch to it.
    PenSqueeze,
    /// Apple Pencil 2 side double-tap on the hovered element. Fires once
    /// per gesture. Usually mapped to "undo" or "switch eraser".
    PenDoubleTap,
    /// Pen/stylus is hovering above the hovered element (in proximity,
    /// not in contact). Continuous: fires per pen-axis update while the
    /// stylus is held above the surface. Maps to W3C
    /// `PointerEvent('pointermove')` with `buttons: 0` and
    /// `pointerType: 'pen'`.
    PenHover,
    /// New GPS / network location fix arrived for a `GeolocationProbe`
    /// in this node's subtree. Payload accessor:
    /// `CallbackInfo::get_geolocation_fix()`.
    GeolocationFix,
    /// Native geolocation subscription errored / was revoked /
    /// timed out.
    GeolocationError,
    /// A motion-sensor reading changed (P6). Window-level mirror:
    /// `WindowEventFilter::SensorChanged`. Read via `get_sensor_reading`.
    SensorChanged,
    /// A gamepad's state changed / it (dis)connected (P6). Read via
    /// `get_primary_gamepad` / `get_gamepad_state`.
    GamepadInput,
    /// Drag started on the hovered element
    DragStart,
    /// Drag in progress on the hovered element
    Drag,
    /// Drag ended on the hovered element
    DragEnd,
    /// Dragged element entered this element (drop target)
    DragEnter,
    /// Dragged element is over this element (drop target, fires continuously)
    DragOver,
    /// Dragged element left this element (drop target)
    DragLeave,
    /// Element was dropped on this element (drop target)
    Drop,
    /// Double-click detected on the hovered element
    DoubleClick,
    /// Long press detected on the hovered element
    LongPress,
    /// Swipe left gesture on the hovered element
    SwipeLeft,
    /// Swipe right gesture on the hovered element
    SwipeRight,
    /// Swipe up gesture on the hovered element
    SwipeUp,
    /// Swipe down gesture on the hovered element
    SwipeDown,
    /// Pinch-in (zoom out) gesture on the hovered element
    PinchIn,
    /// Pinch-out (zoom in) gesture on the hovered element
    PinchOut,
    /// Clockwise rotation gesture on the hovered element
    RotateClockwise,
    /// Counter-clockwise rotation gesture on the hovered element
    RotateCounterClockwise,

    // W3C MouseOut event (bubbling version of MouseLeave)
    /// Mouse left the element OR moved to a child element (W3C `mouseout`, bubbles)
    MouseOut,

    // W3C Focus events (bubbling versions)
    /// Focus is about to move INTO this element or a descendant (W3C `focusin`, bubbles)
    FocusIn,
    /// Focus is about to move OUT of this element or a descendant (W3C `focusout`, bubbles)
    FocusOut,

    // IME Composition events
    /// IME composition started (W3C `compositionstart`)
    CompositionStart,
    /// IME composition updated (W3C `compositionupdate`)
    CompositionUpdate,
    /// IME composition ended (W3C `compositionend`)
    CompositionEnd,

    // Internal System Events (not exposed to user callbacks)
    #[doc(hidden)]
    /// Internal: Single click for text cursor placement
    SystemTextSingleClick,
    #[doc(hidden)]
    /// Internal: Double click for word selection
    SystemTextDoubleClick,
    #[doc(hidden)]
    /// Internal: Triple click for paragraph/line selection
    SystemTextTripleClick,
}

impl HoverEventFilter {
    /// Check if this is an internal system event that should not be exposed to user callbacks
    pub const fn is_system_internal(&self) -> bool {
        matches!(
            self,
            HoverEventFilter::SystemTextSingleClick
                | HoverEventFilter::SystemTextDoubleClick
                | HoverEventFilter::SystemTextTripleClick
        )
    }

    pub fn to_focus_event_filter(&self) -> Option<FocusEventFilter> {
        match self {
            HoverEventFilter::MouseOver => Some(FocusEventFilter::MouseOver),
            HoverEventFilter::MouseDown => Some(FocusEventFilter::MouseDown),
            HoverEventFilter::LeftMouseDown => Some(FocusEventFilter::LeftMouseDown),
            HoverEventFilter::RightMouseDown => Some(FocusEventFilter::RightMouseDown),
            HoverEventFilter::MiddleMouseDown => Some(FocusEventFilter::MiddleMouseDown),
            HoverEventFilter::MouseUp => Some(FocusEventFilter::MouseUp),
            HoverEventFilter::LeftMouseUp => Some(FocusEventFilter::LeftMouseUp),
            HoverEventFilter::RightMouseUp => Some(FocusEventFilter::RightMouseUp),
            HoverEventFilter::MiddleMouseUp => Some(FocusEventFilter::MiddleMouseUp),
            HoverEventFilter::MouseEnter => Some(FocusEventFilter::MouseEnter),
            HoverEventFilter::MouseLeave => Some(FocusEventFilter::MouseLeave),
            HoverEventFilter::Scroll => Some(FocusEventFilter::Scroll),
            HoverEventFilter::ScrollStart => Some(FocusEventFilter::ScrollStart),
            HoverEventFilter::ScrollEnd => Some(FocusEventFilter::ScrollEnd),
            HoverEventFilter::TextInput => Some(FocusEventFilter::TextInput),
            HoverEventFilter::VirtualKeyDown => Some(FocusEventFilter::VirtualKeyDown),
            HoverEventFilter::VirtualKeyUp => Some(FocusEventFilter::VirtualKeyUp),
            HoverEventFilter::HoveredFile => None,
            HoverEventFilter::DroppedFile => None,
            HoverEventFilter::HoveredFileCancelled => None,
            HoverEventFilter::TouchStart => None,
            HoverEventFilter::TouchMove => None,
            HoverEventFilter::TouchEnd => None,
            HoverEventFilter::TouchCancel => None,
            HoverEventFilter::PenDown => Some(FocusEventFilter::PenDown),
            HoverEventFilter::PenMove => Some(FocusEventFilter::PenMove),
            HoverEventFilter::PenUp => Some(FocusEventFilter::PenUp),
            HoverEventFilter::PenEnter => None,
            HoverEventFilter::PenLeave => None,
            HoverEventFilter::PenSqueeze => None,
            HoverEventFilter::PenDoubleTap => None,
            HoverEventFilter::PenHover => None,
            HoverEventFilter::GeolocationFix => None,
            HoverEventFilter::GeolocationError => None,
            HoverEventFilter::SensorChanged => None,
            HoverEventFilter::GamepadInput => None,
            HoverEventFilter::DragStart => Some(FocusEventFilter::DragStart),
            HoverEventFilter::Drag => Some(FocusEventFilter::Drag),
            HoverEventFilter::DragEnd => Some(FocusEventFilter::DragEnd),
            HoverEventFilter::DragEnter => Some(FocusEventFilter::DragEnter),
            HoverEventFilter::DragOver => Some(FocusEventFilter::DragOver),
            HoverEventFilter::DragLeave => Some(FocusEventFilter::DragLeave),
            HoverEventFilter::Drop => Some(FocusEventFilter::Drop),
            HoverEventFilter::DoubleClick => Some(FocusEventFilter::DoubleClick),
            HoverEventFilter::LongPress => Some(FocusEventFilter::LongPress),
            HoverEventFilter::SwipeLeft => Some(FocusEventFilter::SwipeLeft),
            HoverEventFilter::SwipeRight => Some(FocusEventFilter::SwipeRight),
            HoverEventFilter::SwipeUp => Some(FocusEventFilter::SwipeUp),
            HoverEventFilter::SwipeDown => Some(FocusEventFilter::SwipeDown),
            HoverEventFilter::PinchIn => Some(FocusEventFilter::PinchIn),
            HoverEventFilter::PinchOut => Some(FocusEventFilter::PinchOut),
            HoverEventFilter::RotateClockwise => Some(FocusEventFilter::RotateClockwise),
            HoverEventFilter::RotateCounterClockwise => {
                Some(FocusEventFilter::RotateCounterClockwise)
            }
            HoverEventFilter::MouseOut => Some(FocusEventFilter::MouseLeave), // mouseout → closest focus equivalent
            HoverEventFilter::FocusIn => Some(FocusEventFilter::FocusIn),
            HoverEventFilter::FocusOut => Some(FocusEventFilter::FocusOut),
            HoverEventFilter::CompositionStart => Some(FocusEventFilter::CompositionStart),
            HoverEventFilter::CompositionUpdate => Some(FocusEventFilter::CompositionUpdate),
            HoverEventFilter::CompositionEnd => Some(FocusEventFilter::CompositionEnd),
            // System internal events - don't convert to focus events
            HoverEventFilter::SystemTextSingleClick => None,
            HoverEventFilter::SystemTextDoubleClick => None,
            HoverEventFilter::SystemTextTripleClick => None,
        }
    }
}

/// Event filter similar to `HoverEventFilter` that only fires when the element is focused.
///
/// **Important**: In order for this to fire, the item must have a `tabindex` attribute
/// (to indicate that the item is focus-able).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum FocusEventFilter {
    /// Mouse moved over the focused element
    MouseOver,
    /// Any mouse button pressed on the focused element
    MouseDown,
    /// Left mouse button pressed on the focused element
    LeftMouseDown,
    /// Right mouse button pressed on the focused element
    RightMouseDown,
    /// Middle mouse button pressed on the focused element
    MiddleMouseDown,
    /// Any mouse button released on the focused element
    MouseUp,
    /// Left mouse button released on the focused element
    LeftMouseUp,
    /// Right mouse button released on the focused element
    RightMouseUp,
    /// Middle mouse button released on the focused element
    MiddleMouseUp,
    /// Mouse entered the focused element bounds
    MouseEnter,
    /// Mouse left the focused element bounds
    MouseLeave,
    /// Scroll event on the focused element
    Scroll,
    /// Scroll started on the focused element
    ScrollStart,
    /// Scroll ended on the focused element
    ScrollEnd,
    /// Text input received while element is focused
    TextInput,
    /// Virtual key pressed while element is focused
    VirtualKeyDown,
    /// Virtual key released while element is focused
    VirtualKeyUp,
    /// Element received keyboard focus
    FocusReceived,
    /// Element lost keyboard focus
    FocusLost,
    /// Pen/stylus made contact on the focused element
    PenDown,
    /// Pen/stylus moved while in contact on the focused element
    PenMove,
    /// Pen/stylus lifted from the focused element
    PenUp,
    /// Drag started on the focused element
    DragStart,
    /// Drag in progress on the focused element
    Drag,
    /// Drag ended on the focused element
    DragEnd,
    /// Dragged element entered this focused element (drop target)
    DragEnter,
    /// Dragged element is over this focused element (drop target)
    DragOver,
    /// Dragged element left this focused element (drop target)
    DragLeave,
    /// Element was dropped on this focused element (drop target)
    Drop,
    /// Double-click detected on the focused element
    DoubleClick,
    /// Long press detected on the focused element
    LongPress,
    /// Swipe left gesture on the focused element
    SwipeLeft,
    /// Swipe right gesture on the focused element
    SwipeRight,
    /// Swipe up gesture on the focused element
    SwipeUp,
    /// Swipe down gesture on the focused element
    SwipeDown,
    /// Pinch-in (zoom out) gesture on the focused element
    PinchIn,
    /// Pinch-out (zoom in) gesture on the focused element
    PinchOut,
    /// Clockwise rotation gesture on the focused element
    RotateClockwise,
    /// Counter-clockwise rotation gesture on the focused element
    RotateCounterClockwise,

    // W3C Focus events (bubbling versions, fires on focused element when focus changes)
    /// Focus moved into this element or a descendant (W3C `focusin`)
    FocusIn,
    /// Focus moved out of this element or a descendant (W3C `focusout`)
    FocusOut,

    // IME Composition events
    /// IME composition started (W3C `compositionstart`)
    CompositionStart,
    /// IME composition updated (W3C `compositionupdate`)
    CompositionUpdate,
    /// IME composition ended (W3C `compositionend`)
    CompositionEnd,
}

/// Event filter that fires when any action fires on the entire window
/// (regardless of whether any element is hovered or focused over).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum WindowEventFilter {
    /// Mouse moved anywhere in window
    MouseOver,
    /// Any mouse button pressed anywhere in window
    MouseDown,
    /// Left mouse button pressed anywhere in window
    LeftMouseDown,
    /// Right mouse button pressed anywhere in window
    RightMouseDown,
    /// Middle mouse button pressed anywhere in window
    MiddleMouseDown,
    /// Any mouse button released anywhere in window
    MouseUp,
    /// Left mouse button released anywhere in window
    LeftMouseUp,
    /// Right mouse button released anywhere in window
    RightMouseUp,
    /// Middle mouse button released anywhere in window
    MiddleMouseUp,
    /// Mouse entered the window
    MouseEnter,
    /// Mouse left the window
    MouseLeave,
    /// Scroll event anywhere in window
    Scroll,
    /// Scroll started anywhere in window
    ScrollStart,
    /// Scroll ended anywhere in window
    ScrollEnd,
    /// Text input received in window
    TextInput,
    /// Virtual key pressed in window
    VirtualKeyDown,
    /// Virtual key released in window
    VirtualKeyUp,
    /// File is being hovered over the window
    HoveredFile,
    /// File was dropped onto the window
    DroppedFile,
    /// File hover was cancelled
    HoveredFileCancelled,
    /// Window was resized
    Resized,
    /// Window was moved
    Moved,
    /// Touch started anywhere in window
    TouchStart,
    /// Touch moved anywhere in window
    TouchMove,
    /// Touch ended anywhere in window
    TouchEnd,
    /// Touch was cancelled
    TouchCancel,
    /// Window received focus
    FocusReceived,
    /// Window lost focus
    FocusLost,
    /// Window close was requested
    CloseRequested,
    /// System theme changed (light/dark mode)
    ThemeChanged,
    /// Window received OS-level focus
    WindowFocusReceived,
    /// Window lost OS-level focus
    WindowFocusLost,
    /// Pen/stylus made contact anywhere in window
    PenDown,
    /// Pen/stylus moved while in contact anywhere in window
    PenMove,
    /// Pen/stylus lifted anywhere in window
    PenUp,
    /// Pen/stylus entered window proximity
    PenEnter,
    /// Pen/stylus left window proximity
    PenLeave,
    /// Pen barrel-squeeze gesture fired in the window. See
    /// [`HoverEventFilter::PenSqueeze`].
    PenSqueeze,
    /// Pen side double-tap gesture fired in the window. See
    /// [`HoverEventFilter::PenDoubleTap`].
    PenDoubleTap,
    /// Pen hover in the window (in proximity, not in contact). See
    /// [`HoverEventFilter::PenHover`].
    PenHover,
    /// New GPS / network location fix arrived. Payload accessor:
    /// `CallbackInfo::get_geolocation_fix()`. Window-level rather
    /// than per-node because the user's location isn't bound to any
    /// particular DOM node — but a node-level mirror
    /// (`HoverEventFilter::GeolocationFix`) fires on every
    /// `GeolocationProbe` in the tree as well, for the common
    /// "redraw this node when the location changes" pattern.
    GeolocationFix,
    /// Native geolocation subscription dropped or errored (signal
    /// lost, no provider, permission revoked mid-session).
    GeolocationError,
    /// A motion-sensor reading changed (P6). Fires window-level (the device
    /// isn't bound to a node); read via `CallbackInfo::get_sensor_reading`.
    SensorChanged,
    /// A gamepad's buttons / axes changed or it (dis)connected (P6); read via
    /// `get_primary_gamepad` / `get_gamepad_state`.
    GamepadInput,
    /// Drag started anywhere in window
    DragStart,
    /// Drag in progress anywhere in window
    Drag,
    /// Drag ended anywhere in window
    DragEnd,
    /// Dragged element entered a drop target in window
    DragEnter,
    /// Dragged element is over a drop target in window
    DragOver,
    /// Dragged element left a drop target in window
    DragLeave,
    /// Element was dropped on a drop target in window
    Drop,
    /// Double-click detected anywhere in window
    DoubleClick,
    /// Long press detected anywhere in window
    LongPress,
    /// Swipe left gesture anywhere in window
    SwipeLeft,
    /// Swipe right gesture anywhere in window
    SwipeRight,
    /// Swipe up gesture anywhere in window
    SwipeUp,
    /// Swipe down gesture anywhere in window
    SwipeDown,
    /// Pinch-in (zoom out) gesture anywhere in window
    PinchIn,
    /// Pinch-out (zoom in) gesture anywhere in window
    PinchOut,
    /// Clockwise rotation gesture anywhere in window
    RotateClockwise,
    /// Counter-clockwise rotation gesture anywhere in window
    RotateCounterClockwise,
    /// The window's DPI scale factor changed (e.g., moved to a monitor with
    /// different scaling). The new DPI is available via `CallbackInfo::get_hidpi_factor()`.
    DpiChanged,
    /// The window moved to a different monitor. The new monitor is available
    /// via `CallbackInfo::get_current_monitor()`.
    MonitorChanged,
}

impl WindowEventFilter {
    pub fn to_hover_event_filter(&self) -> Option<HoverEventFilter> {
        match self {
            WindowEventFilter::MouseOver => Some(HoverEventFilter::MouseOver),
            WindowEventFilter::MouseDown => Some(HoverEventFilter::MouseDown),
            WindowEventFilter::LeftMouseDown => Some(HoverEventFilter::LeftMouseDown),
            WindowEventFilter::RightMouseDown => Some(HoverEventFilter::RightMouseDown),
            WindowEventFilter::MiddleMouseDown => Some(HoverEventFilter::MiddleMouseDown),
            WindowEventFilter::MouseUp => Some(HoverEventFilter::MouseUp),
            WindowEventFilter::LeftMouseUp => Some(HoverEventFilter::LeftMouseUp),
            WindowEventFilter::RightMouseUp => Some(HoverEventFilter::RightMouseUp),
            WindowEventFilter::MiddleMouseUp => Some(HoverEventFilter::MiddleMouseUp),
            WindowEventFilter::Scroll => Some(HoverEventFilter::Scroll),
            WindowEventFilter::ScrollStart => Some(HoverEventFilter::ScrollStart),
            WindowEventFilter::ScrollEnd => Some(HoverEventFilter::ScrollEnd),
            WindowEventFilter::TextInput => Some(HoverEventFilter::TextInput),
            WindowEventFilter::VirtualKeyDown => Some(HoverEventFilter::VirtualKeyDown),
            WindowEventFilter::VirtualKeyUp => Some(HoverEventFilter::VirtualKeyUp),
            WindowEventFilter::HoveredFile => Some(HoverEventFilter::HoveredFile),
            WindowEventFilter::DroppedFile => Some(HoverEventFilter::DroppedFile),
            WindowEventFilter::HoveredFileCancelled => Some(HoverEventFilter::HoveredFileCancelled),
            // MouseEnter and MouseLeave on the **window** - does not mean a mouseenter
            // and a mouseleave on the hovered element
            WindowEventFilter::MouseEnter => None,
            WindowEventFilter::MouseLeave => None,
            WindowEventFilter::Resized => None,
            WindowEventFilter::Moved => None,
            WindowEventFilter::TouchStart => Some(HoverEventFilter::TouchStart),
            WindowEventFilter::TouchMove => Some(HoverEventFilter::TouchMove),
            WindowEventFilter::TouchEnd => Some(HoverEventFilter::TouchEnd),
            WindowEventFilter::TouchCancel => Some(HoverEventFilter::TouchCancel),
            WindowEventFilter::FocusReceived => None,
            WindowEventFilter::FocusLost => None,
            WindowEventFilter::CloseRequested => None,
            WindowEventFilter::ThemeChanged => None,
            WindowEventFilter::WindowFocusReceived => None, // specific to window!
            WindowEventFilter::WindowFocusLost => None,     // specific to window!
            WindowEventFilter::PenDown => Some(HoverEventFilter::PenDown),
            WindowEventFilter::PenMove => Some(HoverEventFilter::PenMove),
            WindowEventFilter::PenUp => Some(HoverEventFilter::PenUp),
            WindowEventFilter::PenEnter => Some(HoverEventFilter::PenEnter),
            WindowEventFilter::PenLeave => Some(HoverEventFilter::PenLeave),
            WindowEventFilter::PenSqueeze => Some(HoverEventFilter::PenSqueeze),
            WindowEventFilter::PenDoubleTap => Some(HoverEventFilter::PenDoubleTap),
            WindowEventFilter::PenHover => Some(HoverEventFilter::PenHover),
            WindowEventFilter::GeolocationFix => Some(HoverEventFilter::GeolocationFix),
            WindowEventFilter::GeolocationError => Some(HoverEventFilter::GeolocationError),
            WindowEventFilter::SensorChanged => Some(HoverEventFilter::SensorChanged),
            WindowEventFilter::GamepadInput => Some(HoverEventFilter::GamepadInput),
            WindowEventFilter::DragStart => Some(HoverEventFilter::DragStart),
            WindowEventFilter::Drag => Some(HoverEventFilter::Drag),
            WindowEventFilter::DragEnd => Some(HoverEventFilter::DragEnd),
            WindowEventFilter::DragEnter => Some(HoverEventFilter::DragEnter),
            WindowEventFilter::DragOver => Some(HoverEventFilter::DragOver),
            WindowEventFilter::DragLeave => Some(HoverEventFilter::DragLeave),
            WindowEventFilter::Drop => Some(HoverEventFilter::Drop),
            WindowEventFilter::DoubleClick => Some(HoverEventFilter::DoubleClick),
            WindowEventFilter::LongPress => Some(HoverEventFilter::LongPress),
            WindowEventFilter::SwipeLeft => Some(HoverEventFilter::SwipeLeft),
            WindowEventFilter::SwipeRight => Some(HoverEventFilter::SwipeRight),
            WindowEventFilter::SwipeUp => Some(HoverEventFilter::SwipeUp),
            WindowEventFilter::SwipeDown => Some(HoverEventFilter::SwipeDown),
            WindowEventFilter::PinchIn => Some(HoverEventFilter::PinchIn),
            WindowEventFilter::PinchOut => Some(HoverEventFilter::PinchOut),
            WindowEventFilter::RotateClockwise => Some(HoverEventFilter::RotateClockwise),
            WindowEventFilter::RotateCounterClockwise => {
                Some(HoverEventFilter::RotateCounterClockwise)
            }
            // Window-specific events with no hover equivalent
            WindowEventFilter::DpiChanged => None,
            WindowEventFilter::MonitorChanged => None,
        }
    }
}

/// Defines events related to the lifecycle of a DOM node itself.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ComponentEventFilter {
    /// Fired after the component is first mounted into the DOM.
    AfterMount,
    /// Fired just before the component is removed from the DOM.
    BeforeUnmount,
    /// Fired when the node's layout rectangle has been resized.
    NodeResized,
    /// Fired to trigger the default action for an accessibility component.
    DefaultAction,
    /// Fired when the component becomes selected.
    Selected,
    /// Fired when a keyed component's content has changed (props/state update).
    Updated,
}

/// Defines application-level events not tied to a specific window or node.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ApplicationEventFilter {
    /// Fired when a new hardware device is connected.
    DeviceConnected,
    /// Fired when a hardware device is disconnected.
    DeviceDisconnected,
    /// Fired when a new monitor/display is connected to the system.
    /// Callback receives updated monitor list via `CallbackInfo::get_monitors()`.
    MonitorConnected,
    /// Fired when a monitor/display is disconnected from the system.
    MonitorDisconnected,
}

/// Sets the target for what events can reach the callbacks specifically.
///
/// This determines the condition under which an event is fired, such as whether
/// the node is hovered, focused, or if the event is window-global.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C, u8)]
pub enum EventFilter {
    /// Calls the attached callback when the mouse is actively over the
    /// given element.
    Hover(HoverEventFilter),
    /// Calls the attached callback when the element is currently focused.
    Focus(FocusEventFilter),
    /// Calls the callback when anything related to the window is happening.
    /// The "hit item" will be the root item of the DOM.
    /// For example, this can be useful for tracking the mouse position
    /// (in relation to the window). In difference to `Desktop`, this only
    /// fires when the window is focused.
    ///
    /// This can also be good for capturing controller input, touch input
    /// (i.e. global gestures that aren't attached to any component, but rather
    /// the "window" itself).
    Window(WindowEventFilter),
    /// API stub: Something happened with the node itself (node resized, created or removed).
    Component(ComponentEventFilter),
    /// Something happened with the application (started, shutdown, device plugged in).
    Application(ApplicationEventFilter),
}

impl EventFilter {
    pub const fn is_focus_callback(&self) -> bool {
        match self {
            EventFilter::Focus(_) => true,
            _ => false,
        }
    }
    pub const fn is_window_callback(&self) -> bool {
        match self {
            EventFilter::Window(_) => true,
            _ => false,
        }
    }
}

/// Creates a function inside an impl <enum type> block that returns a single
/// variant if the enum is that variant.
macro_rules! get_single_enum_type {
    ($fn_name:ident, $enum_name:ident:: $variant:ident($return_type:ty)) => {
        pub fn $fn_name(&self) -> Option<$return_type> {
            use self::$enum_name::*;
            match self {
                $variant(e) => Some(*e),
                _ => None,
            }
        }
    };
}

impl EventFilter {
    get_single_enum_type!(as_hover_event_filter, EventFilter::Hover(HoverEventFilter));
    get_single_enum_type!(as_focus_event_filter, EventFilter::Focus(FocusEventFilter));
    get_single_enum_type!(
        as_window_event_filter,
        EventFilter::Window(WindowEventFilter)
    );
}

/// Convert from `On` enum to `EventFilter`.
///
/// This determines which specific filter variant is used based on the event type.
/// For example, `On::TextInput` becomes a Focus event filter, while `On::VirtualKeyDown`
/// becomes a Window event filter (since it's global to the window).
impl From<On> for EventFilter {
    fn from(input: On) -> EventFilter {
        use crate::dom::On::*;
        match input {
            MouseOver => EventFilter::Hover(HoverEventFilter::MouseOver),
            MouseDown => EventFilter::Hover(HoverEventFilter::MouseDown),
            LeftMouseDown => EventFilter::Hover(HoverEventFilter::LeftMouseDown),
            MiddleMouseDown => EventFilter::Hover(HoverEventFilter::MiddleMouseDown),
            RightMouseDown => EventFilter::Hover(HoverEventFilter::RightMouseDown),
            MouseUp => EventFilter::Hover(HoverEventFilter::MouseUp),
            LeftMouseUp => EventFilter::Hover(HoverEventFilter::LeftMouseUp),
            MiddleMouseUp => EventFilter::Hover(HoverEventFilter::MiddleMouseUp),
            RightMouseUp => EventFilter::Hover(HoverEventFilter::RightMouseUp),

            MouseEnter => EventFilter::Hover(HoverEventFilter::MouseEnter),
            MouseLeave => EventFilter::Hover(HoverEventFilter::MouseLeave),
            Scroll => EventFilter::Hover(HoverEventFilter::Scroll),
            TextInput => EventFilter::Focus(FocusEventFilter::TextInput), // focus!
            VirtualKeyDown => EventFilter::Window(WindowEventFilter::VirtualKeyDown), // window!
            VirtualKeyUp => EventFilter::Window(WindowEventFilter::VirtualKeyUp), // window!
            HoveredFile => EventFilter::Hover(HoverEventFilter::HoveredFile),
            DroppedFile => EventFilter::Hover(HoverEventFilter::DroppedFile),
            HoveredFileCancelled => EventFilter::Hover(HoverEventFilter::HoveredFileCancelled),
            FocusReceived => EventFilter::Focus(FocusEventFilter::FocusReceived), // focus!
            FocusLost => EventFilter::Focus(FocusEventFilter::FocusLost),         // focus!

            // Accessibility events - treat as hover events (element-specific)
            Default => EventFilter::Hover(HoverEventFilter::MouseUp), // Default action = click
            Collapse => EventFilter::Hover(HoverEventFilter::MouseUp), // Collapse = click
            Expand => EventFilter::Hover(HoverEventFilter::MouseUp),  // Expand = click
            Increment => EventFilter::Hover(HoverEventFilter::MouseUp), // Increment = click
            Decrement => EventFilter::Hover(HoverEventFilter::MouseUp), // Decrement = click
        }
    }
}

// Cross-Platform Event Dispatch System
// NOTE: The old dispatch_synthetic_events / CallbackTarget / CallbackToInvoke / EventDispatchResult
// pipeline has been removed. Event dispatch now goes through dispatch_events_propagated() in
// event_v2.rs which uses propagate_event() for W3C Capture→Target→Bubble propagation.

/// Trait for managers to provide their pending events.
///
/// Each manager (TextInputManager, ScrollManager, etc.) implements this to
/// report what events occurred since the last frame. This enables a unified,
/// lazy event determination system.
pub trait EventProvider {
    /// Get all pending events from this manager.
    ///
    /// Events should include:
    ///
    /// - `target`: The DomNodeId that was affected
    /// - `event_type`: What happened (Input, Scroll, Focus, etc.)
    /// - `source`: EventSource::User for input, EventSource::Programmatic for API calls
    /// - `data`: Type-specific event data
    ///
    /// After calling this, the manager should mark events as "read" so they
    /// aren't returned again next frame.
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent>;
}

/// Deduplicate synthetic events by (target node, event type).
///
/// Groups by (target.dom, target.node, event_type), keeping the latest timestamp.
pub fn deduplicate_synthetic_events(mut events: Vec<SyntheticEvent>) -> Vec<SyntheticEvent> {
    if events.len() <= 1 {
        return events;
    }

    events.sort_by_key(|e| (e.target.dom, e.target.node, e.event_type));

    // Coalesce consecutive events with same target and event_type
    let mut result = Vec::with_capacity(events.len());
    let mut iter = events.into_iter();

    if let Some(mut prev) = iter.next() {
        for curr in iter {
            if prev.target == curr.target && prev.event_type == curr.event_type {
                // Keep the one with later timestamp
                prev = if curr.timestamp > prev.timestamp {
                    curr
                } else {
                    prev
                };
            } else {
                result.push(prev);
                prev = curr;
            }
        }
        result.push(prev);
    }

    result
}



/// Convert EventType to EventFilters (returns multiple filters for generic + specific events)
///
/// For mouse button events, returns both generic (MouseUp) AND button-specific (LeftMouseUp/RightMouseUp).
/// The button-specific filter is derived from the EventData::Mouse payload.
pub fn event_type_to_filters(event_type: EventType, event_data: &EventData) -> Vec<EventFilter> {
    use EventFilter as EF;
    use EventType as E;
    use FocusEventFilter as F;
    use HoverEventFilter as H;
    use WindowEventFilter as W;

    // Helper: get the button-specific MouseDown filter from EventData
    let button_specific_down = || -> Option<EventFilter> {
        match event_data {
            EventData::Mouse(m) => match m.button {
                MouseButton::Left => Some(EF::Hover(H::LeftMouseDown)),
                MouseButton::Right => Some(EF::Hover(H::RightMouseDown)),
                MouseButton::Middle => Some(EF::Hover(H::MiddleMouseDown)),
                MouseButton::Other(_) => None, // no specific filter for other buttons
            },
            _ => Some(EF::Hover(H::LeftMouseDown)), // fallback
        }
    };

    let button_specific_up = || -> Option<EventFilter> {
        match event_data {
            EventData::Mouse(m) => match m.button {
                MouseButton::Left => Some(EF::Hover(H::LeftMouseUp)),
                MouseButton::Right => Some(EF::Hover(H::RightMouseUp)),
                MouseButton::Middle => Some(EF::Hover(H::MiddleMouseUp)),
                MouseButton::Other(_) => None, // no specific filter for other buttons
            },
            _ => Some(EF::Hover(H::LeftMouseUp)), // fallback
        }
    };

    match event_type {
        // Mouse button events - return BOTH generic and button-specific
        E::MouseDown => {
            let mut v = vec![EF::Hover(H::MouseDown)];
            if let Some(f) = button_specific_down() { v.push(f); }
            v
        }
        E::MouseUp => {
            let mut v = vec![EF::Hover(H::MouseUp)];
            if let Some(f) = button_specific_up() { v.push(f); }
            v
        }

        // Click uses LeftMouseDown (W3C: click is left-button only)
        E::Click => vec![EF::Hover(H::LeftMouseDown)],

        // Other mouse events
        E::MouseOver => vec![EF::Hover(H::MouseOver)],
        E::MouseEnter => vec![EF::Hover(H::MouseEnter)],
        E::MouseLeave => vec![EF::Hover(H::MouseLeave)],
        E::MouseOut => vec![EF::Hover(H::MouseOut)],

        E::DoubleClick => vec![EF::Hover(H::DoubleClick), EF::Window(W::DoubleClick)],
        E::ContextMenu => vec![EF::Hover(H::RightMouseDown)],

        // Keyboard events
        E::KeyDown => vec![EF::Focus(F::VirtualKeyDown)],
        E::KeyUp => vec![EF::Focus(F::VirtualKeyUp)],
        E::KeyPress => vec![EF::Focus(F::TextInput)],

        // IME Composition events
        E::CompositionStart => vec![EF::Hover(H::CompositionStart), EF::Focus(F::CompositionStart)],
        E::CompositionUpdate => vec![EF::Hover(H::CompositionUpdate), EF::Focus(F::CompositionUpdate)],
        E::CompositionEnd => vec![EF::Hover(H::CompositionEnd), EF::Focus(F::CompositionEnd)],

        // Focus events
        E::Focus => vec![EF::Focus(F::FocusReceived)],
        E::Blur => vec![EF::Focus(F::FocusLost)],
        E::FocusIn => vec![EF::Hover(H::FocusIn), EF::Focus(F::FocusIn)],
        E::FocusOut => vec![EF::Hover(H::FocusOut), EF::Focus(F::FocusOut)],

        // Input events
        E::Input | E::Change => vec![EF::Focus(F::TextInput)],

        // Scroll events
        E::Scroll | E::ScrollStart | E::ScrollEnd => vec![EF::Hover(H::Scroll)],

        // Drag events
        E::DragStart => vec![EF::Hover(H::DragStart), EF::Window(W::DragStart)],
        E::Drag => vec![EF::Hover(H::Drag), EF::Window(W::Drag)],
        E::DragEnd => vec![EF::Hover(H::DragEnd), EF::Window(W::DragEnd)],
        E::DragEnter => vec![EF::Hover(H::DragEnter), EF::Window(W::DragEnter)],
        E::DragOver => vec![EF::Hover(H::DragOver), EF::Window(W::DragOver)],
        E::DragLeave => vec![EF::Hover(H::DragLeave), EF::Window(W::DragLeave)],
        E::Drop => vec![EF::Hover(H::Drop), EF::Window(W::Drop)],

        // Touch events
        E::TouchStart => vec![EF::Hover(H::TouchStart)],
        E::TouchMove => vec![EF::Hover(H::TouchMove)],
        E::TouchEnd => vec![EF::Hover(H::TouchEnd)],
        E::TouchCancel => vec![EF::Hover(H::TouchCancel)],

        // Window events
        E::WindowResize => vec![EF::Window(W::Resized)],
        E::WindowMove => vec![EF::Window(W::Moved)],
        E::WindowClose => vec![EF::Window(W::CloseRequested)],
        E::WindowFocusIn => vec![EF::Window(W::WindowFocusReceived)],
        E::WindowFocusOut => vec![EF::Window(W::WindowFocusLost)],
        E::ThemeChange => vec![EF::Window(W::ThemeChanged)],
        E::WindowDpiChanged => vec![EF::Window(W::DpiChanged)],
        E::WindowMonitorChanged => vec![EF::Window(W::MonitorChanged)],

        // Application events
        E::MonitorConnected => vec![EF::Application(ApplicationEventFilter::MonitorConnected)],
        E::MonitorDisconnected => vec![EF::Application(ApplicationEventFilter::MonitorDisconnected)],

        // File events
        E::FileHover => vec![EF::Hover(H::HoveredFile)],
        E::FileDrop => vec![EF::Hover(H::DroppedFile)],
        E::FileHoverCancel => vec![EF::Hover(H::HoveredFileCancelled)],

        // Lifecycle events — dispatched on the target node via EventFilter::Component.
        // Both Mount and Unmount map to their respective Component filters so that
        // `.add_callback(EventFilter::Component(ComponentEventFilter::AfterMount))`
        // actually fires after reconcile_dom emits a SyntheticEvent{EventType::Mount,..}.
        E::Mount => vec![EF::Component(ComponentEventFilter::AfterMount)],
        E::Unmount => vec![EF::Component(ComponentEventFilter::BeforeUnmount)],
        E::Update => vec![EF::Component(ComponentEventFilter::Updated)],
        E::Resize => vec![EF::Component(ComponentEventFilter::NodeResized)],

        // Hardware input-device events (P6) — node-level Hover mirror + the
        // window-level filter (the device isn't bound to a node).
        E::SensorChanged => vec![EF::Hover(H::SensorChanged), EF::Window(W::SensorChanged)],
        E::GamepadInput => vec![EF::Hover(H::GamepadInput), EF::Window(W::GamepadInput)],

        // Unsupported events
        _ => vec![],
    }
}



// Internal System Event Processing

/// Framework-determined side effects (system changes).
///
/// Unlike `CallbackChange` (from user callbacks), these are determined by the
/// framework's event analysis: hit tests, gesture detection, focus rules,
/// text selection, keyboard shortcuts, etc.
///
/// Both `CallbackChange` (user) and `SystemChange` (framework) are processed
/// through exhaustive match on `PlatformWindowV2` — adding a new variant
/// causes a compile error in `apply_system_change()`.
#[derive(Debug, Clone, PartialEq)]
#[must_use = "SystemChange must be processed through apply_system_change()"]
pub enum SystemChange {
    // === Text Selection ===

    /// Process a mouse click for text selection (single/double/triple click).
    TextSelectionClick {
        position: LogicalPosition,
        timestamp: Instant,
    },
    /// Extend text selection via mouse drag.
    TextSelectionDrag {
        start_position: LogicalPosition,
        current_position: LogicalPosition,
    },
    /// Unified selection operation: cursor movement, selection extension, or deletion.
    ///
    /// Replaces the old ArrowKeyNavigation and DeleteTextSelection variants.
    /// Every keyboard shortcut maps to a single SelectionOp — see its docs.
    ApplySelectionOp {
        target: DomNodeId,
        op: SelectionOp,
    },

    // === Keyboard Shortcuts ===

    /// Copy selected text to system clipboard (Ctrl+C / Cmd+C).
    CopyToClipboard,
    /// Cut selected text to clipboard and delete (Ctrl+X / Cmd+X).
    CutToClipboard { target: DomNodeId },
    /// Paste text from system clipboard at cursor (Ctrl+V / Cmd+V).
    PasteFromClipboard,
    /// Select all text in focused node (Ctrl+A / Cmd+A).
    SelectAllText,
    /// Undo last text edit (Ctrl+Z / Cmd+Z).
    UndoTextEdit { target: DomNodeId },
    /// Redo last undone edit (Ctrl+Y / Ctrl+Shift+Z / Cmd+Shift+Z).
    RedoTextEdit { target: DomNodeId },

    // === Multi-Cursor ===

    /// Add a cursor at the clicked position (Ctrl+Click).
    /// The position will be hit-tested to find the text cursor location.
    AddCursorAtClick {
        position: LogicalPosition,
    },
    /// Select the next occurrence of the current selection's text (Ctrl+D).
    /// If the primary selection is a cursor, expand it to the word first.
    SelectNextOccurrence {
        target: DomNodeId,
    },

    // === Text Input ===

    /// Apply pending text input from platform (keyboard/IME).
    ApplyPendingTextInput,
    /// Apply text changeset (incremental relayout).
    ApplyTextChangeset,

    // === Drag & Drop ===

    /// Activate node drag on a draggable element.
    ActivateNodeDrag {
        dom_id: crate::dom::DomId,
        node_id: crate::id::NodeId,
    },
    /// Activate window drag (CSD titlebar).
    ActivateWindowDrag,
    /// Set up drag visual state (:dragging pseudo-state, GPU transform key, DragDropManager sync).
    InitDragVisualState,
    /// Set :drag-over pseudo-state on a target node.
    SetDragOverState { target: DomNodeId, active: bool },
    /// Update current drop target in drag context.
    UpdateDropTarget { target: DomNodeId },
    /// Update GPU transform for active node drag.
    UpdateDragGpuTransform,
    /// End drag: clear pseudo-states, remove GPU keys, end drag session.
    DeactivateDrag,

    // === Focus ===

    /// Change focus to a new target (or clear focus if None).
    /// Handles: set_focused_node, apply_focus_restyle, scroll_node_into_view,
    /// cursor_blink_timer start/stop.
    SetFocus {
        new_focus: Option<DomNodeId>,
        old_focus: Option<DomNodeId>,
    },
    /// Clear all text selections.
    ClearAllSelections,
    /// Finalize pending focus changes (cursor initialization after layout).
    FinalizePendingFocusChanges,

    // === Scroll ===

    /// Scroll cursor/selection into view.
    ScrollSelectionIntoView,
    /// Scroll a specific node into view.
    ScrollNodeIntoView { target: DomNodeId },
    /// Scroll cursor into view after text input (needs relayout first).
    ScrollCursorIntoViewAfterTextInput,

    // === Auto-Scroll Timer ===

    /// Start auto-scroll timer for drag-to-scroll (60Hz).
    StartAutoScrollTimer,
    /// Cancel auto-scroll timer.
    StopAutoScrollTimer,
}

impl_option!(
    SystemChange,
    OptionSystemChange,
    copy = false,
    clone = false,
    [Debug, Clone, PartialEq]
);

impl_vec!(SystemChange, SystemChangeVec, SystemChangeVecDestructor, SystemChangeVecDestructorType, SystemChangeVecSlice, OptionSystemChange);
impl_vec_debug!(SystemChange, SystemChangeVec);
impl_vec_clone!(SystemChange, SystemChangeVec, SystemChangeVecDestructor);
impl_vec_partialeq!(SystemChange, SystemChangeVec);

/// Result of pre-callback internal event filtering
#[derive(Debug, Clone, PartialEq)]
pub struct PreCallbackFilterResult {
    /// System changes to process BEFORE user callbacks
    pub system_changes: Vec<SystemChange>,
    /// Regular events that will be passed to user callbacks
    pub user_events: Vec<SyntheticEvent>,
}

/// Flattened focus/selection state for the input interpreter (replaces trait objects).
#[derive(Debug, Clone)]
pub struct InputInterpreterState {
    pub focused_node: Option<DomNodeId>,
    pub click_count: u8,
    pub drag_start_position: Option<LogicalPosition>,
    pub has_selection: bool,
}

/// All context needed by the input interpreter to map events to system changes.
///
/// Passed to the interpreter callback. Contains references to the current
/// events and window state. The interpreter reads this and returns system changes.
pub struct InputInterpreterInfo<'a> {
    pub events: &'a [SyntheticEvent],
    pub hit_test: Option<&'a FullHitTest>,
    pub keyboard_state: &'a crate::window::KeyboardState,
    pub mouse_state: &'a crate::window::MouseState,
    pub state: InputInterpreterState,
}

/// The `extern "C"` callback type for the input interpreter.
///
/// The first `RefAny` is the user data (vim mode, repeat counter, etc.)
/// held in `InputInterpreterCallback.ctx`. The `*const ()` is an opaque
/// pointer to `InputInterpreterInfo` — callers use the safe wrapper
/// methods to access event data. Returns a `PreCallbackFilterResult`.
///
/// For C/Python: the trampoline extracts the foreign callable from `RefAny.ctx`.
/// For Rust: use `InputInterpreterCallback::from(fn_ptr)` which sets ctx=None.
pub type InputInterpreterCallbackType = extern "C" fn(
    crate::refany::RefAny,
    *const InputInterpreterInfo<'static>,  // Opaque; actual lifetime managed by caller
) -> PreCallbackFilterResult;

/// Configurable input interpreter callback.
///
/// Maps raw platform events + window state → semantic `SystemChange` actions.
/// The default (`default_input_interpreter`) handles standard desktop keybindings.
/// Replace this on `LayoutWindow` to implement vim, game controls, etc.
///
/// ## Pattern
/// - **Rust**: `InputInterpreterCallback::from(my_fn_ptr)` — `ctx` is None
/// - **Python/C**: Set `cb` to a trampoline, `ctx` to `RefAny` wrapping the foreign callable
#[repr(C)]
pub struct InputInterpreterCallback {
    pub cb: InputInterpreterCallbackType,
    pub ctx: crate::refany::OptionRefAny,
}

impl_callback!(InputInterpreterCallback, InputInterpreterCallbackType);

impl Default for InputInterpreterCallback {
    fn default() -> Self {
        Self {
            cb: default_input_interpreter_extern,
            ctx: crate::refany::OptionRefAny::None,
        }
    }
}

/// The `extern "C"` callback type for the post-callback filter.
pub type PostFilterCallbackType = extern "C" fn(
    crate::refany::RefAny,
    bool,                    // prevent_default
    SystemChangeVecSlice,    // pre_changes (immutable slice)
    DomNodeId,               // old_focus (0xFFFF = None)
    DomNodeId,               // new_focus (0xFFFF = None)
) -> SystemChangeVec;

/// Configurable post-callback filter.
#[repr(C)]
pub struct PostFilterCallback {
    pub cb: PostFilterCallbackType,
    pub ctx: crate::refany::OptionRefAny,
}

impl_callback!(PostFilterCallback, PostFilterCallbackType);

impl Default for PostFilterCallback {
    fn default() -> Self {
        Self {
            cb: default_post_filter_extern,
            ctx: crate::refany::OptionRefAny::None,
        }
    }
}

// Keep simpler Rust fn pointer aliases for internal use
pub type InputInterpreterFn = fn(
    info: &InputInterpreterInfo,
) -> PreCallbackFilterResult;

pub type PostFilterFn = fn(
    prevent_default: bool,
    pre_changes: &[SystemChange],
    old_focus: Option<DomNodeId>,
    new_focus: Option<DomNodeId>,
) -> Vec<SystemChange>;

/// Mouse button state for drag tracking
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseButtonState {
    pub left_down: bool,
    pub right_down: bool,
    pub middle_down: bool,
}

/// Arrow key / cursor navigation directions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArrowDirection {
    Left,
    Right,
    Up,
    Down,
    /// Home key: move to start of current line
    LineStart,
    /// End key: move to end of current line
    LineEnd,
    /// Ctrl+Home: move to start of document
    DocumentStart,
    /// Ctrl+End: move to end of document
    DocumentEnd,
}

impl ArrowDirection {
    /// Map a `VirtualKeyCode` plus the `ctrl` modifier into an `ArrowDirection`.
    /// Returns `None` if the key is not a navigation key.
    pub fn from_key(vk: crate::window::VirtualKeyCode, ctrl: bool) -> Option<Self> {
        use crate::window::VirtualKeyCode::*;
        Some(match vk {
            Left => ArrowDirection::Left,
            Right => ArrowDirection::Right,
            Up => ArrowDirection::Up,
            Down => ArrowDirection::Down,
            Home if ctrl => ArrowDirection::DocumentStart,
            Home => ArrowDirection::LineStart,
            End if ctrl => ArrowDirection::DocumentEnd,
            End => ArrowDirection::LineEnd,
            _ => return None,
        })
    }

    /// Convert to a `(SelectionDirection, SelectionStep)` pair for the
    /// selection-op interpreter. `ctrl` upgrades arrow keys to word jumps.
    pub fn to_selection(self, ctrl: bool) -> (SelectionDirection, SelectionStep) {
        match self {
            ArrowDirection::Left if ctrl => (SelectionDirection::Backward, SelectionStep::Word),
            ArrowDirection::Right if ctrl => (SelectionDirection::Forward, SelectionStep::Word),
            ArrowDirection::Left => (SelectionDirection::Backward, SelectionStep::Character),
            ArrowDirection::Right => (SelectionDirection::Forward, SelectionStep::Character),
            ArrowDirection::Up => (SelectionDirection::Backward, SelectionStep::VisualLine),
            ArrowDirection::Down => (SelectionDirection::Forward, SelectionStep::VisualLine),
            ArrowDirection::LineStart => (SelectionDirection::Backward, SelectionStep::Line),
            ArrowDirection::LineEnd => (SelectionDirection::Forward, SelectionStep::Line),
            ArrowDirection::DocumentStart => (SelectionDirection::Backward, SelectionStep::Document),
            ArrowDirection::DocumentEnd => (SelectionDirection::Forward, SelectionStep::Document),
        }
    }
}

/// Direction of cursor movement or selection expansion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionDirection {
    Forward,
    Backward,
}

/// Granularity of cursor movement or selection expansion.
///
/// Combined with `SelectionDirection`, determines how far a cursor moves
/// or a selection expands. Reused for navigation, deletion, and visual
/// selection — a single code path for word boundaries etc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionStep {
    /// One grapheme cluster (arrow keys, Backspace, Delete)
    Character,
    /// One word boundary (Ctrl+arrow, Ctrl+Backspace, Ctrl+Delete)
    Word,
    /// To line boundary (Home/End)
    Line,
    /// One visual line up/down (Up/Down arrows)
    VisualLine,
    /// To document boundary (Ctrl+Home/End)
    Document,
}

/// What to do with the selection after moving.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionMode {
    /// Collapse selection to cursor, then move (plain arrow key).
    Move,
    /// Extend selection from anchor to new position (Shift+arrow).
    Extend,
    /// Expand cursor to range in the given direction, then delete the range
    /// (Backspace/Delete). If a range already exists, just delete it.
    Delete,
}

/// A unified selection operation that replaces all cursor movement,
/// selection extension, and text deletion commands.
///
/// Every keyboard shortcut for cursor movement or deletion maps to this:
/// - Arrow Left = (Backward, Character, Move, 1)
/// - Shift+Right = (Forward, Character, Extend, 1)
/// - Ctrl+Backspace = (Backward, Word, Delete, 1)
/// - Home = (Backward, Line, Move, 1)
/// - Ctrl+End = (Forward, Document, Move, 1)
///
/// The `repeat` field enables vim-style commands: 3w = (Forward, Word, Move, 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct SelectionOp {
    pub direction: SelectionDirection,
    pub step: SelectionStep,
    pub mode: SelectionMode,
    pub repeat: usize,
}

impl SelectionOp {
    pub fn new(direction: SelectionDirection, step: SelectionStep, mode: SelectionMode) -> Self {
        Self { direction, step, mode, repeat: 1 }
    }
}

/// Keyboard shortcuts for text editing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyboardShortcut {
    Copy,      // Ctrl+C
    Cut,       // Ctrl+X
    Paste,     // Ctrl+V
    SelectAll, // Ctrl+A
    Undo,      // Ctrl+Z
    Redo,      // Ctrl+Y or Ctrl+Shift+Z
}

impl KeyboardShortcut {
    /// Map a `(VirtualKeyCode, ctrl, shift)` triple to a text-editing shortcut.
    /// Returns `None` if the key combination is not a recognized shortcut or
    /// if `ctrl` is not held.
    pub fn from_key(vk: crate::window::VirtualKeyCode, ctrl: bool, shift: bool) -> Option<Self> {
        use crate::window::VirtualKeyCode::*;
        if !ctrl {
            return None;
        }
        Some(match vk {
            C => KeyboardShortcut::Copy,
            X => KeyboardShortcut::Cut,
            V => KeyboardShortcut::Paste,
            A => KeyboardShortcut::SelectAll,
            Z if shift => KeyboardShortcut::Redo,
            Z => KeyboardShortcut::Undo,
            Y => KeyboardShortcut::Redo,
            _ => return None,
        })
    }
}

/// Default input interpreter: standard desktop keybindings.
///
/// This is the default `InputInterpreterFn` that handles arrow keys, Home/End,
/// Backspace/Delete, Ctrl+C/V/A/Z, mouse clicks, and drag selection.
/// Replace it on `LayoutWindow` to implement vim, game controls, etc.
/// `extern "C"` trampoline for `default_input_interpreter`.
pub extern "C" fn default_input_interpreter_extern(
    _user_data: crate::refany::RefAny,
    info_ptr: *const InputInterpreterInfo<'static>,
) -> PreCallbackFilterResult {
    if info_ptr.is_null() {
        return PreCallbackFilterResult {
            system_changes: Vec::new(),
            user_events: Vec::new(),
        };
    }
    let info = unsafe { &*info_ptr };
    default_input_interpreter(info)
}

/// `extern "C"` trampoline for `default_post_filter`.
pub extern "C" fn default_post_filter_extern(
    _user_data: crate::refany::RefAny,
    prevent_default: bool,
    pre_changes: SystemChangeVecSlice,
    old_focus: DomNodeId,
    new_focus: DomNodeId,
) -> SystemChangeVec {
    let pre_changes_slice = pre_changes.as_slice();
    let old = old_focus.node.into_crate_internal().map(|_| old_focus);
    let new = new_focus.node.into_crate_internal().map(|_| new_focus);
    default_post_filter(prevent_default, pre_changes_slice, old, new).into()
}

pub fn default_input_interpreter(
    info: &InputInterpreterInfo,
) -> PreCallbackFilterResult {
    let ctx = FilterContext {
        hit_test: info.hit_test,
        keyboard_state: info.keyboard_state,
        mouse_state: info.mouse_state,
        click_count: info.state.click_count,
        focused_node: info.state.focused_node,
        drag_start_position: info.state.drag_start_position,
    };

    let (system_changes, user_events) = info.events.iter().fold(
        (Vec::new(), Vec::new()),
        |(mut internal, mut user), event| {
            match process_event_for_internal(&ctx, event) {
                Some(InternalEventAction::AddAndSkip(evt)) => {
                    internal.push(evt);
                }
                Some(InternalEventAction::AddAndPass(evt)) => {
                    internal.push(evt);
                    user.push(event.clone());
                }
                None => {
                    user.push(event.clone());
                }
            }
            (internal, user)
        },
    );

    PreCallbackFilterResult {
        system_changes,
        user_events,
    }
}

/// Backward-compatible wrapper that calls `default_input_interpreter`.
pub fn pre_callback_filter_internal_events<SM, FM>(
    events: &[SyntheticEvent],
    hit_test: Option<&FullHitTest>,
    keyboard_state: &crate::window::KeyboardState,
    mouse_state: &crate::window::MouseState,
    selection_manager: &SM,
    focus_manager: &FM,
) -> PreCallbackFilterResult
where
    SM: SelectionManagerQuery,
    FM: FocusManagerQuery,
{
    let info = InputInterpreterInfo {
        events,
        hit_test,
        keyboard_state,
        mouse_state,
        state: InputInterpreterState {
            focused_node: focus_manager.get_focused_node_id(),
            click_count: selection_manager.get_click_count(),
            drag_start_position: selection_manager.get_drag_start_position(),
            has_selection: selection_manager.has_selection(),
        },
    };
    default_input_interpreter(&info)
}

/// Context for filtering internal events (used by default_input_interpreter)
struct FilterContext<'a> {
    hit_test: Option<&'a FullHitTest>,
    keyboard_state: &'a crate::window::KeyboardState,
    mouse_state: &'a crate::window::MouseState,
    click_count: u8,
    focused_node: Option<DomNodeId>,
    drag_start_position: Option<LogicalPosition>,
}

/// Process a single event and determine if it generates an internal event
fn process_event_for_internal(
    ctx: &FilterContext<'_>,
    event: &SyntheticEvent,
) -> Option<InternalEventAction> {
    match event.event_type {
        EventType::MouseDown => handle_mouse_down(event, ctx.hit_test, ctx.click_count, ctx.mouse_state, ctx.keyboard_state),
        EventType::MouseOver => handle_mouse_over(
            event,
            ctx.hit_test,
            ctx.mouse_state,
            ctx.drag_start_position,
        ),
        EventType::KeyDown => handle_key_down(
            event,
            ctx.keyboard_state,
            ctx.focused_node,
        ),
        _ => None,
    }
}

/// Action to take after processing an event for internal system events
enum InternalEventAction {
    /// Add system change and skip passing to user callbacks
    AddAndSkip(SystemChange),
    /// Add system change but also pass to user callbacks
    AddAndPass(SystemChange),
}

/// Extract first hovered node from hit test
fn get_first_hovered_node(hit_test: Option<&FullHitTest>) -> Option<DomNodeId> {
    let ht = hit_test?;
    let (dom_id, hit_data) = ht.hovered_nodes.iter().next()?;
    let node_id = hit_data.regular_hit_test_nodes.keys().next()?;
    Some(DomNodeId {
        dom: *dom_id,
        node: NodeHierarchyItemId::from_crate_internal(Some(*node_id)),
    })
}

/// Extract mouse position from event data, falling back to mouse_state if not available
fn get_mouse_position_with_fallback(
    event: &SyntheticEvent,
    mouse_state: &crate::window::MouseState,
) -> LogicalPosition {
    match &event.data {
        EventData::Mouse(mouse_data) => mouse_data.position,
        _ => {
            // Fallback: use current cursor position from mouse_state
            // This handles synthetic events from debug API and automation
            // where EventData may not contain the mouse position
            mouse_state.cursor_position.get_position().unwrap_or(LogicalPosition::zero())
        }
    }
}

/// Handle MouseDown event - detect text selection clicks and Ctrl+Click for multi-cursor
fn handle_mouse_down(
    event: &SyntheticEvent,
    hit_test: Option<&FullHitTest>,
    click_count: u8,
    mouse_state: &crate::window::MouseState,
    keyboard_state: &crate::window::KeyboardState,
) -> Option<InternalEventAction> {
    let effective_click_count = if click_count == 0 { 1 } else { click_count };

    if effective_click_count > 3 {
        return None;
    }

    let _target = get_first_hovered_node(hit_test)?;
    let position = get_mouse_position_with_fallback(event, mouse_state);

    // Ctrl+Click (or Cmd+Click on macOS): add cursor at click position
    if keyboard_state.ctrl_down() && effective_click_count == 1 {
        return Some(InternalEventAction::AddAndPass(
            SystemChange::AddCursorAtClick { position },
        ));
    }

    Some(InternalEventAction::AddAndPass(
        SystemChange::TextSelectionClick {
            position,
            timestamp: event.timestamp.clone(),
        },
    ))
}

/// Handle MouseOver event - detect drag selection
fn handle_mouse_over(
    event: &SyntheticEvent,
    hit_test: Option<&FullHitTest>,
    mouse_state: &crate::window::MouseState,
    drag_start_position: Option<LogicalPosition>,
) -> Option<InternalEventAction> {
    if !mouse_state.left_down {
        return None;
    }

    let start_position = drag_start_position?;

    let _target = get_first_hovered_node(hit_test)?;
    let current_position = get_mouse_position_with_fallback(event, mouse_state);

    Some(InternalEventAction::AddAndPass(
        SystemChange::TextSelectionDrag {
            start_position,
            current_position,
        },
    ))
}

/// Handle KeyDown event - detect shortcuts, arrow keys, and delete keys
fn handle_key_down(
    event: &SyntheticEvent,
    keyboard_state: &crate::window::KeyboardState,
    focused_node: Option<DomNodeId>,
) -> Option<InternalEventAction> {
    use crate::window::VirtualKeyCode;

    let target = focused_node?;
    let EventData::Keyboard(_) = &event.data else {
        return None;
    };

    let ctrl = keyboard_state.ctrl_down();
    let shift = keyboard_state.shift_down();
    let vk = keyboard_state.current_virtual_keycode.as_ref()?;

    // Check keyboard shortcuts (Ctrl+key) → emit specific SystemChange variants.
    // Standard editing shortcuts are routed through the `KeyboardShortcut` enum,
    // and a couple of additional Azul-specific Ctrl combos are matched after.
    if ctrl {
        if let Some(shortcut) = KeyboardShortcut::from_key(*vk, ctrl, shift) {
            let change = match shortcut {
                KeyboardShortcut::Copy => SystemChange::CopyToClipboard,
                KeyboardShortcut::Cut => SystemChange::CutToClipboard { target },
                KeyboardShortcut::Paste => SystemChange::PasteFromClipboard,
                KeyboardShortcut::SelectAll => SystemChange::SelectAllText,
                KeyboardShortcut::Undo => SystemChange::UndoTextEdit { target },
                KeyboardShortcut::Redo => SystemChange::RedoTextEdit { target },
            };
            return Some(InternalEventAction::AddAndSkip(change));
        }
        if matches!(vk, VirtualKeyCode::D) {
            return Some(InternalEventAction::AddAndSkip(
                SystemChange::SelectNextOccurrence { target },
            ));
        }
    }

    // Unified: arrow keys, Home/End, Backspace/Delete all map to SelectionOp.
    let mode_for_shift = if shift { SelectionMode::Extend } else { SelectionMode::Move };
    let selection_op = if let Some(arrow) = ArrowDirection::from_key(*vk, ctrl) {
        let (direction, step) = arrow.to_selection(ctrl);
        SelectionOp::new(direction, step, mode_for_shift)
    } else {
        match vk {
            // Backspace/Delete = Delete mode (Ctrl upgrades to Word)
            VirtualKeyCode::Back => SelectionOp::new(
                SelectionDirection::Backward,
                if ctrl { SelectionStep::Word } else { SelectionStep::Character },
                SelectionMode::Delete,
            ),
            VirtualKeyCode::Delete => SelectionOp::new(
                SelectionDirection::Forward,
                if ctrl { SelectionStep::Word } else { SelectionStep::Character },
                SelectionMode::Delete,
            ),
            _ => return None,
        }
    };

    Some(InternalEventAction::AddAndSkip(
        SystemChange::ApplySelectionOp { target, op: selection_op },
    ))
}

/// Trait for querying selection manager state.
///
/// This allows `pre_callback_filter_internal_events` to query manager state
/// without depending on the concrete `SelectionManager` type from layout crate.
pub trait SelectionManagerQuery {
    /// Get the current click count (1 = single, 2 = double, 3 = triple)
    fn get_click_count(&self) -> u8;

    /// Get the drag start position if a drag is in progress
    fn get_drag_start_position(&self) -> Option<LogicalPosition>;

    /// Check if any selection exists (click selection or drag selection)
    fn has_selection(&self) -> bool;
}

/// Trait for querying focus manager state.
///
/// This allows `pre_callback_filter_internal_events` to query manager state
/// without depending on the concrete `FocusManager` type from layout crate.
pub trait FocusManagerQuery {
    /// Get the currently focused node ID
    fn get_focused_node_id(&self) -> Option<DomNodeId>;
}

/// Post-callback filter: Determine additional system changes needed after user callbacks.
///
/// Takes the pre-callback system changes and focus state to determine what
/// post-callback system changes are needed (text input, scrolling, timers).
/// Default post-callback filter: scroll-into-view after cursor ops, auto-scroll during drag.
pub fn default_post_filter(
    prevent_default: bool,
    pre_changes: &[SystemChange],
    old_focus: Option<DomNodeId>,
    new_focus: Option<DomNodeId>,
) -> Vec<SystemChange> {
    post_callback_filter_system_changes(prevent_default, pre_changes, old_focus, new_focus)
}

pub fn post_callback_filter_system_changes(
    prevent_default: bool,
    pre_changes: &[SystemChange],
    old_focus: Option<DomNodeId>,
    new_focus: Option<DomNodeId>,
) -> Vec<SystemChange> {
    let mut changes = Vec::new();

    if prevent_default {
        // Only focus change passes through preventDefault
        if old_focus != new_focus {
            changes.push(SystemChange::SetFocus { new_focus, old_focus });
        }
        return changes;
    }

    // Always apply pending text input
    changes.push(SystemChange::ApplyPendingTextInput);

    // Determine post-callback actions based on pre-callback system changes
    for change in pre_changes {
        match change {
            SystemChange::TextSelectionClick { .. }
            | SystemChange::ApplySelectionOp { .. }
            | SystemChange::AddCursorAtClick { .. }
            | SystemChange::SelectNextOccurrence { .. } => {
                changes.push(SystemChange::ScrollSelectionIntoView);
            }
            SystemChange::TextSelectionDrag { .. } => {
                changes.push(SystemChange::StartAutoScrollTimer);
            }
            SystemChange::CutToClipboard { .. }
            | SystemChange::PasteFromClipboard
            | SystemChange::UndoTextEdit { .. }
            | SystemChange::RedoTextEdit { .. }
            | SystemChange::SelectAllText => {
                changes.push(SystemChange::ScrollSelectionIntoView);
            }
            // Other system changes don't generate post-callback actions
            _ => {}
        }
    }

    // Focus changed during callbacks
    if old_focus != new_focus {
        changes.push(SystemChange::SetFocus { new_focus, old_focus });
    }

    changes
}


#[cfg(test)]
mod tests {
    use super::*;
    use azul_css::AzString;
    use crate::dom::{DomId, DomNodeId};
    use crate::styled_dom::NodeHierarchyItemId;
    use crate::id::NodeId;
    use crate::window::{KeyboardState, MouseState, VirtualKeyCode, VirtualKeyCodeVec, OptionVirtualKeyCode};
    use crate::geom::LogicalPosition;
    use crate::task::{Instant, SystemTick};

    struct MockSelectionManager {
        click_count: u8,
        has_sel: bool,
    }
    impl SelectionManagerQuery for MockSelectionManager {
        fn get_click_count(&self) -> u8 { self.click_count }
        fn get_drag_start_position(&self) -> Option<LogicalPosition> { None }
        fn has_selection(&self) -> bool { self.has_sel }
    }

    struct MockFocusManager(Option<DomNodeId>);
    impl FocusManagerQuery for MockFocusManager {
        fn get_focused_node_id(&self) -> Option<DomNodeId> { self.0 }
    }

    fn focused_node(node_idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId { inner: 0 },
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node_idx))),
        }
    }

    fn make_keyboard_state(vk: VirtualKeyCode) -> KeyboardState {
        let mut ks = KeyboardState::default();
        ks.current_virtual_keycode = OptionVirtualKeyCode::Some(vk);
        ks.pressed_virtual_keycodes = VirtualKeyCodeVec::from_vec(vec![vk]);
        ks
    }

    fn make_keydown_event(target: DomNodeId) -> SyntheticEvent {
        SyntheticEvent::new(
            EventType::KeyDown,
            EventSource::User,
            target,
            Instant::Tick(SystemTick::new(0)),
            EventData::Keyboard(KeyboardEventData {
                key_code: VirtualKeyCode::Back as u32,
                char_code: None,
                modifiers: KeyModifiers::default(),
                repeat: false,
            }),
        )
    }

    #[test]
    fn backspace_generates_delete_text_selection() {
        let target = focused_node(2);
        let events = vec![make_keydown_event(target)];
        let kb = make_keyboard_state(VirtualKeyCode::Back);
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(Some(target));

        let result = pre_callback_filter_internal_events(
            &events, None, &kb, &mouse, &sel, &focus,
        );

        let ops: Vec<_> = result.system_changes.iter()
            .filter(|c| matches!(c, SystemChange::ApplySelectionOp { .. }))
            .collect();
        assert_eq!(ops.len(), 1, "Backspace should generate ApplySelectionOp");
        match &ops[0] {
            SystemChange::ApplySelectionOp { op, .. } => {
                assert_eq!(op.direction, SelectionDirection::Backward);
                assert_eq!(op.step, SelectionStep::Character);
                assert_eq!(op.mode, SelectionMode::Delete);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn delete_key_generates_forward_deletion() {
        let target = focused_node(2);
        let event = SyntheticEvent::new(
            EventType::KeyDown, EventSource::User, target,
            Instant::Tick(SystemTick::new(0)),
            EventData::Keyboard(KeyboardEventData {
                key_code: VirtualKeyCode::Delete as u32,
                char_code: None, modifiers: KeyModifiers::default(), repeat: false,
            }),
        );
        let kb = make_keyboard_state(VirtualKeyCode::Delete);
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(Some(target));
        let result = pre_callback_filter_internal_events(&[event], None, &kb, &mouse, &sel, &focus);
        let ops: Vec<_> = result.system_changes.iter()
            .filter(|c| matches!(c, SystemChange::ApplySelectionOp { .. }))
            .collect();
        assert_eq!(ops.len(), 1);
        match &ops[0] {
            SystemChange::ApplySelectionOp { op, .. } => {
                assert_eq!(op.direction, SelectionDirection::Forward);
                assert_eq!(op.step, SelectionStep::Character);
                assert_eq!(op.mode, SelectionMode::Delete);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn arrow_left_generates_navigation() {
        let target = focused_node(2);
        let event = SyntheticEvent::new(
            EventType::KeyDown, EventSource::User, target,
            Instant::Tick(SystemTick::new(0)),
            EventData::Keyboard(KeyboardEventData {
                key_code: VirtualKeyCode::Left as u32,
                char_code: None, modifiers: KeyModifiers::default(), repeat: false,
            }),
        );
        let kb = make_keyboard_state(VirtualKeyCode::Left);
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(Some(target));
        let result = pre_callback_filter_internal_events(&[event], None, &kb, &mouse, &sel, &focus);
        let ops: Vec<_> = result.system_changes.iter()
            .filter(|c| matches!(c, SystemChange::ApplySelectionOp { .. }))
            .collect();
        assert_eq!(ops.len(), 1, "Left arrow should generate ApplySelectionOp");
        match &ops[0] {
            SystemChange::ApplySelectionOp { op, .. } => {
                assert_eq!(op.direction, SelectionDirection::Backward);
                assert_eq!(op.step, SelectionStep::Character);
                assert_eq!(op.mode, SelectionMode::Move);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn no_focused_node_means_no_keyboard_system_changes() {
        let target = focused_node(2);
        let event = make_keydown_event(target);
        let kb = make_keyboard_state(VirtualKeyCode::Back);
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(None); // No focus!

        let result = pre_callback_filter_internal_events(
            &[event], None, &kb, &mouse, &sel, &focus,
        );

        assert!(result.system_changes.is_empty(),
            "No system changes should be generated without focused node");
    }

    #[test]
    fn keydown_without_keyboard_data_generates_no_system_change() {
        let target = focused_node(2);
        let event = SyntheticEvent::new(
            EventType::KeyDown,
            EventSource::User,
            target,
            Instant::Tick(SystemTick::new(0)),
            EventData::None, // Bug: missing keyboard data
        );
        let kb = make_keyboard_state(VirtualKeyCode::Back);
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(Some(target));

        let result = pre_callback_filter_internal_events(
            &[event], None, &kb, &mouse, &sel, &focus,
        );

        // This test documents the bug we just fixed: EventData::None causes
        // the handle_key_down function to return None (early exit at line 2737)
        assert!(result.system_changes.is_empty(),
            "EventData::None should not generate system changes (documents the old bug)");
    }

    #[test]
    fn ctrl_c_generates_copy() {
        let target = focused_node(2);
        let event = SyntheticEvent::new(
            EventType::KeyDown,
            EventSource::User,
            target,
            Instant::Tick(SystemTick::new(0)),
            EventData::Keyboard(KeyboardEventData {
                key_code: VirtualKeyCode::C as u32,
                char_code: Some('c'),
                modifiers: KeyModifiers { ctrl: true, shift: false, alt: false, meta: false },
                repeat: false,
            }),
        );
        let mut kb = make_keyboard_state(VirtualKeyCode::C);
        kb.pressed_virtual_keycodes = VirtualKeyCodeVec::from_vec(
            vec![VirtualKeyCode::C, VirtualKeyCode::LControl]
        );
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 0, has_sel: false };
        let focus = MockFocusManager(Some(target));

        let result = pre_callback_filter_internal_events(
            &[event], None, &kb, &mouse, &sel, &focus,
        );

        let copy_changes: Vec<_> = result.system_changes.iter()
            .filter(|c| matches!(c, SystemChange::CopyToClipboard))
            .collect();

        assert_eq!(copy_changes.len(), 1, "Ctrl+C should generate CopyToClipboard");
    }

    fn make_hit_test_with_node(node_idx: usize) -> crate::hit_test::FullHitTest {
        use crate::hit_test::{FullHitTest, HitTest, HitTestItem};
        use crate::dom::OptionDomNodeId;
        use std::collections::BTreeMap;

        let node_id = NodeId::new(node_idx);
        let dom_id = DomId { inner: 0 };

        let mut regular = BTreeMap::new();
        regular.insert(node_id, HitTestItem {
            point_in_viewport: LogicalPosition::new(100.0, 200.0),
            point_relative_to_item: LogicalPosition::new(50.0, 30.0),
            is_focusable: true,
            is_virtual_view_hit: None,
            hit_depth: 0,
        });

        let mut hovered = BTreeMap::new();
        hovered.insert(dom_id, HitTest {
            regular_hit_test_nodes: regular,
            scroll_hit_test_nodes: BTreeMap::new(),
            scrollbar_hit_test_nodes: BTreeMap::new(),
            cursor_hit_test_nodes: BTreeMap::new(),
        });

        FullHitTest {
            hovered_nodes: hovered,
            focused_node: OptionDomNodeId::None,
        }
    }

    #[test]
    fn mousedown_generates_text_selection_click() {
        let target = focused_node(2);
        let event = SyntheticEvent::new(
            EventType::MouseDown,
            EventSource::User,
            target,
            Instant::Tick(SystemTick::new(0)),
            EventData::Mouse(MouseEventData {
                position: LogicalPosition::new(100.0, 200.0),
                button: crate::events::MouseButton::Left,
                buttons: 1,
                modifiers: KeyModifiers::default(),
            }),
        );
        let hit_test = make_hit_test_with_node(2);
        let kb = KeyboardState::default();
        let mouse = MouseState::default();
        let sel = MockSelectionManager { click_count: 1, has_sel: false };
        let focus = MockFocusManager(Some(target));

        let result = pre_callback_filter_internal_events(
            &[event], Some(&hit_test), &kb, &mouse, &sel, &focus,
        );

        let click_changes: Vec<_> = result.system_changes.iter()
            .filter(|c| matches!(c, SystemChange::TextSelectionClick { .. }))
            .collect();

        assert_eq!(click_changes.len(), 1, "MouseDown with hit_test should generate TextSelectionClick");
    }

    #[test]
    fn process_event_result_max_self_picks_higher_variant() {
        let lo = ProcessEventResult::ShouldReRenderCurrentWindow;
        let hi = ProcessEventResult::ShouldRegenerateDomCurrentWindow;
        assert_eq!(lo.max_self(hi), hi);
        assert_eq!(hi.max_self(lo), hi);
        assert_eq!(lo.max_self(lo), lo);
    }

    #[test]
    fn arrow_direction_from_key_maps_arrows_and_home_end() {
        use crate::window::VirtualKeyCode::*;
        assert_eq!(ArrowDirection::from_key(Left, false), Some(ArrowDirection::Left));
        assert_eq!(ArrowDirection::from_key(Right, false), Some(ArrowDirection::Right));
        assert_eq!(ArrowDirection::from_key(Up, false), Some(ArrowDirection::Up));
        assert_eq!(ArrowDirection::from_key(Down, false), Some(ArrowDirection::Down));
        assert_eq!(ArrowDirection::from_key(Home, false), Some(ArrowDirection::LineStart));
        assert_eq!(ArrowDirection::from_key(End, false), Some(ArrowDirection::LineEnd));
        assert_eq!(ArrowDirection::from_key(Home, true), Some(ArrowDirection::DocumentStart));
        assert_eq!(ArrowDirection::from_key(End, true), Some(ArrowDirection::DocumentEnd));
        assert_eq!(ArrowDirection::from_key(C, false), None);
    }

    #[test]
    fn arrow_direction_to_selection_respects_ctrl() {
        let (d, s) = ArrowDirection::Left.to_selection(false);
        assert_eq!((d, s), (SelectionDirection::Backward, SelectionStep::Character));
        let (d, s) = ArrowDirection::Left.to_selection(true);
        assert_eq!((d, s), (SelectionDirection::Backward, SelectionStep::Word));
        let (d, s) = ArrowDirection::Up.to_selection(false);
        assert_eq!((d, s), (SelectionDirection::Backward, SelectionStep::VisualLine));
        let (d, s) = ArrowDirection::DocumentEnd.to_selection(false);
        assert_eq!((d, s), (SelectionDirection::Forward, SelectionStep::Document));
    }

    #[test]
    fn keyboard_shortcut_from_key_recognizes_editing_combos() {
        use crate::window::VirtualKeyCode::*;
        assert_eq!(KeyboardShortcut::from_key(C, true, false), Some(KeyboardShortcut::Copy));
        assert_eq!(KeyboardShortcut::from_key(X, true, false), Some(KeyboardShortcut::Cut));
        assert_eq!(KeyboardShortcut::from_key(V, true, false), Some(KeyboardShortcut::Paste));
        assert_eq!(KeyboardShortcut::from_key(A, true, false), Some(KeyboardShortcut::SelectAll));
        assert_eq!(KeyboardShortcut::from_key(Z, true, false), Some(KeyboardShortcut::Undo));
        assert_eq!(KeyboardShortcut::from_key(Z, true, true), Some(KeyboardShortcut::Redo));
        assert_eq!(KeyboardShortcut::from_key(Y, true, false), Some(KeyboardShortcut::Redo));
        // Non-ctrl combos must not match
        assert_eq!(KeyboardShortcut::from_key(C, false, false), None);
        // Unknown keys
        assert_eq!(KeyboardShortcut::from_key(D, true, false), None);
    }

    #[test]
    fn mouse_button_state_round_trips_from_mouse_state() {
        let mut ms = MouseState::default();
        ms.left_down = true;
        ms.middle_down = true;
        let bs: MouseButtonState = (&ms).into();
        assert!(bs.left_down);
        assert!(!bs.right_down);
        assert!(bs.middle_down);
        assert!(bs.any_down());

        let none = MouseButtonState { left_down: false, right_down: false, middle_down: false };
        assert!(!none.any_down());
    }

    #[test]
    fn callback_to_call_collects_hits_for_dom() {
        let dom_id = DomId { inner: 0 };
        let hit_test = make_hit_test_with_node(2);
        let filter = EventFilter::Hover(HoverEventFilter::MouseDown);
        let calls = CallbackToCall::from_hit_test(&hit_test, dom_id, filter.clone());
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].node_id, NodeId::new(2));
        assert_eq!(calls[0].event_filter, filter);
        assert!(calls[0].hit_test_item.is_some());

        // Unknown DOM id => empty list
        let other = CallbackToCall::from_hit_test(
            &hit_test,
            DomId { inner: 999 },
            EventFilter::Hover(HoverEventFilter::MouseUp),
        );
        assert!(other.is_empty());

        // Direct constructor builds expected fields
        let direct = CallbackToCall::new(
            NodeId::new(7),
            None,
            EventFilter::Focus(FocusEventFilter::FocusReceived),
        );
        assert_eq!(direct.node_id, NodeId::new(7));
        assert!(direct.hit_test_item.is_none());
    }

    #[test]
    fn restyle_relayout_aliases_are_btreemap_compatible() {
        // RestyleNodes / RelayoutNodes are aliases for BTreeMap<NodeId, Vec<ChangedCssProperty>>.
        // Confirm we can construct empty ones via the alias and that they accept the same keys.
        let restyle: RestyleNodes = BTreeMap::new();
        let relayout: RelayoutNodes = BTreeMap::new();
        assert!(restyle.is_empty());
        assert!(relayout.is_empty());

        // RelayoutWords is BTreeMap<NodeId, AzString>.
        let mut words: RelayoutWords = BTreeMap::new();
        words.insert(NodeId::new(1), AzString::from_const_str("hello"));
        assert_eq!(words.get(&NodeId::new(1)).map(|s| s.as_str()), Some("hello"));
    }

    #[test]
    fn detect_lifecycle_events_with_reconciliation_is_callable() {
        // Smoke test: empty old/new node data must produce no events and an
        // empty migration map. This proves the function is callable from
        // the public API and threads through `crate::diff::reconcile_dom`.
        let dom_id = DomId { inner: 0 };
        let old_data: Vec<crate::dom::NodeData> = Vec::new();
        let new_data: Vec<crate::dom::NodeData> = Vec::new();
        let old_hier: Vec<crate::styled_dom::NodeHierarchyItem> = Vec::new();
        let new_hier: Vec<crate::styled_dom::NodeHierarchyItem> = Vec::new();
        let old_layout = OrderedMap::default();
        let new_layout = OrderedMap::default();
        let result: LifecycleEventResult = detect_lifecycle_events_with_reconciliation(
            dom_id,
            &old_data,
            &new_data,
            &old_hier,
            &new_hier,
            &old_layout,
            &new_layout,
            Instant::Tick(SystemTick::new(0)),
        );
        assert!(result.events.is_empty());
        assert!(result.node_id_mapping.is_empty());
    }

    #[test]
    fn nodedata_focusable_and_activation_traits_are_wired() {
        use crate::dom::{NodeData, NodeType};
        use crate::events::{ActivationBehavior as _, Focusable as _};

        // <button> is naturally focusable and has activation behavior.
        let btn = NodeData::create_node(NodeType::Button);
        assert!(<NodeData as Focusable>::is_naturally_focusable(&btn));
        assert!(<NodeData as Focusable>::is_focusable(&btn));
        assert!(<NodeData as ActivationBehavior>::has_activation_behavior(&btn));
        assert!(<NodeData as ActivationBehavior>::is_activatable(&btn));

        // A plain <div> is neither naturally focusable nor activatable.
        let div = NodeData::create_node(NodeType::Div);
        assert!(!<NodeData as Focusable>::is_naturally_focusable(&div));
        assert!(!<NodeData as ActivationBehavior>::has_activation_behavior(&div));

        // <input> is naturally focusable.
        let input = NodeData::create_node(NodeType::Input);
        assert!(<NodeData as Focusable>::is_naturally_focusable(&input));
    }
}