azul-core 0.0.7

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
//! 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::{
    props::{
        basic::{LayoutPoint, LayoutRect, LayoutSize},
        property::CssProperty,
    },
    AzString, LayoutDebugMessage,
};
use rust_fontconfig::FcFontCache;

use crate::{
    callbacks::Update,
    dom::{DomId, DomNodeId, On},
    geom::{LogicalPosition, LogicalRect},
    gl::OptionGlContextPtr,
    gpu::GpuEventChanges,
    hit_test::{FullHitTest, HitTestItem, ScrollPosition},
    id::NodeId,
    resources::{ImageCache, RendererResources},
    styled_dom::{ChangedCssProperty, NodeHierarchyItemId},
    task::Instant,
    window::RawWindowHandle,
    FastBTreeSet, FastHashMap,
};

/// Easing functions für smooth scrolling (für Scroll-Animationen)
#[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,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
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,
    // Only refresh the display (in case of pure scroll or GPU-only events)
    ShouldRegenerateDomCurrentWindow = 4,
    ShouldRegenerateDomAllWindows = 5,
}

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

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)
    }
}

// Phase 3.5: New Event System Types

/// 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,
}

/// 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,

    // 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,
}

/// 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
    }
}

// Phase 3.5, Step 3: Event Propagation System

/// 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::Not(_) => {
            // Not filters are inverted - will be implemented in future
            false
        }
        EventFilter::Component(_) | EventFilter::Application(_) => {
            // Lifecycle and application events - will be implemented in future
            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 if it's left button
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (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,
        (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,
        _ => 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) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (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) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseDown, EventType::MouseDown) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (MouseUp, EventType::MouseUp) => true,
        (LeftMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Left
            } else {
                false
            }
        }
        (RightMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Right
            } else {
                false
            }
        }
        (MiddleMouseUp, EventType::MouseUp) => {
            if let EventData::Mouse(mouse_data) = &event.data {
                mouse_data.button == MouseButton::Middle
            } else {
                false
            }
        }
        (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,
        (FocusReceived, EventType::Focus) => true,
        (FocusLost, EventType::Blur) => true,
        (CloseRequested, EventType::WindowClose) => true,
        (ThemeChanged, EventType::ThemeChange) => true,
        (WindowFocusReceived, EventType::WindowFocusIn) => true,
        (WindowFocusLost, EventType::WindowFocusOut) => 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,
    }
}

// Phase 3.5, Step 4: Lifecycle Event Detection

/// 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::InitialMount,
            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::FastHashMap<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
/// 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_layout: &crate::FastHashMap<NodeId, LogicalRect>,
    new_layout: &crate::FastHashMap<NodeId, LogicalRect>,
    timestamp: Instant,
) -> LifecycleEventResult {
    let diff_result = crate::diff::reconcile_dom(
        old_node_data,
        new_node_data,
        old_layout,
        new_layout,
        dom_id,
        timestamp,
    );

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

// Phase 3.5: Event Filter System

/// 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,
    /// 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::VirtualKeyDown),
            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::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,
    /// 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::VirtualKeyDown),
            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::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,
        }
    }
}

/// The inverse of an `onclick` event filter, fires when an item is *not* hovered / focused.
/// This is useful for cleanly implementing things like popover dialogs or dropdown boxes that
/// want to close when the user clicks any where *but* the item itself.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C, u8)]
pub enum NotEventFilter {
    Hover(HoverEventFilter),
    Focus(FocusEventFilter),
}

impl NotEventFilter {
    pub fn as_event_filter(&self) -> EventFilter {
        match self {
            NotEventFilter::Hover(e) => EventFilter::Hover(*e),
            NotEventFilter::Focus(e) => EventFilter::Focus(*e),
        }
    }
}

/// 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,
}

/// 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),
    /// Inverse of `Hover` - calls the attached callback if the mouse is **not**
    /// over the given element. This is particularly useful for popover menus
    /// where you want to close the menu when the user clicks anywhere else but
    /// the menu itself.
    Not(NotEventFilter),
    /// 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_not_event_filter, EventFilter::Not(NotEventFilter));
    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.

