quadraui 0.1.8

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
//! Cross-backend mouse + scroll dispatch.
//!
//! Backends call into these free functions with raw (platform-translated)
//! mouse and scroll events. Quadraui consults the [`ModalStack`] first,
//! decides which widget — if any — should receive the event, and returns
//! a `Vec<UiEvent>` the backend pushes onto its per-frame event queue.
//!
//! The key guarantee: **events landing inside an open modal cannot fall
//! through to widgets behind it**. This centralizes modal event handling
//! across backends, eliminating bugs where modals are added to one backend
//! but forgotten in another.
//!
//! # What's here
//!
//! [`dispatch_mouse_down`], [`dispatch_mouse_drag`], [`dispatch_mouse_up`],
//! [`dispatch_scroll`], and [`dispatch_click`] — the full event-routing
//! pipeline for modal-aware mouse and scroll handling.
//!
//! # What's explicitly not here
//!
//! - Inner hit refinement within a modal — `Palette`, `Dialog`, etc.
//!   have their own `*Layout::hit_test` for that. The dispatcher
//!   identifies the topmost modal under the cursor; the app still
//!   calls the primitive's hit test afterward if it needs an
//!   item-level target.
//! - Base-layer hit testing — the editor, sidebar, tabs, and so on.
//!   Those events still go through each backend's existing mouse
//!   handlers, which are already per-backend. A future change could
//!   route them through here too.

use crate::event::{MouseButton, Point, ScrollDelta, UiEvent};
use crate::modal_stack::ModalStack;
use crate::primitives::palette::PaletteEvent;
use crate::primitives::scrollbar::ScrollAxis;
use crate::primitives::split_tree::SplitDirection;
use crate::types::WidgetId;
use crate::Modifiers;

// ─── Drag state ─────────────────────────────────────────────────────────────

/// What's being dragged, if anything. Backends hold one [`DragState`]
/// (typically on the same struct that owns the [`ModalStack`]) and
/// update it from the click / drag / release handlers via
/// [`DragState::begin`] / [`DragState::end`]. The dispatch functions
/// below consult it to decide which primitive-specific event to emit.
#[derive(Debug, Clone, PartialEq)]
pub enum DragTarget {
    /// A vertical scrollbar drag. `track_start` and `track_length`
    /// are in the backend's native units (pixels for GTK; cells for
    /// TUI) and define the track region the thumb can traverse.
    /// `max_scroll` is supplied directly by the caller (typically
    /// `total - visible`) so the dispatcher doesn't need to know
    /// the unit system. The dispatcher maps a drag
    /// point's y to a scroll offset via linear interpolation:
    ///
    /// ```text
    /// rel    = (y - track_start) / track_length   (clamped 0..=1)
    /// offset = round(rel * max_scroll)
    /// ```
    ScrollbarY {
        /// Which widget's scrollbar is being dragged. Used to route
        /// the resulting event back to the right primitive.
        widget: WidgetId,
        /// Track top in the backend's native y-coordinate.
        track_start: f32,
        /// Track length in the backend's native units. Must be > 0.
        track_length: f32,
        /// Actual painted thumb length in the same units as
        /// `track_length`. The dispatcher uses this directly for
        /// `effective_track = track_length - thumb_length` — no
        /// recomputation from visible/total counts.
        thumb_length: f32,
        /// Maximum scroll offset the drag can produce. The caller
        /// supplies this directly (typically `total - visible`)
        /// so the dispatcher doesn't need to know the unit system.
        max_scroll: usize,
        /// Where on the thumb the cursor was at click-down time, as
        /// the cursor's offset from the thumb's top in the backend's
        /// native units. The dispatcher subtracts this from
        /// `position.y` before computing `rel`, so the cursor stays
        /// at the same relative spot on the thumb during the drag —
        /// the standard "thumb doesn't jump when you grab it" UX
        /// every native scrollbar provides. Set to `0.0` for clicks
        /// on the track *outside* the thumb (jump-to-position
        /// behavior — the thumb hops so its top lands at the cursor).
        grab_offset: f32,
        /// When true, offset 0 means "at the bottom" (scrollback
        /// style). The dispatcher flips the ratio so the thumb sits
        /// at the bottom when offset is 0 and at the top when fully
        /// scrolled back.
        inverted: bool,
    },
    /// A horizontal scrollbar drag. Same shape as [`DragTarget::ScrollbarY`]
    /// but operates on the x-axis: `track_start` is the leftmost x of
    /// the track, `track_length` is the track width, and the dispatcher
    /// reads `position.x` (not `position.y`) to compute the offset.
    ScrollbarX {
        widget: WidgetId,
        /// Track left in the backend's native x-coordinate.
        track_start: f32,
        /// Track length in the backend's native units. Must be > 0.
        track_length: f32,
        /// Actual painted thumb length. See
        /// [`DragTarget::ScrollbarY::thumb_length`].
        thumb_length: f32,
        /// Maximum scroll offset. See
        /// [`DragTarget::ScrollbarY::max_scroll`].
        max_scroll: usize,
        /// Cursor's x-offset from the thumb's left at click-down. See
        /// [`DragTarget::ScrollbarY`] for why this matters.
        grab_offset: f32,
        /// When true, offset 0 means "at the right edge". See
        /// [`DragTarget::ScrollbarY::inverted`].
        inverted: bool,
    },
    /// A text-selection drag. `region` is the id of the
    /// [`TextRegion`] where the drag started; `anchor` is the screen
    /// position at click-down. The anchor is fixed for the lifetime of
    /// the drag; [`dispatch_mouse_drag`] reads it to emit
    /// [`UiEvent::TextSelectionChanged`] with the current cursor as
    /// the `focus`.
    TextSelection {
        /// Which text region is being selected.
        region: WidgetId,
        /// Screen position where the drag started.
        anchor: Point,
    },
    /// A [`crate::SplitTree`] divider drag. `tree` identifies which
    /// tree this divider belongs to — apps hosting more than one split
    /// tree (e.g. vimcode's per-window-group tree and its own in-group
    /// vim-window tree) use this to route the resulting event to the
    /// right state. `split_index` is the divider's pre-order index
    /// (see [`crate::SplitTreeDivider::split_index`]).
    ///
    /// `axis_start` / `axis_size` are the *parent* rect's extent along
    /// the split axis — copied from
    /// [`crate::SplitTreeDivider::axis_start`] /
    /// [`crate::SplitTreeDivider::axis_size`] at drag-start so
    /// [`dispatch_mouse_drag`] can convert a cursor position directly
    /// into a ratio without re-running the tree's `layout()` on every
    /// mouse-move:
    ///
    /// ```text
    /// ratio = (cursor_axis - axis_start) / axis_size   (clamped 0..=1)
    /// ```
    ///
    /// `direction` selects which cursor coordinate feeds `cursor_axis`
    /// (`x` for [`SplitDirection::Horizontal`], `y` for
    /// [`SplitDirection::Vertical`] — matching
    /// [`crate::SplitTree::layout`]'s axis convention).
    SplitDivider {
        tree: WidgetId,
        split_index: usize,
        direction: SplitDirection,
        axis_start: f32,
        axis_size: f32,
    },
}

/// One drag in progress, or none. Backends hold one instance; call
/// [`Self::begin`] on mouse-down over a draggable region and
/// [`Self::end`] on mouse-up. The dispatch functions here read it to
/// decide whether a mouse-move should produce a drag-update event.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DragState {
    current: Option<DragTarget>,
}

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

    /// Start tracking a drag. Overwrites any previous state —
    /// backends are expected to call [`Self::end`] on mouse-up before
    /// beginning the next drag, but overwriting is the safer default
    /// than panicking (spurious duplicate begins do happen in
    /// gesture-heavy paths).
    pub fn begin(&mut self, target: DragTarget) {
        self.current = Some(target);
    }

    /// Clear the drag. No-op if nothing is in progress.
    pub fn end(&mut self) {
        self.current = None;
    }

    pub fn is_active(&self) -> bool {
        self.current.is_some()
    }

    pub fn target(&self) -> Option<&DragTarget> {
        self.current.as_ref()
    }
}

// ─── Dispatch functions ─────────────────────────────────────────────────────

