htui 0.2.0

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

use std::sync::{Arc, Mutex};

use boa_engine::JsValue;
use crossterm::style::Color;
use htui::events::{
    ElementRef, EventBindings, EventType, Geometry, HitMap, HitRegion,
    interaction::{
        HoverState, on_click, on_mouse_down, on_mouse_move_dispatch, on_mouse_up, on_move,
    },
};
use htui::html::css_parse::{
    DynamicState, Parser as CssParser, PseudoClass, Selector, css_into_node,
    css_into_node_with_hover, reset_css_attr,
};
use htui::html::{css_parse, html_parse};
use htui::layout::layout::TermMap;
use htui::layout::{BoxConstraint, Cursor, Rect, layout_tree};
use htui::script::{ScriptEngine, ScriptMsg, apply_message};
use htui::tdom::node::{Node, NodeArena, NodeId, NodeType};
use htui::tui::graph_api::{
    DirtyInfo, DrainedBatch, InputState, OverlayKind, RenderCmd, SelectOpenState, SelectionMode,
    TermLayout, apply_input_key, handle_click, handle_mouse_down, handle_mouse_move,
    handle_mouse_up,
};

use crossterm::event::{KeyCode, MouseButton};

// ---------------------------------------------------------------------------
// `#[htui::command]` / `#[derive(IntoJs)]` — tauri-style host bindings.
// ---------------------------------------------------------------------------

/// Command return type: struct → JS object with `#[js_name]` renames.
#[derive(htui::IntoJs)]
struct Greeting {
    name: String,
    #[js_name = "loudName"]
    loud_name: String,
    times: u64,
}

/// No-capture command: args `FromJs`, return `IntoJs`.
#[htui::command]
fn greet(name: String, times: u64) -> Greeting {
    Greeting {
        name: name.clone(),
        loud_name: format!("{name}!!"),
        times,
    }
}

/// Command returning `Result`: `Err` must surface as a JS throw.
#[htui::command]
fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err("division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

/// Command argument type: struct read back from a JS object, with
/// `#[js_name]` mapping the JS property name to the Rust field.
#[derive(htui::FromJs)]
struct Threshold {
    #[js_name = "maxCpu"]
    max_cpu: f64,
    label: String,
}

/// Command taking a `#[derive(FromJs)]` struct argument.
#[htui::command]
fn clamp(value: f64, config: Threshold) -> Result<f64, String> {
    if config.max_cpu <= 0.0 {
        return Err(format!("{}: maxCpu must be positive", config.label));
    }
    Ok(value.min(config.max_cpu))
}

// ============================================================
// `<input>` field events (focus / blur / input / change) + `el.value`
// ============================================================

#[test]
fn input_events_dispatch_via_listeners_and_onstar_attributes() {
    // The four input events must fire along the DOM ancestor chain for both
    // `addEventListener` listeners and compiled `on*` attributes.
    let (mut engine, _geo) = build_geometry(
        r#"<script>
          var seen = [];
          var el = document.getElementById('f');
          el.addEventListener('focus', function () { seen.push('a-focus'); });
          el.addEventListener('blur', function () { seen.push('a-blur'); });
          el.addEventListener('input', function () { seen.push('a-input'); });
          el.addEventListener('change', function () { seen.push('a-change'); });
          globalThis.__seen = seen;
        </script>
        <div onfocus="seen.push('p-focus')" onblur="seen.push('p-blur')">
          <input id="f" value="a" oninput="seen.push('i-input')" onchange="seen.push('i-change')">
        </div>"#,
        EventBindings::default(),
    );
    let arena = engine.arena();
    let input_id = find_node_by_id(&arena, "f");
    let region = region_of(&arena, input_id);

    engine.fire(&region, EventType::Focus, 0, 0);
    engine.fire(&region, EventType::Input, 0, 0);
    engine.fire(&region, EventType::Change, 0, 0);
    engine.fire(&region, EventType::Blur, 0, 0);

    let seen = eval_str(&mut engine, "String(globalThis.__seen.join(','))");
    assert_eq!(
        seen, "a-focus,p-focus,a-input,i-input,a-change,i-change,a-blur,p-blur",
        "addEventListener listeners fire before the element's on* attribute \
         handler (DOM inner-invoke order); target before ancestors"
    );
}

#[test]
fn input_value_property_reads_and_writes_the_dom() {
    // `el.value` reads the DOM attribute; writing it marks the node dirty so
    // the next frame re-renders (equal writes short-circuit).
    let (mut engine, _geo) = build_geometry(
        r#"<script>
          var el = document.getElementById('f');
          globalThis.__before = el.value;
          el.value = 'typed';
          globalThis.__after = el.value;
          el.value = 'typed';
        </script>
        <input id="f" value="init">"#,
        EventBindings::default(),
    );
    assert_eq!(eval_str(&mut engine, "globalThis.__before"), "init");
    assert_eq!(eval_str(&mut engine, "globalThis.__after"), "typed");
    let arena = engine.arena();
    let stored = arena
        .get(find_node_by_id(&arena, "f"))
        .and_then(|n| n.attributes.get("value"))
        .cloned();
    assert_eq!(stored.as_deref(), Some("typed"));
}

#[test]
fn click_input_focuses_and_click_elsewhere_blurs() {
    // The input loop's click rule: clicking an `<input>` focuses it, and any
    // other click (blank space here) blurs it — both repainting via
    // `RenderInput` so the field's caret / focus frame disappear.
    let (mut engine, geo) = build_geometry(
        r#"<div id="a"><input id="name" value="Ada"></div><div id="b">blank</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let input_region = map.resolve_by_id("name").expect("input region");
    let (ix, iy) = center(input_region.rect);

    let mut state = InputState::new();
    let cmds = click(&mut state, &mut engine, &map, ix, iy);
    assert_eq!(state.focused_input, Some(input_region.node_id));
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::RenderInput {
                node_id,
                focused: true,
                ..
            } if *node_id == input_region.node_id
        )),
        "clicking the field must queue a focused repaint"
    );

    // Click far below the document (blank space) → the field must blur.
    let cmds = click(&mut state, &mut engine, &map, 0, 1000);
    assert!(state.focused_input.is_none(), "click outside must blur");
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::RenderInput {
                node_id,
                focused: false,
                selection: None,
                ..
            } if *node_id == input_region.node_id
        )),
        "blur must queue an unfocused repaint with the selection cleared"
    );
}

#[test]
fn click_on_inline_anchor_resolves_to_the_anchor() {
    // An inline `<a>` owns no LayoutBox — its text folds into the parent
    // block's inline runs. Its runs still carry the anchor's node id (same
    // mechanism as `<label>`), so the hit map gives the link text its own
    // region: the click target is the anchor itself, and listeners on the
    // anchor fire.
    let (mut engine, geo) = build_geometry(
        r#"<p id="p">before <a id="link" href="https://www.baidu.com/s" onclick="globalThis.__clicked = (globalThis.__clicked || 0) + 1">Baidu</a> after</p>"#,
        EventBindings::default(),
    );
    let arena = engine.arena();
    let anchor = find_node_by_id(&arena, "link");

    let map = HitMap::build(&geo);
    assert!(
        map.iter().any(|r| r.node_id == anchor),
        "the inline anchor must own a hit region"
    );

    let region = map.resolve_by_id("link").expect("anchor region by id");
    let (x, y) = center(region.rect);

    // hit_test at the link text must resolve to the anchor, not the block.
    let hit = map.hit_test(x, y).expect("hit under the link text");
    assert_eq!(hit.node_id, anchor, "deepest hit must be the anchor");

    // Full input-loop path: the click dispatches a Click event whose target
    // is the anchor, so its listener runs.
    let mut state = InputState::new();
    click(&mut state, &mut engine, &map, x, y);
    assert_eq!(
        eval_str(&mut engine, "String(globalThis.__clicked || 0)"),
        "1",
        "clicking the link text must fire the anchor's onclick"
    );
}

#[test]
fn click_another_input_commits_the_previous_field() {
    // Clicking a second field switches focus: the previous field is repainted
    // unfocused and its edited value is committed into the DOM (single source
    // of truth), while the new field focuses with its own value.
    let (mut engine, geo) = build_geometry(
        r#"<div id="a"><input id="name" value="Ada"></div>
        <div id="b"><input id="city" value="Tokyo"></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let name = map.resolve_by_id("name").expect("name region");
    let city = map.resolve_by_id("city").expect("city region");
    let (nx, ny) = center(name.rect);
    let (cx, cy) = center(city.rect);

    let mut state = InputState::new();
    click(&mut state, &mut engine, &map, nx, ny);
    // Type into the focused field.
    assert!(apply_input_key(
        &mut state.input_value,
        &mut state.input_cursor,
        KeyCode::Char('!'),
    ));

    // Click the other field.
    let cmds = click(&mut state, &mut engine, &map, cx, cy);
    assert_eq!(state.focused_input, Some(city.node_id));
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::RenderInput {
                node_id,
                focused: false,
                ..
            } if *node_id == name.node_id
        )),
        "the previous field must be repainted unfocused"
    );
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::RenderInput {
                node_id,
                focused: true,
                ..
            } if *node_id == city.node_id
        )),
        "the new field must be repainted focused"
    );

    // The edited value was committed to the DOM on blur.
    let arena = engine.arena();
    let committed = arena
        .get(name.node_id)
        .and_then(|n| n.attributes.get("value"))
        .cloned();
    assert_eq!(committed.as_deref(), Some("Ada!"));
}

#[test]
fn mouse_down_on_input_focuses_and_positions_caret() {
    // Pressing inside a field focuses it (blurring any previous field) and
    // enters drag-selection mode with the caret at the press point.
    let (mut engine, geo) = build_geometry(
        r#"<div><input id="name" value="hello" width="20"></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("name").expect("input region");
    let (x, y) = center(region.rect);

    let mut state = InputState::new();
    let cmds = mouse_down(&mut state, &mut engine, &map, x, y, MouseButton::Left);
    assert!(
        state.drag_selecting,
        "press on a field starts drag-selection mode"
    );
    assert_eq!(state.focused_input, Some(region.node_id));
    assert_eq!(state.input_sel_anchor, Some(state.input_cursor));
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::RenderInput {
                node_id,
                focused: true,
                ..
            } if *node_id == region.node_id
        )),
        "the field must be repainted focused with the caret in place"
    );
}

#[test]
fn drag_on_input_selects_a_character_range() {
    // Press at the first content column (caret at char 0), drag right two
    // columns: the selection (0, 2) must be carried by the repaint command.
    let (mut engine, geo) = build_geometry(
        r#"<div><input id="name" value="hello" width="20"></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("name").expect("input region");
    let rx = region.rect.x as u32;
    let ry = region.rect.y as u32;

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, rx, ry, MouseButton::Left);
    assert_eq!(state.input_cursor, 0, "press on the first column → char 0");

    // The input loop tracks the press position; a plain move is a drag.
    state.pressed = Some((0, 0));
    let cmds = mouse_move(&mut state, &mut engine, &map, rx + 2, ry);
    assert_eq!(state.input_cursor, 2, "drag to the third column → char 2");
    let sel = cmds.iter().find_map(|c| match c {
        RenderCmd::RenderInput {
            selection: Some(s), ..
        } => Some(*s),
        _ => None,
    });
    assert_eq!(sel, Some((0, 2)), "drag must select chars 0..2");
}

#[test]
fn drag_on_page_text_emits_text_selection() {
    // A press alone never creates a page text selection (browsers select only
    // on a real drag, so a jittery click leaves no residue); once the drag
    // passes the threshold, dragging updates its endpoint and queues a
    // `TextSelection` repaint.
    let (mut engine, geo) = build_geometry(
        r#"<div id="a">some text</div><div id="b">more text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, 0, 0, MouseButton::Left);
    assert_eq!(
        state.text_sel_anchor, None,
        "a press alone defers the selection start"
    );
    assert_eq!(state.text_sel_end, None);
    assert_eq!(state.text_sel_mode, SelectionMode::Flow);

    state.pressed = Some((0, 0));
    let cmds = mouse_move(&mut state, &mut engine, &map, 4, 0);
    assert_eq!(
        state.text_sel_anchor,
        Some((0, 0)),
        "the anchor is the press point"
    );
    assert_eq!(state.text_sel_end, Some((4, 0)));
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::TextSelection {
                anchor: Some((0, 0)),
                end: Some((4, 0)),
                mode: SelectionMode::Flow
            }
        )),
        "a left-drag over page text must queue a flow TextSelection repaint"
    );
}

#[test]
fn page_drag_fires_selectionchange_at_gesture_end() {
    // Browser selectionchange is a coalesced change notification rather than
    // one event per pointer pixel. The terminal gesture boundary is mouse-up.
    let (mut engine, geo) = build_geometry(
        r#"<script>
             globalThis.selectionChanges = 0;
             window.addEventListener('selectionchange', () => {
               globalThis.selectionChanges += 1;
             });
           </script>
           <div id="a">some text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, 0, 0, MouseButton::Left);
    state.pressed = Some((0, 0));
    let _ = mouse_move(&mut state, &mut engine, &map, 4, 0);
    assert_eq!(
        eval_str(&mut engine, "String(globalThis.selectionChanges)"),
        "0",
        "drag motion must not flood selectionchange"
    );

    mouse_up(&mut state, &mut engine, &map, 4, 0);
    assert_eq!(
        eval_str(&mut engine, "String(globalThis.selectionChanges)"),
        "1",
        "selectionchange fires once when the drag gesture ends"
    );
}