/// Process callback results and potentially generate new synthetic events.
///
/// This function handles the recursive nature of event processing:
/// 1. Process immediate callback results (state changes, images, etc.)
/// 2. Check if new synthetic events should be generated
/// 3. Recursively process those events (up to max_depth to prevent infinite loops)
///
/// Returns true if any callbacks resulted in DOM changes requiring re-layout.
pub fn should_recurse_callbacks<T: CallbackResultRef>(
    callback_results: &[T],
    max_depth: usize,
    current_depth: usize,
) -> bool {
    if current_depth >= max_depth {
        return false;
    }

    // Check if any callback result indicates we should continue processing
    for result in callback_results {
        // If stop_propagation is set, stop processing further events
        if result.stop_propagation() {
            return false;
        }

        // Check if DOM was modified (requires re-layout and re-processing)
        if result.should_regenerate_dom() {
            return current_depth + 1 < max_depth;
        }
    }

    false
}

/// Trait to abstract over callback result types.
/// This allows the core event system to work with results without depending on layout layer.
pub trait CallbackResultRef {
    fn stop_propagation(&self) -> bool;
    fn stop_immediate_propagation(&self) -> bool;
    fn prevent_default(&self) -> bool;
    fn should_regenerate_dom(&self) -> bool;
}

// Unified Event Determination System (Phase 3.5+)

/// 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)],

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



// Internal System Event Processing

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

/// 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,
}

/// System event to process AFTER user callbacks
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PostCallbackSystemEvent {
    /// Apply text input to focused contenteditable element
    ApplyTextInput,
    /// Focus changed during callbacks
    FocusChanged,
    /// Apply text changeset (separate creation from application)
    ApplyTextChangeset,
    /// Scroll cursor/selection into view
    ScrollIntoView,
    /// Start auto-scroll timer for drag-to-scroll
    StartAutoScrollTimer,
    /// Cancel auto-scroll timer
    CancelAutoScrollTimer,
}

/// Internal system event for pre-callback processing
#[derive(Debug, Clone, PartialEq)]
pub enum PreCallbackSystemEvent {
    /// Single/double/triple click for text selection
    TextClick {
        target: DomNodeId,
        position: LogicalPosition,
        click_count: u8,
        timestamp: Instant,
    },
    /// Mouse drag for selection extension
    TextDragSelection {
        target: DomNodeId,
        start_position: LogicalPosition,
        current_position: LogicalPosition,
        is_dragging: bool,
    },
    /// Arrow key navigation with optional selection extension
    ArrowKeyNavigation {
        target: DomNodeId,
        direction: ArrowDirection,
        extend_selection: bool, // Shift key held
        word_jump: bool,        // Ctrl key held
    },
    /// Keyboard shortcut (Ctrl+C/X/A)
    KeyboardShortcut {
        target: DomNodeId,
        shortcut: KeyboardShortcut,
    },
    /// Delete currently selected text (Backspace/Delete key)
    DeleteSelection {
        target: DomNodeId,
        forward: bool, // true = Delete key (forward), false = Backspace (backward)
    },
}

/// Arrow key directions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArrowDirection {
    Left,
    Right,
    Up,
    Down,
}

/// 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
}

/// Result of post-callback internal event filtering  
#[derive(Debug, Clone, PartialEq)]
pub struct PostCallbackFilterResult {
    /// System events to process AFTER user callbacks
    pub system_events: Vec<PostCallbackSystemEvent>,
}

/// Pre-callback filter: Extract internal system events from synthetic events.
///
/// Separates internal system events (text selection, shortcuts) from user-facing events.
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 ctx = FilterContext {
        hit_test,
        keyboard_state,
        mouse_state,
        click_count: selection_manager.get_click_count(),
        focused_node: focus_manager.get_focused_node_id(),
        drag_start_position: selection_manager.get_drag_start_position(),
        selection_manager,
    };

    let (internal_events, user_events) = 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 {
        internal_events,
        user_events,
    }
}

/// Context for filtering internal events
struct FilterContext<'a, SM> {
    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>,
    selection_manager: &'a SM,
}

/// Process a single event and determine if it generates an internal event
fn process_event_for_internal<SM: SelectionManagerQuery>(
    ctx: &FilterContext<'_, SM>,
    event: &SyntheticEvent,
) -> Option<InternalEventAction> {
    match event.event_type {
        EventType::MouseDown => handle_mouse_down(event, ctx.hit_test, ctx.click_count, ctx.mouse_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.selection_manager,
            ctx.focused_node,
        ),
        _ => None,
    }
}

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