/// Translate a raw mouse-down event into a `Vec<UiEvent>`, consulting
/// the modal stack first.
///
/// # Returns
///
/// Three cases:
///
/// 1. **Click landed on an open modal.** Emits
///    `[UiEvent::MouseDown { widget: Some(id), .. }]`. The app's
///    dispatch matches on the widget id and routes to the modal's
///    inner hit-test if it needs finer resolution.
/// 2. **Click landed outside every open modal, but a modal is open.**
///    Emits `[UiEvent::MouseDown { widget: None, .. }, UiEvent::Palette(id, Closed)]`
///    where `id` is the topmost modal (the one the backdrop click
///    dismisses). This is the "click outside to close" convention every
///    desktop platform follows. **Base-layer widgets must not receive
///    the event** — the event vec doesn't include a second
///    `MouseDown` for a base widget, and the caller should consume on
///    the emission of `PaletteEvent::Closed`.
/// 3. **No modal open.** Emits `[UiEvent::MouseDown { widget: None, .. }]`
///    with no primitive event; the backend's existing base-layer
///    mouse handlers deal with it as they did before the pilot.
///
/// Callers that only care about case 1 (e.g. a GTK event handler that
/// wants to stop the drag from leaking to the editor) can check the
/// returned vec:
///
/// ```ignore
/// let events = dispatch_mouse_down(&stack, pos, button, mods);
/// if events.iter().any(|e| matches!(e, UiEvent::MouseDown { widget: Some(_), .. })
///     || matches!(e, UiEvent::Palette(_, PaletteEvent::Closed)))
/// {
///     // modal consumed the click — don't run base-layer dispatch
///     return;
/// }
/// ```
///
/// # Note on `PaletteEvent::Closed`
///
/// Today this dispatcher always emits [`PaletteEvent::Closed`] for
/// backdrop clicks regardless of which primitive type is topmost on
/// the stack. That's a pilot-scope simplification — the palette is
/// the only consumer wired up in commit 1. When a second modal type
/// needs the backdrop-dismiss behaviour (e.g. Dialog), we'll generalise
/// to a `ModalDismissed(WidgetId)` event or per-primitive variants.
pub fn dispatch_mouse_down(
    stack: &ModalStack,
    position: Point,
    button: MouseButton,
    modifiers: Modifiers,
) -> Vec<UiEvent> {
    // Case 1: click landed inside an open modal.
    if let Some(widget_id) = stack.hit_test(position) {
        return vec![UiEvent::MouseDown {
            widget: Some(widget_id.clone()),
            button,
            position,
            modifiers,
        }];
    }

    // Case 2: modal(s) open but click was outside them → dismiss topmost.
    if let Some(top) = stack.top() {
        return vec![
            UiEvent::MouseDown {
                widget: None,
                button,
                position,
                modifiers,
            },
            UiEvent::Palette(top.id.clone(), PaletteEvent::Closed),
        ];
    }

    // Case 3: no modals open. Event belongs to the base layer.
    vec![UiEvent::MouseDown {
        widget: None,
        button,
        position,
        modifiers,
    }]
}

/// Translate a mouse-move event. When no drag is in progress, emits a
/// plain [`UiEvent::MouseMoved`]. When a [`DragTarget::ScrollbarY`]
/// drag is active, additionally emits a generic
/// [`UiEvent::ScrollOffsetChanged { widget, new_offset }`] with the
/// derived scroll offset. The app's dispatch matches on the event
/// (and switches on `widget` to route to the right scroll-state
/// field) without needing the track geometry — this function owns
/// the translation.
///
/// # How the offset is computed
///
/// `ratio = ((point.y - track_start) / track_length).clamp(0, 1)`
/// `new_offset = round(ratio * max_scroll)` where `max_scroll` is
/// supplied directly by the `DragTarget`.
///
/// This mirrors the math TUI already uses in `mouse.rs`'s
/// `dragging_picker_sb` branch, extended to f32 so it works for
/// pixel-unit backends (GTK, macOS) as well as cell-unit backends
/// (TUI).
pub fn dispatch_mouse_drag(
    drag: &DragState,
    position: Point,
    buttons: crate::event::ButtonMask,
) -> Vec<UiEvent> {
    let mut events = vec![UiEvent::MouseMoved { position, buttons }];

    match drag.target() {
        Some(DragTarget::ScrollbarY {
            widget,
            track_start,
            track_length,
            thumb_length,
            max_scroll,
            grab_offset,
            inverted,
        }) if *track_length > 0.0 && *max_scroll > 0 => {
            let effective_track = (*track_length - *thumb_length).max(1.0);
            let rel = (position.y - *track_start - *grab_offset) / effective_track;
            let clamped = rel.clamp(0.0, 1.0);
            let clamped = if *inverted { 1.0 - clamped } else { clamped };
            let new_offset = (clamped * *max_scroll as f32).round() as usize;
            events.push(UiEvent::ScrollOffsetChanged {
                widget: widget.clone(),
                new_offset,
            });
        }
        Some(DragTarget::ScrollbarX {
            widget,
            track_start,
            track_length,
            thumb_length,
            max_scroll,
            grab_offset,
            inverted,
        }) if *track_length > 0.0 && *max_scroll > 0 => {
            let effective_track = (*track_length - *thumb_length).max(1.0);
            let rel = (position.x - *track_start - *grab_offset) / effective_track;
            let clamped = rel.clamp(0.0, 1.0);
            let clamped = if *inverted { 1.0 - clamped } else { clamped };
            let new_offset = (clamped * *max_scroll as f32).round() as usize;
            events.push(UiEvent::ScrollOffsetChanged {
                widget: widget.clone(),
                new_offset,
            });
        }
        Some(DragTarget::TextSelection { region, anchor }) => {
            events.push(UiEvent::TextSelectionChanged {
                region: region.clone(),
                anchor: *anchor,
                focus: position,
            });
        }
        Some(DragTarget::SplitDivider {
            tree,
            split_index,
            direction,
            axis_start,
            axis_size,
        }) if *axis_size > 0.0 => {
            let cursor_axis = match direction {
                SplitDirection::Horizontal => position.x,
                SplitDirection::Vertical => position.y,
            };
            let new_ratio = ((cursor_axis - *axis_start) / *axis_size).clamp(0.0, 1.0);
            events.push(UiEvent::SplitDividerDragged {
                tree: tree.clone(),
                split_index: *split_index,
                new_ratio,
            });
        }
        _ => {}
    }

    events
}

/// Translate a mouse-up event. Always emits [`UiEvent::MouseUp`] and
/// clears any active drag state. If the click landed inside a modal,
/// the `MouseUp` carries the modal's `widget` id — matching
/// [`dispatch_mouse_down`]'s precedence — so apps can treat a drag
/// that crosses the modal boundary atomically.
pub fn dispatch_mouse_up(
    stack: &ModalStack,
    drag: &mut DragState,
    position: Point,
    button: MouseButton,
) -> Vec<UiEvent> {
    drag.end();
    let widget = stack.hit_test(position).cloned();
    vec![UiEvent::MouseUp {
        widget,
        button,
        position,
    }]
}

// ─── Text region ─────────────────────────────────────────────────────────────

/// A selectable text region registered during paint. Apps push one
/// entry per selectable text area each frame;
/// [`dispatch_click`] hit-tests the list to begin a
/// [`DragTarget::TextSelection`] drag when the user clicks inside.
///
/// Push in paint order (back-to-front). The dispatcher walks
/// last-to-first so the topmost-painted region wins on overlap.
/// Text regions take priority over [`ScrollSurface`] *bodies* (not
/// scrollbars) — a text region registered inside a scroll surface body
/// will capture clicks first.
///
/// # Relationship with `ScrollSurface`
///
/// A text region is typically co-located with a scroll surface: the
/// scroll surface owns the scrollbar; the text region owns the content
/// body. Register them both, and the precedence chain
/// (scrollbar thumb/track → text region → surface body → none) falls
/// out automatically.
///
/// # `lines` field
///
/// Optional text content — one `String` per display row. Backends that
/// cannot read text back from a cell buffer (GTK, macOS, win) use this to
/// extract the selected substring when the user copies (Ctrl-C). TUI
/// ignores this field and reads cells from its ratatui buffer instead.
/// Leave as `vec![]` for TUI-only apps or when text extraction is not
/// needed.
#[derive(Debug, Clone, PartialEq)]
pub struct TextRegion {
    pub id: WidgetId,
    pub bounds: crate::event::Rect,
    /// Source text lines for pixel-based backends (GTK, macOS, win).
    /// TUI ignores this (reads from the ratatui cell buffer).
    /// Empty means no text content is available for extraction.
    pub lines: Vec<String>,
}

/// Compute the screen-cell ranges covered by a line-wise text selection.
///
/// Given `anchor` and `focus` in screen coordinates (TUI: cells;
/// GTK/macOS: pixels) and the `bounds` of the [`TextRegion`], returns
/// a `Vec` of `(row, col_start, col_end)` tuples (half-open:
/// `col_start..col_end`) in document order (top-to-bottom).
///
/// **Line-wise stream semantics** (same as most terminal selections):
///
/// | Position | Range |
/// |---|---|
/// | First row | `anchor_col .. region_end_col` |
/// | Middle rows | `region_start_col .. region_end_col` |
/// | Last row | `region_start_col .. focus_col + 1` |
/// | Single row | `min_col .. max_col + 1` |
///
/// Coordinates are clamped to `bounds`. Returns an empty `Vec` when
/// `anchor == focus` (selection collapsed to a point — plain click).
///
/// # Units
///
/// `row` is a discrete line/cell-row index (it indexes
/// [`TextRegion::lines`] and is always integral) and stays `u16`.
/// `col_start` and `col_end` are `f32` to match other native-unit
/// spans in this crate ([`Point`], [`crate::event::Rect`]); callers
/// pass pre-quantized cell-space coordinates (the "+1" is one *unit*,
/// i.e. one character cell, not one pixel).
pub fn text_selection_line_range(
    anchor: Point,
    focus: Point,
    bounds: crate::event::Rect,
) -> Vec<(u16, f32, f32)> {
    // Empty when anchor == focus (no movement → collapsed click).
    let ax = anchor.x.round() as i32;
    let ay = anchor.y.round() as i32;
    let fx = focus.x.round() as i32;
    let fy = focus.y.round() as i32;
    if ax == fx && ay == fy {
        return Vec::new();
    }

    // Put in document order (top-to-bottom, left-to-right).
    let (start, end) = if ay < fy || (ay == fy && ax <= fx) {
        (anchor, focus)
    } else {
        (focus, anchor)
    };

    let region_x = bounds.x.round();
    let region_end_x = (bounds.x + bounds.width).round();
    let region_y = bounds.y.round() as u16;
    let region_end_y = (bounds.y + bounds.height).round() as u16;

    // Clamp start/end rows and cols to region.
    let start_row = (start.y.round() as u16).clamp(region_y, region_end_y.saturating_sub(1));
    let end_row = (end.y.round() as u16).clamp(region_y, region_end_y.saturating_sub(1));
    let start_col = start.x.round().clamp(region_x, region_end_x);
    // End col is inclusive → add one unit for the half-open range, then clamp.
    let end_col = (end.x.round() + 1.0).clamp(region_x, region_end_x);

    if start_row == end_row {
        if start_col >= end_col {
            return Vec::new();
        }
        return vec![(start_row, start_col, end_col)];
    }

    let mut ranges = Vec::with_capacity((end_row - start_row + 1) as usize);
    // First row: from start_col to region end.
    ranges.push((start_row, start_col, region_end_x));
    // Middle rows: full region width.
    for row in (start_row + 1)..end_row {
        ranges.push((row, region_x, region_end_x));
    }
    // Last row: from region start to end_col.
    ranges.push((end_row, region_x, end_col));
    ranges
}