#[test]
fn pressing_elsewhere_replaces_the_page_selection() {
    // A second press clears the previous selection (rendering it away); the
    // new selection is anchored only once its drag begins — the render thread
    // needs the explicit clear.
    let (mut engine, geo) =
        build_geometry(r#"<div id="a">some text</div>"#, EventBindings::default());
    let map = HitMap::build(&geo);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, 0, 0, MouseButton::Left);
    state.pressed = Some((0, 0));
    mouse_move(&mut state, &mut engine, &map, 3, 0);
    assert!(state.text_sel_anchor.is_some(), "a selection now exists");

    let cmds = mouse_down(&mut state, &mut engine, &map, 2, 2, MouseButton::Left);
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::TextSelection {
                anchor: None,
                end: None,
                ..
            }
        )),
        "the previous selection must be cleared on a new press"
    );
    assert_eq!(
        state.text_sel_anchor, None,
        "the new selection is deferred until its drag begins"
    );
}

#[test]
fn blank_body_press_can_anchor_an_upward_flow_drag() {
    // A browser can start a drag in body whitespace outside the text box. The
    // terminal hit map has no box there, but body remains the implicit target;
    // dragging upward may then enter text and produce a selection.
    let (mut engine, geo) = build_geometry(
        r#"<div id="text">some text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, 5, 5, MouseButton::Left);
    state.pressed = Some((5, 5));
    let cmds = mouse_move(&mut state, &mut engine, &map, 3, 0);

    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::TextSelection {
                anchor: Some((5, 5)),
                end: Some((3, 0)),
                mode: SelectionMode::Flow
            }
        )),
        "body whitespace must be usable as a flow-selection origin"
    );
}

#[test]
fn right_drag_emits_a_block_selection() {
    // Right-drag is the rectangle (block) selection: the command must carry
    // `SelectionMode::Block` so the render thread highlights a rectangle.
    // Like the left flow selection it only starts once the drag begins.
    let (mut engine, geo) = build_geometry(
        r#"<div id="a">some text</div><div id="b">more text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, 2, 0, MouseButton::Right);
    assert_eq!(state.text_sel_mode, SelectionMode::Block);
    assert_eq!(
        state.text_sel_anchor, None,
        "a press alone defers the selection start"
    );

    state.pressed = Some((2, 0));
    let cmds = mouse_move(&mut state, &mut engine, &map, 5, 2);
    assert_eq!(
        state.text_sel_anchor,
        Some((2, 0)),
        "the anchor is the press point"
    );
    assert!(
        cmds.iter().any(|c| matches!(
            c,
            RenderCmd::TextSelection {
                anchor: Some((2, 0)),
                end: Some((5, 2)),
                mode: SelectionMode::Block
            }
        )),
        "a right-drag must queue a block TextSelection repaint"
    );
    assert!(
        !state.drag_selecting,
        "right-drag never enters the field-internal drag mode"
    );
}

#[test]
fn jittery_click_on_a_button_leaves_no_selection() {
    // A button press with a one-cell wiggle (a sloppy but common click) must
    // not leave a highlighted character behind: the selection is deferred
    // until the drag clears the threshold, so no `TextSelection` is ever
    // queued and the anchor stays clear through the release.
    let (mut engine, geo) = build_geometry(
        r#"<div id="btn">▶ button text</div><div id="next">other</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let btn = map.resolve_by_id("btn").expect("btn region");
    let (bx, by) = center(btn.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, bx, by, MouseButton::Left);
    assert_eq!(state.text_sel_anchor, None, "press alone: no selection yet");

    // The input loop tracks the press position; the pointer wiggles one cell
    // right while the button is held (still a click, not a drag).
    state.pressed = Some((bx as u16, by as u16));
    let cmds = mouse_move(&mut state, &mut engine, &map, bx + 1, by);
    assert!(
        !cmds
            .iter()
            .any(|c| matches!(c, RenderCmd::TextSelection { .. })),
        "a sub-threshold wiggle must not queue a TextSelection"
    );
    assert_eq!(state.text_sel_anchor, None);

    // Release on the jittered cell: still no selection residue.
    mouse_up(&mut state, &mut engine, &map, (bx + 1) as u16, by as u16);
    assert_eq!(state.text_sel_anchor, None, "no residue after release");
    assert_eq!(state.text_sel_end, None);
}

#[test]
fn drag_from_a_button_never_selects_page_text_or_clicks() {
    // A button owns its gesture. Even when the pointer travels far enough to
    // be a drag, it must not arm the page flow selection; and because the
    // gesture crossed the drag threshold, release must not activate it either.
    let (mut engine, geo) = build_geometry(
        r#"<script>
             globalThis.clicks = 0;
             document.getElementById('btn')
               .addEventListener('click', () => globalThis.clicks += 1);
           </script>
           <button id="btn">Save</button><div id="next">other</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let btn = map.resolve_by_id("btn").expect("button region");
    let (bx, by) = center(btn.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, bx, by, MouseButton::Left);
    state.pressed = Some((bx as u16, by as u16));

    let cmds = mouse_move(&mut state, &mut engine, &map, bx + 3, by);
    assert!(
        !cmds
            .iter()
            .any(|c| matches!(c, RenderCmd::TextSelection { .. })),
        "a drag originating on a button must not queue a page TextSelection"
    );
    assert_eq!(state.text_sel_anchor, None);
    assert_eq!(state.text_sel_end, None);

    mouse_up(&mut state, &mut engine, &map, (bx + 3) as u16, by as u16);
    assert_eq!(
        eval_str(&mut engine, "String(globalThis.clicks)"),
        "0",
        "a real drag must not turn into a button click"
    );
}

#[test]
fn small_jitter_on_a_button_still_clicks() {
    // Movement below the shared threshold is a sloppy click, not a drag. The
    // release must remain on the same logical button for activation.
    let (mut engine, geo) = build_geometry(
        r#"<script>
             globalThis.clicks = 0;
             document.getElementById('btn')
               .addEventListener('click', () => globalThis.clicks += 1);
           </script>
           <button id="btn">Save</button>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let btn = map.resolve_by_id("btn").expect("button region");
    let (bx, by) = center(btn.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, bx, by, MouseButton::Left);
    state.pressed = Some((bx as u16, by as u16));
    let _ = mouse_move(&mut state, &mut engine, &map, bx + 1, by);
    mouse_up(&mut state, &mut engine, &map, (bx + 1) as u16, by as u16);

    assert_eq!(
        eval_str(&mut engine, "String(globalThis.clicks)"),
        "1",
        "a sub-threshold jitter on the same button is a click"
    );
}

#[test]
fn disabled_flow_copy_blocks_left_drag_selection() {
    // With `copy_flow` off, a left-drag over page content must never start a
    // selection: the press does not arm the flow mode and the drag queues no
    // `TextSelection` (so there is nothing to copy on `Ctrl+C`).
    let (mut engine, geo) = build_geometry(
        r#"<div id="a">some text</div><div id="b">more text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);

    let mut state = InputState::new();
    state.copy_flow = false;
    mouse_down(&mut state, &mut engine, &map, 0, 0, MouseButton::Left);
    assert_eq!(state.text_sel_anchor, None);
    assert_eq!(state.text_sel_end, None);

    state.pressed = Some((0, 0));
    let cmds = mouse_move(&mut state, &mut engine, &map, 4, 0);
    assert_eq!(
        state.text_sel_anchor, None,
        "disabled flow copy must never start a selection"
    );
    assert_eq!(state.text_sel_end, None);
    assert!(
        !cmds
            .iter()
            .any(|c| matches!(c, RenderCmd::TextSelection { .. })),
        "a disabled flow copy must queue no TextSelection"
    );
}

#[test]
fn disabled_block_copy_blocks_right_drag_selection() {
    // With `copy_block` off, a right-drag must never start a selection — and
    // in particular must not fall back to the stale `Flow` mode from the
    // default state, which would otherwise highlight a wrong-shaped selection
    // on a disabled feature.
    let (mut engine, geo) = build_geometry(
        r#"<div id="a">some text</div><div id="b">more text</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);

    let mut state = InputState::new();
    state.copy_block = false;
    mouse_down(&mut state, &mut engine, &map, 2, 0, MouseButton::Right);
    assert_eq!(state.text_sel_anchor, None);

    state.pressed = Some((2, 0));
    let cmds = mouse_move(&mut state, &mut engine, &map, 5, 2);
    assert_eq!(
        state.text_sel_anchor, None,
        "disabled block copy must never start a selection"
    );
    assert_eq!(state.text_sel_end, None);
    assert!(
        !cmds
            .iter()
            .any(|c| matches!(c, RenderCmd::TextSelection { .. })),
        "a disabled block copy must queue no TextSelection"
    );
}

#[test]
fn arena_behind_a_pending_document_merges_without_losing_css() {
    // A reload reply can be followed by another script reply before the
    // render thread drains its channel. The newer arena must merge into the
    // document snapshot; replacing it would lose the new document CSS source.
    let mut id_arena = NodeArena::default();
    let first = id_arena.insert(Node::from(NodeType::Document));
    let second = id_arena.insert(Node::from(NodeType::Document));
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderDocument {
        arena: Arc::new(NodeArena::default()),
        root_id: first,
        document_css: Arc::from("p { color: red; }"),
        scroll_y: 0,
        zoom: 1.0,
        dirty: DirtyInfo {
            nodes: vec![first],
            ..DirtyInfo::default()
        },
    });

    let fresh_arena = Arc::new(NodeArena::default());
    batch.absorb(RenderCmd::RenderArena {
        arena: Arc::clone(&fresh_arena),
        root_id: second,
        scroll_y: 7,
        zoom: 2.0,
        dynamic: DynamicState::default(),
        dirty: DirtyInfo {
            nodes: vec![second],
            ..DirtyInfo::default()
        },
    });

    match batch.take_snapshot() {
        Some(RenderCmd::RenderDocument {
            arena,
            root_id,
            document_css,
            scroll_y,
            zoom,
            dirty,
        }) => {
            assert!(Arc::ptr_eq(&arena, &fresh_arena));
            assert_eq!(root_id, second);
            assert_eq!(&*document_css, "p { color: red; }");
            assert_eq!((scroll_y, zoom), (7, 2.0));
            assert!(dirty.nodes.contains(&first));
            assert!(dirty.nodes.contains(&second));
        }
        other => panic!("expected the document snapshot to survive, got {other:?}"),
    }
}

#[test]
fn reset_document_state_clears_replaced_document_interaction() {
    // Whole-document reload invalidates every input-side node id and canvas
    // coordinate. Scroll / zoom survive, but focus, edits, drags, page
    // selection and an open dropdown must not leak into the fresh arena.
    let mut id_arena = NodeArena::default();
    let focused = id_arena.insert(Node::from(NodeType::Input));
    let dropdown = id_arena.insert(Node::from(NodeType::Select));

    let mut state = InputState::new();
    state.pressed = Some((3, 4));
    state.focused_input = Some(focused);
    state.focused_is_textarea = true;
    state.input_value = "editing".into();
    state.input_cursor = 3;
    state.input_sel_anchor = Some(0);
    state.drag_selecting = true;
    state.text_sel_anchor = Some((0, 0));
    state.text_sel_end = Some((5, 1));
    state.open_select = Some(SelectOpenState {
        node_id: dropdown,
        kind: OverlayKind::Select,
        rect: Rect::new(0, 0, 4, 2),
        options: Vec::new(),
        rows: Vec::new(),
        highlight: 0,
    });

    let mut cmds = Vec::new();
    state.reset_document_state(&mut cmds);

    assert_eq!(state.pressed, None);
    assert_eq!(state.focused_input, None);
    assert!(!state.focused_is_textarea);
    assert_eq!(state.input_value, "");
    assert_eq!(state.input_cursor, 0);
    assert_eq!(state.input_sel_anchor, None);
    assert!(!state.drag_selecting);
    assert_eq!(state.text_sel_anchor, None);
    assert_eq!(state.text_sel_end, None);
    assert!(state.open_select.is_none());
    assert!(state.resize_pending);
    assert!(
        cmds.iter()
            .any(|c| matches!(c, RenderCmd::SelectClose { node_id } if *node_id == dropdown))
    );
}

#[test]
fn focus_behind_a_pending_arena_merges_into_the_arena_dynamic() {
    // A `Focus` queued behind a pending `RenderArena` merges into that
    // arena's interaction state, preserving both its DOM mutations and the
    // `:focus` update in one repaint.
    let new_focus = NodeId::default();
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderArena {
        arena: Arc::new(NodeArena::default()),
        root_id: NodeId::default(),
        scroll_y: 0,
        zoom: 1.0,
        dynamic: DynamicState {
            hovered: Some(NodeId::default()),
            ..Default::default()
        },
        dirty: DirtyInfo::default(),
    });
    batch.absorb(RenderCmd::Focus {
        node_id: Some(new_focus),
    });
    match batch.take_snapshot() {
        Some(RenderCmd::RenderArena { dynamic, .. }) => {
            assert_eq!(
                dynamic.focused,
                Some(new_focus),
                "the focus delta must merge into the arena's dynamic state"
            );
        }
        other => panic!("expected the arena snapshot to survive, got {other:?}"),
    }
    assert!(batch.take_hover().is_none(), "no hover was queued");
}

#[test]
fn hover_behind_a_pending_arena_is_deferred_not_dropped() {
    // A newer `Hover` behind a pending `RenderArena` must not supersede the
    // DOM mutation; the drain defers it so the freshest highlight is applied
    // on top of the arena render.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderArena {
        arena: Arc::new(NodeArena::default()),
        root_id: NodeId::default(),
        scroll_y: 0,
        zoom: 1.0,
        dynamic: DynamicState::default(),
        dirty: DirtyInfo::default(),
    });
    batch.absorb(RenderCmd::Hover { node_id: None });
    assert!(
        matches!(batch.take_snapshot(), Some(RenderCmd::RenderArena { .. })),
        "the arena snapshot must survive the deferred hover"
    );
    assert!(
        matches!(batch.take_hover(), Some(RenderCmd::Hover { node_id: None })),
        "the newer hover must be deferred, not dropped"
    );
}

#[test]
fn hover_behind_a_pending_redraw_is_deferred_not_dropped() {
    // A resize pushes a `Redraw`, and pointer motion in the same batch queues
    // a `Hover` behind it. The drain defers the hover so the re-layout
    // remains intact.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::Redraw {
        scroll_y: 0,
        zoom: 1.0,
    });
    batch.absorb(RenderCmd::Hover { node_id: None });
    assert!(
        matches!(batch.take_snapshot(), Some(RenderCmd::Redraw { .. })),
        "the resize re-layout must survive the deferred hover"
    );
    assert!(
        matches!(batch.take_hover(), Some(RenderCmd::Hover { node_id: None })),
        "the newer hover must be deferred, not dropped"
    );
}