/// 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
fn handle_mouse_down(
    event: &SyntheticEvent,
    hit_test: Option<&FullHitTest>,
    click_count: u8,
    mouse_state: &crate::window::MouseState,
) -> Option<InternalEventAction> {
    // Note: click_count == 0 means this is a new click sequence (first click)
    // The actual click count will be determined in process_mouse_click_for_selection
    // We use 1 here as a placeholder for new clicks
    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);

    Some(InternalEventAction::AddAndPass(
        PreCallbackSystemEvent::TextClick {
            target,
            position,
            click_count: effective_click_count,
            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(
        PreCallbackSystemEvent::TextDragSelection {
            target,
            start_position,
            current_position,
            is_dragging: true,
        },
    ))
}

/// Handle KeyDown event - detect shortcuts, arrow keys, and delete keys
fn handle_key_down<SM: SelectionManagerQuery>(
    event: &SyntheticEvent,
    keyboard_state: &crate::window::KeyboardState,
    selection_manager: &SM,
    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)
    if ctrl {
        let shortcut = match vk {
            VirtualKeyCode::C => Some(KeyboardShortcut::Copy),
            VirtualKeyCode::X => Some(KeyboardShortcut::Cut),
            VirtualKeyCode::V => Some(KeyboardShortcut::Paste),
            VirtualKeyCode::A => Some(KeyboardShortcut::SelectAll),
            VirtualKeyCode::Z if !shift => Some(KeyboardShortcut::Undo),
            VirtualKeyCode::Z if shift => Some(KeyboardShortcut::Redo),
            VirtualKeyCode::Y => Some(KeyboardShortcut::Redo),
            _ => None,
        };
        if let Some(shortcut) = shortcut {
            return Some(InternalEventAction::AddAndSkip(
                PreCallbackSystemEvent::KeyboardShortcut { target, shortcut },
            ));
        }
    }

    // Check arrow key navigation
    let direction = match vk {
        VirtualKeyCode::Left => Some(ArrowDirection::Left),
        VirtualKeyCode::Up => Some(ArrowDirection::Up),
        VirtualKeyCode::Right => Some(ArrowDirection::Right),
        VirtualKeyCode::Down => Some(ArrowDirection::Down),
        _ => None,
    };
    if let Some(direction) = direction {
        return Some(InternalEventAction::AddAndSkip(
            PreCallbackSystemEvent::ArrowKeyNavigation {
                target,
                direction,
                extend_selection: shift,
                word_jump: ctrl,
            },
        ));
    }

    // Check delete keys (only when selection exists)
    if !selection_manager.has_selection() {
        return None;
    }

    let forward = match vk {
        VirtualKeyCode::Back => Some(false),
        VirtualKeyCode::Delete => Some(true),
        _ => None,
    }?;

    Some(InternalEventAction::AddAndSkip(
        PreCallbackSystemEvent::DeleteSelection { target, forward },
    ))
}

/// 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: Analyze applied changes and generate system events
pub fn post_callback_filter_internal_events(
    prevent_default: bool,
    internal_events: &[PreCallbackSystemEvent],
    old_focus: Option<DomNodeId>,
    new_focus: Option<DomNodeId>,
) -> PostCallbackFilterResult {
    if prevent_default {
        let focus_event = (old_focus != new_focus).then_some(PostCallbackSystemEvent::FocusChanged);
        return PostCallbackFilterResult {
            system_events: focus_event.into_iter().collect(),
        };
    }

    let event_actions = internal_events
        .iter()
        .filter_map(internal_event_to_system_event);

    let focus_event = (old_focus != new_focus).then_some(PostCallbackSystemEvent::FocusChanged);

    let system_events = core::iter::once(PostCallbackSystemEvent::ApplyTextInput)
        .chain(event_actions)
        .chain(focus_event)
        .collect();

    PostCallbackFilterResult { system_events }
}