// ─── Scroll dispatch ──────────────────────────────────────────────────────

/// A scrollable surface registered during paint. The consumer pushes
/// one entry per scrollable widget each frame; [`dispatch_scroll`]
/// hit-tests the list to route wheel events to the right widget.
///
/// Push in paint order (back-to-front). The dispatcher walks
/// last-to-first so the topmost-painted surface wins on overlap —
/// same semantics as [`ModalStack`].
#[derive(Debug, Clone, PartialEq)]
pub struct ScrollSurface {
    pub id: WidgetId,
    pub bounds: crate::event::Rect,
    /// Optional scrollbar geometry. When present, [`dispatch_click`]
    /// can route thumb clicks (auto-start drag) and track clicks
    /// (page up/down) without per-backend code.
    pub scrollbar: Option<SurfaceScrollbar>,
}

/// Translate a raw scroll-wheel event into a `Vec<UiEvent>`, consulting
/// the modal stack first, then the registered scroll surfaces.
///
/// # Scroll delta sign convention
///
/// Positive `delta.y` = scroll content **up** (toward the top of the
/// document). Backends normalise their native direction before
/// constructing [`ScrollDelta`] — see [`ScrollDelta`] for the
/// canonical definition. Compose helpers ([`TreeController`],
/// [`SidebarSystem`]) consume the delta directly without per-call-site
/// negation.
///
/// # Returns
///
/// Three cases:
///
/// 1. **Scroll landed inside an open modal.** Emits
///    `[UiEvent::Scroll { widget: Some(modal_id), delta, position }]`.
///    The app routes to the modal's inner scroll handler.
/// 2. **Modal(s) open but scroll was outside them.** Emits nothing —
///    scroll behind an open modal is swallowed (you can't scroll the
///    editor while a dialog is up).
/// 3. **No modal open.** Hit-tests `scroll_surfaces` last-to-first
///    (topmost-painted wins). If a surface matches, emits
///    `[UiEvent::Scroll { widget: Some(surface_id), delta, position }]`.
///    If no surface matches, emits
///    `[UiEvent::Scroll { widget: None, delta, position }]` for
///    base-layer handling.
pub fn dispatch_scroll(
    stack: &ModalStack,
    scroll_surfaces: &[ScrollSurface],
    position: Point,
    delta: ScrollDelta,
) -> Vec<UiEvent> {
    // Case 1: scroll inside an open modal.
    if let Some(widget_id) = stack.hit_test(position) {
        return vec![UiEvent::Scroll {
            widget: Some(widget_id.clone()),
            delta,
            position,
        }];
    }

    // Case 2: modal(s) open but scroll was outside → swallow.
    if !stack.is_empty() {
        return Vec::new();
    }

    // Case 3: no modals. Hit-test scroll surfaces (last-to-first).
    for surface in scroll_surfaces.iter().rev() {
        if position.x >= surface.bounds.x
            && position.x < surface.bounds.x + surface.bounds.width
            && position.y >= surface.bounds.y
            && position.y < surface.bounds.y + surface.bounds.height
        {
            return vec![UiEvent::Scroll {
                widget: Some(surface.id.clone()),
                delta,
                position,
            }];
        }
    }

    // No surface matched — base-layer event.
    vec![UiEvent::Scroll {
        widget: None,
        delta,
        position,
    }]
}

// ─── Click dispatch with scrollbar awareness ──────────────────────────────

/// Scrollbar geometry for a [`ScrollSurface`]. Registered during paint
/// so [`dispatch_click`] can route scrollbar clicks (thumb drag, track
/// page) without per-backend code. Supports both vertical and
/// horizontal scrollbars via the `axis` field.
#[derive(Debug, Clone, PartialEq)]
pub struct SurfaceScrollbar {
    /// Vertical or horizontal. Determines which coordinate axis
    /// `dispatch_click` uses for grab offset, track-click paging,
    /// and which `DragTarget` variant is created.
    pub axis: ScrollAxis,
    /// Full scrollbar track bounds (gutter area).
    pub track_bounds: crate::event::Rect,
    /// Current thumb bounds within the track.
    pub thumb_bounds: crate::event::Rect,
    /// Total number of scrollable items (lines, rows, cols, etc.).
    pub total_items: usize,
    /// Number of items visible in the viewport.
    pub visible_items: usize,
    /// Current scroll offset (index of the first visible item).
    pub scroll_offset: usize,
    /// When true, offset 0 means "at the bottom" (scrollback style).
    /// Propagated to the `DragTarget`'s `inverted` field on thumb
    /// click and used to flip track-click page direction.
    pub inverted: bool,
}

/// Translate a raw mouse-down event, consulting the modal stack first,
/// then the registered scroll surfaces (including their scrollbar
/// regions) and text regions. Supersedes [`dispatch_mouse_down`] for
/// consumers that register scroll surfaces and/or text regions.
///
/// # Returns
///
/// Priority order:
///
/// 1. **Click inside an open modal** → `MouseDown { widget: Some(modal_id) }`.
/// 2. **Click outside every modal, but modal open** → dismiss topmost
///    (same as [`dispatch_mouse_down`]).
/// 3. **Click on a scroll surface's scrollbar thumb** → starts a
///    [`DragTarget::ScrollbarY`] or [`DragTarget::ScrollbarX`] drag
///    (depending on `SurfaceScrollbar::axis`), emits
///    `MouseDown { widget: Some(surface_id) }`.
/// 4. **Click on a scroll surface's scrollbar track** (above or below
///    thumb) → emits `ScrollOffsetChanged { widget, new_offset }`
///    with the offset paged up or down by `visible_items`.
/// 5. **Click inside a registered [`TextRegion`]** → starts a
///    [`DragTarget::TextSelection`] drag, emits
///    `MouseDown { widget: Some(region_id) }`. Text regions take
///    priority over scroll surface bodies (not scrollbars).
/// 6. **Click on a scroll surface body** (not scrollbar, not text
///    region) → `MouseDown { widget: Some(surface_id) }`.
/// 7. **No surface or region matched** → `MouseDown { widget: None }`.
pub fn dispatch_click(
    stack: &ModalStack,
    scroll_surfaces: &[ScrollSurface],
    text_regions: &[TextRegion],
    drag: &mut DragState,
    position: Point,
    button: MouseButton,
    modifiers: Modifiers,
) -> Vec<UiEvent> {
    // Case 1: click inside an open modal.
    if let Some(widget_id) = stack.hit_test(position) {
        return vec![UiEvent::MouseDown {
            widget: Some(widget_id.clone()),
            button,
            position,
            modifiers,
        }];
    }

    // Case 2: modal open but click outside → dismiss topmost.
    if let Some(top) = stack.top() {
        return vec![
            UiEvent::MouseDown {
                widget: None,
                button,
                position,
                modifiers,
            },
            UiEvent::Palette(top.id.clone(), PaletteEvent::Closed),
        ];
    }

    // Case 3–5: no modals. Hit-test scroll surfaces (last-to-first).
    for surface in scroll_surfaces.iter().rev() {
        if !surface.bounds.contains(position) {
            continue;
        }

        // Check scrollbar regions first (if present).
        if let Some(ref sb) = surface.scrollbar {
            let in_track = sb.track_bounds.contains(position);

            if in_track {
                let in_thumb = sb.thumb_bounds.contains(position);

                if in_thumb {
                    let max_scroll = sb.total_items.saturating_sub(sb.visible_items);
                    match sb.axis {
                        ScrollAxis::Vertical => {
                            let grab_offset = position.y - sb.thumb_bounds.y;
                            drag.begin(DragTarget::ScrollbarY {
                                widget: surface.id.clone(),
                                track_start: sb.track_bounds.y,
                                track_length: sb.track_bounds.height,
                                thumb_length: sb.thumb_bounds.height,
                                max_scroll,
                                grab_offset,
                                inverted: sb.inverted,
                            });
                        }
                        ScrollAxis::Horizontal => {
                            let grab_offset = position.x - sb.thumb_bounds.x;
                            drag.begin(DragTarget::ScrollbarX {
                                widget: surface.id.clone(),
                                track_start: sb.track_bounds.x,
                                track_length: sb.track_bounds.width,
                                thumb_length: sb.thumb_bounds.width,
                                max_scroll,
                                grab_offset,
                                inverted: sb.inverted,
                            });
                        }
                    }
                    return vec![UiEvent::MouseDown {
                        widget: Some(surface.id.clone()),
                        button,
                        position,
                        modifiers,
                    }];
                }

                // Track click → page forward or back. For vertical,
                // "before" = above thumb; for horizontal, "before" =
                // left of thumb. When inverted, the direction flips.
                let max_offset = sb.total_items.saturating_sub(sb.visible_items);
                let before_thumb = match sb.axis {
                    ScrollAxis::Vertical => position.y < sb.thumb_bounds.y,
                    ScrollAxis::Horizontal => position.x < sb.thumb_bounds.x,
                };
                let page_back = if sb.inverted {
                    !before_thumb
                } else {
                    before_thumb
                };
                let new_offset = if page_back {
                    sb.scroll_offset.saturating_sub(sb.visible_items)
                } else {
                    (sb.scroll_offset + sb.visible_items).min(max_offset)
                };
                return vec![UiEvent::ScrollOffsetChanged {
                    widget: surface.id.clone(),
                    new_offset,
                }];
            }
        }

        // Case 5: Check text regions before falling through to body click.
        // Walk last-to-first so the topmost-painted region wins on overlap.
        for tr in text_regions.iter().rev() {
            if tr.bounds.contains(position) {
                drag.begin(DragTarget::TextSelection {
                    region: tr.id.clone(),
                    anchor: position,
                });
                return vec![UiEvent::MouseDown {
                    widget: Some(tr.id.clone()),
                    button,
                    position,
                    modifiers,
                }];
            }
        }

        // Case 6: body click (not on scrollbar, not on text region).
        return vec![UiEvent::MouseDown {
            widget: Some(surface.id.clone()),
            button,
            position,
            modifiers,
        }];
    }

    // No scroll surface hit. Still check standalone text regions
    // (not nested inside any scroll surface).
    for tr in text_regions.iter().rev() {
        if tr.bounds.contains(position) {
            drag.begin(DragTarget::TextSelection {
                region: tr.id.clone(),
                anchor: position,
            });
            return vec![UiEvent::MouseDown {
                widget: Some(tr.id.clone()),
                button,
                position,
                modifiers,
            }];
        }
    }

    // Case 7: no surface or region matched.
    vec![UiEvent::MouseDown {
        widget: None,
        button,
        position,
        modifiers,
    }]
}