#[test]
fn rerender_behind_a_pending_arena_folds_the_scroll() {
    // A scroll queued behind a pending `RenderArena` must fold into the arena
    // instead of replacing it: the arena carries DOM mutations a pure
    // viewport command must not drop.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderArena {
        arena: Arc::new(NodeArena::default()),
        root_id: NodeId::default(),
        scroll_y: 0,
        zoom: 1.0,
        dynamic: DynamicState::default(),
        dirty: DirtyInfo::default(),
    });
    batch.absorb(RenderCmd::Rerender { scroll_y: 9 });
    match batch.take_snapshot() {
        Some(RenderCmd::RenderArena { scroll_y, .. }) => {
            assert_eq!(scroll_y, 9, "the newer scroll must fold into the arena");
        }
        other => panic!("expected the arena snapshot to survive, got {other:?}"),
    }
}

#[test]
fn redraw_behind_a_pending_arena_folds_scroll_and_zoom() {
    // Same fold rule for `Redraw` (resize / zoom): the DOM mutations win,
    // the viewport state updates in place.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderArena {
        arena: Arc::new(NodeArena::default()),
        root_id: NodeId::default(),
        scroll_y: 0,
        zoom: 1.0,
        dynamic: DynamicState::default(),
        dirty: DirtyInfo::default(),
    });
    batch.absorb(RenderCmd::Redraw {
        scroll_y: 5,
        zoom: 2.0,
    });
    match batch.take_snapshot() {
        Some(RenderCmd::RenderArena { scroll_y, zoom, .. }) => {
            assert_eq!(scroll_y, 5);
            assert_eq!(zoom, 2.0);
        }
        other => panic!("expected the arena snapshot to survive, got {other:?}"),
    }
}

#[test]
fn focus_behind_a_pending_redraw_is_deferred_not_dropped() {
    // Focus moving while a resize `Redraw` is pending must defer like a
    // hover, not supersede the re-layout.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::Redraw {
        scroll_y: 0,
        zoom: 1.0,
    });
    batch.absorb(RenderCmd::Focus {
        node_id: Some(NodeId::default()),
    });
    assert!(
        matches!(batch.take_snapshot(), Some(RenderCmd::Redraw { .. })),
        "the resize re-layout must survive the deferred focus"
    );
    assert!(
        matches!(batch.take_focus(), Some(RenderCmd::Focus { .. })),
        "the focus delta must be deferred, not dropped"
    );
}

#[test]
fn rerender_still_supersedes_a_pending_redraw() {
    // Two viewport-only snapshots: the later one carries the newest complete
    // state and wins, as before.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::Redraw {
        scroll_y: 0,
        zoom: 1.0,
    });
    batch.absorb(RenderCmd::Rerender { scroll_y: 7 });
    assert!(
        matches!(
            batch.take_snapshot(),
            Some(RenderCmd::Rerender { scroll_y: 7 })
        ),
        "the latest viewport snapshot must win"
    );
}

#[test]
fn focus_without_a_pending_arena_supersedes_as_a_snapshot() {
    // With no arena pending, a later `Focus` fully supersedes an earlier one
    // (both are complete interaction-state deltas).
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::Focus {
        node_id: Some(NodeId::default()),
    });
    batch.absorb(RenderCmd::Focus { node_id: None });
    match batch.take_snapshot() {
        Some(RenderCmd::Focus { node_id }) => assert_eq!(node_id, None),
        other => panic!("expected the latest focus, got {other:?}"),
    }
}

#[test]
fn stateful_commands_run_in_order_and_selection_keeps_the_latest() {
    // `RenderInput` / `Select*` must survive in arrival order (a focus switch
    // queues blur + focus; a `SelectClose` must not be swallowed), while the
    // incremental `TextSelection` keeps only the latest of the batch.
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::RenderInput {
        node_id: NodeId::default(),
        value: "a".into(),
        cursor: 1,
        focused: true,
        selection: None,
    });
    batch.absorb(RenderCmd::SelectOpen {
        node_id: NodeId::default(),
        filter: None,
    });
    batch.absorb(RenderCmd::TextSelection {
        anchor: Some((0, 0)),
        end: Some((1, 0)),
        mode: SelectionMode::Flow,
    });
    batch.absorb(RenderCmd::SelectClose {
        node_id: NodeId::default(),
    });
    batch.absorb(RenderCmd::TextSelection {
        anchor: None,
        end: None,
        mode: SelectionMode::Block,
    });
    assert_eq!(batch.drain_inputs().count(), 1);
    let selects: Vec<RenderCmd> = batch.drain_selects().collect();
    assert_eq!(selects.len(), 2, "both select commands must survive");
    assert!(matches!(selects[0], RenderCmd::SelectOpen { .. }));
    assert!(matches!(selects[1], RenderCmd::SelectClose { .. }));
    match batch.take_text_selection() {
        Some(RenderCmd::TextSelection { anchor, mode, .. }) => {
            assert_eq!(anchor, None, "only the latest selection matters");
            assert_eq!(mode, SelectionMode::Block);
        }
        other => panic!("expected the latest selection, got {other:?}"),
    }
}

#[test]
fn quit_supersedes_the_batch_and_flags_the_drain() {
    let mut batch = DrainedBatch::new();
    batch.absorb(RenderCmd::Redraw {
        scroll_y: 0,
        zoom: 1.0,
    });
    batch.absorb(RenderCmd::Quit);
    assert!(batch.quit_requested(), "the drain must stop after a Quit");
    assert!(matches!(batch.take_snapshot(), Some(RenderCmd::Quit)));
}