/// Convert internal event to post-callback system event
fn internal_event_to_system_event(
    event: &PreCallbackSystemEvent,
) -> Option<PostCallbackSystemEvent> {
    use PostCallbackSystemEvent::*;
    use PreCallbackSystemEvent::*;

    match event {
        TextClick { .. } | ArrowKeyNavigation { .. } | DeleteSelection { .. } => {
            Some(ScrollIntoView)
        }
        TextDragSelection { is_dragging, .. } => Some(if *is_dragging {
            StartAutoScrollTimer
        } else {
            CancelAutoScrollTimer
        }),
        KeyboardShortcut { shortcut, .. } => shortcut_to_system_event(*shortcut),
    }
}

/// Convert keyboard shortcut to system event (if any)
fn shortcut_to_system_event(shortcut: KeyboardShortcut) -> Option<PostCallbackSystemEvent> {
    use KeyboardShortcut::*;
    match shortcut {
        Cut | Paste | Undo | Redo => Some(PostCallbackSystemEvent::ScrollIntoView),
        Copy | SelectAll => None,
    }
}

#[cfg(test)]
mod tests {
    //! Unit tests for the Phase 3.5 event system
    //!
    //! Tests cover:
    //! - Event type creation
    //! - DOM path traversal
    //! - Event propagation (capture/target/bubble)
    //! - Event filter matching
    //! - Lifecycle event detection

    use std::collections::BTreeMap;

    use crate::{
        dom::{DomId, DomNodeId},
        events::*,
        geom::{LogicalPosition, LogicalRect, LogicalSize},
        id::{Node, NodeHierarchy, NodeId},
        styled_dom::NodeHierarchyItemId,
        task::{Instant, SystemTick},
    };

    // Helper: Create a test Instant
    fn test_instant() -> Instant {
        Instant::Tick(SystemTick::new(0))
    }

    // Helper: Create a simple 3-node tree (root -> child1 -> grandchild)
    fn create_test_hierarchy() -> NodeHierarchy {
        let nodes = vec![
            Node {
                parent: None,
                previous_sibling: None,
                next_sibling: None,
                last_child: Some(NodeId::new(1)),
            },
            Node {
                parent: Some(NodeId::new(0)),
                previous_sibling: None,
                next_sibling: None,
                last_child: Some(NodeId::new(2)),
            },
            Node {
                parent: Some(NodeId::new(1)),
                previous_sibling: None,
                next_sibling: None,
                last_child: None,
            },
        ];
        NodeHierarchy::new(nodes)
    }

    #[test]
    fn test_event_source_enum() {
        // Test that EventSource variants can be created
        let _user = EventSource::User;
        let _programmatic = EventSource::Programmatic;
        let _synthetic = EventSource::Synthetic;
        let _lifecycle = EventSource::Lifecycle;
    }

    #[test]
    fn test_event_phase_enum() {
        // Test that EventPhase variants can be created
        let _capture = EventPhase::Capture;
        let _target = EventPhase::Target;
        let _bubble = EventPhase::Bubble;

        // Test default
        assert_eq!(EventPhase::default(), EventPhase::Bubble);
    }

    #[test]
    fn test_synthetic_event_creation() {
        let dom_id = DomId { inner: 1 };
        let node_id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let target = DomNodeId {
            dom: dom_id,
            node: node_id,
        };

        let event = SyntheticEvent::new(
            EventType::Click,
            EventSource::User,
            target,
            test_instant(),
            EventData::None,
        );

        assert_eq!(event.event_type, EventType::Click);
        assert_eq!(event.source, EventSource::User);
        assert_eq!(event.phase, EventPhase::Target);
        assert_eq!(event.target, target);
        assert_eq!(event.current_target, target);
        assert!(!event.stopped);
        assert!(!event.stopped_immediate);
        assert!(!event.prevented_default);
    }

    #[test]
    fn test_stop_propagation() {
        let dom_id = DomId { inner: 1 };
        let node_id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let target = DomNodeId {
            dom: dom_id,
            node: node_id,
        };

        let mut event = SyntheticEvent::new(
            EventType::Click,
            EventSource::User,
            target,
            test_instant(),
            EventData::None,
        );

        assert!(!event.is_propagation_stopped());

        event.stop_propagation();

        assert!(event.is_propagation_stopped());
        assert!(!event.is_immediate_propagation_stopped());
    }

    #[test]
    fn test_stop_immediate_propagation() {
        let dom_id = DomId { inner: 1 };
        let node_id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let target = DomNodeId {
            dom: dom_id,
            node: node_id,
        };

        let mut event = SyntheticEvent::new(
            EventType::Click,
            EventSource::User,
            target,
            test_instant(),
            EventData::None,
        );

        event.stop_immediate_propagation();

        assert!(event.is_propagation_stopped());
        assert!(event.is_immediate_propagation_stopped());
    }