// ─── One-shot pointer routing ──────────────────────────────────────────────

/// The `MouseDown` / `MouseMoved` / `MouseUp` routing sequence every
/// runner (`gtk::run`, `gtk::testing`, `macos::run`, `win::run`,
/// `tui::backend`) carried inline as its own copy: call the matching
/// `dispatch_*` function above, and — on `MouseDown` — additionally track
/// the newly-focused text region so Ctrl-A can resolve it even before the
/// first drag-move fires a `TextSelectionChanged` event. Any other
/// `UiEvent` variant passes straight through unchanged (a one-element
/// vec), so a caller can route every event through this function
/// unconditionally instead of matching the variant itself first.
///
/// `widget` on the incoming `MouseDown`/`MouseUp` is ignored — every
/// `dispatch_*` function recomputes it from `stack`/the registered
/// regions, exactly as the 7 inlined copies this replaces did (none of
/// them read the field either).
///
/// # Scroll surfaces
///
/// Always passes `&[]` for [`dispatch_click`]'s `scroll_surfaces` — every
/// one of the 7 copies did the same, because none of the four runners
/// (GTK, macOS, Windows, TUI) register a [`ScrollSurface`] anywhere in
/// the tree today. That makes the scrollbar-click arbitration above
/// (`ScrollSurface`/[`SurfaceScrollbar`]) unreachable *from quadraui's own
/// runners* — but not dead: `vimcode` (this crate's primary consumer)
/// calls [`dispatch_click`] directly with its own non-empty
/// `scroll_surfaces` list (`src/app.rs`), bypassing quadraui's runners
/// entirely, so the parameter is load-bearing for that caller even though
/// no in-tree caller populates it. Wiring per-frame `ScrollSurface`
/// registration into the four runners (so `dispatch_click`'s scrollbar
/// path becomes reachable in-tree too) is a real per-backend feature, not
/// a dedup — left as follow-up work, not folded into this consolidation.
///
/// `#[cfg(...)]`-gated to mirror `crate::text_selection`'s own gate — this
/// module is compiled unconditionally (`dispatch` has no toolkit
/// dependency of its own) but `TextSelectionState` only exists when at
/// least one backend that embeds it is being built.
#[cfg(any(
    feature = "tui",
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
pub(crate) fn route_pointer(
    stack: &ModalStack,
    drag: &mut DragState,
    text_state: &mut crate::text_selection::TextSelectionState,
    event: UiEvent,
) -> Vec<UiEvent> {
    match event {
        UiEvent::MouseDown {
            button,
            position,
            modifiers,
            ..
        } => {
            let events = dispatch_click(
                stack,
                &[],
                &text_state.text_regions,
                drag,
                position,
                button,
                modifiers,
            );
            if let Some(DragTarget::TextSelection { region, .. }) = drag.target() {
                text_state.track_focused_text_region(region.clone());
            }
            events
        }
        UiEvent::MouseMoved { position, buttons } => dispatch_mouse_drag(drag, position, buttons),
        UiEvent::MouseUp {
            button, position, ..
        } => dispatch_mouse_up(stack, drag, position, button),
        other => vec![other],
    }
}

// ─── Double-click synthesis ────────────────────────────────────────────────
//
// Backend-agnostic: relocated here from `tui::events` so
// `macos::run` can reuse it without pulling in the `tui` feature. TUI's
// `TuiBackend` batches translated events and calls
// [`DoubleClickDetector::process`] on the whole slice each poll; macOS
// dispatches synchronously per `NSEvent`, so `macos::backend::MacBackend`
// wraps a single event in a one-element array before calling `process`.

use std::time::{Duration, Instant};

const DOUBLE_CLICK_MS: u64 = 400;
/// Tuned for TUI's **character-cell** coordinate grid, where adjacent
/// cells are a whole unit apart — a 1.5-cell tolerance comfortably
/// covers "same cell" while rejecting "next cell over". Backends whose
/// `MouseDown` positions are in a different unit (e.g. macOS's
/// point-precision `NSEvent` coordinates) must not inherit this value;
/// see [`DoubleClickDetector::with_radius`] and
/// `quadraui/docs/LESSONS.md`'s "No hardcoded px / cell / DIP
/// constants" rule — constants belong on the backend, not shared code.
const DOUBLE_CLICK_RADIUS: f32 = 1.5;

/// Detects double-clicks from repeated `MouseDown` events within a
/// time window at the same position. Stateful — lives on the backend
/// (`TuiBackend::double_click`, `MacBackend::double_click`).
pub struct DoubleClickDetector {
    last_click_time: Option<Instant>,
    last_click_pos: Point,
    last_click_button: MouseButton,
    /// Position tolerance, in whatever unit the caller's `MouseDown`
    /// positions use. Defaults to [`DOUBLE_CLICK_RADIUS`] (TUI's
    /// character-cell tolerance) via [`Self::new`] /
    /// [`Self::default`]; callers in a different coordinate system
    /// should use [`Self::with_radius`] instead.
    radius: f32,
}