#[test]
fn click_select_opens_the_dropdown() {
    // Clicking a `<select>` opens its dropdown: the input loop remembers the
    // options and overlay geometry, and queues a `SelectOpen` repaint.
    let (mut engine, geo) = build_geometry(
        r#"<div><select id="s"><option value="a">Alpha</option><option value="b">Beta</option></select></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("s").expect("select region");
    let (sx, sy) = center(region.rect);

    let mut state = InputState::new();
    let cmds = mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    assert!(
        state.open_select.is_some(),
        "clicking a select must open its dropdown"
    );
    let open = state.open_select.clone().unwrap();
    assert_eq!(open.node_id, region.node_id);
    assert_eq!(open.options.len(), 2);
    assert_eq!(
        open.highlight, 0,
        "first option highlighted when nothing selected"
    );
    assert!(
        cmds.iter()
            .any(|c| matches!(c, RenderCmd::SelectOpen { .. })),
        "opening must queue a SelectOpen repaint"
    );
}

#[test]
fn picking_a_select_option_commits_the_value_and_fires_change() {
    // Clicking an option row picks it: the dropdown closes, the value is
    // committed to the DOM, and a `change` event fires along the DOM path.
    let (mut engine, geo) = build_geometry(
        r#"<script>
          var seen = [];
          var s = document.getElementById('s');
          s.addEventListener('change', function () { seen.push(s.value); });
          globalThis.__seen = seen;
        </script>
        <div><select id="s"><option value="a">Alpha</option><option value="b">Beta</option></select></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("s").expect("select region");
    let (sx, sy) = center(region.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    let open = state.open_select.clone().unwrap();
    // Click the second option row (one row below the field).
    let cmds = mouse_down(
        &mut state,
        &mut engine,
        &map,
        open.rect.x as u32,
        open.rect.y as u32 + 1,
        MouseButton::Left,
    );
    assert!(
        state.open_select.is_none(),
        "picking an option closes the dropdown"
    );
    assert!(
        cmds.iter()
            .any(|c| matches!(c, RenderCmd::SelectClose { .. })),
        "closing must queue a SelectClose repaint"
    );
    let arena = engine.arena();
    let value = arena
        .get(region.node_id)
        .and_then(|n| n.attributes.get("value"))
        .cloned();
    assert_eq!(
        value.as_deref(),
        Some("b"),
        "chosen option value must be committed"
    );
    assert_eq!(
        eval_str(&mut engine, "String(globalThis.__seen.join(','))"),
        "b",
        "change must fire with the new value"
    );
}

#[test]
fn hovering_a_select_option_moves_the_highlight() {
    // While the dropdown is open, a button-free pointer move over an option
    // row moves the highlight (browser hover) and queues a `SelectMove`.
    let (mut engine, geo) = build_geometry(
        r#"<div><select id="s"><option value="a">Alpha</option><option value="b">Beta</option></select></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("s").expect("select region");
    let (sx, sy) = center(region.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    let open = state.open_select.clone().unwrap();

    let cmds = mouse_move(
        &mut state,
        &mut engine,
        &map,
        open.rect.x as u32,
        open.rect.y as u32 + 1,
    );
    assert_eq!(
        state.open_select.as_ref().unwrap().highlight,
        1,
        "hovering the second row must move the highlight"
    );
    assert!(
        cmds.iter()
            .any(|c| matches!(c, RenderCmd::SelectMove { highlight: 1, .. })),
        "a hover move must queue a SelectMove repaint"
    );

    // Hovering the same row again emits nothing (highlight unchanged).
    let cmds = mouse_move(
        &mut state,
        &mut engine,
        &map,
        open.rect.x as u32,
        open.rect.y as u32 + 1,
    );
    assert!(
        cmds.iter()
            .all(|c| !matches!(c, RenderCmd::SelectMove { .. })),
        "an unchanged highlight must not repaint"
    );
}

#[test]
fn dragging_over_select_options_moves_the_highlight() {
    // The browser's native interaction: press the select, drag over the
    // options (button held) — the highlight must follow the pointer, even on
    // the bottommost option row.
    let (mut engine, geo) = build_geometry(
        r#"<div><select id="s"><option value="a">Alpha</option><option value="b">Beta</option><option value="c">Gamma</option></select></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("s").expect("select region");
    let (sx, sy) = center(region.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    let open = state.open_select.clone().unwrap();

    // Button held while dragging to the bottommost row.
    state.pressed = Some((0, 0));
    let cmds = mouse_move(
        &mut state,
        &mut engine,
        &map,
        open.rect.x as u32,
        open.rect.y as u32 + 2,
    );
    assert_eq!(
        state.open_select.as_ref().unwrap().highlight,
        2,
        "dragging must highlight the bottommost option too"
    );
    assert!(
        cmds.iter()
            .any(|c| matches!(c, RenderCmd::SelectMove { highlight: 2, .. })),
        "drag hover must queue a SelectMove"
    );
}

#[test]
fn clicking_outside_a_select_closes_it_without_changing_the_value() {
    let (mut engine, geo) = build_geometry(
        r#"<div><select id="s" value="a"><option value="a">A</option><option value="b">B</option></select><div id="other">text</div></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("s").expect("select region");
    let (sx, sy) = center(region.rect);

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    assert!(state.open_select.is_some());

    // Click far away (below the document): closes, value untouched.
    mouse_down(&mut state, &mut engine, &map, 0, 1000, MouseButton::Left);
    assert!(state.open_select.is_none());
    let arena = engine.arena();
    let value = arena
        .get(region.node_id)
        .and_then(|n| n.attributes.get("value"))
        .cloned();
    assert_eq!(
        value.as_deref(),
        Some("a"),
        "dismissing must not change the value"
    );
}

// ============================================================
// Flow-selection text extraction (`layout::extract_flow_text`)
// ============================================================

#[test]
fn flow_extraction_joins_wrapped_lines_within_a_block() {
    // A long paragraph wraps across several visual rows; copying the whole
    // block must yield one continuous string — no newline at the wrap points
    // — exactly like a browser. Inline spaces are preserved by the wrap phase
    // (only the hanging space at a break is dropped), so the concatenation
    // restores the original text.
    let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa";
    let (_, geo) = build_geometry(&format!("<div>{text}</div>"), EventBindings::default());
    let lines: Vec<(u32, u32, u32)> = (0..10).map(|y| (y, 0, 200)).collect();
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &lines);
    assert_eq!(copied, text, "wrapped lines of one block must concatenate");
}

#[test]
fn flow_extraction_breaks_between_blocks() {
    // Two sibling blocks: the selection crosses a block boundary, so a
    // newline must be inserted between them.
    let (_, geo) = build_geometry(
        r#"<div>alpha</div><div>beta</div>"#,
        EventBindings::default(),
    );
    let lines = vec![(0u32, 0u32, 200u32), (1u32, 0u32, 200u32)];
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &lines);
    assert_eq!(
        copied, "alpha\nbeta",
        "blocks must be separated by a newline"
    );
}

#[test]
fn flow_extraction_breaks_between_nested_blocks() {
    // Blocks nested inside a container still count as distinct blocks: the
    // paragraphs are separated even though a common ancestor wraps them.
    let (_, geo) = build_geometry(
        r#"<div><p>one</p><p>two</p></div>"#,
        EventBindings::default(),
    );
    // `<p>`'s 1-row UA margins: "one" sits on row 1, "two" on row 3 (the
    // adjacent margins collapse to one blank row between them). Select the
    // whole band; empty margin rows must not leak into the copied text.
    let lines = vec![
        (0u32, 0u32, 200u32),
        (1u32, 0u32, 200u32),
        (2u32, 0u32, 200u32),
        (3u32, 0u32, 200u32),
    ];
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &lines);
    assert_eq!(copied, "one\ntwo");
}

#[test]
fn flow_extraction_slices_selected_columns() {
    // A partial-column selection takes only the covered characters of a line.
    let (_, geo) = build_geometry(r#"<div>alpha</div>"#, EventBindings::default());
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &[(0, 0, 3)]);
    assert_eq!(copied, "alp");
}

#[test]
fn selection_text_lines_clip_to_actual_text() {
    // Full-row bands must be clipped down to the columns the text actually
    // covers, so the highlight never spills over borders / padding / trailing
    // whitespace.
    let (_, geo) = build_geometry(r#"<div>alpha</div>"#, EventBindings::default());
    let lines = htui::layout::selection_text_lines(&geo.arena, &geo.boxes, &[(0, 0, 200)]);
    assert_eq!(
        lines,
        vec![(0, 0, 5)],
        "highlight must stop at the last glyph"
    );
}

#[test]
fn user_select_none_excludes_flow_highlight_and_copy() {
    // CSS `user-select: none` is a document author's selection boundary: the
    // text still renders, but neither highlight bands nor copied flow text may
    // include it.
    let geo = build_styled_geometry(
        "<style>.secret { user-select: none; }</style>\
         <div>one</div><div id=\"secret\" class=\"secret\">secret</div><div>two</div>",
    );
    let lines: Vec<_> = (0..4).map(|row| (row, 0, 200)).collect();
    assert_eq!(
        htui::layout::selection_text_lines(&geo.arena, &geo.boxes, &lines),
        vec![(0, 0, 3), (2, 0, 3)],
        "user-select:none must produce no highlight bands"
    );
    assert_eq!(
        htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &lines),
        "one\ntwo",
        "user-select:none must not leak into copied text"
    );
}

#[test]
fn user_select_none_blocks_a_left_drag_selection_start() {
    let html = "<style>.secret { user-select: none; }</style>\
                <div id=\"secret\" class=\"secret\">secret</div><div id=\"next\">other</div>";
    let geo = build_styled_geometry(html);
    let map = HitMap::build(&geo);
    let secret = map.resolve_by_id("secret").cloned().expect("secret region");
    let (sx, sy) = center(secret.rect);
    let mut engine = ScriptEngine::new(html, "", EventBindings::default()).expect("engine");

    let mut state = InputState::new();
    mouse_down(&mut state, &mut engine, &map, sx, sy, MouseButton::Left);
    state.pressed = Some((sx as u16, sy as u16));
    let cmds = mouse_move(&mut state, &mut engine, &map, sx + 3, sy);

    assert!(
        !cmds
            .iter()
            .any(|c| matches!(c, RenderCmd::TextSelection { .. })),
        "a drag starting on user-select:none must not queue TextSelection"
    );
    assert_eq!(state.text_sel_anchor, None);
    assert_eq!(state.text_sel_end, None);
}

#[test]
fn flow_extraction_omits_replaced_control_text() {
    // A left-drag flow selection copies document text. Control values and
    // button labels belong to their own interaction/copy paths, so crossing a
    // `<button>` must not inject its label into the page-selection clipboard.
    let (_, geo) = build_geometry(
        "<div>before</div><button>Save</button><div>after</div>",
        EventBindings::default(),
    );
    let lines: Vec<_> = (0..6).map(|row| (row, 0, 200)).collect();
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &lines);
    assert_eq!(copied, "before\nafter");
    assert!(
        !copied.contains("Save"),
        "button labels must not leak into flow selection text"
    );
}

#[test]
fn selection_text_lines_keep_partial_columns() {
    // A selection that starts inside the text keeps the intersection, and a
    // band past the text yields nothing.
    let (_, geo) = build_geometry(r#"<div>alpha</div>"#, EventBindings::default());
    let lines = htui::layout::selection_text_lines(&geo.arena, &geo.boxes, &[(0, 2, 200)]);
    assert_eq!(lines, vec![(0, 2, 5)]);
    let past = htui::layout::selection_text_lines(&geo.arena, &geo.boxes, &[(0, 10, 200)]);
    assert!(
        past.is_empty(),
        "a band past the text must highlight nothing"
    );
}

#[test]
fn flow_copy_stays_inside_the_dragged_column() {
    // Side-by-side flex columns share canvas rows. The raw flow bands are
    // full-canvas-width for every row between the anchor and the end, so a
    // straight vertical drag inside the right column would collect the left
    // column's text on the same rows. The bands must be clipped to the drag's
    // common block (the right column) before highlighting and copying.
    let geo = build_styled_geometry(
        "<style>.wrap { display: flex; } .col { width: 20ch; }</style>\
         <div class=\"wrap\">\
         <div class=\"col\"><div>left-a</div><div>left-b</div></div>\
         <div class=\"col\"><div id=\"r1\">right-a</div><div id=\"r2\">right-b</div>\
         <div id=\"r3\">right-c</div></div></div>",
    );
    let map = HitMap::build(&geo);
    let r1 = map.resolve_by_id("r1").cloned().expect("right row 1");
    let r3 = map.resolve_by_id("r3").cloned().expect("right row 3");
    // Anchor on the first row's first character, end past the last row's
    // text — a straight vertical drag with the column-wide sweep.
    let anchor = (r1.rect.x as u32, r1.rect.y as u32);
    let end = (r3.rect.x as u32 + 6, r3.rect.y as u32);

    // Raw bands exactly as `selection_lines` builds them for a downward drag:
    // the anchor row from the anchor column, full-width middle rows, the end
    // row up to the end column.
    let (ay, ey) = (anchor.1, end.1);
    assert!(ey > ay + 1, "the fixture needs a full-width middle row");
    let mut raw = vec![(ay, anchor.0, 200u32)];
    for y in ay + 1..ey {
        raw.push((y, 0, 200));
    }
    raw.push((ey, 0, end.0 + 1));

    let unscoped = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &raw);
    assert!(
        unscoped.contains("left-b"),
        "fixture hazard: the full-width middle band must cover the left column"
    );

    let scoped = htui::layout::clip_flow_lines_scoped(&geo.boxes, anchor, end, &raw);
    let copied = htui::layout::extract_flow_text(&geo.arena, &geo.boxes, &scoped);
    assert_eq!(
        copied, "right-a\nright-b\nright-c",
        "a vertical drag in one column must not copy the neighbouring column"
    );
    let highlighted = htui::layout::selection_text_lines(&geo.arena, &geo.boxes, &scoped);
    assert!(
        highlighted.iter().all(|&(_, cs, _)| cs >= r1.rect.x as u32),
        "the highlight must stay inside the dragged column: {highlighted:?}"
    );
}

#[test]
fn command_macro_exposes_rust_functions_to_js() {
    let mut bindings = EventBindings::default();
    bindings.command("greet", greet_command());
    bindings.command("divide", divide_command());
    bindings.command("clamp", clamp_command());

    let mut engine = ScriptEngine::new(
        r#"
        <script>
          var g = greet("Ada", 3);
          globalThis.__greetName = g.name;
          globalThis.__greetLoud = g.loudName;
          globalThis.__greetTimes = g.times;
          try {
            globalThis.__bad = divide(1, 0);
          } catch (e) {
            globalThis.__bad = 'threw: ' + e.message;
          }
          globalThis.__good = divide(10, 4);
          globalThis.__clamped = clamp(95, { maxCpu: 80, label: "cpu" });
          globalThis.__clamped2 = clamp(95, { maxCpu: 99, label: "cpu" });
          try {
            globalThis.__badClamp = clamp(95, { maxCpu: -1, label: "cpu" });
          } catch (e) {
            globalThis.__badClamp = 'threw: ' + e.message;
          }
        </script>
        <p>ok</p>
        "#,
        "",
        bindings,
    )
    .expect("engine");

    assert_eq!(
        eval_str(&mut engine, "globalThis.__greetName"),
        "Ada",
        "struct field must map to the JS property"
    );
    assert_eq!(
        eval_str(&mut engine, "globalThis.__greetLoud"),
        "Ada!!",
        "#[js_name] must rename the property"
    );
    assert_eq!(eval_str(&mut engine, "globalThis.__greetTimes"), "3");
    assert_eq!(
        eval_str(&mut engine, "globalThis.__bad"),
        "threw: division by zero",
        "Result::Err must throw a catchable JS error"
    );
    assert_eq!(eval_str(&mut engine, "globalThis.__good"), "2.5");
    assert_eq!(
        eval_str(&mut engine, "globalThis.__clamped"),
        "80",
        "#[derive(FromJs)] must read a struct arg, #[js_name] maps maxCpu → max_cpu"
    );
    assert_eq!(
        eval_str(&mut engine, "globalThis.__clamped2"),
        "95",
        "struct arg with a value below the clamp must pass through"
    );
    assert_eq!(
        eval_str(&mut engine, "globalThis.__badClamp"),
        "threw: cpu: maxCpu must be positive",
        "command Err must throw a catchable JS error"
    );
}

/// Evaluate `String(<expr>)` and return the stringified result.
fn eval_str(engine: &mut ScriptEngine, expr: &str) -> String {
    let v = engine
        .eval_source(&format!("String({expr})"))
        .expect("eval must succeed");
    v.as_string()
        .map(|s| s.to_std_string_lossy())
        .unwrap_or_default()
}

const COLS: u16 = 80;
const ROWS: u16 = 24;

fn setup(html: &str) -> (NodeId, NodeArena) {
    let mut parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = parser.parse();
    if !embedded.trim().is_empty() {
        let mut css_parser = css_parse::Parser::new(&embedded);
        let rules = css_parser.parse();
        css_parse::css_into_node(&mut arena, root_id, &rules);
    }
    (root_id, arena)
}

/// Build the engine + geometry for a document.
///
/// Mirrors the runtime path: the engine owns the live arena (scripts run at
/// construction), and the hit map is built from that arena's layout.
fn build_geometry(html: &str, bindings: EventBindings) -> (ScriptEngine, Geometry) {
    let engine = ScriptEngine::new(html, "", bindings).expect("engine initializes");
    let arena = engine.arena();
    let root_id = engine.root_id();
    let term_map = TermMap {
        columns: COLS,
        rows: ROWS,
    };
    let containing = BoxConstraint::root(&term_map);
    let mut cursor = Cursor::new();
    let boxes = layout_tree(
        &arena,
        root_id,
        containing,
        &mut cursor,
        term_map.columns as usize,
        term_map.rows as usize,
    );
    let geo = Geometry {
        arena: Arc::new(arena),
        boxes,
        root_id,
    };
    (engine, geo)
}

/// Geometry for a document with its `<style>` CSS cascaded — the styled
/// counterpart of `build_geometry` (`ScriptEngine::new` returns a raw
/// uncascaded arena, so inline-only or `<style>` styling needs this path).
fn build_styled_geometry(html: &str) -> Geometry {
    let mut parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = parser.parse();
    if !embedded.trim().is_empty() {
        let mut css_parser = CssParser::new(&embedded);
        let rules = css_parser.parse();
        css_into_node(&mut arena, root_id, &rules);
    }
    let term_map = TermMap {
        columns: COLS,
        rows: ROWS,
    };
    let containing = BoxConstraint::root(&term_map);
    let mut cursor = Cursor::new();
    let boxes = layout_tree(
        &arena,
        root_id,
        containing,
        &mut cursor,
        term_map.columns as usize,
        term_map.rows as usize,
    );
    Geometry {
        arena: Arc::new(arena),
        boxes,
        root_id,
    }
}

/// `NodeId` of the element whose `id` attribute equals `id`.
fn find_node_by_id(arena: &NodeArena, id: &str) -> NodeId {
    arena
        .iter()
        .find(|(_, n)| n.attributes.get("id").map(String::as_str) == Some(id))
        .map(|(nid, _)| nid)
        .expect("element with id exists")
}

/// Depth-first search for the first box belonging to `node_id`.
fn find_box(
    boxes: &[htui::layout::LayoutBox],
    node_id: NodeId,
) -> Option<&htui::layout::LayoutBox> {
    for b in boxes {
        if b.node_id == node_id {
            return Some(b);
        }
        if let Some(found) = find_box(&b.children, node_id) {
            return Some(found);
        }
    }
    None
}

/// A canvas point inside `rect` (its centre).
fn center(rect: Rect) -> (u32, u32) {
    (
        rect.x as u32 + rect.width.max(1) as u32 / 2,
        rect.y as u32 + rect.height.max(1) as u32 / 2,
    )
}

/// Build bindings with a single host function.
fn host_bindings(
    name: &str,
    mut f: impl FnMut(&mut htui::script::HostCtx) -> JsValue + Send + 'static,
) -> EventBindings {
    let mut bindings = EventBindings::default();
    bindings
        .host
        .insert(name.to_string(), Box::new(move |call| Ok(f(call))));
    bindings
}

/// A host function that increments a shared counter and returns `undefined`.
fn counting_host(counter: Arc<Mutex<usize>>) -> EventBindings {
    host_bindings("tick", move |_| {
        *counter.lock().unwrap() += 1;
        JsValue::undefined()
    })
}

/// Minimal hit region for `node_id` (no geometry) to fire non-pointer events
/// (focus / blur / input / change) along the DOM ancestor chain.
fn region_of(arena: &NodeArena, node_id: NodeId) -> HitRegion {
    let mut path = Vec::new();
    let mut current = Some(node_id);
    while let Some(id) = current {
        let node = &arena[id];
        path.push(ElementRef {
            id: node.get_id().cloned(),
            node_id: id,
        });
        current = node.parent;
    }
    HitRegion {
        node_id,
        rect: Rect::new(0, 0, 0, 0),
        client: Rect::new(0, 0, 0, 0),
        path: path.into(),
    }
}

// ============================================================
// Input-loop drivers (test-side script thread)
// ============================================================

/// Drive the collected script messages against a real engine — the test-side
/// counterpart of the production script thread — and fold the replies into
/// the returned commands (hover updates + host-pushed cmds + dirty snapshots).
fn drive_msgs(
    state: &mut InputState,
    engine: &mut ScriptEngine,
    map: &HitMap,
    msgs: Vec<ScriptMsg>,
) -> Vec<RenderCmd> {
    let mut cmds = Vec::new();
    let mut hover = HoverState::new();
    for msg in msgs {
        let ev = apply_message(engine, &mut hover, map, msg);
        cmds.extend(ev.cmds);
        if let Some(d) = ev.dirty {
            cmds.push(RenderCmd::RenderArena {
                arena: d.arena,
                root_id: d.root_id,
                scroll_y: state.scroll_y,
                zoom: state.zoom,
                dynamic: DynamicState {
                    hovered: ev.hovered,
                    ..Default::default()
                },
                dirty: d.dirty,
            });
        }
    }
    cmds
}

/// Click at canvas coordinates, executing the queued messages like the script
/// thread would.
fn click(
    state: &mut InputState,
    engine: &mut ScriptEngine,
    map: &HitMap,
    x: u32,
    y: u32,
) -> Vec<RenderCmd> {
    let arena = engine.arena();
    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_click(state, map, &arena, x, y, &mut msgs, &mut cmds);
    cmds.extend(drive_msgs(state, engine, map, msgs));
    cmds
}

/// Mouse-down at canvas coordinates, executing the queued messages like the
/// script thread would.
fn mouse_down(
    state: &mut InputState,
    engine: &mut ScriptEngine,
    map: &HitMap,
    x: u32,
    y: u32,
    button: MouseButton,
) -> Vec<RenderCmd> {
    let arena = engine.arena();
    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_mouse_down(state, map, &arena, x, y, button, &mut msgs, &mut cmds);
    cmds.extend(drive_msgs(state, engine, map, msgs));
    cmds
}

/// Pointer move at canvas coordinates, executing the queued messages like the
/// script thread would.
fn mouse_move(
    state: &mut InputState,
    engine: &mut ScriptEngine,
    map: &HitMap,
    x: u32,
    y: u32,
) -> Vec<RenderCmd> {
    let arena = engine.arena();
    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_mouse_move(state, map, &arena, x, y, &mut msgs, &mut cmds);
    cmds.extend(drive_msgs(state, engine, map, msgs));
    cmds
}

/// Left mouse-up at screen coordinates, executing the queued messages like
/// the script thread would.
fn mouse_up(
    state: &mut InputState,
    engine: &mut ScriptEngine,
    map: &HitMap,
    sx: u16,
    sy: u16,
) -> Vec<RenderCmd> {
    let arena = engine.arena();
    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_mouse_up(
        state,
        map,
        &arena,
        (sx, sy),
        MouseButton::Left,
        &mut msgs,
        &mut cmds,
    );
    cmds.extend(drive_msgs(state, engine, map, msgs));
    cmds
}

// ============================================================
// Hit regions
// ============================================================

#[test]
fn every_element_becomes_a_hit_region() {
    let (_, geo) = build_geometry(
        r#"<div id="outer"><p id="inner">inner</p><p>plain</p></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    // Elements without listeners are regions too, so CSS `:hover` rules can
    // target any element.
    assert!(
        map.iter().any(|r| r.id().is_none()),
        "id-less elements must be regions"
    );
    assert!(map.resolve_by_id("outer").is_some());
    assert!(map.resolve_by_id("inner").is_some());
    assert!(map.resolve_by_id("missing").is_none());
}

#[test]
fn hit_test_prefers_the_deepest_element() {
    let (_, geo) = build_geometry(
        r#"<div id="outer"><div id="inner" style="width: 10ch">inner</div></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let inner_rect = map.resolve_by_id("inner").expect("inner region").rect;

    // The centre of the inner element resolves to the inner element (deepest),
    // not its ancestor.
    let (x, y) = center(inner_rect);
    assert_eq!(
        map.hit_test(x, y).expect("inner cell must hit").id(),
        Some("inner")
    );
    // A point outside every element hits nothing.
    assert!(map.hit_test(0, 1000).is_none());
}

#[test]
fn hit_test_resolves_overlaps_by_paint_order() {
    // Browser rule: the hit target is the element painted on top. A
    // positioned box earlier in the DOM paints above the static content
    // beneath it, so it — not the later static sibling — wins the overlap
    // (the previous smallest-area rule could pick either).
    let geo = build_styled_geometry(
        r#"<style>
            #overlay { position: absolute; top: 0ch; left: 0ch; width: 10ch; height: 2ch; }
            #static { width: 10ch; }
        </style>
        <div id="overlay">ov</div><div id="static">static text</div>"#,
    );
    let map = HitMap::build(&geo);
    let overlay = map.resolve_by_id("overlay").expect("overlay region").rect;
    let stat = map.resolve_by_id("static").expect("static region").rect;
    // The fixture must actually overlap; otherwise the test proves nothing.
    let (x, y) = (overlay.x.max(stat.x), overlay.y.max(stat.y));
    assert!(
        overlay.contains(x as u32, y as u32) && stat.contains(x as u32, y as u32),
        "fixture boxes must overlap: overlay={overlay:?} static={stat:?}"
    );
    assert_eq!(
        map.hit_test(x as u32, y as u32)
            .expect("overlap must hit")
            .id(),
        Some("overlay"),
        "the positioned box painted above the static content must win"
    );
}

#[test]
fn hit_test_orders_overlaps_by_z_index() {
    // Higher z-index paints on top even when it comes first in the DOM —
    // the previous smallest-area rule would have picked the later sibling
    // on an area tie.
    let geo = build_styled_geometry(
        r#"<style>
            #high { position: absolute; top: 0ch; left: 0ch; width: 10ch; height: 2ch; z-index: 2; }
            #low { position: absolute; top: 0ch; left: 0ch; width: 10ch; height: 2ch; z-index: 1; }
        </style>
        <div id="high">h</div><div id="low">l</div>"#,
    );
    let map = HitMap::build(&geo);
    let high = map.resolve_by_id("high").expect("high region").rect;
    let low = map.resolve_by_id("low").expect("low region").rect;
    let (x, y) = (high.x.max(low.x), high.y.max(low.y));
    assert!(
        high.contains(x as u32, y as u32) && low.contains(x as u32, y as u32),
        "fixture boxes must overlap: high={high:?} low={low:?}"
    );
    assert_eq!(
        map.hit_test(x as u32, y as u32)
            .expect("overlap must hit")
            .id(),
        Some("high"),
        "the higher z-index box must win the overlap"
    );
}

#[test]
fn click_on_empty_space_dispatches_nothing() {
    let (mut engine, geo) =
        build_geometry(r#"<div id="btn">click me</div>"#, EventBindings::default());
    let map = HitMap::build(&geo);
    let mut hover = HoverState::new();
    // Below the document: no region, no event, no commands.
    let cmds = on_click(&mut hover, &map, &mut engine, 0, 1000);
    assert!(cmds.is_empty());
    assert!(hover.current().is_none());
}

// ============================================================
// Attribute handlers (`on*` compiled to `function (event) { … }`)
// ============================================================

#[test]
fn click_dispatches_the_matching_listener() {
    // The attribute handler compiles to `function (event) { go() }`; `go`
    // resolves to the registered host function.
    let (mut engine, geo) = build_geometry(
        r#"<div id="btn" onclick="go()">click me</div>"#,
        host_bindings("go", |_| JsValue::undefined()),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("btn").expect("region");
    let (x, y) = center(region.rect);

    let mut hover = HoverState::new();
    let cmds = on_click(&mut hover, &map, &mut engine, x, y);
    // The click fires `go` and returns no render command, but hover sync emits
    // a Hover command.
    assert!(cmds.iter().any(|c| matches!(c, RenderCmd::Hover { .. })));
}

#[test]
fn bare_identifier_never_invokes_like_the_browser() {
    // `onclick="go"` compiles to `function (event) { go }`: the identifier
    // resolves but is never called.
    let seen = Arc::new(Mutex::new(0usize));
    let seen2 = Arc::clone(&seen);
    let (mut engine, geo) = build_geometry(
        r#"<div id="btn" onclick="go">click me</div>"#,
        host_bindings("go", move |_| {
            *seen2.lock().unwrap() += 1;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("btn").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    on_click(&mut hover, &map, &mut engine, x, y);
    assert_eq!(*seen.lock().unwrap(), 0);
}

#[test]
fn click_bubbles_to_an_interactive_ancestor() {
    // Child has no listener, so the click bubbles up to the ancestor's `onclick`.
    let seen = Arc::new(Mutex::new(0usize));
    let seen2 = Arc::clone(&seen);
    let (mut engine, geo) = build_geometry(
        r#"<div id="wrap" onclick="buy()"><p id="child">text</p></div>"#,
        host_bindings("buy", move |_| {
            *seen2.lock().unwrap() += 1;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("child").expect("child region");
    let (x, y) = center(region.rect);

    let mut hover = HoverState::new();
    on_click(&mut hover, &map, &mut engine, x, y);
    assert_eq!(*seen.lock().unwrap(), 1);
}

// ============================================================
// addEventListener + DOM mutation
// ============================================================

#[test]
fn add_event_listener_registers_a_js_listener() {
    // A `<script>` registers a click listener; clicking the button runs the
    // JS function which calls back into a host function.
    let seen = Arc::new(Mutex::new(0usize));
    let seen2 = Arc::clone(&seen);
    let html = r#"
      <script>
        document.getElementById('btn').addEventListener('click', function () { tick(); });
      </script>
      <div id="btn">click me</div>
    "#;
    let (mut engine, geo) = build_geometry(html, counting_host(seen2));
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("btn").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    on_click(&mut hover, &map, &mut engine, x, y);
    assert_eq!(*seen.lock().unwrap(), 1);
}

#[test]
fn add_event_listener_is_idempotent_for_identical_listener() {
    // Browser semantics: re-registering the same (type, callback) pair is a
    // no-op — the listener must fire once per event, not once per add call.
    let seen = Arc::new(Mutex::new(0usize));
    let seen2 = Arc::clone(&seen);
    let html = r#"
      <script>
        var h = function () { tick(); };
        var btn = document.getElementById('btn');
        btn.addEventListener('click', h);
        btn.addEventListener('click', h);
      </script>
      <div id="btn">click me</div>
    "#;
    let (mut engine, geo) = build_geometry(html, counting_host(seen2));
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("btn").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    on_click(&mut hover, &map, &mut engine, x, y);
    assert_eq!(*seen.lock().unwrap(), 1);
}

#[test]
fn remove_child_drops_listeners_of_the_detached_subtree() {
    // A node leaving the document must not retain its listeners in the
    // GC-rooted registry — otherwise removeChild churn grows the registry
    // (and every closure the listeners captured) without bound.
    let html = r#"
      <script>
        var wrap = document.getElementById('wrap');
        wrap.addEventListener('click', function () {});
        document.getElementById('btn').addEventListener('click', function () {});
        document.body.removeChild(wrap);
      </script>
      <div id="wrap"><div id="btn">b</div></div>
    "#;
    let mut engine = ScriptEngine::new(html, "", EventBindings::default()).expect("engine");
    assert_eq!(
        eval_str(
            &mut engine,
            "Object.keys(globalThis.__htuiListeners).length"
        ),
        "0",
        "the removed node and its subtree must leave no listener entries"
    );
}

#[test]
fn replace_child_drops_listeners_of_the_replaced_subtree() {
    let html = r#"
      <script>
        var wrap = document.getElementById('wrap');
        wrap.addEventListener('click', function () {});
        document.getElementById('btn').addEventListener('click', function () {});
        document.body.replaceChild(document.createElement('div'), wrap);
      </script>
      <div id="wrap"><div id="btn">b</div></div>
    "#;
    let mut engine = ScriptEngine::new(html, "", EventBindings::default()).expect("engine");
    assert_eq!(
        eval_str(
            &mut engine,
            "Object.keys(globalThis.__htuiListeners).length"
        ),
        "0",
        "the replaced node and its subtree must leave no listener entries"
    );
}

#[test]
fn removing_a_sibling_keeps_the_survivor_listener() {
    // Clearing is scoped to the detached subtree: a listener on a node that
    // stays in the document must survive a sibling's removal.
    let html = r#"
      <script>
        document.getElementById('live').addEventListener('click', function () {});
        document.body.removeChild(document.getElementById('gone'));
      </script>
      <div id="gone">g</div>
      <div id="live">l</div>
    "#;
    let mut engine = ScriptEngine::new(html, "", EventBindings::default()).expect("engine");
    assert_eq!(
        eval_str(
            &mut engine,
            "Object.keys(globalThis.__htuiListeners).length"
        ),
        "1",
        "only the removed node's entry must be cleared"
    );
}

#[test]
fn js_can_mutate_the_dom_and_marks_dirty() {
    let html = r#"
      <script>
        document.getElementById('out').textContent = 'hello world';
      </script>
      <p id="out">before</p>
    "#;
    let mut engine = ScriptEngine::new(html, "", EventBindings::default()).expect("engine");
    assert!(
        !engine.take_dirty().is_empty(),
        "script textContent mutation must mark dirty"
    );
    let arena = engine.arena();
    let node = find_node_by_id(&arena, "out");
    let text: String = arena[node]
        .children
        .iter()
        .filter_map(|&c| match &arena[c].node_type {
            htui::tdom::node::NodeType::Text => arena[c].data.as_deref(),
            _ => None,
        })
        .collect();
    assert_eq!(text, "hello world");
}

#[test]
fn stop_propagation_stops_the_ancestor_listener() {
    // Child stops propagation, so the ancestor listener never fires.
    let hits: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let hits2 = Arc::clone(&hits);
    let html = r#"
      <script>
        document.getElementById('child')
          .addEventListener('click', function (e) { report('child'); e.stopPropagation(); });
        document.getElementById('wrap')
          .addEventListener('click', function () { report('wrap'); });
      </script>
      <div id="wrap"><p id="child">text</p></div>
    "#;
    let (mut engine, geo) = build_geometry(
        html,
        host_bindings("report", move |call| {
            if let Some(s) = call.arg::<String>(0).ok().flatten() {
                hits2.lock().unwrap().push(s);
            }
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("child").expect("child region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    on_click(&mut hover, &map, &mut engine, x, y);

    assert_eq!(*hits.lock().unwrap(), vec!["child".to_string()]);
}

// ============================================================
// Hover
// ============================================================

#[test]
fn hover_emits_restyle_command_on_enter_and_leave() {
    let (mut engine, geo) = build_geometry(
        r#"<div id="a">a</div><div id="b">b</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let a_region = map.resolve_by_id("a").expect("a region");
    let b_region = map.resolve_by_id("b").expect("b region");
    let (ax, ay) = center(a_region.rect);
    let (bx, by) = center(b_region.rect);

    let mut hover = HoverState::new();
    let cmds1 = on_move(&mut hover, &map, &mut engine, ax, ay);
    assert!(cmds1.iter().any(|c| matches!(
        c,
        RenderCmd::Hover { node_id: Some(n) } if *n == a_region.node_id
    )));
    let cmds2 = on_move(&mut hover, &map, &mut engine, bx, by);
    // Leaving a must fire mouseout + hover with b's node.
    assert!(cmds2.iter().any(|c| matches!(
        c,
        RenderCmd::Hover { node_id: Some(n) } if *n == b_region.node_id
    )));
}

#[test]
fn hover_fires_mouseover_and_mouseout_listeners() {
    let hits: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let hits2 = Arc::clone(&hits);
    let html = r#"
      <script>
        document.getElementById('a')
          .addEventListener('mouseover', function () { report('enter'); });
        document.getElementById('a')
          .addEventListener('mouseout', function () { report('leave'); });
      </script>
      <div id="a">a</div>
    "#;
    let (mut engine, geo) = build_geometry(
        html,
        host_bindings("report", move |call| {
            if let Some(s) = call.arg::<String>(0).ok().flatten() {
                hits2.lock().unwrap().push(s);
            }
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("a").expect("a region");
    let (x, y) = center(region.rect);

    let mut hover = HoverState::new();
    on_move(&mut hover, &map, &mut engine, x, y); // enter
    // Move far away to leave.
    on_move(&mut hover, &map, &mut engine, 0, 1000);

    assert_eq!(
        *hits.lock().unwrap(),
        vec!["enter".to_string(), "leave".to_string()]
    );
}

// ============================================================
// Viewport change (terminal resize) resilience
// ============================================================

/// Re-lay-out the engine's live arena at `(columns, rows)` — the test-side
/// counterpart of the render thread re-laying out after a terminal resize.
/// The arena clone keeps the same node ids, exactly like the runtime's
/// `RenderArena` path, so listeners / hover tracking survive the reflow.
fn relayout(engine: &ScriptEngine, columns: u16, rows: u16) -> Geometry {
    let arena = engine.arena();
    let root_id = engine.root_id();
    let term_map = TermMap { columns, rows };
    let containing = BoxConstraint::root(&term_map);
    let mut cursor = Cursor::new();
    let boxes = layout_tree(
        &arena,
        root_id,
        containing,
        &mut cursor,
        term_map.columns as usize,
        term_map.rows as usize,
    );
    Geometry {
        arena: Arc::new(arena),
        boxes,
        root_id,
    }
}

#[test]
fn resize_relayout_keeps_node_ids_and_events_fire() {
    let hits: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let hits2 = Arc::clone(&hits);
    let html = r#"
      <script>
        document.getElementById('btn')
          .addEventListener('click', function () { report('click'); });
        document.getElementById('btn')
          .addEventListener('mouseover', function () { report('over'); });
      </script>
      <div id="btn" style="padding: 1ch 10ch;">button</div>
    "#;
    let (mut engine, geo) = build_geometry(
        html,
        host_bindings("report", move |call| {
            if let Some(s) = call.arg::<String>(0).ok().flatten() {
                hits2.lock().unwrap().push(s);
            }
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("btn").expect("btn region");
    let (x, y) = center(region.rect);

    let mut hover = HoverState::new();
    on_move(&mut hover, &map, &mut engine, x, y);
    assert_eq!(*hits.lock().unwrap(), vec!["over".to_string()]);

    // A terminal resize re-lays-out the same live arena and rebuilds the hit
    // map. Node ids are slotmap keys and survive the arena clone, so the
    // listeners and hover tracking keep working against the fresh geometry.
    let geo2 = relayout(&engine, 40, 10);
    let map2 = HitMap::build(&geo2);
    let region2 = map2.resolve_by_id("btn").expect("btn survives resize");
    let (x2, y2) = center(region2.rect);
    on_click(&mut hover, &map2, &mut engine, x2, y2);

    assert_eq!(
        *hits.lock().unwrap(),
        vec!["over".to_string(), "click".to_string()]
    );
}

#[test]
fn resize_reflow_revalidates_hover_under_the_stationary_pointer() {
    let hits: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let hits2 = Arc::clone(&hits);
    let html = r#"
      <script>
        document.getElementById('a')
          .addEventListener('mouseover', function () { report('over-a'); });
        document.getElementById('a')
          .addEventListener('mouseout', function () { report('out-a'); });
        document.getElementById('b')
          .addEventListener('mouseover', function () { report('over-b'); });
        document.getElementById('b')
          .addEventListener('mouseout', function () { report('out-b'); });
      </script>
      <div id="a" style="padding: 1ch;">AAAA AAAA AAAA AAAA AAAA AAAA AAAA AAAA AAAA AAAA AAAA AAAA</div>
      <div id="b" style="padding: 1ch;">bbbb</div>
    "#;
    let (mut engine, geo) = build_geometry(
        html,
        host_bindings("report", move |call| {
            if let Some(s) = call.arg::<String>(0).ok().flatten() {
                hits2.lock().unwrap().push(s);
            }
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let b_region = map.resolve_by_id("b").expect("b region");
    let (bx, by) = center(b_region.rect);

    let mut hover = HoverState::new();
    on_move(&mut hover, &map, &mut engine, bx, by); // enter b
    assert_eq!(*hits.lock().unwrap(), vec!["over-b".to_string()]);

    // Narrow reflow: `a` wraps taller and pushes `b` down, so the cell under
    // the stationary pointer now belongs to `a`. The synthetic `Move` the run
    // loop queues after a resize (once the rebuilt hit map is published)
    // re-validates hover: b must receive `mouseout`, a `mouseover`.
    let geo2 = relayout(&engine, 20, 24);
    let map2 = HitMap::build(&geo2);
    // `b`'s top row in the wide layout falls inside the (taller) `a` once the
    // text wraps; assert the reflow actually moved b away from that cell.
    let px = 10;
    let py = b_region.rect.y as u32 + 1;
    let under = map2.hit_test(px, py).expect("cell under pointer");
    assert_ne!(
        under.node_id, b_region.node_id,
        "the narrow reflow must push b below the stationary pointer"
    );

    on_move(&mut hover, &map2, &mut engine, px, py);

    assert_eq!(
        *hits.lock().unwrap(),
        vec![
            "over-b".to_string(),
            "out-b".to_string(),
            "over-a".to_string()
        ]
    );
}

#[test]
fn stale_press_from_lost_release_does_not_kill_hover() {
    // Simulate a resize that dropped the button release: `pressed` stays set
    // (the console delivered the `Down` but lost the `Up`). The input loop
    // clears it on the next button-free `Moved` event, so hover tracking
    // (`ScriptMsg::Move`) resumes instead of every move being read as a drag.
    let (engine, geo) = build_geometry("<div id='a'>a</div>", EventBindings::default());
    let map = HitMap::build(&geo);
    let arena = engine.arena();
    let region = map.resolve_by_id("a").expect("a region");
    let (x, y) = center(region.rect);
    let mut state = InputState::new();
    state.pressed = Some((x as u16, y as u16));
    state.drag_selecting = true;

    assert!(state.drop_stale_press(), "stale press must be dropped");
    assert!(state.pressed.is_none());
    assert!(!state.drag_selecting);

    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_mouse_move(&mut state, &map, &arena, x, y, &mut msgs, &mut cmds);
    assert!(
        msgs.iter().any(|m| matches!(m, ScriptMsg::Move { .. })),
        "hover tracking must resume after a stale press is cleared"
    );
}

// ============================================================
// invoke_action (manual JS global invocation)
// ============================================================

#[test]
fn invoke_action_calls_a_js_global_function() {
    let sampled: Arc<Mutex<f64>> = Arc::new(Mutex::new(0.0));
    let sampled2 = Arc::clone(&sampled);
    let html = r#"
      <script>
        function refresh() { report(42); }
      </script>
      <p>monitor</p>
    "#;
    let mut engine = ScriptEngine::new(
        html,
        "",
        host_bindings("report", move |call| {
            if let Some(n) = call.arg::<f64>(0).ok().flatten() {
                *sampled2.lock().unwrap() = n;
            }
            JsValue::undefined()
        }),
    )
    .expect("engine");
    engine.invoke_action("refresh");
    assert_eq!(*sampled.lock().unwrap(), 42.0);
}

#[test]
fn unknown_action_is_ignored_without_error() {
    let mut engine = ScriptEngine::new("<p>x</p>", "", EventBindings::default()).expect("engine");
    // Must not panic, must not produce render commands.
    assert!(engine.invoke_action("nope").is_empty());
}

#[test]
fn refresh_pipeline_updates_the_dom() {
    // Full demo pipeline: JS `refresh()` calls the host `sample()` (returns a
    // JS object) and writes textContent into the DOM, marking the engine dirty
    // so the input loop would emit `RenderArena`.
    let html = r#"
      <script>
        function refresh() {
          var d = sample();
          document.getElementById('cpu').textContent = d.cpu;
        }
      </script>
      <p id="cpu">n/a</p>
    "#;
    let mut bindings = EventBindings::default();
    bindings.host.insert(
        "sample".to_string(),
        htui::script::host_fn(|ctx| {
            let mut obj = ctx.object();
            obj.set("cpu", "23%");
            Ok(obj)
        }),
    );
    let mut engine = ScriptEngine::new(html, "", bindings).expect("engine");

    // Before refresh: initial script didn't call sample, so cpu is untouched.
    assert!(engine.take_dirty().is_empty());
    engine.invoke_action("refresh");
    assert!(
        !engine.take_dirty().is_empty(),
        "refresh must mark the DOM dirty"
    );

    let arena = engine.arena();
    let cpu = find_node_by_id(&arena, "cpu");
    let text: String = arena[cpu]
        .children
        .iter()
        .filter_map(|&c| match &arena[c].node_type {
            htui::tdom::node::NodeType::Text => arena[c].data.as_deref(),
            _ => None,
        })
        .collect();
    assert_eq!(text, "23%");
}

#[test]
fn refresh_renders_the_progress_bar() {
    // End-to-end over the interactive path: JS `refresh()` calls the host
    // `sample()` and writes a progress-bar string into `<p id=cpu>`, then the
    // engine's arena is laid out the way the render thread does it. The bar
    // glyphs (fill + track) must appear in the canvas.
    let html = r#"
      <script>
        function refresh() {
          var d = sample();
          document.getElementById('cpu').textContent = d.cpu;
        }
      </script>
      <p id="cpu">n/a</p>
    "#;
    let mut bindings = EventBindings::default();
    bindings.host.insert(
        "sample".to_string(),
        htui::script::host_fn(|ctx| {
            let mut obj = ctx.object();
            obj.set("cpu", "[########--------] 45%");
            Ok(obj)
        }),
    );
    let mut engine = ScriptEngine::new(html, "", bindings).expect("engine");
    engine.invoke_action("refresh");
    assert!(
        !engine.take_dirty().is_empty(),
        "refresh must mark the DOM dirty"
    );

    let arena = engine.arena();
    let root_id = engine.root_id();
    let map = TermMap {
        columns: COLS,
        rows: ROWS,
    };
    let mut tl = htui::tui::graph_api::TermLayout::new(&map, 1.0);
    tl.draw(&arena, root_id, &map);
    let frame = tl.render_to_bytes();
    let text = String::from_utf8_lossy(&frame);
    assert!(text.contains("#"), "progress-bar fill must render");
    assert!(text.contains("-"), "progress-bar track must render");
    assert!(text.contains("45%"), "percentage must render");
}

// ============================================================
// CSS `:hover` (unchanged side-channel behaviour)
// ============================================================

#[test]
fn hover_pseudo_class_parses() {
    let mut css_parser = CssParser::new("#panel:hover { background-color: #3a3a3a; }");
    let rules = css_parser.parse();
    let entry = rules.0.first().expect("one rule");
    let selector = &entry.selector;
    // `#panel:hover` → one compound `[Id, PseudoClass]`, no combinators.
    assert!(selector.combinators.is_empty());
    assert!(selector.compounds.iter().any(|c| {
        c.iter()
            .any(|s| matches!(s, Selector::PseudoClass(PseudoClass::Hover)))
    }));
}

#[test]
fn hover_pseudo_class_applies_only_to_the_hovered_node() {
    let (root_id, mut arena) =
        setup(r#"<div id="a" class="box">a</div><div id="b" class="box">b</div>"#);
    let mut css_parser = CssParser::new(".box:hover { background-color: #00ff00; }");
    let rules = css_parser.parse();
    let a = find_node_by_id(&arena, "a");
    let b = find_node_by_id(&arena, "b");

    reset_css_attr(&mut arena, root_id);
    css_into_node_with_hover(&mut arena, root_id, &rules, Some(a));
    assert_eq!(
        arena[a].css_attr.get_bg_color(),
        Some(Color::Rgb { r: 0, g: 255, b: 0 })
    );
    assert_eq!(arena[b].css_attr.get_bg_color(), None);
}

#[test]
fn hover_pseudo_class_matches_ancestors_of_the_hovered_node() {
    let (root_id, mut arena) = setup(r#"<div id="panel"><p id="inner">x</p></div>"#);
    let mut css_parser = CssParser::new("#panel:hover { background-color: #3a3a3a; }");
    let rules = css_parser.parse();
    let inner = find_node_by_id(&arena, "inner");

    reset_css_attr(&mut arena, root_id);
    css_into_node_with_hover(&mut arena, root_id, &rules, Some(inner));
    let panel = find_node_by_id(&arena, "panel");
    assert_eq!(
        arena[panel].css_attr.get_bg_color(),
        Some(Color::Rgb {
            r: 58,
            g: 58,
            b: 58
        })
    );
}

#[test]
fn hover_cascade_paints_the_highlight_onto_the_canvas() {
    let html = r#"<div id="panel" class="box">panel</div>"#;
    let mut css_parser = CssParser::new(".box:hover { background-color: #00ff00; }");
    let rules = css_parser.parse();

    let (root_id, mut arena) = setup(html);
    reset_css_attr(&mut arena, root_id);
    css_into_node(&mut arena, root_id, &rules);
    let hovered = find_node_by_id(&arena, "panel");
    assert_eq!(arena[hovered].css_attr.get_bg_color(), None);

    // Re-cascade with the hovered node: the rule now applies.
    reset_css_attr(&mut arena, root_id);
    css_into_node_with_hover(&mut arena, root_id, &rules, Some(hovered));
    assert_eq!(
        arena[hovered].css_attr.get_bg_color(),
        Some(Color::Rgb { r: 0, g: 255, b: 0 })
    );
}

#[test]
fn hover_background_fills_padding_cells_not_just_the_text_run() {
    // A `:hover` background introduced by the render thread's re-cascade (the
    // element had no background when its boxes were laid out) must fill the
    // whole padding-box, not only the text columns. Without this, the padding
    // cells of a bordered/padded `.btn:hover` keep the page background,
    // making the highlight look like a hollow frame.
    let html = r#"<div id="save" class="btn">Save</div>"#;
    let css = ".btn { padding-left: 1ch; padding-right: 1ch; border: 1ch solid #7aa2f7; }\n\
               .btn:hover { background-color: #28304d; }";
    let (root_id, mut arena) = setup(html);
    let mut css_parser = CssParser::new(css);
    let rules = css_parser.parse();
    let save = find_node_by_id(&arena, "save");

    // Layout with the base cascade: `.btn` carries no background, so the
    // box's layout-time `fill_bg` is false — exactly what the `Hover` render
    // command sees when it re-paints without re-laying-out.
    reset_css_attr(&mut arena, root_id);
    css_into_node(&mut arena, root_id, &rules);
    let term_map = TermMap {
        columns: COLS,
        rows: ROWS,
    };
    let containing = BoxConstraint::root(&term_map);
    let mut cursor = Cursor::new();
    let boxes = layout_tree(
        &arena,
        root_id,
        containing,
        &mut cursor,
        COLS as usize,
        ROWS as usize,
    );
    let r = find_box(&boxes, save).expect("btn box").rect;
    assert_eq!(r.height, 3, "border-top + content + border-bottom");

    // Re-cascade with the button hovered (no re-layout) and paint from the
    // cached layout, like the render thread's `Hover` handler.
    reset_css_attr(&mut arena, root_id);
    css_into_node_with_hover(&mut arena, root_id, &rules, Some(save));
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.repaint_from(&arena, &boxes);

    let hover_bg = Some(Color::Rgb {
        r: 0x28,
        g: 0x30,
        b: 0x4d,
    });
    let cols = COLS as usize;
    let content_row = (r.y + 1) as usize; // directly below the top border
    let left_padding = (r.x + 1) as usize; // after the left border
    let right_padding = (r.x + r.width - 2) as usize; // before the right border
    assert_eq!(
        tl.layout[content_row * cols + left_padding].bcolor,
        hover_bg,
        "left padding cell must be filled by the hover background"
    );
    assert_eq!(
        tl.layout[content_row * cols + right_padding].bcolor,
        hover_bg,
        "right padding cell must be filled by the hover background"
    );
    assert_eq!(
        tl.layout[content_row * cols + left_padding + 1].bcolor,
        hover_bg,
        "text run cell must keep the hover background"
    );
}

#[test]
fn hover_clear_reuses_cached_boxes_without_stale_run_background() {
    // The inverse of the hover-on fill: when the geometry was laid out from
    // the *hovered* cascade (a DOM mutation that re-laid-out under the
    // pointer — e.g. a button click that toggled its label), the `Hover`
    // clear repaint reuses those cached boxes with a fresh un-hovered
    // cascade. The block's own background must come from the fresh cascade
    // (`effective_bg`), not from the runs baked at layout time — otherwise
    // the glyph cell keeps the stale `:hover` background, the single
    // highlighted character left behind after a button click.
    let html = r#"<div id="save" class="btn">Save</div>"#;
    let css = ".btn { padding-left: 1ch; padding-right: 1ch; border: 1ch solid #7aa2f7; }\n\
               .btn:hover { background-color: #28304d; }";
    let (root_id, mut arena) = setup(html);
    let mut css_parser = CssParser::new(css);
    let rules = css_parser.parse();
    let save = find_node_by_id(&arena, "save");

    // Layout from the *hovered* cascade — the geometry the render thread
    // caches after a DOM mutation that happened while the pointer sat over
    // the element.
    reset_css_attr(&mut arena, root_id);
    css_into_node_with_hover(&mut arena, root_id, &rules, Some(save));
    let term_map = TermMap {
        columns: COLS,
        rows: ROWS,
    };
    let containing = BoxConstraint::root(&term_map);
    let mut cursor = Cursor::new();
    let boxes = layout_tree(
        &arena,
        root_id,
        containing,
        &mut cursor,
        COLS as usize,
        ROWS as usize,
    );
    let r = find_box(&boxes, save).expect("btn box").rect;

    // Hover clear: re-cascade without hover and repaint the element's
    // region from the cached boxes, like the render thread's `Hover { None }`.
    reset_css_attr(&mut arena, root_id);
    css_into_node(&mut arena, root_id, &rules);
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.repaint_region(&arena, &boxes, r);

    let hover_bg = Some(Color::Rgb {
        r: 0x28,
        g: 0x30,
        b: 0x4d,
    });
    let cols = COLS as usize;
    let content_row = (r.y + 1) as usize; // directly below the top border
    for x in (r.x as usize)..(r.x + r.width) as usize {
        assert_ne!(
            tl.layout[content_row * cols + x].bcolor,
            hover_bg,
            "no cell of the un-hovered button may keep the :hover background"
        );
    }
}

/// A press-and-drag-away release must clear the pressed element's `:hover`
/// highlight.
///
/// The hover state freezes while a button is held (button-free moves are the
/// only thing that re-validate it), so releasing away from the press cell
/// without re-validating leaves the pressed button highlighted until the next
/// pointer move — the highlight residue after a button press. `handle_mouse_up`
/// re-validates the hover at the release position.
#[test]
fn press_and_drag_away_clears_the_button_hover_on_release() {
    let (mut engine, geo) = build_geometry(
        r#"<div id="btn">click me</div><div id="other">other</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let btn = map.resolve_by_id("btn").expect("btn region");
    let other = map.resolve_by_id("other").expect("other region");
    let (bx, by) = center(btn.rect);
    let (ox, oy) = center(other.rect);

    let mut state = InputState::new();
    // One persistent hover state, like the script thread's.
    let mut hover = HoverState::new();
    let arena = engine.arena();

    // Move over the button → hover = button (the `:hover` highlight appears).
    let ev = apply_message(
        &mut engine,
        &mut hover,
        &map,
        ScriptMsg::Move { x: bx, y: by },
    );
    assert_eq!(ev.hovered, Some(btn.node_id), "hover enters the button");

    // Press on the button.
    let mut down_msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_mouse_down(
        &mut state,
        &map,
        &arena,
        bx,
        by,
        MouseButton::Left,
        &mut down_msgs,
        &mut cmds,
    );
    state.pressed = Some((bx as u16, by as u16));

    // Drag away while the button is held: hover must stay frozen on it.
    let mut drag_msgs = Vec::new();
    handle_mouse_move(&mut state, &map, &arena, ox, oy, &mut drag_msgs, &mut cmds);
    assert!(
        drag_msgs.is_empty(),
        "no hover updates may be queued while a button is held"
    );
    assert_eq!(
        hover.current().map(|r| r.node_id),
        Some(btn.node_id),
        "hover stays on the pressed button during the drag"
    );

    // Release on the other element: the release re-validates the hover.
    let mut up_msgs = Vec::new();
    let mut up_cmds = Vec::new();
    handle_mouse_up(
        &mut state,
        &map,
        &arena,
        (ox as u16, oy as u16),
        MouseButton::Left,
        &mut up_msgs,
        &mut up_cmds,
    );
    assert!(state.pressed.is_none(), "the press is cleared on release");
    assert!(
        up_msgs.iter().any(|m| matches!(
            m,
            ScriptMsg::Move { x, y } if *x == ox && *y == oy
        )),
        "the release must re-validate the hover at the release position"
    );
    for msg in up_msgs {
        let ev = apply_message(&mut engine, &mut hover, &map, msg);
        cmds.extend(ev.cmds);
    }
    assert_eq!(
        hover.current().map(|r| r.node_id),
        Some(other.node_id),
        "hover moves to the element under the release point"
    );
    assert!(
        !cmds.iter().any(|c| matches!(
            c,
            RenderCmd::Hover { node_id: Some(n) } if *n == btn.node_id
        )),
        "no Hover command may keep the button highlighted after the release"
    );
}

// ---------------------------------------------------------------------------
// Dynamic `on*` wiring — attribute handlers stay live on JS-inserted DOM.
// Every test dispatches through `ScriptEngine::fire` with a hand-built hit
// region, so the attribute-handler slot (not just the listener list) is
// exercised end-to-end.
// ---------------------------------------------------------------------------

const DYNAMIC_WIRING_HTML: &str = r#"
  <script>
    var n = 0;
    function bump() {
      n += 1;
      document.getElementById('status').textContent = String(n);
    }
    function alt() {
      n += 10;
      document.getElementById('status').textContent = String(n);
    }
  </script>
  <div id="host"></div>
  <button id="b" onclick="bump()">b</button>
  <p id="status">0</p>
"#;

fn click_region(node_id: NodeId, id: &str) -> HitRegion {
    HitRegion {
        node_id,
        rect: Rect {
            x: 0,
            y: 0,
            width: 10,
            height: 1,
        },
        client: Rect {
            x: 0,
            y: 0,
            width: 10,
            height: 1,
        },
        path: vec![ElementRef {
            id: Some(id.to_string()),
            node_id,
        }]
        .into(),
    }
}

#[test]
fn inner_html_onclick_wires_after_mutation() {
    let mut engine =
        ScriptEngine::new(DYNAMIC_WIRING_HTML, "", EventBindings::default()).expect("engine");
    engine
        .eval_source(
            r#"document.getElementById('host').innerHTML =
                   '<div id="dyn" onclick="bump()"></div>'"#,
        )
        .expect("innerHTML write");

    let dyn_id = find_node_by_id(&engine.arena(), "dyn");
    let region = click_region(dyn_id, "dyn");
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "1",
        "the injected onclick must fire exactly once per click"
    );
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "2",
        "the injected handler must not double-fire"
    );
}

#[test]
fn set_attribute_onclick_replaces_handler() {
    let mut engine =
        ScriptEngine::new(DYNAMIC_WIRING_HTML, "", EventBindings::default()).expect("engine");
    let region = click_region(find_node_by_id(&engine.arena(), "b"), "b");
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "1",
        "boot"
    );

    engine
        .eval_source(r#"document.getElementById('b').setAttribute('onclick', 'alt()')"#)
        .expect("setAttribute");

    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "11",
        "the new handler must replace the old one (1 + 10), not add to it"
    );
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "21",
        "the replaced handler stays single-slot across clicks"
    );
}

#[test]
fn remove_attribute_onclick_unwires_handler() {
    let mut engine =
        ScriptEngine::new(DYNAMIC_WIRING_HTML, "", EventBindings::default()).expect("engine");
    let region = click_region(find_node_by_id(&engine.arena(), "b"), "b");
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "1",
        "boot"
    );

    engine
        .eval_source(r#"document.getElementById('b').removeAttribute('onclick')"#)
        .expect("removeAttribute");
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "1",
        "the unwired handler must not fire after removeAttribute"
    );
}

#[test]
fn appended_child_onclick_becomes_clickable() {
    let mut engine =
        ScriptEngine::new(DYNAMIC_WIRING_HTML, "", EventBindings::default()).expect("engine");
    engine
        .eval_source(
            r#"var d = document.createElement('div');
               d.id = 'dyn';
               d.setAttribute('onclick', 'bump()');
               document.getElementById('host').appendChild(d);"#,
        )
        .expect("createElement + setAttribute + appendChild");

    let dyn_id = find_node_by_id(&engine.arena(), "dyn");
    let region = click_region(dyn_id, "dyn");
    engine.fire(&region, EventType::Click, 0, 0);
    assert_eq!(
        eval_str(&mut engine, "document.getElementById('status').textContent"),
        "1",
        "an appended element whose onclick was set before insertion must fire"
    );
}

#[test]
fn range_slider_drag_commits_value_and_dispatches_events() {
    let html = r#"
      <script>
        window.events = [];
        const range = document.getElementById('range');
        range.addEventListener('input', () => {
          window.events.push('input:' + range.value);
        });
        range.addEventListener('change', () => {
          window.events.push('change:' + range.value);
        });
      </script>
      <input id="range" type="range" min="0" max="10" step="1" value="0" width="11">
    "#;
    let (mut engine, geo) = build_geometry(html, EventBindings::default());
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("range").expect("range region");
    let y = center(region.rect).1;
    let left = region.rect.x as u32;
    let right = left + region.rect.width.max(1) as u32 - 1;

    let mut state = InputState::new();
    state.pressed = Some((left as u16, y as u16));
    let _ = mouse_down(&mut state, &mut engine, &map, left, y, MouseButton::Left);
    assert!(state.drag_selecting, "range press enters drag mode");
    assert_eq!(
        eval_str(&mut engine, "range.value").as_str(),
        "0",
        "clicking on the initial thumb does not change the value"
    );

    let middle = left + 5;
    state.pressed = Some((middle as u16, y as u16));
    let _ = mouse_move(&mut state, &mut engine, &map, middle, y);
    assert_eq!(eval_str(&mut engine, "range.value"), "5");
    assert_eq!(
        eval_str(&mut engine, "window.events.join(',')"),
        "input:5,change:5"
    );

    // The console may deliver release without a final drag event; the slider
    // must still commit at the release coordinate.
    state.pressed = Some((right as u16, y as u16));
    let _ = mouse_up(&mut state, &mut engine, &map, right as u16, y as u16);
    assert_eq!(eval_str(&mut engine, "range.value"), "10");
    assert_eq!(
        eval_str(&mut engine, "window.events.join(',')"),
        "input:5,change:5,input:10,change:10"
    );
}

#[test]
fn mousedown_dispatches_to_listener() {
    let seen = Arc::new(Mutex::new(false));
    let s2 = Arc::clone(&seen);
    let (mut engine, geo) = build_geometry(
        r#"<div id="pad" onmousedown="go()">press</div>"#,
        host_bindings("go", move |_| {
            *s2.lock().unwrap() = true;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("pad").expect("region");
    let (x, y) = center(region.rect);
    on_mouse_down(&map, &mut engine, x, y);
    assert!(*seen.lock().unwrap(), "mousedown listener fires");
}

#[test]
fn mouseup_dispatches_to_listener() {
    let seen = Arc::new(Mutex::new(false));
    let s2 = Arc::clone(&seen);
    let (mut engine, geo) = build_geometry(
        r#"<div id="pad" onmouseup="go()">release</div>"#,
        host_bindings("go", move |_| {
            *s2.lock().unwrap() = true;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("pad").expect("region");
    let (x, y) = center(region.rect);
    on_mouse_up(&map, &mut engine, x, y);
    assert!(*seen.lock().unwrap(), "mouseup listener fires");
}

#[test]
fn mousemove_dispatches_to_listener() {
    let seen = Arc::new(Mutex::new(0usize));
    let s2 = Arc::clone(&seen);
    let (mut engine, geo) = build_geometry(
        r#"<div id="pad" onmousemove="go()">move</div>"#,
        host_bindings("go", move |_| {
            *s2.lock().unwrap() += 1;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("pad").expect("region");
    let (x, y) = center(region.rect);
    on_mouse_move_dispatch(&map, &mut engine, x, y);
    on_mouse_move_dispatch(&map, &mut engine, x + 1, y);
    assert_eq!(
        *seen.lock().unwrap(),
        2,
        "mousemove fires on every dispatch"
    );
}

#[test]
fn mouse_events_work_via_apply_message() {
    let count = Arc::new(Mutex::new(0usize));
    let c2 = Arc::clone(&count);
    let (mut engine, geo) = build_geometry(
        r#"<div id="pad" onmousedown="go()" onmouseup="go()" onmousemove="go()">x</div>"#,
        host_bindings("go", move |_| {
            *c2.lock().unwrap() += 1;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("pad").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::MouseDown { x, y });
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::MouseMove { x, y });
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::MouseUp { x, y });
    assert_eq!(*count.lock().unwrap(), 3, "all three mouse events fire");
}

#[test]
fn add_event_listener_mousemove_works() {
    let count = Arc::new(Mutex::new(0usize));
    let c2 = Arc::clone(&count);
    let (mut engine, geo) = build_geometry(
        r#"<div id="pad">x</div>
        <script>document.getElementById("pad").addEventListener("mousemove", function() { go() })</script>"#,
        host_bindings("go", move |_| {
            *c2.lock().unwrap() += 1;
            JsValue::undefined()
        }),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("pad").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::MouseMove { x, y });
    assert_eq!(
        *count.lock().unwrap(),
        1,
        "addEventListener('mousemove') fires"
    );
}

// ---------------------------------------------------------------------------
// dblclick / contextmenu / wheel / enter-leave / mouse payload coords
// ---------------------------------------------------------------------------

/// Read `globalThis.__seen` (a JS array of strings) as a comma-joined string.
fn eval_seen(engine: &mut ScriptEngine) -> String {
    engine
        .eval_source("globalThis.__seen.join(',')")
        .expect("eval")
        .as_string()
        .map(|s| s.to_std_string_lossy())
        .unwrap_or_default()
}

#[test]
fn second_quick_click_on_same_cell_emits_dblclick() {
    let (mut engine, geo) = build_geometry(
        r#"<script>
          globalThis.__seen = [];
          document.getElementById("t").addEventListener("click", function(){ __seen.push("click") });
          document.getElementById("t").addEventListener("dblclick", function(){ __seen.push("dblclick") });
        </script>
        <div id="t" style="width: 20; height: 2">target</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("t").expect("region");
    let (x, y) = center(region.rect);

    // Input side: the second click on the same cell emits the DblClick msg.
    let mut state = InputState::new();
    let mut msgs = Vec::new();
    let mut cmds = Vec::new();
    handle_click(
        &mut state,
        &map,
        &engine.arena(),
        x,
        y,
        &mut msgs,
        &mut cmds,
    );
    handle_click(
        &mut state,
        &map,
        &engine.arena(),
        x,
        y,
        &mut msgs,
        &mut cmds,
    );
    assert!(
        msgs.iter().any(|m| matches!(m, ScriptMsg::DblClick { .. })),
        "second click must emit DblClick: {msgs:?}"
    );

    // Script side: the dispatch reaches the element's dblclick listeners.
    let mut hover = HoverState::new();
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::DblClick { x, y });
    assert_eq!(eval_seen(&mut engine), "dblclick");
}

#[test]
fn contextmenu_dispatches_to_hit_target() {
    let (mut engine, geo) = build_geometry(
        r#"<script>
          globalThis.__seen = [];
          document.getElementById("t").addEventListener("contextmenu", function(e){
            __seen.push("ctx:" + e.isTrusted);
          });
        </script>
        <div id="t" style="width: 20; height: 2">target</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("t").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    apply_message(
        &mut engine,
        &mut hover,
        &map,
        ScriptMsg::ContextMenu { x, y },
    );
    assert_eq!(eval_seen(&mut engine), "ctx:true");
}

#[test]
fn wheel_dispatch_reports_prevent_default_verdict() {
    // Without preventDefault: gate verdict false — the built-in scroll runs.
    let (mut engine, geo) = build_geometry(
        r#"<script>
          globalThis.__delta = null;
          document.getElementById("t").addEventListener("wheel", function(e){
            __delta = e.deltaY;
          });
        </script>
        <div id="t" style="width: 20; height: 2">target</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("t").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    let event = apply_message(
        &mut engine,
        &mut hover,
        &map,
        ScriptMsg::Wheel {
            gate_id: 7,
            x,
            y,
            up: false,
        },
    );
    assert_eq!(event.wheel_gate, Some((7, false)), "no preventDefault");
    let delta = engine
        .eval_source("String(globalThis.__delta)")
        .expect("eval")
        .as_string()
        .map(|s| s.to_std_string_lossy())
        .unwrap_or_default();
    assert_eq!(delta, "3", "downward tick carries +3");

    // With preventDefault: gate verdict true — the built-in scroll is skipped.
    let (mut engine2, geo2) = build_geometry(
        r#"<script>
          document.getElementById("t").addEventListener("wheel", function(e){
            e.preventDefault();
          });
        </script>
        <div id="t" style="width: 20; height: 2">target</div>"#,
        EventBindings::default(),
    );
    let map2 = HitMap::build(&geo2);
    let region2 = map2.resolve_by_id("t").expect("region");
    let (x2, y2) = center(region2.rect);
    let mut hover2 = HoverState::new();
    let event2 = apply_message(
        &mut engine2,
        &mut hover2,
        &map2,
        ScriptMsg::Wheel {
            gate_id: 9,
            x: x2,
            y: y2,
            up: false,
        },
    );
    assert_eq!(event2.wheel_gate, Some((9, true)), "preventDefault gates");
}

#[test]
fn mouseenter_leave_fire_on_target_only_while_over_out_bubble() {
    let (mut engine, geo) = build_geometry(
        r#"<script>
          globalThis.__seen = [];
          for (var id of ["outer", "inner"]) {
            var el = document.getElementById(id);
            el.addEventListener("mouseenter", function(){ __seen.push(this.id + ":enter") });
            el.addEventListener("mouseover", function(){ __seen.push(this.id + ":over") });
            el.addEventListener("mouseleave", function(){ __seen.push(this.id + ":leave") });
            el.addEventListener("mouseout", function(){ __seen.push(this.id + ":out") });
          }
        </script>
        <div id="outer" style="width: 30; height: 4"><div id="inner" style="width: 10; height: 2">i</div></div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let inner = map.resolve_by_id("inner").expect("inner");
    let outer = map.resolve_by_id("outer").expect("outer");
    let (ix, iy) = center(inner.rect);
    // A point on the outer box away from the inner one.
    let (ox, oy) = ((outer.rect.x + 1) as u32, (outer.rect.y + 1) as u32);

    let mut hover = HoverState::new();
    // Move onto inner: `mouseenter` fires only on inner (no bubble), while
    // `mouseover` bubbles to outer.
    apply_message(
        &mut engine,
        &mut hover,
        &map,
        ScriptMsg::Move { x: ix, y: iy },
    );
    let seen = eval_seen(&mut engine);
    assert!(
        seen.contains("inner:enter") && !seen.contains("outer:enter"),
        "mouseenter does not bubble: {seen}"
    );
    assert!(
        seen.contains("inner:over") && seen.contains("outer:over"),
        "mouseover bubbles: {seen}"
    );

    // Move to outer: `mouseleave` fires only on inner, `mouseout` bubbles.
    apply_message(
        &mut engine,
        &mut hover,
        &map,
        ScriptMsg::Move { x: ox, y: oy },
    );
    let seen = eval_seen(&mut engine);
    assert!(
        seen.contains("inner:leave") && !seen.contains("outer:leave"),
        "mouseleave does not bubble: {seen}"
    );
    assert!(
        seen.contains("inner:out") && seen.contains("outer:out"),
        "mouseout bubbles: {seen}"
    );
}

#[test]
fn mouse_events_carry_client_and_page_coordinates() {
    let (mut engine, geo) = build_geometry(
        r#"<script>
          globalThis.__coords = null;
          document.getElementById("t").addEventListener("click", function(e){
            __coords = [e.clientX, e.clientY, e.pageX, e.pageY, String(e.isTrusted)];
          });
        </script>
        <div id="t" style="width: 20; height: 2">target</div>"#,
        EventBindings::default(),
    );
    let map = HitMap::build(&geo);
    let region = map.resolve_by_id("t").expect("region");
    let (x, y) = center(region.rect);
    let mut hover = HoverState::new();
    // Direct-engine dispatch has no input loop attached → scroll offset 0 →
    // client == page (the offset path is covered by the spawned-thread test
    // in script_dom_api_tests).
    apply_message(&mut engine, &mut hover, &map, ScriptMsg::Click { x, y });
    let coords = engine
        .eval_source("globalThis.__coords.join('/')")
        .expect("eval")
        .as_string()
        .map(|s| s.to_std_string_lossy())
        .unwrap_or_default();
    let parts: Vec<&str> = coords.split('/').collect();
    assert_eq!(parts.len(), 5, "coords: {coords}");
    assert_eq!(parts[4], "true", "engine dispatch is trusted");
    let px: f64 = parts[2].parse().expect("pageX");
    let py: f64 = parts[3].parse().expect("pageY");
    let cx: f64 = parts[0].parse().expect("clientX");
    let cy: f64 = parts[1].parse().expect("clientY");
    assert_eq!(px, f64::from(x), "pageX = canvas x");
    assert_eq!(py, f64::from(y), "pageY = canvas y");
    assert_eq!(cx, px, "clientX = pageX (no horizontal scroll)");
    assert_eq!(cy, py, "clientY = pageY (no page scroll attached)");
}