    #[test]
    fn test_prevent_default() {
        let dom_id = DomId { inner: 1 };
        let node_id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let target = DomNodeId {
            dom: dom_id,
            node: node_id,
        };

        let mut event = SyntheticEvent::new(
            EventType::Click,
            EventSource::User,
            target,
            test_instant(),
            EventData::None,
        );

        assert!(!event.is_default_prevented());

        event.prevent_default();

        assert!(event.is_default_prevented());
    }

    #[test]
    fn test_get_dom_path_single_node() {
        let hierarchy = NodeHierarchy::new(vec![Node {
            parent: None,
            previous_sibling: None,
            next_sibling: None,
            last_child: None,
        }]);

        let target = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let path = get_dom_path(&hierarchy, target);

        assert_eq!(path.len(), 1);
        assert_eq!(path[0], NodeId::new(0));
    }

    #[test]
    fn test_get_dom_path_three_nodes() {
        let hierarchy = create_test_hierarchy();

        // Test path to grandchild (node 2)
        let target = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(2)));
        let path = get_dom_path(&hierarchy, target);

        assert_eq!(path.len(), 3);
        assert_eq!(path[0], NodeId::new(0)); // root
        assert_eq!(path[1], NodeId::new(1)); // child
        assert_eq!(path[2], NodeId::new(2)); // grandchild
    }

    #[test]
    fn test_get_dom_path_middle_node() {
        let hierarchy = create_test_hierarchy();

        // Test path to middle node (node 1)
        let target = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(1)));
        let path = get_dom_path(&hierarchy, target);

        assert_eq!(path.len(), 2);
        assert_eq!(path[0], NodeId::new(0)); // root
        assert_eq!(path[1], NodeId::new(1)); // child
    }

    #[test]
    fn test_propagate_event_empty_callbacks() {
        let hierarchy = create_test_hierarchy();
        let dom_id = DomId { inner: 1 };
        let target_node = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(2)));
        let target = DomNodeId {
            dom: dom_id,
            node: target_node,
        };

        let mut event = SyntheticEvent::new(
            EventType::Click,
            EventSource::User,
            target,
            test_instant(),
            EventData::None,
        );

        let callbacks: BTreeMap<NodeId, Vec<EventFilter>> = BTreeMap::new();
        let result = propagate_event(&mut event, &hierarchy, &callbacks);

        // No callbacks, so nothing should be invoked
        assert_eq!(result.callbacks_to_invoke.len(), 0);
        assert!(!result.default_prevented);
    }

    #[test]
    fn test_mouse_event_data_creation() {
        let mouse_data = MouseEventData {
            position: LogicalPosition { x: 100.0, y: 200.0 },
            button: MouseButton::Left,
            buttons: 1,
            modifiers: KeyModifiers::new(),
        };

        assert_eq!(mouse_data.position.x, 100.0);
        assert_eq!(mouse_data.position.y, 200.0);
        assert_eq!(mouse_data.button, MouseButton::Left);
    }

    #[test]
    fn test_key_modifiers() {
        let modifiers = KeyModifiers::new().with_shift().with_ctrl();

        assert!(modifiers.shift);
        assert!(modifiers.ctrl);
        assert!(!modifiers.alt);
        assert!(!modifiers.meta);
        assert!(!modifiers.is_empty());

        let empty = KeyModifiers::new();
        assert!(empty.is_empty());
    }

    #[test]
    fn test_lifecycle_event_mount() {
        let dom_id = DomId { inner: 1 };
        let old_hierarchy = None;
        let new_hierarchy = create_test_hierarchy();
        let old_layout = None;
        let new_layout = {
            let mut map = BTreeMap::new();
            map.insert(
                NodeId::new(0),
                LogicalRect {
                    origin: LogicalPosition { x: 0.0, y: 0.0 },
                    size: LogicalSize {
                        width: 100.0,
                        height: 100.0,
                    },
                },
            );
            map.insert(
                NodeId::new(1),
                LogicalRect {
                    origin: LogicalPosition { x: 10.0, y: 10.0 },
                    size: LogicalSize {
                        width: 80.0,
                        height: 80.0,
                    },
                },
            );
            map.insert(
                NodeId::new(2),
                LogicalRect {
                    origin: LogicalPosition { x: 20.0, y: 20.0 },
                    size: LogicalSize {
                        width: 60.0,
                        height: 60.0,
                    },
                },
            );
            Some(map)
        };

        let events = detect_lifecycle_events(
            dom_id,
            dom_id,
            old_hierarchy,
            Some(&new_hierarchy),
            old_layout.as_ref(),
            new_layout.as_ref(),
            test_instant(),
        );

        // All 3 nodes should have Mount events
        assert_eq!(events.len(), 3);

        for event in &events {
            assert_eq!(event.event_type, EventType::Mount);
            assert_eq!(event.source, EventSource::Lifecycle);

            if let EventData::Lifecycle(data) = &event.data {
                assert_eq!(data.reason, LifecycleReason::InitialMount);
                assert!(data.previous_bounds.is_none());
            } else {
                panic!("Expected Lifecycle event data");
            }
        }
    }

    #[test]
    fn test_lifecycle_event_unmount() {
        let dom_id = DomId { inner: 1 };
        let old_hierarchy = create_test_hierarchy();
        let new_hierarchy = None;
        let old_layout = {
            let mut map = BTreeMap::new();
            map.insert(
                NodeId::new(0),
                LogicalRect {
                    origin: LogicalPosition { x: 0.0, y: 0.0 },
                    size: LogicalSize {
                        width: 100.0,
                        height: 100.0,
                    },
                },
            );
            Some(map)
        };
        let new_layout = None;

        let events = detect_lifecycle_events(
            dom_id,
            dom_id,
            Some(&old_hierarchy),
            new_hierarchy,
            old_layout.as_ref(),
            new_layout,
            test_instant(),
        );

        // All 3 nodes should have Unmount events
        assert_eq!(events.len(), 3);

        for event in &events {
            assert_eq!(event.event_type, EventType::Unmount);
            assert_eq!(event.source, EventSource::Lifecycle);
        }
    }

    #[test]
    fn test_lifecycle_event_resize() {
        let dom_id = DomId { inner: 1 };
        let hierarchy = create_test_hierarchy();

        let old_layout = {
            let mut map = BTreeMap::new();
            map.insert(
                NodeId::new(0),
                LogicalRect {
                    origin: LogicalPosition { x: 0.0, y: 0.0 },
                    size: LogicalSize {
                        width: 100.0,
                        height: 100.0,
                    },
                },
            );
            Some(map)
        };

        let new_layout = {
            let mut map = BTreeMap::new();
            map.insert(
                NodeId::new(0),
                LogicalRect {
                    origin: LogicalPosition { x: 0.0, y: 0.0 },
                    size: LogicalSize {
                        width: 200.0,
                        height: 100.0,
                    }, // Width changed
                },
            );
            Some(map)
        };

        let events = detect_lifecycle_events(
            dom_id,
            dom_id,
            Some(&hierarchy),
            Some(&hierarchy),
            old_layout.as_ref(),
            new_layout.as_ref(),
            test_instant(),
        );

        // Should have 1 Resize event
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::Resize);
        assert_eq!(events[0].source, EventSource::Lifecycle);

        if let EventData::Lifecycle(data) = &events[0].data {
            assert_eq!(data.reason, LifecycleReason::Resize);
            assert!(data.previous_bounds.is_some());
            assert_eq!(data.current_bounds.size.width, 200.0);
        } else {
            panic!("Expected Lifecycle event data");
        }
    }

    #[test]
    fn test_event_filter_hover_match() {
        let dom_id = DomId { inner: 1 };
        let node_id = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
        let target = DomNodeId {
            dom: dom_id,
            node: node_id,
        };

        let _event = SyntheticEvent::new(
            EventType::MouseDown,
            EventSource::User,
            target,
            test_instant(),
            EventData::Mouse(MouseEventData {
                position: LogicalPosition { x: 0.0, y: 0.0 },
                button: MouseButton::Left,
                buttons: 1,
                modifiers: KeyModifiers::new(),
            }),
        );

        // This is tested internally via matches_hover_filter
        // We can't test it directly without making the function public
        // but it's tested indirectly through propagate_event
    }
}