impl Default for DoubleClickDetector {
    fn default() -> Self {
        Self {
            last_click_time: None,
            last_click_pos: Point::default(),
            last_click_button: MouseButton::default(),
            radius: DOUBLE_CLICK_RADIUS,
        }
    }
}

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

    /// Same detector, but with a caller-supplied position-tolerance
    /// `radius` instead of [`DOUBLE_CLICK_RADIUS`]. Use this whenever
    /// the consumer's `MouseDown` positions aren't TUI's character-cell
    /// grid — e.g. `MacBackend` wraps native `NSEvent` coordinates,
    /// which are point-precision, so a 1.5-point tolerance (the raw
    /// cell-tuned constant) is far tighter than two real clicks can
    /// reliably land within.
    pub fn with_radius(radius: f32) -> Self {
        Self {
            radius,
            ..Self::default()
        }
    }

    /// Process a batch of translated events. Replaces `MouseDown` with
    /// `DoubleClick` when the same button clicks at the same position
    /// within the time window.
    pub fn process(&mut self, events: &mut [UiEvent]) {
        let now = Instant::now();
        for ev in events.iter_mut() {
            if let UiEvent::MouseDown {
                button, position, ..
            } = ev
            {
                let is_double = self
                    .last_click_time
                    .map(|t| now.duration_since(t) < Duration::from_millis(DOUBLE_CLICK_MS))
                    .unwrap_or(false)
                    && *button == self.last_click_button
                    && (position.x - self.last_click_pos.x).abs() <= self.radius
                    && (position.y - self.last_click_pos.y).abs() <= self.radius;

                if is_double {
                    *ev = UiEvent::DoubleClick {
                        widget: None,
                        position: *position,
                    };
                    self.last_click_time = None;
                } else {
                    self.last_click_time = Some(now);
                    self.last_click_pos = *position;
                    self.last_click_button = *button;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Rect;
    use crate::types::WidgetId;

    fn id(s: &str) -> WidgetId {
        WidgetId::new(s)
    }

    fn pt(x: f32, y: f32) -> Point {
        Point { x, y }
    }

    fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
        Rect {
            x,
            y,
            width: w,
            height: h,
        }
    }

    #[test]
    fn click_inside_modal_emits_single_mousedown_with_widget() {
        let mut stack = ModalStack::new();
        stack.push(id("palette"), rect(10.0, 10.0, 100.0, 100.0));
        let events = dispatch_mouse_down(
            &stack,
            pt(50.0, 50.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::MouseDown { widget, button, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("palette"));
                assert_eq!(*button, MouseButton::Left);
            }
            _ => panic!("expected MouseDown, got {:?}", events[0]),
        }
    }

    #[test]
    fn click_outside_open_modal_dismisses_topmost() {
        let mut stack = ModalStack::new();
        stack.push(id("palette"), rect(10.0, 10.0, 50.0, 50.0));
        // Click well outside the palette's bounds.
        let events = dispatch_mouse_down(
            &stack,
            pt(500.0, 500.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 2);
        // First event: MouseDown with widget None (backdrop click).
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown { widget: None, .. }
        ));
        // Second event: palette Closed.
        match &events[1] {
            UiEvent::Palette(wid, PaletteEvent::Closed) => {
                assert_eq!(wid, &id("palette"));
            }
            _ => panic!("expected Palette::Closed, got {:?}", events[1]),
        }
    }

    #[test]
    fn click_when_no_modal_open_emits_single_mousedown_with_no_widget() {
        let stack = ModalStack::new();
        let events = dispatch_mouse_down(
            &stack,
            pt(100.0, 100.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown { widget: None, .. }
        ));
    }

    #[test]
    fn stacked_modals_click_inside_top_targets_top() {
        // Palette open; then a dialog on top of it. Click in the
        // overlap region should target the dialog, not the palette.
        let mut stack = ModalStack::new();
        stack.push(id("palette"), rect(0.0, 0.0, 200.0, 200.0));
        stack.push(id("dialog"), rect(50.0, 50.0, 100.0, 100.0));
        let events = dispatch_mouse_down(
            &stack,
            pt(100.0, 100.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        match &events[0] {
            UiEvent::MouseDown { widget, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("dialog"));
            }
            _ => panic!(),
        }
    }

    #[test]
    fn stacked_modals_click_inside_lower_targets_lower() {
        // Click lands in palette's bounds but outside the dialog on top.
        // The lower-modal id is what should be reported — the click is
        // still inside a modal, so no backdrop-dismiss.
        let mut stack = ModalStack::new();
        stack.push(id("palette"), rect(0.0, 0.0, 200.0, 200.0));
        stack.push(id("dialog"), rect(50.0, 50.0, 100.0, 100.0));
        let events = dispatch_mouse_down(
            &stack,
            pt(10.0, 10.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::MouseDown { widget, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("palette"));
            }
            _ => panic!(),
        }
    }

    // ── Drag tests ────────────────────────────────────────────────────

    fn buttons_mask_left() -> crate::event::ButtonMask {
        crate::event::ButtonMask {
            left: true,
            ..Default::default()
        }
    }

    #[test]
    fn drag_state_begin_and_end() {
        let mut drag = DragState::new();
        assert!(!drag.is_active());
        drag.begin(DragTarget::ScrollbarY {
            widget: id("picker"),
            track_start: 100.0,
            track_length: 200.0,
            thumb_length: 16.0,
            max_scroll: 40,
            grab_offset: 0.0,
            inverted: false,
        });
        assert!(drag.is_active());
        match drag.target().unwrap() {
            DragTarget::ScrollbarY { widget, .. } => assert_eq!(widget, &id("picker")),
            DragTarget::ScrollbarX { .. } => panic!("expected ScrollbarY"),
            DragTarget::TextSelection { .. } => panic!("expected ScrollbarY"),
            DragTarget::SplitDivider { .. } => panic!("expected ScrollbarY"),
        }
        drag.end();
        assert!(!drag.is_active());
        assert!(drag.target().is_none());
    }

    #[test]
    fn dispatch_mouse_drag_without_drag_emits_only_moved() {
        let drag = DragState::new();
        let events = dispatch_mouse_drag(&drag, pt(50.0, 50.0), buttons_mask_left());
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
    }

    #[test]
    fn dispatch_mouse_drag_with_scrollbar_emits_scroll_offset_changed() {
        // Track 80 units from y=100; 100 items, viewport shows 20.
        // thumb_ratio = 20/100 = 0.2 → thumb_length = 16
        // effective_track = 64; max_scroll = 80
        // Mouse at y=100+32 (halfway through effective_track) → offset 40.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("picker"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 0.0,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(500.0, 132.0), buttons_mask_left());
        assert_eq!(events.len(), 2);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
        match &events[1] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget, &id("picker"));
                assert_eq!(*new_offset, 40);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn dispatch_mouse_drag_clamps_above_and_below_track() {
        // Same geometry as above: max_scroll = 80, effective_track = 64.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("p"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 0.0,
            inverted: false,
        });
        // Above track: offset = 0.
        let events = dispatch_mouse_drag(&drag, pt(0.0, 50.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => {
                assert_eq!(*new_offset, 0);
            }
            _ => panic!(),
        }
        // Below effective track: clamped to max_scroll = 80.
        let events = dispatch_mouse_drag(&drag, pt(0.0, 500.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => {
                assert_eq!(*new_offset, 80);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn dispatch_mouse_drag_with_zero_track_does_not_crash_or_emit() {
        // Pathological input — no track. Should emit only MouseMoved.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("p"),
            track_start: 0.0,
            track_length: 0.0,
            thumb_length: 0.0,
            max_scroll: 90,
            grab_offset: 0.0,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(0.0, 0.0), buttons_mask_left());
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
    }

    #[test]
    fn dispatch_mouse_up_clears_drag_state() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("p"),
            track_start: 0.0,
            track_length: 10.0,
            thumb_length: 5.0,
            max_scroll: 10,
            grab_offset: 0.0,
            inverted: false,
        });
        let stack = ModalStack::new();
        let events = dispatch_mouse_up(&stack, &mut drag, pt(5.0, 5.0), MouseButton::Left);
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], UiEvent::MouseUp { .. }));
        assert!(!drag.is_active());
    }

    // ── SplitDivider drag tests ─────────────────────────────────────

    #[test]
    fn split_divider_drag_horizontal_computes_ratio() {
        // Parent bounds 41 wide starting at x=0 (matches a SplitTree
        // divider's axis_start/axis_size for a Horizontal split).
        let mut drag = DragState::new();
        drag.begin(DragTarget::SplitDivider {
            tree: id("tree"),
            split_index: 0,
            direction: SplitDirection::Horizontal,
            axis_start: 0.0,
            axis_size: 40.0,
        });
        // Cursor at x=30 → ratio 0.75.
        let events = dispatch_mouse_drag(&drag, pt(30.0, 5.0), buttons_mask_left());
        assert_eq!(events.len(), 2);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
        match &events[1] {
            UiEvent::SplitDividerDragged {
                tree,
                split_index,
                new_ratio,
            } => {
                assert_eq!(tree, &id("tree"));
                assert_eq!(*split_index, 0);
                assert!((new_ratio - 0.75).abs() < 0.001);
            }
            other => panic!("expected SplitDividerDragged, got {:?}", other),
        }
    }

    #[test]
    fn split_divider_drag_vertical_reads_y_axis() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::SplitDivider {
            tree: id("tree"),
            split_index: 2,
            direction: SplitDirection::Vertical,
            axis_start: 100.0,
            axis_size: 50.0,
        });
        // Cursor at y=125 → (125-100)/50 = 0.5. x is irrelevant for Vertical.
        let events = dispatch_mouse_drag(&drag, pt(999.0, 125.0), buttons_mask_left());
        match &events[1] {
            UiEvent::SplitDividerDragged {
                split_index,
                new_ratio,
                ..
            } => {
                assert_eq!(*split_index, 2);
                assert!((new_ratio - 0.5).abs() < 0.001);
            }
            other => panic!("expected SplitDividerDragged, got {:?}", other),
        }
    }

    #[test]
    fn split_divider_drag_clamps_beyond_bounds() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::SplitDivider {
            tree: id("tree"),
            split_index: 0,
            direction: SplitDirection::Horizontal,
            axis_start: 0.0,
            axis_size: 40.0,
        });
        // Cursor well before axis_start → clamps to 0.0.
        let events = dispatch_mouse_drag(&drag, pt(-100.0, 5.0), buttons_mask_left());
        match &events[1] {
            UiEvent::SplitDividerDragged { new_ratio, .. } => assert_eq!(*new_ratio, 0.0),
            other => panic!("expected SplitDividerDragged, got {:?}", other),
        }
        // Cursor well past axis_start + axis_size → clamps to 1.0.
        let events = dispatch_mouse_drag(&drag, pt(1000.0, 5.0), buttons_mask_left());
        match &events[1] {
            UiEvent::SplitDividerDragged { new_ratio, .. } => assert_eq!(*new_ratio, 1.0),
            other => panic!("expected SplitDividerDragged, got {:?}", other),
        }
    }

    #[test]
    fn split_divider_drag_with_zero_axis_size_does_not_crash_or_emit() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::SplitDivider {
            tree: id("tree"),
            split_index: 0,
            direction: SplitDirection::Horizontal,
            axis_start: 0.0,
            axis_size: 0.0,
        });
        let events = dispatch_mouse_drag(&drag, pt(5.0, 5.0), buttons_mask_left());
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
    }

    #[test]
    fn split_divider_drag_ends_on_mouse_up() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::SplitDivider {
            tree: id("tree"),
            split_index: 0,
            direction: SplitDirection::Horizontal,
            axis_start: 0.0,
            axis_size: 40.0,
        });
        let stack = ModalStack::new();
        dispatch_mouse_up(&stack, &mut drag, pt(5.0, 5.0), MouseButton::Left);
        assert!(!drag.is_active());
    }

    #[test]
    fn dispatch_mouse_drag_with_grab_offset_keeps_thumb_relative_to_cursor() {
        // Same geometry as the basic test: track 80 from y=100, viewport 20,
        // total 100 → effective_track 64, max_scroll 80. With grab_offset=8
        // the cursor at y=140 sits 8 units below the thumb's top, so the
        // math sees effective y=132 → rel=32/64=0.5 → offset 40 (matches
        // the no-grab base test where cursor was at y=132 directly).
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("p"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 8.0,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(500.0, 140.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 40),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn dispatch_mouse_drag_horizontal_scrollbar() {
        // Mirror of the basic Y-axis test on the X axis. Track 80 from x=100;
        // 100 cols total, viewport shows 20. thumb_length=16, effective=64,
        // max_scroll=80. Cursor at x=132 (halfway through effective) → 40.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarX {
            widget: id("editor:hsb"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 0.0,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(132.0, 500.0), buttons_mask_left());
        assert_eq!(events.len(), 2);
        match &events[1] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget, &id("editor:hsb"));
                assert_eq!(*new_offset, 40);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn dispatch_mouse_drag_horizontal_grab_offset_preserves_relative() {
        // Same geometry as horizontal_scrollbar test; with grab_offset=8 the
        // cursor at x=140 maps to effective x=132 → 40.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarX {
            widget: id("editor:hsb"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 8.0,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(140.0, 500.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 40),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn painted_thumb_length_controls_effective_track() {
        // Track 400px, 20 visible out of 4000 total.
        // Painted thumb = 20px → effective = 380; max_scroll = 3980.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarX {
            widget: id("editor:hsb"),
            track_start: 100.0,
            track_length: 400.0,
            thumb_length: 20.0,
            max_scroll: 3980,
            grab_offset: 0.0,
            inverted: false,
        });
        // Cursor at x = 100 + 380 (end of effective track) → ratio 1.0 → 3980
        let events = dispatch_mouse_drag(&drag, pt(480.0, 0.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 3980),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
        // Halfway: x = 100 + 190 = 290 → ratio 0.5 → 1990
        let events = dispatch_mouse_drag(&drag, pt(290.0, 0.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 1990),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    // ── Round-trip: fit_thumb ↔ dispatch agreement ─────────────────
    //
    // The rasteriser calls `fit_thumb` to position the thumb. The
    // dispatcher inverts that position back to a scroll offset.
    // These tests prove the two agree for every scroll offset
    // including 0 and max_scroll.

    fn assert_round_trip(
        label: &str,
        track_start: f32,
        track_length: f32,
        total: usize,
        visible: usize,
        min_thumb: f32,
        scroll: usize,
    ) {
        use crate::primitives::scrollbar::fit_thumb;
        let max_scroll = total.saturating_sub(visible);
        let (thumb_start, thumb_len) = fit_thumb(
            scroll as f32,
            total as f32,
            visible as f32,
            track_length,
            min_thumb,
        );
        let grab = thumb_len / 2.0;
        let cursor_x = track_start + thumb_start + grab;
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarX {
            widget: id("sb"),
            track_start,
            track_length,
            thumb_length: thumb_len,
            max_scroll,
            grab_offset: grab,
            inverted: false,
        });
        let events = dispatch_mouse_drag(&drag, pt(cursor_x, 0.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => {
                assert_eq!(
                    *new_offset, scroll,
                    "{label}: expected offset {scroll}, got {new_offset}"
                );
            }
            other => panic!("{label}: expected ScrollOffsetChanged, got {other:?}"),
        }
    }

    #[test]
    fn round_trip_vimcode_numbers_at_max() {
        assert_round_trip("3609 max", 50.0, 800.0, 3609, 137, 20.0, 3609 - 137);
    }

    #[test]
    fn round_trip_vimcode_numbers_at_zero() {
        assert_round_trip("3609 zero", 50.0, 800.0, 3609, 137, 20.0, 0);
    }

    #[test]
    fn round_trip_vimcode_numbers_at_midpoint() {
        assert_round_trip("3609 mid", 50.0, 800.0, 3609, 137, 20.0, 1736);
    }

    #[test]
    fn round_trip_small_content_at_max() {
        assert_round_trip("small max", 0.0, 100.0, 200, 50, 10.0, 150);
    }

    #[test]
    fn round_trip_large_min_thumb_at_max() {
        // thumb dominates: min_thumb = 40 on 100px track → effective = 60
        assert_round_trip("big thumb max", 0.0, 100.0, 5000, 50, 40.0, 4950);
    }

    #[test]
    fn round_trip_cursor_past_track_end_reaches_max() {
        use crate::primitives::scrollbar::fit_thumb;
        let track_start = 50.0;
        let track_length = 800.0;
        let total = 3609_usize;
        let visible = 137_usize;
        let max_scroll = total - visible;
        let (_, thumb_len) = fit_thumb(0.0, total as f32, visible as f32, track_length, 20.0);
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarX {
            widget: id("sb"),
            track_start,
            track_length,
            thumb_length: thumb_len,
            max_scroll,
            grab_offset: 0.0,
            inverted: false,
        });
        // Cursor WAY past track end — must still clamp to max_scroll
        let events = dispatch_mouse_drag(
            &drag,
            pt(track_start + track_length + 200.0, 0.0),
            buttons_mask_left(),
        );
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => {
                assert_eq!(*new_offset, max_scroll);
            }
            other => panic!("expected ScrollOffsetChanged, got {other:?}"),
        }
    }

    #[test]
    fn dispatch_mouse_up_carries_modal_widget_if_over() {
        let mut stack = ModalStack::new();
        stack.push(id("palette"), rect(0.0, 0.0, 100.0, 100.0));
        let mut drag = DragState::new();
        let events = dispatch_mouse_up(&stack, &mut drag, pt(50.0, 50.0), MouseButton::Left);
        match &events[0] {
            UiEvent::MouseUp { widget, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("palette"));
            }
            _ => panic!(),
        }
    }

    // ── Scroll dispatch tests ─────────────────────────────────────────

    fn delta(dy: f32) -> ScrollDelta {
        ScrollDelta::new(0.0, dy)
    }

    #[test]
    fn scroll_inside_modal_routes_to_modal() {
        let mut stack = ModalStack::new();
        stack.push(id("picker"), rect(10.0, 10.0, 100.0, 100.0));
        let events = dispatch_scroll(&stack, &[], pt(50.0, 50.0), delta(-3.0));
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::Scroll {
                widget, delta: d, ..
            } => {
                assert_eq!(widget.as_ref().unwrap(), &id("picker"));
                assert_eq!(d.y, -3.0);
            }
            other => panic!("expected Scroll, got {:?}", other),
        }
    }

    #[test]
    fn scroll_outside_open_modal_is_swallowed() {
        let mut stack = ModalStack::new();
        stack.push(id("dialog"), rect(10.0, 10.0, 50.0, 50.0));
        let events = dispatch_scroll(&stack, &[], pt(500.0, 500.0), delta(-1.0));
        assert!(events.is_empty(), "scroll behind modal should be swallowed");
    }

    #[test]
    fn scroll_routes_to_topmost_surface() {
        let stack = ModalStack::new();
        let surfaces = vec![
            ScrollSurface {
                id: id("editor"),
                bounds: rect(0.0, 0.0, 200.0, 200.0),
                scrollbar: None,
            },
            ScrollSurface {
                id: id("sidebar"),
                bounds: rect(0.0, 0.0, 50.0, 200.0),
                scrollbar: None,
            },
        ];
        // Point (25, 100) is inside both surfaces. Sidebar was pushed
        // last (painted on top) → wins.
        let events = dispatch_scroll(&stack, &surfaces, pt(25.0, 100.0), delta(-1.0));
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::Scroll { widget, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("sidebar"));
            }
            other => panic!("expected Scroll, got {:?}", other),
        }
    }

    #[test]
    fn scroll_on_non_overlapping_surface() {
        let stack = ModalStack::new();
        let surfaces = vec![
            ScrollSurface {
                id: id("editor"),
                bounds: rect(50.0, 0.0, 150.0, 200.0),
                scrollbar: None,
            },
            ScrollSurface {
                id: id("sidebar"),
                bounds: rect(0.0, 0.0, 50.0, 200.0),
                scrollbar: None,
            },
        ];
        // Point (100, 100) is inside editor only.
        let events = dispatch_scroll(&stack, &surfaces, pt(100.0, 100.0), delta(2.0));
        match &events[0] {
            UiEvent::Scroll { widget, .. } => {
                assert_eq!(widget.as_ref().unwrap(), &id("editor"));
            }
            other => panic!("expected Scroll, got {:?}", other),
        }
    }

    #[test]
    fn scroll_with_no_surfaces_emits_no_widget() {
        let stack = ModalStack::new();
        let events = dispatch_scroll(&stack, &[], pt(50.0, 50.0), delta(-1.0));
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::Scroll { widget, .. } => {
                assert!(widget.is_none());
            }
            other => panic!("expected Scroll, got {:?}", other),
        }
    }

    #[test]
    fn scroll_outside_all_surfaces_emits_no_widget() {
        let stack = ModalStack::new();
        let surfaces = vec![ScrollSurface {
            id: id("panel"),
            bounds: rect(0.0, 0.0, 50.0, 50.0),
            scrollbar: None,
        }];
        let events = dispatch_scroll(&stack, &surfaces, pt(100.0, 100.0), delta(-1.0));
        match &events[0] {
            UiEvent::Scroll { widget, .. } => {
                assert!(widget.is_none());
            }
            other => panic!("expected Scroll, got {:?}", other),
        }
    }

    // ── dispatch_click tests ──────────────────────────────────────────

    fn surface_with_scrollbar() -> ScrollSurface {
        ScrollSurface {
            id: id("log"),
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            scrollbar: Some(SurfaceScrollbar {
                axis: ScrollAxis::Vertical,
                track_bounds: rect(39.0, 0.0, 1.0, 30.0),
                thumb_bounds: rect(39.0, 20.0, 1.0, 8.0),
                total_items: 100,
                visible_items: 30,
                scroll_offset: 60,
                inverted: false,
            }),
        }
    }

    #[test]
    fn click_thumb_starts_drag() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_scrollbar()];
        let mut drag = DragState::new();
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 22.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown {
                widget: Some(w),
                ..
            } if w.as_str() == "log"
        ));
        assert!(drag.is_active());
        match drag.target().unwrap() {
            DragTarget::ScrollbarY {
                widget, max_scroll, ..
            } => {
                assert_eq!(widget.as_str(), "log");
                assert_eq!(*max_scroll, 70);
            }
            other => panic!("expected ScrollbarY, got {:?}", other),
        }
    }

    #[test]
    fn click_track_before_pages_up() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_scrollbar()];
        let mut drag = DragState::new();
        // Click above the thumb (thumb starts at y=20).
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 5.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget.as_str(), "log");
                // scroll_offset=60, page up by visible_items=30 → 30.
                assert_eq!(*new_offset, 30);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
        assert!(!drag.is_active());
    }

    #[test]
    fn click_track_after_pages_down() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_scrollbar()];
        let mut drag = DragState::new();
        // Click below the thumb (thumb ends at y=28).
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 29.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget.as_str(), "log");
                // scroll_offset=60, page down by 30, max=70 → 70.
                assert_eq!(*new_offset, 70);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn click_body_not_scrollbar_emits_mousedown() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_scrollbar()];
        let mut drag = DragState::new();
        // Click in the body area (not on the scrollbar gutter).
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(10.0, 10.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown {
                widget: Some(w),
                ..
            } if w.as_str() == "log"
        ));
        assert!(!drag.is_active());
    }

    #[test]
    fn click_no_surfaces_emits_no_widget() {
        let stack = ModalStack::new();
        let mut drag = DragState::new();
        let events = dispatch_click(
            &stack,
            &[],
            &[],
            &mut drag,
            pt(50.0, 50.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown { widget: None, .. }
        ));
    }

    #[test]
    fn click_modal_takes_priority_over_surfaces() {
        let mut stack = ModalStack::new();
        stack.push(id("dialog"), rect(0.0, 0.0, 100.0, 100.0));
        let surfaces = vec![surface_with_scrollbar()];
        let mut drag = DragState::new();
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 22.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        // Should route to the modal, not the scrollbar.
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown {
                widget: Some(w),
                ..
            } if w.as_str() == "dialog"
        ));
        assert!(!drag.is_active());
    }

    // ── Inverted scrollbar tests ─────────────────────────────────────

    #[test]
    fn inverted_drag_flips_offset() {
        // Same geometry as the basic drag test: track 80 from y=100,
        // viewport 20, total 100. effective_track=64, max_scroll=80.
        // Normal: cursor at y=132 (halfway) → offset 40.
        // Inverted: same position → offset 80 - 40 = 40… wait:
        //   rel = 32/64 = 0.5, inverted → 1.0 - 0.5 = 0.5 → 40.
        // To see the flip, use the track top: y=100 → rel=0, inv→1.0 → 80.
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("term"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 0.0,
            inverted: true,
        });
        // Cursor at track top → normal offset 0, inverted offset 80.
        let events = dispatch_mouse_drag(&drag, pt(0.0, 100.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 80),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
        // Cursor at track bottom → normal offset 80, inverted offset 0.
        let events = dispatch_mouse_drag(&drag, pt(0.0, 500.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 0),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn inverted_drag_halfway_matches_non_inverted() {
        // At the exact midpoint, both normal and inverted produce the
        // same offset (symmetry check).
        let mut drag = DragState::new();
        drag.begin(DragTarget::ScrollbarY {
            widget: id("term"),
            track_start: 100.0,
            track_length: 80.0,
            thumb_length: 16.0,
            max_scroll: 80,
            grab_offset: 0.0,
            inverted: true,
        });
        let events = dispatch_mouse_drag(&drag, pt(0.0, 132.0), buttons_mask_left());
        match &events[1] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 40),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    fn surface_with_inverted_scrollbar() -> ScrollSurface {
        ScrollSurface {
            id: id("term"),
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            scrollbar: Some(SurfaceScrollbar {
                axis: ScrollAxis::Vertical,
                track_bounds: rect(39.0, 0.0, 1.0, 30.0),
                thumb_bounds: rect(39.0, 20.0, 1.0, 8.0),
                total_items: 100,
                visible_items: 30,
                scroll_offset: 60,
                inverted: true,
            }),
        }
    }

    #[test]
    fn inverted_thumb_click_propagates_flag() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_inverted_scrollbar()];
        let mut drag = DragState::new();
        dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 22.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert!(drag.is_active());
        match drag.target().unwrap() {
            DragTarget::ScrollbarY { inverted, .. } => assert!(*inverted),
            DragTarget::ScrollbarX { .. }
            | DragTarget::TextSelection { .. }
            | DragTarget::SplitDivider { .. } => {
                panic!("expected ScrollbarY")
            }
        }
    }

    #[test]
    fn inverted_track_click_flips_page_direction() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_inverted_scrollbar()];
        let mut drag = DragState::new();
        // Click ABOVE the thumb (y=5 < thumb y=20).
        // Normal: page up → offset 60 - 30 = 30.
        // Inverted: above thumb pages FORWARD → offset 60 + 30 = 70 (capped at 70).
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 5.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        match &events[0] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 70),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }

        // Click BELOW the thumb (y=29 > thumb bottom y=28).
        // Normal: page down → offset 60 + 30 = 70.
        // Inverted: below thumb pages BACK → offset 60 - 30 = 30.
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(39.5, 29.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        match &events[0] {
            UiEvent::ScrollOffsetChanged { new_offset, .. } => assert_eq!(*new_offset, 30),
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    // ── Horizontal scroll surface tests ──────────────────────────────

    fn surface_with_h_scrollbar() -> ScrollSurface {
        // Horizontal scrollbar at the bottom of a 400×300 surface.
        // Track spans x=0..400 at y=296, height=4.
        // Thumb at x=50..90 (40px wide).
        // 2000 total cols, 200 visible, offset 250.
        ScrollSurface {
            id: id("editor"),
            bounds: rect(0.0, 0.0, 400.0, 300.0),
            scrollbar: Some(SurfaceScrollbar {
                axis: ScrollAxis::Horizontal,
                track_bounds: rect(0.0, 296.0, 400.0, 4.0),
                thumb_bounds: rect(50.0, 296.0, 40.0, 4.0),
                total_items: 2000,
                visible_items: 200,
                scroll_offset: 250,
                inverted: false,
            }),
        }
    }

    #[test]
    fn h_scrollbar_thumb_click_starts_scrollbar_x_drag() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_h_scrollbar()];
        let mut drag = DragState::new();
        // Click on the thumb at x=60, y=297
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(60.0, 297.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(
            matches!(&events[0], UiEvent::MouseDown { widget: Some(w), .. } if w.as_str() == "editor")
        );
        assert!(drag.is_active());
        match drag.target().unwrap() {
            DragTarget::ScrollbarX {
                widget,
                track_start,
                track_length,
                thumb_length,
                max_scroll,
                grab_offset,
                ..
            } => {
                assert_eq!(widget.as_str(), "editor");
                assert_eq!(*track_start, 0.0);
                assert_eq!(*track_length, 400.0);
                assert_eq!(*thumb_length, 40.0);
                assert_eq!(*max_scroll, 1800);
                assert!(*grab_offset > 9.0 && *grab_offset < 11.0); // 60.0 - 50.0 = 10.0
            }
            DragTarget::ScrollbarY { .. }
            | DragTarget::TextSelection { .. }
            | DragTarget::SplitDivider { .. } => {
                panic!("expected ScrollbarX")
            }
        }
    }

    #[test]
    fn h_scrollbar_track_click_left_of_thumb_pages_back() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_h_scrollbar()];
        let mut drag = DragState::new();
        // Click left of thumb (x=10 < thumb x=50)
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(10.0, 297.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        match &events[0] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget.as_str(), "editor");
                // page back: 250 - 200 = 50
                assert_eq!(*new_offset, 50);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn h_scrollbar_track_click_right_of_thumb_pages_forward() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_h_scrollbar()];
        let mut drag = DragState::new();
        // Click right of thumb (x=200 > thumb right x=90)
        let events = dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(200.0, 297.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        match &events[0] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget.as_str(), "editor");
                // page forward: 250 + 200 = 450
                assert_eq!(*new_offset, 450);
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    #[test]
    fn h_scrollbar_drag_produces_scroll_offset() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_h_scrollbar()];
        let mut drag = DragState::new();
        // Click thumb to start drag
        dispatch_click(
            &stack,
            &surfaces,
            &[],
            &mut drag,
            pt(60.0, 297.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert!(drag.is_active());
        // Drag cursor to x=370 (near track end)
        let events = dispatch_mouse_drag(&drag, pt(370.0, 297.0), buttons_mask_left());
        assert_eq!(events.len(), 2);
        match &events[1] {
            UiEvent::ScrollOffsetChanged { widget, new_offset } => {
                assert_eq!(widget.as_str(), "editor");
                assert_eq!(*new_offset, 1800); // max_scroll
            }
            other => panic!("expected ScrollOffsetChanged, got {:?}", other),
        }
    }

    // ── TextRegion / text-selection tests ─────────────────────────────

    #[test]
    fn click_text_region_starts_text_selection_drag() {
        let stack = ModalStack::new();
        let mut drag = DragState::new();
        let text_regions = vec![TextRegion {
            id: id("log:body"),
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            lines: vec![],
        }];
        let events = dispatch_click(
            &stack,
            &[],
            &text_regions,
            &mut drag,
            pt(10.0, 5.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown {
                widget: Some(w), ..
            } if w.as_str() == "log:body"
        ));
        assert!(drag.is_active());
        match drag.target().unwrap() {
            DragTarget::TextSelection { region, anchor } => {
                assert_eq!(region.as_str(), "log:body");
                assert_eq!(*anchor, pt(10.0, 5.0));
            }
            other => panic!("expected TextSelection, got {:?}", other),
        }
    }

    #[test]
    fn scrollbar_wins_over_text_region() {
        let stack = ModalStack::new();
        let surfaces = vec![surface_with_scrollbar()];
        let text_regions = vec![TextRegion {
            id: id("log:body"),
            // Covers the whole surface including the scrollbar column.
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            lines: vec![],
        }];
        let mut drag = DragState::new();
        // Click on scrollbar thumb (x=39.5, y=22) — scrollbar must win.
        dispatch_click(
            &stack,
            &surfaces,
            &text_regions,
            &mut drag,
            pt(39.5, 22.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert!(matches!(
            drag.target().unwrap(),
            DragTarget::ScrollbarY { .. }
        ));
    }

    #[test]
    fn text_region_wins_over_surface_body() {
        let stack = ModalStack::new();
        let surfaces = vec![ScrollSurface {
            id: id("log"),
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            scrollbar: None,
        }];
        let text_regions = vec![TextRegion {
            id: id("log:body"),
            bounds: rect(0.0, 0.0, 40.0, 30.0),
            lines: vec![],
        }];
        let mut drag = DragState::new();
        let events = dispatch_click(
            &stack,
            &surfaces,
            &text_regions,
            &mut drag,
            pt(10.0, 5.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown { widget: Some(w), .. } if w.as_str() == "log:body"
        ));
        assert!(matches!(
            drag.target().unwrap(),
            DragTarget::TextSelection { .. }
        ));
    }

    #[test]
    fn modal_wins_over_text_region() {
        let mut stack = ModalStack::new();
        stack.push(id("dialog"), rect(0.0, 0.0, 100.0, 100.0));
        let text_regions = vec![TextRegion {
            id: id("body"),
            bounds: rect(0.0, 0.0, 100.0, 100.0),
            lines: vec![],
        }];
        let mut drag = DragState::new();
        let events = dispatch_click(
            &stack,
            &[],
            &text_regions,
            &mut drag,
            pt(50.0, 50.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        // Modal wins — no TextSelection drag started.
        assert!(!drag.is_active());
        assert!(matches!(
            &events[0],
            UiEvent::MouseDown { widget: Some(w), .. } if w.as_str() == "dialog"
        ));
    }

    #[test]
    fn dispatch_mouse_drag_text_selection_emits_changed() {
        let mut drag = DragState::new();
        drag.begin(DragTarget::TextSelection {
            region: id("log:body"),
            anchor: pt(5.0, 2.0),
        });
        let events = dispatch_mouse_drag(&drag, pt(10.0, 5.0), buttons_mask_left());
        assert_eq!(events.len(), 2);
        assert!(matches!(events[0], UiEvent::MouseMoved { .. }));
        match &events[1] {
            UiEvent::TextSelectionChanged {
                region,
                anchor,
                focus,
            } => {
                assert_eq!(region.as_str(), "log:body");
                assert_eq!(*anchor, pt(5.0, 2.0));
                assert_eq!(*focus, pt(10.0, 5.0));
            }
            other => panic!("expected TextSelectionChanged, got {:?}", other),
        }
    }

    // ── text_selection_line_range tests ──────────────────────────────────

    #[test]
    fn line_range_empty_when_anchor_equals_focus() {
        let bounds = rect(0.0, 0.0, 40.0, 10.0);
        let ranges = text_selection_line_range(pt(5.0, 3.0), pt(5.0, 3.0), bounds);
        assert!(ranges.is_empty(), "collapsed selection must be empty");
    }

    #[test]
    fn line_range_single_row() {
        // Same row, anchor before focus.
        let bounds = rect(0.0, 0.0, 40.0, 10.0);
        let ranges = text_selection_line_range(pt(5.0, 3.0), pt(10.0, 3.0), bounds);
        // Half-open: 5..11 (focus_col 10 is inclusive → +1 = 11).
        assert_eq!(ranges, vec![(3, 5.0, 11.0)]);
    }

    #[test]
    fn line_range_single_row_reversed() {
        // Same row, focus before anchor — must swap to document order.
        let bounds = rect(0.0, 0.0, 40.0, 10.0);
        let ranges = text_selection_line_range(pt(10.0, 3.0), pt(5.0, 3.0), bounds);
        assert_eq!(ranges, vec![(3, 5.0, 11.0)]);
    }

    #[test]
    fn line_range_multi_row() {
        let bounds = rect(0.0, 0.0, 40.0, 10.0);
        // anchor at (2,1), focus at (5,3).
        let ranges = text_selection_line_range(pt(2.0, 1.0), pt(5.0, 3.0), bounds);
        // Row 1: 2..40 (start_col to region_end)
        // Row 2: 0..40 (full width)
        // Row 3: 0..6  (region_start to focus_col+1)
        assert_eq!(ranges, vec![(1, 2.0, 40.0), (2, 0.0, 40.0), (3, 0.0, 6.0)]);
    }

    #[test]
    fn line_range_multi_row_reversed() {
        let bounds = rect(0.0, 0.0, 40.0, 10.0);
        // Swap anchor and focus — must produce same result in document order.
        let ranges = text_selection_line_range(pt(5.0, 3.0), pt(2.0, 1.0), bounds);
        assert_eq!(ranges, vec![(1, 2.0, 40.0), (2, 0.0, 40.0), (3, 0.0, 6.0)]);
    }

    #[test]
    fn line_range_clamped_to_bounds() {
        // Region starts at x=5, y=2; anchor/focus way outside — must clamp.
        let bounds = rect(5.0, 2.0, 20.0, 5.0);
        let ranges = text_selection_line_range(pt(0.0, 0.0), pt(100.0, 100.0), bounds);
        // start row clamped to 2, end row clamped to 6 (2+5-1),
        // start_col clamped to 5, end_col clamped to 25.
        assert_eq!(
            ranges[0],
            (2, 5.0, 25.0),
            "first row: anchor clamped to region x"
        );
        assert_eq!(
            *ranges.last().unwrap(),
            (6, 5.0, 25.0),
            "last row: focus clamped to region end"
        );
        // All middle rows are full region width.
        for &(_, c_start, c_end) in &ranges[1..ranges.len() - 1] {
            assert_eq!(c_start, 5.0);
            assert_eq!(c_end, 25.0);
        }
    }

    // ── DoubleClickDetector tests ────────────────────────────────────

    fn mouse_down(x: f32, y: f32) -> UiEvent {
        UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(x, y),
            modifiers: Modifiers::default(),
        }
    }

    #[test]
    fn double_click_detected_on_same_position() {
        let mut det = DoubleClickDetector::new();
        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);
        assert!(matches!(events[0], UiEvent::MouseDown { .. }));

        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);
        assert!(
            matches!(events[0], UiEvent::DoubleClick { .. }),
            "second click at same position should be DoubleClick"
        );
    }

    #[test]
    fn no_double_click_at_different_position() {
        let mut det = DoubleClickDetector::new();
        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);

        let mut events = vec![mouse_down(20.0, 10.0)];
        det.process(&mut events);
        assert!(
            matches!(events[0], UiEvent::MouseDown { .. }),
            "click at different position should NOT be DoubleClick"
        );
    }

    #[test]
    fn triple_click_resets_to_single() {
        let mut det = DoubleClickDetector::new();
        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);

        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);
        assert!(matches!(events[0], UiEvent::DoubleClick { .. }));

        // Third click at same position — resets to single (no triple-click).
        let mut events = vec![mouse_down(5.0, 3.0)];
        det.process(&mut events);
        assert!(
            matches!(events[0], UiEvent::MouseDown { .. }),
            "third click should reset to MouseDown"
        );
    }
}