teksilo-core 0.9.0

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

//! Overlay system for tooltips, dropdown menus, context menus, and popovers.
//!
//! Overlays render outside the normal layout hierarchy. They float above the
//! main content, positioned relative to an anchor widget or the pointer.
//! The `OverlayManager` coordinates creation, positioning, stacking, dismissal,
//! event routing, and accessibility.

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

use teksilo_canvas::{Point, Rect, Size, Vec2};
use teksilo_tokens::Corner;

use crate::environment::LayoutDirection;
use crate::signal::Signal;
use crate::widget_id::WidgetId;

/// Callback invoked by the framework when an overlay is dismissed —
/// regardless of the dismiss path (Escape, click outside, pointer
/// leave, explicit API call, cascade). The anchor widget uses this
/// hook to reset its own interaction state so that SR-facing
/// properties like `set_expanded` on a `ComboBox` or a submenu
/// trigger stay consistent with the actual overlay-visible state.
///
/// Fired exactly once per overlay lifetime, at the point the
/// overlay is removed from the stack. `Fn` rather than `FnOnce`
/// simply because it's easier to pass around by `Rc`; the
/// framework only invokes it once.
pub type OverlayDismissCallback = Rc<dyn Fn()>;

/// Unique identifier for an active overlay.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OverlayId(u64);

impl OverlayId {
    pub(crate) fn new(id: u64) -> Self {
        Self(id)
    }
}

/// How an overlay is positioned relative to its anchor.
#[derive(Debug, Clone)]
pub enum OverlayPlacement {
    /// Below the anchor, leading-edge aligned (dropdown).
    Below,
    /// Above the anchor (fallback when no space below).
    Above,
    /// To the trailing side of the anchor (submenu).
    TrailingEdge,
    /// At the pointer position (context menu).
    AtPointer(Point),
    /// Near the anchor with a preferred alignment and offset (tooltip).
    NearAnchor { offset: Vec2 },
    /// Centered within the viewport (dialog).
    Centered,
    /// Bottom-centered within the viewport (snackbar/toast).
    BottomCenter,
    /// Below the anchor if space allows, otherwise above (combo box dropdown).
    /// The viewport height is supplied by `position_overlays()` at layout time.
    BelowPreferred,
    /// Snaps content to a viewport corner with a per-axis margin
    /// (used by `ToastHost` for stacked toast notifications, also
    /// suitable for picture-in-picture, floating action overlays).
    /// Anchor bounds are ignored. The leading/trailing axis honours
    /// `LayoutDirection`: `TopTrailing` is top-right under LTR and
    /// top-left under RTL.
    ViewportCorner { corner: Corner, margin: Vec2 },
    /// Fills the entire viewport, anchor-independent. Used by the
    /// modal-presentation pipeline to mount a dialog scrim behind a
    /// centered modal panel — the scrim covers the full window so the
    /// content behind dims uniformly. Anchor bounds are ignored.
    FullViewport,
}

/// Placement preference for a tooltip relative to its anchor. Resolved to
/// a concrete [`OverlayPlacement`] at show time (see
/// `WidgetTree::tooltip_overlay_placement`).
///
/// `Below` is the default (drop below the anchor, flip above near the
/// viewport edge). `Side` opens to the anchor's trailing side (RTL-aware,
/// with a leading fallback) — for anchors stacked **vertically** (menu
/// items, a vertical tab strip, list/tree rows, a docking activity rail,
/// a vertical `RadioTileGroup`) where a `Below` tooltip would cover the
/// next sibling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TooltipPlacement {
    /// Below the anchor (flips above near the viewport edge). The default.
    #[default]
    Below,
    /// To the anchor's trailing side (RTL-aware, leading fallback).
    Side,
}

/// When an overlay is dismissed.
#[derive(Debug, Clone)]
pub enum DismissBehavior {
    /// Dismiss when the user clicks outside the overlay.
    ClickOutside,
    /// Dismiss when the user presses Escape.
    EscapeKey,
    /// Dismiss on either Escape or an outside click.
    EscapeOrClickOutside,
    /// Dismiss when the pointer leaves both anchor and overlay.
    PointerLeave { delay: Duration },
    /// Dismiss only via explicit API call.
    Manual,
}

/// Where the overlay renders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OverlayLayer {
    /// Rendered within the application window's wgpu surface.
    InTree,
    /// Rendered in a separate native OS window.
    NativePopup,
    /// Framework decides based on content size.
    Auto,
}

/// A request to show an overlay.
pub struct OverlayRequest {
    /// The root widget of the overlay content.
    pub content_id: WidgetId,
    /// The widget this overlay is anchored to.
    pub anchor: WidgetId,
    /// Positioning relative to the anchor.
    pub placement: OverlayPlacement,
    /// How the overlay is dismissed.
    pub dismiss: DismissBehavior,
    /// Rendering layer.
    pub layer: OverlayLayer,
    /// Parent overlay (for submenu cascading).
    pub parent_overlay: Option<OverlayId>,
    /// Invoked when the overlay is dismissed by any path. Use this
    /// to reset anchor-side state (e.g. `ComboBox.interaction`)
    /// when the framework tears down the overlay without going
    /// through the anchor's own key/tap handlers.
    pub on_dismiss: Option<OverlayDismissCallback>,
    /// Optional fade-in / fade-out duration. When `Some`, the
    /// framework attaches an animated opacity scope to `content_id`
    /// at show time (using the existing `set_opacity` rendering
    /// pipeline — no `Fade` widget required from the caller), tweens
    /// the opacity from 0 → 1 over `duration`, and on dismiss
    /// reverses the tween and defers the actual stack removal by
    /// `duration`. Construct with [`OverlayRequest::with_fade`] when
    /// the struct-literal idiom isn't ergonomic.
    pub fade_duration: Option<Duration>,
}

impl OverlayRequest {
    /// Attach a fade-in / fade-out animation to this request.
    /// `duration` controls both directions. The framework wires
    /// everything internally — caller does not create a `Fade`
    /// widget or manage a signal:
    ///
    /// ```text
    /// let req = OverlayRequest { content_id, anchor, ... }
    ///     .with_fade(theme.motion.duration_fast);
    /// ```
    pub fn with_fade(mut self, duration: Duration) -> Self {
        self.fade_duration = Some(duration);
        self
    }
}

/// Fade-on-show / fade-on-dismiss state for an overlay. Populated by
/// the framework when an [`OverlayRequest`] carries `fade_duration`.
/// The framework owns the `Signal<f32>` (an animated 0..1 opacity)
/// and applies it to the overlay's content via `set_opacity`, so the
/// caller doesn't need to wrap the content in a `Fade` widget — the
/// rendering walker's opacity scope (Item 1) does the work.
///
/// Mirrors the `pointer_leave_started_real/_sim` and
/// `shown_at_real/_sim` dual-clock pattern used elsewhere in
/// `ActiveOverlay`: the real-clock field drives the live event loop;
/// the sim-clock field drives the headless `tick_animations` /
/// `advance_time` test path so deterministic tests can advance the
/// fade-out window without `std::thread::sleep`.
#[derive(Clone)]
pub(crate) struct OverlayFadeState {
    /// Animated opacity (0..1) bound to the overlay's content via
    /// `WidgetTree::set_opacity`. The framework starts the tween at
    /// 0 and animates to 1 on show, then animates back to 0 on
    /// dismiss before the deferred removal fires.
    pub opacity: Signal<f32>,
    /// Tween duration on both directions. Picked from
    /// `theme.motion.duration_fast` for tooltip / popover and
    /// `duration_normal` for snackbar / dialog.
    pub duration: Duration,
    /// `Some(start_real)` when a dismiss has been requested and the
    /// fade-out tween has started. The real-clock processor
    /// considers the overlay ready for removal once
    /// `Instant::now() - start_real >= duration`.
    pub dismissing_started_real: Option<Instant>,
    /// `Some(start_sim)` set in lockstep with `dismissing_started_real`
    /// using the tree's `sim_clock`. The sim-clock processor uses
    /// it for deterministic headless tests.
    pub dismissing_started_sim: Option<Instant>,
}

/// An active overlay in the stack.
pub(crate) struct ActiveOverlay {
    pub id: OverlayId,
    pub content_id: WidgetId,
    pub anchor: WidgetId,
    pub placement: OverlayPlacement,
    pub dismiss: DismissBehavior,
    pub layer: OverlayLayer,
    pub parent_overlay: Option<OverlayId>,
    /// Computed bounds after positioning.
    pub bounds: Rect,
    /// Widget that had focus before this overlay was shown.
    /// Used to restore focus when the overlay is dismissed.
    pub focus_restore: Option<WidgetId>,
    /// When pointer-leave dismissal started (real time).
    pub pointer_leave_started_real: Option<std::time::Instant>,
    /// When pointer-leave dismissal started (simulated time).
    pub pointer_leave_started_sim: Option<std::time::Instant>,
    /// Dismiss automatically after this duration, if set.
    pub auto_dismiss_after: Option<Duration>,
    /// While the auto-dismiss timer is paused (via
    /// [`OverlayManager::pause_auto_dismiss`]), `auto_dismiss_after`
    /// is cleared and the time that *would have remained* is stashed
    /// here. [`OverlayManager::resume_auto_dismiss`] restores
    /// `auto_dismiss_after = Some(this)` and stamps a fresh
    /// `shown_at_*`. `None` whenever the overlay is not paused.
    pub paused_remaining: Option<Duration>,
    /// When the overlay was shown (real time).
    pub shown_at_real: std::time::Instant,
    /// When the overlay was shown (simulated time).
    pub shown_at_sim: std::time::Instant,
    /// Dismiss callback supplied by the show request. Invoked
    /// exactly once when the overlay is removed from the stack,
    /// regardless of dismiss path.
    pub on_dismiss: Option<OverlayDismissCallback>,
    /// Optional fade-in / fade-out state. Configured post-show via
    /// `OverlayManager::set_fade`. When `Some`, all dismiss paths
    /// (auto, escape, click-outside, pointer-leave, manual) defer
    /// the actual removal until the fade-out tween completes.
    pub fade: Option<OverlayFadeState>,
}

impl ActiveOverlay {
    /// Whether this overlay is already on its way out — dismissed, but still
    /// on the stack while its fade-out tween runs.
    ///
    /// Such an overlay still answers every stack query, so anything that
    /// *targets* an overlay has to step over it: dismissing it a second time
    /// collapses the tween it is in the middle of, and (for input) spends the
    /// keystroke on a corpse while leaving whatever sits underneath
    /// unreachable.
    pub(crate) fn is_dismissing(&self) -> bool {
        self.fade
            .as_ref()
            .is_some_and(|fade| fade.dismissing_started_real.is_some())
    }
}

// Manual Debug impl: `Rc<dyn Fn()>` doesn't derive Debug, but the
// surrounding systems (tests, logging) want ActiveOverlay to be
// printable. Skip the callback field and tag it with a placeholder.
impl std::fmt::Debug for ActiveOverlay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ActiveOverlay")
            .field("id", &self.id)
            .field("content_id", &self.content_id)
            .field("anchor", &self.anchor)
            .field("placement", &self.placement)
            .field("dismiss", &self.dismiss)
            .field("layer", &self.layer)
            .field("parent_overlay", &self.parent_overlay)
            .field("bounds", &self.bounds)
            .field("focus_restore", &self.focus_restore)
            .field(
                "pointer_leave_started_real",
                &self.pointer_leave_started_real,
            )
            .field("pointer_leave_started_sim", &self.pointer_leave_started_sim)
            .field("auto_dismiss_after", &self.auto_dismiss_after)
            .field("shown_at_real", &self.shown_at_real)
            .field("shown_at_sim", &self.shown_at_sim)
            .field(
                "on_dismiss",
                &self.on_dismiss.as_ref().map(|_| "<callback>"),
            )
            .field("fading", &self.fade.is_some())
            .finish()
    }
}

/// Maximum overlay nesting depth. Bounds runaway cascades: a rich-tooltip
/// `[label](:key)` link loop (A→B→A) keeps minting fresh nested overlays
/// (and dormant widgets) on each hop with no natural ceiling. A real
/// menu-submenu or tooltip cascade never gets close to this — once a new
/// overlay would exceed it, `OverlayManager::show*` drops the request
/// instead of growing the stack without bound.
pub(crate) const MAX_OVERLAY_NESTING_DEPTH: usize = 12;

/// Manages the overlay stack — creation, positioning, dismissal, cascading.
/// Leading-edge-aligned x for a `Below` / `Above` overlay, clamped so the
/// overlay stays inside the viewport.
///
/// In LTR the leading edge is `anchor.x`; in RTL it is the anchor's physical
/// right edge. **Both are clamped.** The LTR arm used to be a bare `anchor.x`,
/// which silently ran a popover off the right edge of the window whenever its
/// trigger sat near that edge and its content was wider than the trigger — the
/// ordinary case for a status-bar or toolbar-trailing control. The RTL arm has
/// always clamped; there was no reason for the two to differ.
///
/// `max(0.0)` last, so a viewport narrower than the overlay pins it to the
/// leading edge and clips at the trailing one, rather than pushing its start
/// off-screen where the first thing the reader needs would be the part lost.
fn leading_aligned_x(anchor: Rect, actual_width: f32, vw: f32, rtl: bool) -> f32 {
    let leading = if rtl {
        anchor.x + anchor.width - actual_width
    } else {
        anchor.x
    };
    leading.min(vw - actual_width).max(0.0)
}

pub struct OverlayManager {
    pub(crate) stack: Vec<ActiveOverlay>,
    next_id: u64,
    /// Latest known sim-clock value, mirrored from
    /// `WidgetTree::sim_clock` via [`Self::set_sim_clock`]. Read by
    /// `dismiss` to stamp `dismissing_started_sim` in lockstep with
    /// `dismissing_started_real`. Defaults to `Instant::now()` so
    /// constructions outside a tree (tests of OverlayManager in
    /// isolation) still produce sensible values.
    sim_clock: Instant,
    /// Monotonic counter bumped on every stack mutation (show /
    /// dismiss). External observers — notably the inspector's Overlays
    /// tab — bind to this signal to know when the visible overlay set
    /// has changed without polling. Mirrors the
    /// `ShortcutRegistry::version` pattern.
    version: Signal<u64>,
}

impl OverlayManager {
    pub fn new() -> Self {
        Self {
            stack: Vec::new(),
            next_id: 1,
            sim_clock: Instant::now(),
            version: Signal::new(0),
        }
    }

    /// Reactive handle bumped on every overlay mutation (show /
    /// dismiss / cascade). Cheap clone. Same shape as
    /// [`crate::shortcut::ShortcutRegistry::version`].
    pub fn version(&self) -> &Signal<u64> {
        &self.version
    }

    /// Bump the version signal. Called from every stack-mutating path.
    fn bump_version(&self) {
        self.version.set(self.version.get().wrapping_add(1));
    }

    /// Mirror the tree's sim_clock onto the manager so the fade
    /// dismiss path can stamp the sim-time start in lockstep with
    /// real time. Called by `WidgetTree` whenever `sim_clock` is
    /// advanced (e.g. from `tick_animations` and `advance_time`).
    pub(crate) fn set_sim_clock(&mut self, now_sim: Instant) {
        self.sim_clock = now_sim;
    }

    /// Show a new overlay. Returns the OverlayId.
    pub fn show(&mut self, request: OverlayRequest) -> OverlayId {
        self.show_with_auto_dismiss(request, None)
    }

    /// Show a new overlay that dismisses automatically after `duration`.
    pub fn show_for(&mut self, request: OverlayRequest, duration: Duration) -> OverlayId {
        self.show_with_auto_dismiss(request, Some(duration))
    }

    fn show_with_auto_dismiss(
        &mut self,
        request: OverlayRequest,
        auto_dismiss_after: Option<Duration>,
    ) -> OverlayId {
        let id = OverlayId::new(self.next_id);
        self.next_id += 1;

        // Bound cascade depth — see `MAX_OVERLAY_NESTING_DEPTH`. If this
        // overlay would nest deeper than the cap, drop it silently: don't
        // push, and return the (now unused) id so callers' follow-ups
        // (`set_shown_at_sim`, `set_top_focus_restore`) safely no-op on
        // the absent overlay. This is reachable by degenerate-but-real
        // user action (a cyclic tooltip `:key` cascade), so it must not
        // panic — graceful drop is the whole point.
        if self.ancestor_depth(request.parent_overlay) >= MAX_OVERLAY_NESTING_DEPTH {
            return id;
        }

        let now = std::time::Instant::now();

        let overlay = ActiveOverlay {
            id,
            content_id: request.content_id,
            anchor: request.anchor,
            placement: request.placement,
            dismiss: request.dismiss,
            layer: request.layer,
            parent_overlay: request.parent_overlay,
            bounds: Rect::ZERO,
            focus_restore: None,
            pointer_leave_started_real: None,
            pointer_leave_started_sim: None,
            auto_dismiss_after,
            paused_remaining: None,
            shown_at_real: now,
            shown_at_sim: now,
            on_dismiss: request.on_dismiss,
            fade: None,
        };
        self.stack.push(overlay);
        self.bump_version();
        id
    }

    /// Internal: install a framework-managed opacity signal as the
    /// overlay's fade state. Called by `WidgetTree::show_overlay`
    /// when [`OverlayRequest::fade_duration`] is `Some`. The
    /// framework also applies the same signal to `content_id` via
    /// `set_opacity` (so the rendering walker emits the per-frame
    /// opacity scope) and kicks off the 0→1 fade-in tween.
    pub(crate) fn attach_fade(&mut self, id: OverlayId, opacity: Signal<f32>, duration: Duration) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
            overlay.fade = Some(OverlayFadeState {
                opacity,
                duration,
                dismissing_started_real: None,
                dismissing_started_sim: None,
            });
        }
    }

    /// Public read-only accessor for the fade state. Returns the
    /// duration if fade is configured, `None` otherwise. Used by
    /// `WidgetTree::dismiss_overlay` to know whether to leave the
    /// content active for the fade-out window.
    pub fn fade_duration(&self, id: OverlayId) -> Option<Duration> {
        self.stack
            .iter()
            .find(|o| o.id == id)
            .and_then(|o| o.fade.as_ref().map(|f| f.duration))
    }

    pub fn next_auto_dismiss_deadline(&self) -> Option<std::time::Instant> {
        self.stack
            .iter()
            .filter_map(|overlay| {
                overlay
                    .auto_dismiss_after
                    .map(|delay| overlay.shown_at_real + delay)
            })
            .min()
    }

    /// Earliest instant at which a [`DismissBehavior::PointerLeave`] overlay
    /// whose leave-grace is already running becomes due for dismissal.
    ///
    /// The counterpart of
    /// [`next_auto_dismiss_deadline`](Self::next_auto_dismiss_deadline) for the
    /// hover-opened overlays (tooltips, hover submenus). Without it the event
    /// loop has no reason to wake between the pointer's last motion event and
    /// the end of the grace window: `next_timer_deadline` would return `None`,
    /// winit would sit in `ControlFlow::Wait`, and the overlay would stay on
    /// screen until some unrelated input happened to redraw the window.
    pub fn next_pointer_leave_deadline(&self) -> Option<std::time::Instant> {
        self.stack
            .iter()
            .filter_map(|overlay| {
                let DismissBehavior::PointerLeave { delay } = overlay.dismiss else {
                    return None;
                };
                Some(overlay.pointer_leave_started_real? + delay)
            })
            .min()
    }

    /// Pause the auto-dismiss timer for an overlay shown with
    /// [`show_for`](Self::show_for). The remaining time
    /// (`auto_dismiss_after - elapsed`) is stashed; subsequent calls
    /// to [`next_auto_dismiss_deadline`](Self::next_auto_dismiss_deadline)
    /// ignore this overlay until [`resume_auto_dismiss`](Self::resume_auto_dismiss)
    /// is called. Idempotent — pausing an already-paused overlay is
    /// a no-op (the originally-stashed remaining time is preserved).
    ///
    /// Used by `ToastHost` to implement hover-pause: when the user
    /// is hovering over any live toast, all live toasts pause their
    /// timers so the user can read each one without losing the
    /// notification they're about to act on.
    ///
    /// No-op on overlays without `auto_dismiss_after` (persistent
    /// overlays don't have a timer to pause) and on unknown ids.
    pub fn pause_auto_dismiss(&mut self, id: OverlayId) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
            && overlay.paused_remaining.is_none()
            && let Some(delay) = overlay.auto_dismiss_after.take()
        {
            let elapsed = overlay.shown_at_real.elapsed();
            overlay.paused_remaining = Some(delay.saturating_sub(elapsed));
        }
    }

    /// Resume an auto-dismiss timer paused via
    /// [`pause_auto_dismiss`](Self::pause_auto_dismiss). The stashed
    /// remaining time becomes the new `auto_dismiss_after`, and
    /// `shown_at_real` / `shown_at_sim` are reset to now so the
    /// deadline computation works correctly. Idempotent — resuming
    /// an un-paused overlay is a no-op.
    pub fn resume_auto_dismiss(&mut self, id: OverlayId) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
            && let Some(remaining) = overlay.paused_remaining.take()
        {
            overlay.auto_dismiss_after = Some(remaining);
            let now = std::time::Instant::now();
            overlay.shown_at_real = now;
            overlay.shown_at_sim = self.sim_clock;
        }
    }

    /// Whether the auto-dismiss timer for an overlay is currently paused.
    /// `false` for overlays without `auto_dismiss_after`, unknown ids,
    /// and overlays whose timer is running.
    pub fn is_auto_dismiss_paused(&self, id: OverlayId) -> bool {
        self.stack
            .iter()
            .find(|o| o.id == id)
            .is_some_and(|o| o.paused_remaining.is_some())
    }

    pub(crate) fn set_shown_at_sim(&mut self, id: OverlayId, shown_at_sim: std::time::Instant) {
        if let Some(overlay) = self.stack.iter_mut().find(|overlay| overlay.id == id) {
            overlay.shown_at_sim = shown_at_sim;
        }
    }

    /// Count the ancestor chain length for an overlay whose parent is
    /// `parent` — i.e. the nesting depth the *new* overlay would have.
    /// A root (`parent == None`) is depth 0; a child of a root is depth
    /// 1; and so on. The walk is bounded by the stack length so a
    /// malformed parent cycle can't loop forever.
    fn ancestor_depth(&self, parent: Option<OverlayId>) -> usize {
        let mut depth = 0;
        let mut current = parent;
        while let Some(p) = current {
            depth += 1;
            if depth > self.stack.len() {
                // Defensive: malformed parent cycle. Report a depth that
                // trips the guard rather than spinning.
                break;
            }
            current = self
                .stack
                .iter()
                .find(|overlay| overlay.id == p)
                .and_then(|overlay| overlay.parent_overlay);
        }
        depth
    }

    pub(crate) fn is_descendant_of(&self, child: OverlayId, ancestor: OverlayId) -> bool {
        let mut current = self
            .stack
            .iter()
            .find(|overlay| overlay.id == child)
            .and_then(|overlay| overlay.parent_overlay);

        while let Some(parent) = current {
            if parent == ancestor {
                return true;
            }
            current = self
                .stack
                .iter()
                .find(|overlay| overlay.id == parent)
                .and_then(|overlay| overlay.parent_overlay);
        }

        false
    }

    pub(crate) fn overlay(&self, id: OverlayId) -> Option<&ActiveOverlay> {
        self.stack.iter().find(|overlay| overlay.id == id)
    }

    /// Public accessor for an overlay's currently-laid-out screen
    /// rect. Returns `None` for unknown ids and for overlays that
    /// have not yet been through a layout pass (`bounds == Rect::ZERO`
    /// in that case, but we still hand it back — callers should not
    /// trust a zero-sized rect for hit-test geometry).
    ///
    /// Used by [`MenuList`](../../teksilo_widgets/menu_list/struct.MenuList.html)'s
    /// safe-triangle submenu hover gate, which needs the open
    /// submenu's near-edge to test whether the cursor trajectory is
    /// still headed toward the submenu.
    pub fn bounds_for(&self, id: OverlayId) -> Option<Rect> {
        self.overlay(id).map(|o| o.bounds)
    }

    pub(crate) fn topmost_centered(&self) -> Option<&ActiveOverlay> {
        self.stack
            .iter()
            .rev()
            .find(|overlay| matches!(overlay.placement, OverlayPlacement::Centered))
    }

    /// Dismiss an overlay and all its children (cascade), returning the
    /// dismissed content widget IDs and the overlay's focus_restore target.
    pub fn dismiss_with_focus_restore(
        &mut self,
        id: OverlayId,
    ) -> (Vec<WidgetId>, Option<WidgetId>) {
        let focus_restore = self
            .stack
            .iter()
            .find(|overlay| overlay.id == id)
            .and_then(|overlay| overlay.focus_restore);
        let dismissed = self.dismiss(id);
        (dismissed, focus_restore)
    }

    /// Dismiss all descendant overlays of `parent`, optionally preserving the
    /// subtree rooted at `preserve`.
    pub fn dismiss_descendants_of(
        &mut self,
        parent: OverlayId,
        preserve: Option<OverlayId>,
    ) -> (Vec<WidgetId>, Option<WidgetId>) {
        let mut to_dismiss = Vec::new();

        for overlay in &self.stack {
            if !self.is_descendant_of(overlay.id, parent) {
                continue;
            }
            if preserve
                .is_some_and(|keep| overlay.id == keep || self.is_descendant_of(overlay.id, keep))
            {
                continue;
            }
            to_dismiss.push(overlay.id);
        }

        if to_dismiss.is_empty() {
            return (Vec::new(), None);
        }

        let focus_restore = self
            .stack
            .iter()
            .rev()
            .find(|overlay| to_dismiss.contains(&overlay.id))
            .and_then(|overlay| overlay.focus_restore);

        let dismissed_content: Vec<WidgetId> = self
            .stack
            .iter()
            .filter(|overlay| to_dismiss.contains(&overlay.id))
            .map(|overlay| overlay.content_id)
            .collect();
        let callbacks: Vec<OverlayDismissCallback> = self
            .stack
            .iter()
            .filter(|overlay| to_dismiss.contains(&overlay.id))
            .filter_map(|overlay| overlay.on_dismiss.clone())
            .collect();
        self.stack
            .retain(|overlay| !to_dismiss.contains(&overlay.id));
        for cb in callbacks {
            cb();
        }

        (dismissed_content, focus_restore)
    }

    /// Update the placement of an existing overlay.
    pub fn update_placement(&mut self, id: OverlayId, placement: OverlayPlacement) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
            overlay.placement = placement;
        }
    }

    /// Update the parent-overlay link of an existing overlay. Used by the
    /// modal-presentation pipeline to retroactively attach the dialog
    /// scrim (pushed first, below the modal in the stack) to the modal
    /// (pushed second) so that dismissing the modal cascades through
    /// `dismiss_immediate` and also dismisses the scrim.
    pub fn set_parent_overlay(&mut self, id: OverlayId, parent: Option<OverlayId>) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
            overlay.parent_overlay = parent;
        }
    }

    /// Dismiss an overlay and all its children (cascade).
    /// Returns the content widget IDs of all dismissed overlays.
    ///
    /// **Fade-aware**: when an overlay was shown with
    /// [`OverlayRequest::with_fade`] and is not yet fading out, this
    /// method instead kicks off the fade-out tween on the framework-
    /// owned opacity signal and marks `dismiss_at`, returning an
    /// empty vec — the actual stack removal and content dormancy
    /// happen later via
    /// [`process_pending_fade_dismissals`](Self::process_pending_fade_dismissals).
    /// Cascaded descendants vanish with the leaf's fade-out (they're
    /// typically submenus the user dismissed *via* the leaf, and a
    /// per-descendant tween would compete with the leaf's).
    pub fn dismiss(&mut self, id: OverlayId) -> Vec<WidgetId> {
        // Fade gate: if the target overlay has fade and isn't
        // already fading out, kick off the fade-out and defer the
        // entire cascade. Stamps both real and sim start times in
        // lockstep — the sim time uses the manager's mirrored
        // `sim_clock`, kept in sync by `WidgetTree::set_sim_clock`.
        let sim_now = self.sim_clock;
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
            && let Some(fade) = &mut overlay.fade
            && fade.dismissing_started_real.is_none()
        {
            // Animate opacity 1 → 0 over `duration`. Uses the same
            // try_animate_with_options path the rest of the
            // animation system uses; the scheduler picks it up next
            // frame and ticks the signal, dirty-marking the
            // content's opacity binding for repaint.
            let _ = fade
                .opacity
                .try_animate_with_options(crate::animation::AnimationRequest {
                    target: 0.0,
                    duration: fade.duration,
                    easing: teksilo_tokens::Easing::EaseOut,
                    frame_interval: None,
                    looping: false,
                    epsilon: 0.0,
                    max_duration: None,
                });
            let now_real = Instant::now();
            fade.dismissing_started_real = Some(now_real);
            fade.dismissing_started_sim = Some(sim_now);
            return Vec::new();
        }
        self.dismiss_immediate(id)
    }

    /// Internal: same shape as the original `dismiss`, but bypasses
    /// the fade gate. Used both by `dismiss` (no fade configured /
    /// already fading out) and by `process_pending_fade_dismissals`
    /// when a fade-out tween has completed. Also used by the orphaned-
    /// overlay GC (`WidgetTree::gc_orphaned_overlays`), where fading is
    /// impossible because the content widget is already destroyed.
    pub(crate) fn dismiss_immediate(&mut self, id: OverlayId) -> Vec<WidgetId> {
        // Collect IDs to dismiss: the target + all descendants
        let mut to_dismiss = vec![id];
        let mut i = 0;
        while i < to_dismiss.len() {
            let parent = to_dismiss[i];
            for overlay in &self.stack {
                if overlay.parent_overlay == Some(parent) && !to_dismiss.contains(&overlay.id) {
                    to_dismiss.push(overlay.id);
                }
            }
            i += 1;
        }
        let dismissed_content: Vec<WidgetId> = self
            .stack
            .iter()
            .filter(|o| to_dismiss.contains(&o.id))
            .map(|o| o.content_id)
            .collect();
        // Collect dismiss callbacks (via Rc::clone) before retain
        // so we can invoke them AFTER the borrow is released.
        // Callbacks may do anything, including touching the arena,
        // so running them mid-retain would risk re-entrancy.
        let callbacks: Vec<OverlayDismissCallback> = self
            .stack
            .iter()
            .filter(|o| to_dismiss.contains(&o.id))
            .filter_map(|o| o.on_dismiss.clone())
            .collect();
        self.stack.retain(|o| !to_dismiss.contains(&o.id));
        if !to_dismiss.is_empty() {
            self.bump_version();
        }
        for cb in callbacks {
            cb();
        }
        dismissed_content
    }

    /// Drain overlays whose real-clock fade-out tween has completed.
    /// Call from the live layout pass; the framework dormants the
    /// returned content widget IDs and restores focus where
    /// appropriate. Each entry is
    /// `(overlay_id, dismissed_content_ids, focus_restore)` so the
    /// layout pass can run the same dormant-and-restore-focus flow
    /// it uses for
    /// [`dismiss_with_focus_restore`](Self::dismiss_with_focus_restore).
    pub fn process_pending_fade_dismissals(
        &mut self,
        now: Instant,
    ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
        self.process_pending_fade_dismissals_with(|fade| {
            let started = fade.dismissing_started_real?;
            Some(now.saturating_duration_since(started) >= fade.duration)
        })
    }

    /// Sim-clock variant for deterministic headless tests. Same
    /// shape as [`process_pending_fade_dismissals`](Self::process_pending_fade_dismissals)
    /// but reads `dismissing_started_sim`.
    pub fn process_pending_fade_dismissals_sim(
        &mut self,
        now_sim: Instant,
    ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
        self.process_pending_fade_dismissals_with(|fade| {
            let started = fade.dismissing_started_sim?;
            Some(now_sim.saturating_duration_since(started) >= fade.duration)
        })
    }

    fn process_pending_fade_dismissals_with(
        &mut self,
        mut elapsed_done: impl FnMut(&OverlayFadeState) -> Option<bool>,
    ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
        let ready: Vec<(OverlayId, Option<WidgetId>)> = self
            .stack
            .iter()
            .filter_map(|o| {
                let fade = o.fade.as_ref()?;
                if elapsed_done(fade)? {
                    Some((o.id, o.focus_restore))
                } else {
                    None
                }
            })
            .collect();
        ready
            .into_iter()
            .map(|(id, focus_restore)| {
                let dismissed = self.dismiss_immediate(id);
                (id, dismissed, focus_restore)
            })
            .collect()
    }

    /// Earliest real-clock deadline at which a fading-out overlay
    /// wants to finish its dismissal. Used by the event-loop wakeup
    /// logic to schedule the next frame.
    pub fn next_fade_dismiss_deadline(&self) -> Option<Instant> {
        self.stack
            .iter()
            .filter_map(|o| {
                let fade = o.fade.as_ref()?;
                let started = fade.dismissing_started_real?;
                Some(started + fade.duration)
            })
            .min()
    }

    /// Dismiss the topmost overlay unconditionally (e.g., ArrowLeft for submenu cascading).
    /// Returns the overlay ID, content widget IDs, and focus_restore target.
    pub fn dismiss_top(&mut self) -> Option<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
        if let Some(overlay) = self.stack.last() {
            let id = overlay.id;
            let focus_restore = overlay.focus_restore;
            let content_ids = self.dismiss(id);
            Some((id, content_ids, focus_restore))
        } else {
            None
        }
    }

    /// Try to dismiss an overlay on Escape, respecting `DismissBehavior`.
    ///
    /// Scans the stack top-down for the first overlay that Escape may close,
    /// rather than consulting only `stack.last()`. Two reasons:
    ///
    /// - A hover-opened overlay (`PointerLeave` — every shown tooltip) is
    ///   Escape-dismissible. WCAG 2.2 SC 1.4.13(a) requires content shown on
    ///   hover to be dismissible *without moving the pointer*, and Escape is
    ///   that mechanism; previously no key could close a plain tooltip.
    /// - A tooltip lives on the same stack as whatever it is anchored inside.
    ///   Hovering a menu item long enough to raise its tooltip put a
    ///   non-Escape overlay on top, so Escape silently did nothing at all
    ///   until the tooltip's own 100 ms leave-grace expired — the keystroke
    ///   was swallowed, not forwarded to the menu underneath.
    ///
    /// `Manual` overlays still block the scan: they are modal-ish by
    /// construction and own the keystroke.
    pub fn try_dismiss_top_on_escape(
        &mut self,
    ) -> Option<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
        let target = self
            .stack
            .iter()
            .rev()
            // An overlay already fading out stays on the stack until its tween
            // finishes, but it is on its way out and no longer owns the
            // keystroke — targeting it again would spend an Escape on a corpse
            // and leave whatever is underneath unreachable.
            .filter(|o| !o.is_dismissing())
            .find_map(|o| match o.dismiss {
                DismissBehavior::EscapeKey
                | DismissBehavior::EscapeOrClickOutside
                | DismissBehavior::PointerLeave { .. } => Some(Some(o.id)),
                // Opaque to Escape and to everything under it.
                DismissBehavior::Manual => Some(None),
                DismissBehavior::ClickOutside => None,
            })??;
        let focus_restore = self
            .stack
            .iter()
            .find(|o| o.id == target)
            .and_then(|o| o.focus_restore);
        let content_ids = self.dismiss(target);
        Some((target, content_ids, focus_restore))
    }

    /// Set the focus_restore target for the topmost overlay.
    pub fn set_top_focus_restore(&mut self, focus_restore: WidgetId) {
        if let Some(overlay) = self.stack.last_mut() {
            overlay.focus_restore = Some(focus_restore);
        }
    }

    /// Dismiss all overlays.
    /// Returns the content widget IDs of all dismissed overlays.
    /// Fires every dismissed overlay's `on_dismiss` callback after the
    /// stack is cleared — same contract as [`dismiss`](Self::dismiss),
    /// so wrappers like [`PopoverButton`](crate::widget::EventContext)'s
    /// `popover_open` signal flip back to `false` when a `MenuItem`
    /// fires `ctx.dismiss_all_overlays()`. Without this, the trigger's
    /// next click would observe stale-true and silently retoggle
    /// instead of reopening the menu.
    pub fn dismiss_all(&mut self) -> Vec<WidgetId> {
        let content_ids: Vec<WidgetId> = self.stack.iter().map(|o| o.content_id).collect();
        if content_ids.is_empty() {
            return content_ids;
        }
        // Collect dismiss callbacks (via Rc::clone) before clear so we
        // can invoke them AFTER the borrow is released. Callbacks may
        // do anything, including touching the arena, so running them
        // mid-clear would risk re-entrancy. Mirrors the pattern in
        // [`dismiss_immediate`](Self::dismiss_immediate).
        let callbacks: Vec<OverlayDismissCallback> = self
            .stack
            .iter()
            .filter_map(|o| o.on_dismiss.clone())
            .collect();
        self.stack.clear();
        self.bump_version();
        for cb in callbacks {
            cb();
        }
        content_ids
    }

    /// Dismiss every overlay whose content is **not** in `keep`, running each
    /// dismissed overlay's `on_dismiss`. Used when opening a context menu: any
    /// overlay that *contains* the right-clicked widget (e.g. the modal the editor
    /// lives in) is kept, so the menu doesn't tear down its own host.
    pub fn dismiss_except(&mut self, keep: &std::collections::HashSet<WidgetId>) -> Vec<WidgetId> {
        let dismissed: Vec<WidgetId> = self
            .stack
            .iter()
            .filter(|o| !keep.contains(&o.content_id))
            .map(|o| o.content_id)
            .collect();
        if dismissed.is_empty() {
            return dismissed;
        }
        // Clone callbacks before mutating the stack, then run them after the
        // borrow is released (they may touch the arena) — mirrors `dismiss_all`.
        let callbacks: Vec<OverlayDismissCallback> = self
            .stack
            .iter()
            .filter(|o| !keep.contains(&o.content_id))
            .filter_map(|o| o.on_dismiss.clone())
            .collect();
        self.stack.retain(|o| keep.contains(&o.content_id));
        self.bump_version();
        for cb in callbacks {
            cb();
        }
        dismissed
    }

    /// Whether there are any active overlays.
    pub fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }

    /// Number of active overlays.
    pub fn len(&self) -> usize {
        self.stack.len()
    }

    /// Get all active overlay content widget IDs (for rendering).
    pub fn active_content_ids(&self) -> Vec<WidgetId> {
        self.stack.iter().map(|o| o.content_id).collect()
    }

    /// Get all active overlay IDs (for testing/querying). Excludes
    /// overlays currently fading out — once a dismiss has been
    /// requested the overlay is conceptually gone (the visible
    /// opacity tween is on the way to 0 and the deferred removal
    /// will fire on the next layout pass after the fade-out
    /// completes), so user code asking "is this overlay still up?"
    /// gets the expected answer.
    pub fn active_ids(&self) -> Vec<OverlayId> {
        self.stack
            .iter()
            .filter(|o| {
                o.fade
                    .as_ref()
                    .is_none_or(|f| f.dismissing_started_real.is_none())
            })
            .map(|o| o.id)
            .collect()
    }

    /// Get the anchor widget for an overlay.
    pub fn anchor_for(&self, id: OverlayId) -> Option<WidgetId> {
        self.stack.iter().find(|o| o.id == id).map(|o| o.anchor)
    }

    /// Screen rects of every overlay that is currently *interactive* —
    /// open and not yet fading out, the same predicate
    /// [`hit_test`](Self::hit_test) uses to route pointer events.
    /// Zero-area entries are skipped: an overlay shown this frame has
    /// not been through its first layout pass yet (`bounds ==
    /// Rect::ZERO`), and a degenerate rect must not be mistaken for a
    /// hit at the origin.
    ///
    /// Consumed by the paint pass, which hands the list to
    /// [`Widget::after_paint`](crate::widget::Widget::after_paint) via
    /// `WidgetTreeView` so chrome aggregators can subtract floating
    /// content from the regions they publish — `TitleBar` carves these
    /// out of the OS caption so an overlay above the title bar (the
    /// hamburger `MenuBar`'s revealed bar, a tall modal) stays
    /// clickable on Windows instead of dragging the window.
    pub fn interactive_rects(&self) -> Vec<Rect> {
        self.stack
            .iter()
            .filter(|o| {
                o.fade
                    .as_ref()
                    .is_none_or(|f| f.dismissing_started_real.is_none())
            })
            .map(|o| o.bounds)
            .filter(|r| r.width > 0.0 && r.height > 0.0)
            .collect()
    }

    /// Get the topmost overlay.
    #[allow(dead_code)] // used for overlay z-ordering and focus management
    pub(crate) fn topmost(&self) -> Option<&ActiveOverlay> {
        self.stack.last()
    }

    /// Check if a point hits any overlay (topmost first).
    /// Returns the overlay ID if hit, None if the point is outside all overlays.
    ///
    /// Overlays whose fade-out has begun are skipped — the same predicate
    /// [`active_ids`](Self::active_ids) uses. A dismissed-but-still-fading
    /// overlay lingers in the stack until
    /// [`process_pending_fade_dismissals`](Self::process_pending_fade_dismissals)
    /// removes it; treating it as hittable would route clicks into the
    /// vanishing content (and suppress outside-click dismissal of the
    /// overlays beneath it) for the whole fade duration.
    pub fn hit_test(&self, point: Point) -> Option<OverlayId> {
        for overlay in self.stack.iter().rev() {
            let fading_out = overlay
                .fade
                .as_ref()
                .is_some_and(|f| f.dismissing_started_real.is_some());
            if !fading_out && overlay.bounds.contains(point) {
                return Some(overlay.id);
            }
        }
        None
    }

    /// Handle a click-outside event: if the click is outside all overlays
    /// with ClickOutside dismiss behavior, dismiss them.
    /// Returns the content widget IDs of dismissed overlays (empty if none)
    /// and the focus-restore target — the widget that was focused before
    /// the *bottommost* dismissed overlay opened. Topmost overlays'
    /// `focus_restore` would point inside an overlay that's also being
    /// dismissed in the same pass, which would leave focus on a
    /// dormant widget; the bottommost target represents focus before
    /// any of the dismissed overlays opened. Aligns the click-outside
    /// path with the Esc / ArrowLeft-cascade paths, both of which
    /// already restore focus from the dismissed overlay.
    ///
    /// The third return value lists the anchor widgets of the dismissed
    /// *click-opened* overlays (`ClickOutside` / `EscapeOrClickOutside`).
    /// The dispatcher consumes a primary press that lands on one of these
    /// anchors so the trigger merely closes its overlay rather than
    /// reopening it; every other dismiss-press falls through to the widget
    /// under the cursor (so one click both dismisses the overlay and
    /// activates the control beneath). Hover-opened (`PointerLeave`)
    /// overlays contribute no anchor — a press on their anchor passes
    /// through, e.g. clicking a button that still has its tooltip up.
    pub fn handle_click_outside(
        &mut self,
        point: Point,
    ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<WidgetId>) {
        if self.stack.is_empty() {
            return (Vec::new(), None, Vec::new());
        }

        // Dismissal is *layered*, not stack-wide. A press that lands inside
        // overlay `k` is still *outside* every overlay stacked above `k`, so
        // those upper overlays with a click-outside policy must close — e.g. a
        // sticky tooltip (or a combo dropdown) floating above a modal is
        // dismissed when the user clicks elsewhere in the modal. Overlays at
        // or below `k` keep their content: the press landed within the stack,
        // not outside it.
        //
        // `hit_index` is the topmost non-fading overlay containing the point,
        // or `None` for a press on the bare background (then nothing is
        // "below" the press and every dismissable overlay closes — the
        // classic outside-click). This replaces an earlier stack-wide
        // short-circuit that returned as soon as the press hit *any* overlay:
        // once a modal — or its full-viewport scrim — was open, that guard
        // made *no* click-outside overlay dismissable at all.
        let hit_index = self.stack.iter().enumerate().rev().find_map(|(i, o)| {
            let fading_out = o
                .fade
                .as_ref()
                .is_some_and(|f| f.dismissing_started_real.is_some());
            (!fading_out && o.bounds.contains(point)).then_some(i)
        });

        // Collect the overlays this outside-click should close, and — for
        // the *click-opened* ones — their anchor widgets. The anchors let
        // the dispatcher decide whether the same press may fall through to
        // the widget beneath: a press on a click-opened overlay's own
        // anchor is consumed, since the anchor's tap handler would
        // otherwise reopen what this press just dismissed. Hover-opened
        // overlays (`PointerLeave`) are not click toggles, so their
        // anchors are omitted and a press there falls through.
        let mut to_dismiss: Vec<OverlayId> = Vec::new();
        let mut toggle_anchors: Vec<WidgetId> = Vec::new();
        for (i, o) in self.stack.iter().enumerate() {
            // Skip the hit overlay and everything beneath it — the press
            // landed inside them (or was covered by them), so they survive.
            if hit_index.is_some_and(|k| i <= k) {
                continue;
            }
            match o.dismiss {
                DismissBehavior::ClickOutside | DismissBehavior::EscapeOrClickOutside => {
                    to_dismiss.push(o.id);
                    toggle_anchors.push(o.anchor);
                }
                DismissBehavior::PointerLeave { .. } => to_dismiss.push(o.id),
                DismissBehavior::EscapeKey | DismissBehavior::Manual => {}
            }
        }

        if to_dismiss.is_empty() {
            return (Vec::new(), None, Vec::new());
        }

        let focus_restore = self
            .stack
            .iter()
            .find(|o| to_dismiss.contains(&o.id))
            .and_then(|o| o.focus_restore);

        let mut all_dismissed = Vec::new();
        for id in to_dismiss {
            all_dismissed.extend(self.dismiss(id));
        }
        (all_dismissed, focus_restore, toggle_anchors)
    }

    /// Compute overlay positions based on anchor bounds.
    /// Called after layout to position overlays correctly.
    /// `viewport` is (width, height) used for clamping overlays to the visible area.
    ///
    /// `anchor_bounds_fn` returns `None` when the anchor widget is no
    /// longer in the arena (destroyed by a host's rebuild while the
    /// overlay is still up). In that case the overlay's bounds are
    /// left untouched — keeping it at its last valid position rather
    /// than collapsing to the (0,0) origin from a `Rect::ZERO`
    /// fallback.
    pub fn position_overlays(
        &mut self,
        anchor_bounds_fn: impl Fn(WidgetId) -> Option<Rect>,
        viewport: (f32, f32),
        layout_direction: LayoutDirection,
    ) {
        let (vw, vh) = viewport;
        let rtl = matches!(layout_direction, LayoutDirection::RightToLeft);
        for overlay in &mut self.stack {
            let anchor = match anchor_bounds_fn(overlay.anchor) {
                Some(a) => a,
                None => {
                    // Anchor destroyed. Anchor-independent placements must still
                    // be positioned — e.g. a `Centered` modal opened from a menu
                    // item that has since closed (the menu item is the anchor,
                    // but `Centered` doesn't use it). Anchor-relative placements
                    // keep their previous bounds.
                    if matches!(
                        overlay.placement,
                        OverlayPlacement::Centered
                            | OverlayPlacement::FullViewport
                            | OverlayPlacement::BottomCenter
                            | OverlayPlacement::ViewportCorner { .. }
                            | OverlayPlacement::AtPointer(_)
                    ) {
                        Rect::ZERO
                    } else {
                        continue;
                    }
                }
            };
            let content_size = overlay.bounds.size(); // Will be set from content layout

            overlay.bounds = match &overlay.placement {
                OverlayPlacement::Below => {
                    let actual_width = content_size.width.max(anchor.width);
                    let x = leading_aligned_x(anchor, actual_width, vw, rtl);
                    Rect::new(
                        x,
                        anchor.y + anchor.height + 4.0,
                        actual_width,
                        content_size.height,
                    )
                }
                OverlayPlacement::Above => {
                    let actual_width = content_size.width.max(anchor.width);
                    let x = leading_aligned_x(anchor, actual_width, vw, rtl);
                    Rect::new(
                        x,
                        anchor.y - content_size.height - 4.0,
                        actual_width,
                        content_size.height,
                    )
                }
                OverlayPlacement::TrailingEdge => {
                    // In LTR trailing is to the right; in RTL trailing is to the left.
                    let x = if rtl {
                        let x_left = anchor.x - content_size.width - 2.0;
                        if x_left >= 0.0 {
                            x_left
                        } else {
                            // Fallback: open to the leading side (right in RTL)
                            anchor.x + anchor.width + 2.0
                        }
                    } else {
                        let x_right = anchor.x + anchor.width + 2.0;
                        if x_right + content_size.width <= vw {
                            x_right
                        } else {
                            // Fallback: open to the leading side (left in LTR)
                            anchor.x - content_size.width - 2.0
                        }
                    };
                    let y = anchor.y.min(vh - content_size.height).max(0.0);
                    Rect::new(x, y, content_size.width, content_size.height)
                }
                OverlayPlacement::AtPointer(point) => {
                    // Clamp to viewport so menus don't overflow off-screen
                    let x = point.x.min(vw - content_size.width).max(0.0);
                    let y = if point.y + content_size.height <= vh {
                        point.y
                    } else {
                        // Not enough space below pointer — open above
                        (point.y - content_size.height).max(0.0)
                    };
                    Rect::new(x, y, content_size.width, content_size.height)
                }
                OverlayPlacement::NearAnchor { offset } => {
                    // Prefer below the anchor at `offset` + 4 px.
                    // Flip above when the content would otherwise spill
                    // past the viewport bottom — same pattern as
                    // `BelowPreferred`. Without this, a tooltip whose
                    // anchor sits near the window edge gets clipped by
                    // the surface bounds (overlays paint unclipped, but
                    // the window itself still bounds the framebuffer).
                    let below_y = anchor.y + anchor.height + offset.y + 4.0;
                    let fits_below = below_y + content_size.height <= vh;
                    let y = if fits_below {
                        below_y
                    } else {
                        // Symmetric offset above: same gap as below.
                        let above_y = anchor.y - content_size.height - offset.y - 4.0;
                        above_y.max(0.0)
                    };
                    // Horizontal anchoring is direction-aware: LTR aligns
                    // the content's leading (left) edge to the anchor's
                    // left edge + offset; RTL mirrors it, aligning the
                    // content's trailing (right) edge to the anchor's
                    // right edge - offset. The clamp then keeps it in view
                    // when the anchor is near a viewport edge.
                    let unclamped_x = if rtl {
                        anchor.x + anchor.width - content_size.width - offset.x
                    } else {
                        anchor.x + offset.x
                    };
                    let x = unclamped_x.min(vw - content_size.width).max(0.0);
                    Rect::new(x, y, content_size.width, content_size.height)
                }
                OverlayPlacement::Centered => Rect::new(
                    ((vw - content_size.width) / 2.0).max(0.0),
                    ((vh - content_size.height) / 2.0).max(0.0),
                    content_size.width.min(vw),
                    content_size.height.min(vh),
                ),
                OverlayPlacement::BottomCenter => Rect::new(
                    ((vw - content_size.width) / 2.0).max(0.0),
                    (vh - content_size.height - 24.0).max(0.0),
                    content_size.width.min(vw),
                    content_size.height.min(vh),
                ),
                OverlayPlacement::BelowPreferred => {
                    let below_y = anchor.y + anchor.height + 4.0;
                    let fits_below = below_y + content_size.height <= vh;
                    let y = if fits_below {
                        below_y
                    } else {
                        anchor.y - content_size.height - 4.0
                    };
                    let actual_width = content_size.width.max(anchor.width);
                    // Align leading edges, same logic as Below.
                    let x = if rtl {
                        (anchor.x + anchor.width - actual_width)
                            .min(vw - actual_width)
                            .max(0.0)
                    } else {
                        anchor.x.min(vw - actual_width).max(0.0)
                    };
                    Rect::new(x, y, actual_width, content_size.height)
                }
                OverlayPlacement::ViewportCorner { corner, margin } => {
                    let (x, y) = corner.resolve(
                        (content_size.width, content_size.height),
                        (vw, vh),
                        (margin.x, margin.y),
                        rtl,
                    );
                    Rect::new(
                        x,
                        y,
                        content_size.width.min(vw),
                        content_size.height.min(vh),
                    )
                }
                OverlayPlacement::FullViewport => Rect::new(0.0, 0.0, vw, vh),
            };
        }
    }

    /// Set the content bounds for an overlay (after its content has been laid out).
    pub fn set_content_bounds(&mut self, id: OverlayId, size: Size) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
            overlay.bounds = Rect::new(overlay.bounds.x, overlay.bounds.y, size.width, size.height);
        }
    }

    /// Get overlay by content widget ID (for routing events to the correct overlay).
    pub fn find_by_content(&self, content_id: WidgetId) -> Option<OverlayId> {
        self.stack
            .iter()
            .find(|o| o.content_id == content_id)
            .map(|o| o.id)
    }

    /// Convenience accessor for the safe-triangle hover gate: returns
    /// the bounds rect of the open overlay whose root content widget
    /// id matches `content_id`, or `None` when no such overlay is
    /// active. Equivalent to `find_by_content` + `bounds_for` chained.
    pub fn bounds_for_content(&self, content_id: WidgetId) -> Option<Rect> {
        self.stack
            .iter()
            .find(|o| o.content_id == content_id)
            .map(|o| o.bounds)
    }

    /// Change the dismiss behavior of an active overlay in place.
    ///
    /// Used by rich tooltips that promote from "ephemeral hover" to
    /// "sticky panel" after a dwell timer: at t=2s the tooltip calls
    /// this to swap `PointerLeave` for `EscapeOrClickOutside`, so the
    /// overlay stops vanishing the moment the pointer leaves the
    /// anchor. Also cancels any in-flight pointer-leave countdown.
    pub fn set_dismiss(&mut self, id: OverlayId, behavior: DismissBehavior) {
        if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
            overlay.dismiss = behavior;
            overlay.pointer_leave_started_real = None;
            overlay.pointer_leave_started_sim = None;
        }
    }
}

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

impl std::fmt::Debug for OverlayManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OverlayManager")
            .field("active_count", &self.stack.len())
            .finish()
    }
}

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

    fn fake_id(n: u64) -> WidgetId {
        KeyData::from_ffi(n).into()
    }

    /// A `Below`/`Above` overlay must stay inside the viewport in **LTR**, not
    /// only RTL.
    ///
    /// The LTR arm was a bare `anchor.x`, so a popover whose trigger sat near
    /// the right edge — a status-bar button, a toolbar-trailing control — ran
    /// off the screen and lost its trailing edge. Nothing caught it because the
    /// RTL arm, which has always clamped, is the one that looks like it needs
    /// the arithmetic.
    #[test]
    fn a_wide_overlay_near_the_trailing_edge_is_clamped_into_the_viewport() {
        let vw = 1200.0;
        // A 380 px-wide popover under a 90 px button whose left edge is at 1035:
        // unclamped it would end at 1415, 215 px past the window.
        let anchor = Rect::new(1035.0, 760.0, 90.0, 28.0);
        let x = leading_aligned_x(anchor, 380.0, vw, false);
        assert!(
            x + 380.0 <= vw + 0.01,
            "overlay must not extend past the viewport: x={x}"
        );
        assert!(x >= 0.0, "and must not start off the leading edge: x={x}");

        // Comfortably inside, the leading edge is still honoured exactly —
        // clamping must not nudge overlays that already fit.
        let inside = Rect::new(100.0, 760.0, 90.0, 28.0);
        assert_eq!(leading_aligned_x(inside, 380.0, vw, false), 100.0);

        // RTL keeps aligning to the anchor's physical right edge.
        let x_rtl = leading_aligned_x(inside, 380.0, vw, true);
        assert!(x_rtl >= 0.0 && x_rtl + 380.0 <= vw + 0.01);
    }

    /// A viewport narrower than the overlay pins the **leading** edge and clips
    /// the trailing one — losing the start of the content would hide the first
    /// thing the reader needs (a search field, a title).
    #[test]
    fn an_overlay_wider_than_the_viewport_keeps_its_leading_edge_visible() {
        let x = leading_aligned_x(Rect::new(40.0, 10.0, 60.0, 20.0), 900.0, 500.0, false);
        assert_eq!(x, 0.0);
    }

    #[test]
    fn dismiss_all_fires_on_dismiss_callbacks() {
        // Regression: a `MenuItem`'s tap handler calls
        // `ctx.dismiss_all_overlays()` to close the menu after firing
        // its action. The dismiss callback set on the parent
        // `PopoverButton`/`PopoverIconButton`'s `OverlayRequest`
        // (which flips `popover_open` back to `false`) must fire so
        // the next trigger click reopens the menu instead of
        // observing stale-true and silently retoggling.
        use std::cell::Cell;
        use std::rc::Rc;
        let mut mgr = OverlayManager::new();
        let fired_a = Rc::new(Cell::new(0_u32));
        let fired_b = Rc::new(Cell::new(0_u32));
        let cb_a: OverlayDismissCallback = {
            let f = fired_a.clone();
            Rc::new(move || f.set(f.get() + 1))
        };
        let cb_b: OverlayDismissCallback = {
            let f = fired_b.clone();
            Rc::new(move || f.set(f.get() + 1))
        };
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: Some(cb_a),
            fade_duration: None,
        });
        mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: fake_id(2),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: Some(cb_b),
            fade_duration: None,
        });
        let dismissed = mgr.dismiss_all();
        assert_eq!(dismissed.len(), 2);
        assert!(mgr.is_empty());
        assert_eq!(
            fired_a.get(),
            1,
            "first overlay's on_dismiss must fire exactly once",
        );
        assert_eq!(
            fired_b.get(),
            1,
            "second overlay's on_dismiss must fire exactly once",
        );
    }

    #[test]
    fn show_and_dismiss() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        assert_eq!(mgr.len(), 1);

        mgr.dismiss(id);
        assert!(mgr.is_empty());
    }

    #[test]
    fn cascade_dismissal() {
        let mut mgr = OverlayManager::new();
        let parent = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        let _child = mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: fake_id(10),
            placement: OverlayPlacement::TrailingEdge,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: Some(parent),
            on_dismiss: None,
            fade_duration: None,
        });
        assert_eq!(mgr.len(), 2);

        // Dismissing parent cascades to child
        mgr.dismiss(parent);
        assert!(mgr.is_empty());
    }

    #[test]
    fn cascade_depth_is_bounded() {
        // A cyclic tooltip `:key` cascade (A→B→A) keeps minting nested
        // overlays with no natural ceiling. `MAX_OVERLAY_NESTING_DEPTH`
        // bounds it: once a new overlay would nest at the cap, `show`
        // drops it rather than growing the stack forever — and must not
        // panic, since this is reachable by real user clicking.
        let mut mgr = OverlayManager::new();
        let mut parent = mgr.show(OverlayRequest {
            content_id: fake_id(100),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        // Root is depth 0; fill the chain so MAX overlays exist, the
        // deepest at depth MAX-1.
        for i in 1..MAX_OVERLAY_NESTING_DEPTH {
            parent = mgr.show(OverlayRequest {
                content_id: fake_id(100 + i as u64),
                anchor: fake_id(1),
                placement: OverlayPlacement::Below,
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: Some(parent),
                on_dismiss: None,
                fade_duration: None,
            });
        }
        assert_eq!(
            mgr.len(),
            MAX_OVERLAY_NESTING_DEPTH,
            "chain should fill exactly to the cap"
        );

        // The next child would nest at depth == MAX → dropped.
        let dropped = mgr.show(OverlayRequest {
            content_id: fake_id(999),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: Some(parent),
            on_dismiss: None,
            fade_duration: None,
        });
        assert_eq!(
            mgr.len(),
            MAX_OVERLAY_NESTING_DEPTH,
            "over-cap overlay must not be pushed"
        );
        assert!(
            mgr.stack.iter().all(|o| o.id != dropped),
            "the dropped overlay id must not appear in the stack"
        );
    }

    #[test]
    fn dismiss_top() {
        let mut mgr = OverlayManager::new();
        let _a = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        let b = mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: fake_id(2),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let dismissed = mgr.dismiss_top();
        assert_eq!(dismissed.map(|(id, _, _)| id), Some(b));
        assert_eq!(mgr.len(), 1);
    }

    #[test]
    fn click_outside_dismisses() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        // Set overlay bounds
        let id = mgr.active_ids()[0];
        mgr.set_content_bounds(id, Size::new(100.0, 50.0));

        // Click inside — no dismiss
        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(50.0, 25.0));
        assert!(dismissed.is_empty());
        assert_eq!(mgr.len(), 1);

        // Click outside — dismissed
        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert!(!dismissed.is_empty());
        assert!(mgr.is_empty());
    }

    #[test]
    fn click_outside_returns_focus_restore() {
        let mut mgr = OverlayManager::new();
        let trigger = fake_id(99);
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        let id = mgr.active_ids()[0];
        mgr.set_content_bounds(id, Size::new(100.0, 50.0));
        mgr.set_top_focus_restore(trigger);

        let (dismissed, focus_restore, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert_eq!(dismissed.len(), 1);
        assert_eq!(focus_restore, Some(trigger));
    }

    #[test]
    fn click_outside_focus_restore_picks_bottommost() {
        // When click-outside dismisses several stacked top-level
        // overlays in one pass, focus should land on the *oldest*
        // overlay's restore target — the focus state from before any
        // overlay opened. The topmost overlay's restore target points
        // inside the (now-dismissed) overlay below it.
        let mut mgr = OverlayManager::new();
        let pre_overlay_focus = fake_id(99);
        let inside_a = fake_id(50);
        let a = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.set_content_bounds(a, Size::new(100.0, 50.0));
        mgr.set_top_focus_restore(pre_overlay_focus);
        let b = mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: fake_id(2),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.set_content_bounds(b, Size::new(100.0, 50.0));
        mgr.set_top_focus_restore(inside_a);

        let (_, focus_restore, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert_eq!(focus_restore, Some(pre_overlay_focus));
    }

    #[test]
    fn manual_dismiss_ignores_click_outside() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert!(dismissed.is_empty());
        assert_eq!(mgr.len(), 1);
    }

    #[test]
    fn escape_dismisses_escape_or_click_outside() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeOrClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let dismissed = mgr.try_dismiss_top_on_escape();
        assert_eq!(dismissed.map(|(oid, _, _)| oid), Some(id));
        assert!(mgr.is_empty());
    }

    #[test]
    fn escape_dismisses_escape_key_only() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeKey,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        // Escape should dismiss
        let dismissed = mgr.try_dismiss_top_on_escape();
        assert_eq!(dismissed.map(|(oid, _, _)| oid), Some(id));
        assert!(mgr.is_empty());
    }

    #[test]
    fn escape_does_not_dismiss_click_outside_only() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        assert!(mgr.try_dismiss_top_on_escape().is_none());
        assert_eq!(mgr.len(), 1);
    }

    #[test]
    fn escape_does_not_dismiss_manual() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        assert!(mgr.try_dismiss_top_on_escape().is_none());
        assert_eq!(mgr.len(), 1);
    }

    #[test]
    fn click_outside_dismisses_escape_or_click_outside() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeOrClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let id = mgr.active_ids()[0];
        mgr.set_content_bounds(id, Size::new(100.0, 50.0));

        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert!(!dismissed.is_empty());
        assert!(mgr.is_empty());
    }

    #[test]
    fn click_outside_reports_click_opened_anchors_only() {
        // An outside click dismisses both a click-opened dropdown and a
        // hover-opened tooltip, but only the click-opened overlay's anchor
        // is reported as a re-toggle guard: clicking a tooltip's anchor
        // should still fall through to the widget beneath.
        let mut mgr = OverlayManager::new();
        let click_anchor = fake_id(1);
        let hover_anchor = fake_id(2);

        let click_overlay = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: click_anchor,
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeOrClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.set_content_bounds(click_overlay, Size::new(100.0, 50.0));

        let hover_overlay = mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: hover_anchor,
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::PointerLeave {
                delay: std::time::Duration::from_millis(150),
            },
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.set_content_bounds(hover_overlay, Size::new(100.0, 50.0));

        let (dismissed, _focus, toggle_anchors) =
            mgr.handle_click_outside(Point::new(500.0, 500.0));

        // Both overlays close on the outside click...
        assert_eq!(dismissed.len(), 2);
        assert!(mgr.is_empty());
        // ...but only the click-opened dropdown contributes a guard anchor.
        assert_eq!(toggle_anchors, vec![click_anchor]);
    }

    #[test]
    fn click_outside_does_not_dismiss_escape_key_only() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::EscapeKey,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
        assert!(dismissed.is_empty());
        assert_eq!(mgr.len(), 1);
    }

    #[test]
    fn click_outside_is_layered_over_a_modal() {
        // A modal card with a sticky tooltip floating above it (as a rich
        // tooltip becomes after it dwells). Regression for: while any modal
        // (or its full-viewport scrim) was open, the old stack-wide `hit_test`
        // short-circuit made *no* click-outside overlay dismissable, so the
        // sticky tooltip never closed on a click elsewhere in the modal.
        fn set_bounds(mgr: &mut OverlayManager, id: OverlayId, r: Rect) {
            mgr.stack.iter_mut().find(|o| o.id == id).unwrap().bounds = r;
        }
        // Build a fresh [modal, tooltip] stack. The modal card spans
        // x∈[300,900], y∈[60,740]; the sticky tooltip sits near the card's
        // bottom and *overflows* below it (y∈[620,760]).
        fn build() -> (OverlayManager, OverlayId, OverlayId) {
            let mut mgr = OverlayManager::new();
            let modal = mgr.show(OverlayRequest {
                content_id: fake_id(10),
                anchor: fake_id(1),
                placement: OverlayPlacement::Centered,
                dismiss: DismissBehavior::EscapeOrClickOutside,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            });
            set_bounds(&mut mgr, modal, Rect::new(300.0, 60.0, 600.0, 680.0));
            let tooltip = mgr.show(OverlayRequest {
                content_id: fake_id(11),
                anchor: fake_id(2),
                placement: OverlayPlacement::Below,
                // A promoted sticky rich tooltip: EscapeOrClickOutside.
                dismiss: DismissBehavior::EscapeOrClickOutside,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            });
            set_bounds(&mut mgr, tooltip, Rect::new(400.0, 620.0, 200.0, 140.0));
            (mgr, modal, tooltip)
        }

        // 1. Click elsewhere inside the modal card (outside the tooltip) →
        //    the tooltip (stacked above) dismisses; the modal stays up.
        let (mut mgr, modal, _tooltip) = build();
        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(350.0, 100.0));
        assert!(dismissed.contains(&fake_id(11)), "tooltip should dismiss");
        assert!(
            mgr.active_ids().contains(&modal),
            "modal must survive a click inside itself"
        );

        // 2. Click inside the tooltip — even the part overflowing below the
        //    card — leaves BOTH standing (nothing is stacked above the hit).
        let (mut mgr, modal, tooltip) = build();
        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(450.0, 750.0));
        assert!(
            dismissed.is_empty(),
            "clicking the tooltip dismisses nothing"
        );
        assert!(mgr.active_ids().contains(&modal));
        assert!(mgr.active_ids().contains(&tooltip));

        // 3. Click the bare background (outside both) → both dismiss, as
        //    before (each per its own click-outside policy).
        let (mut mgr, _modal, _tooltip) = build();
        let (dismissed, _, _) = mgr.handle_click_outside(Point::new(10.0, 10.0));
        assert!(dismissed.contains(&fake_id(10)));
        assert!(dismissed.contains(&fake_id(11)));
        assert!(mgr.is_empty());
    }

    #[test]
    fn active_content_ids() {
        let mut mgr = OverlayManager::new();
        mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.show(OverlayRequest {
            content_id: fake_id(20),
            anchor: fake_id(2),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        let ids = mgr.active_content_ids();
        assert_eq!(ids.len(), 2);
        assert_eq!(ids[0], fake_id(10));
        assert_eq!(ids[1], fake_id(20));
    }

    #[test]
    fn hit_test_topmost_first() {
        let mut mgr = OverlayManager::new();
        let a = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        let b = mgr.show(OverlayRequest {
            content_id: fake_id(11),
            anchor: fake_id(2),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        // Both overlays at origin with same bounds
        mgr.set_content_bounds(a, Size::new(100.0, 50.0));
        mgr.set_content_bounds(b, Size::new(100.0, 50.0));

        // Hit test should find topmost (b)
        assert_eq!(mgr.hit_test(Point::new(50.0, 25.0)), Some(b));
    }

    #[test]
    fn hit_test_skips_a_fading_out_overlay() {
        // Regression: dismissing a faded overlay only starts the fade-out and
        // defers stack removal, so the overlay lingers in the stack (and its
        // content stays interactive) for the fade duration. `hit_test` must
        // treat it as gone — matching `active_ids` — so clicks reach the
        // widget underneath and outside-click dismissal of lower overlays
        // isn't suppressed by the ghost.
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Below,
            dismiss: DismissBehavior::ClickOutside,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: Some(Duration::from_millis(150)),
        });
        mgr.set_content_bounds(id, Size::new(100.0, 50.0));
        let point = Point::new(50.0, 25.0);

        // Live overlay: hittable, and reported by active_ids.
        assert_eq!(mgr.hit_test(point), Some(id));
        assert!(mgr.active_ids().contains(&id));

        // The fade machinery is populated post-show by the framework.
        mgr.attach_fade(id, Signal::new(1.0), Duration::from_millis(150));

        // Dismissing only starts the fade-out — the overlay is still in the
        // stack until `process_pending_fade_dismissals` fires.
        let dismissed = mgr.dismiss(id);
        assert!(dismissed.is_empty(), "fade-out defers removal");
        assert_eq!(mgr.stack.len(), 1, "overlay lingers during the fade");

        // Both predicates now agree it's gone.
        assert_eq!(
            mgr.hit_test(point),
            None,
            "fading overlay no longer eats clicks"
        );
        assert!(!mgr.active_ids().contains(&id));
    }

    #[test]
    fn centered_placement_uses_viewport_center() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::Centered,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        mgr.set_content_bounds(id, Size::new(240.0, 120.0));
        mgr.position_overlays(
            |_| Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );

        let bounds = mgr
            .stack
            .iter()
            .find(|overlay| overlay.id == id)
            .unwrap()
            .bounds;
        assert!((bounds.x - 280.0).abs() < 0.01);
        assert!((bounds.y - 240.0).abs() < 0.01);
    }

    #[test]
    fn bottom_center_placement_uses_viewport_bottom_margin() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::BottomCenter,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });

        mgr.set_content_bounds(id, Size::new(240.0, 64.0));
        mgr.position_overlays(
            |_| Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );

        let bounds = mgr
            .stack
            .iter()
            .find(|overlay| overlay.id == id)
            .unwrap()
            .bounds;
        assert!((bounds.x - 280.0).abs() < 0.01);
        assert!((bounds.y - 512.0).abs() < 0.01);
    }

    // --- ViewportCorner placement ---

    fn show_corner_overlay(
        mgr: &mut OverlayManager,
        corner: Corner,
        margin: Vec2,
        size: Size,
    ) -> OverlayId {
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(10),
            anchor: fake_id(1),
            placement: OverlayPlacement::ViewportCorner { corner, margin },
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        mgr.set_content_bounds(id, size);
        id
    }

    fn overlay_bounds(mgr: &OverlayManager, id: OverlayId) -> Rect {
        mgr.stack.iter().find(|o| o.id == id).unwrap().bounds
    }

    #[test]
    fn viewport_corner_top_leading_ltr() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::TopLeading,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        assert!((b.x - 24.0).abs() < 0.01, "x = {}", b.x);
        assert!((b.y - 24.0).abs() < 0.01, "y = {}", b.y);
    }

    #[test]
    fn viewport_corner_top_trailing_ltr() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::TopTrailing,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        // 800 - 380 - 24 = 396
        assert!((b.x - 396.0).abs() < 0.01, "x = {}", b.x);
        assert!((b.y - 24.0).abs() < 0.01);
    }

    #[test]
    fn viewport_corner_bottom_leading_ltr() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::BottomLeading,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        // 600 - 100 - 24 = 476
        assert!((b.x - 24.0).abs() < 0.01);
        assert!((b.y - 476.0).abs() < 0.01, "y = {}", b.y);
    }

    #[test]
    fn viewport_corner_bottom_trailing_ltr() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::BottomTrailing,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        assert!((b.x - 396.0).abs() < 0.01);
        assert!((b.y - 476.0).abs() < 0.01);
    }

    #[test]
    fn viewport_corner_top_trailing_rtl_flips_to_left() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::TopTrailing,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::RightToLeft,
        );
        let b = overlay_bounds(&mgr, id);
        // RTL flips Trailing to physical left
        assert!((b.x - 24.0).abs() < 0.01, "x = {}", b.x);
        assert!((b.y - 24.0).abs() < 0.01);
    }

    #[test]
    fn viewport_corner_bottom_leading_rtl_flips_to_right() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::BottomLeading,
            Vec2::new(24.0, 24.0),
            Size::new(380.0, 100.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::RightToLeft,
        );
        let b = overlay_bounds(&mgr, id);
        assert!((b.x - 396.0).abs() < 0.01, "x = {}", b.x);
        assert!((b.y - 476.0).abs() < 0.01);
    }

    #[test]
    fn viewport_corner_ignores_anchor_bounds() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::BottomTrailing,
            Vec2::new(0.0, 0.0),
            Size::new(100.0, 100.0),
        );
        // Even with an absurd anchor location, ViewportCorner only uses viewport.
        mgr.position_overlays(
            |_| Some(Rect::new(123.0, 456.0, 7.0, 8.0)),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        assert_eq!((b.x, b.y), (700.0, 500.0));
    }

    #[test]
    fn near_anchor_horizontal_is_direction_aware() {
        // NearAnchor (used by tooltips): LTR aligns the content's leading
        // (left) edge to the anchor's left edge; RTL mirrors it, aligning
        // the content's trailing (right) edge to the anchor's right edge.
        // Anchor x=600, w=100 (right edge 700); content w=200; offset 0.
        // Viewport 800×600 — wide enough that the clamp doesn't bite.
        let anchor = Rect::new(600.0, 100.0, 100.0, 20.0);
        let resolved_x = |dir: LayoutDirection| {
            let mut mgr = OverlayManager::new();
            let id = mgr.show(OverlayRequest {
                content_id: fake_id(10),
                anchor: fake_id(1),
                placement: OverlayPlacement::NearAnchor {
                    offset: Vec2::new(0.0, 8.0),
                },
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            });
            mgr.set_content_bounds(id, Size::new(200.0, 50.0));
            mgr.position_overlays(|_| Some(anchor), (800.0, 600.0), dir);
            overlay_bounds(&mgr, id).x
        };
        // LTR: anchor.x + offset.x = 600.
        assert!(
            (resolved_x(LayoutDirection::LeftToRight) - 600.0).abs() < 0.01,
            "LTR x = {}",
            resolved_x(LayoutDirection::LeftToRight)
        );
        // RTL: anchor.x + anchor.width - content.w - offset.x = 500.
        assert!(
            (resolved_x(LayoutDirection::RightToLeft) - 500.0).abs() < 0.01,
            "RTL x = {}",
            resolved_x(LayoutDirection::RightToLeft)
        );
    }

    // --- Auto-dismiss pause / resume ---

    #[test]
    fn pause_auto_dismiss_removes_overlay_from_deadline_set() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show_for(
            OverlayRequest {
                content_id: fake_id(10),
                anchor: fake_id(1),
                placement: OverlayPlacement::Centered,
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            },
            Duration::from_secs(10),
        );
        assert!(mgr.next_auto_dismiss_deadline().is_some());
        assert!(!mgr.is_auto_dismiss_paused(id));

        mgr.pause_auto_dismiss(id);
        assert!(mgr.is_auto_dismiss_paused(id));
        assert!(
            mgr.next_auto_dismiss_deadline().is_none(),
            "paused overlay must drop out of the deadline-min query"
        );

        mgr.resume_auto_dismiss(id);
        assert!(!mgr.is_auto_dismiss_paused(id));
        assert!(mgr.next_auto_dismiss_deadline().is_some());
    }

    #[test]
    fn pause_then_resume_restores_remaining_time() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show_for(
            OverlayRequest {
                content_id: fake_id(11),
                anchor: fake_id(1),
                placement: OverlayPlacement::Centered,
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            },
            Duration::from_secs(10),
        );

        mgr.pause_auto_dismiss(id);
        // Sleep equivalent: rely on the fact pausing right after show
        // captures ~10s remaining (elapsed is ~0).
        let overlay = mgr.stack.iter().find(|o| o.id == id).unwrap();
        let remaining = overlay.paused_remaining.unwrap();
        assert!(
            remaining >= Duration::from_secs(9),
            "remaining should be near the original 10s, got {remaining:?}"
        );
        assert!(remaining <= Duration::from_secs(10));

        mgr.resume_auto_dismiss(id);
        let overlay = mgr.stack.iter().find(|o| o.id == id).unwrap();
        // After resume, auto_dismiss_after equals the previously-stashed
        // remaining, and shown_at_real has been refreshed so the new
        // deadline starts from "now + remaining".
        assert_eq!(overlay.auto_dismiss_after, Some(remaining));
        assert!(overlay.paused_remaining.is_none());
    }

    #[test]
    fn pause_is_idempotent() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show_for(
            OverlayRequest {
                content_id: fake_id(12),
                anchor: fake_id(1),
                placement: OverlayPlacement::Centered,
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            },
            Duration::from_secs(10),
        );
        mgr.pause_auto_dismiss(id);
        let first_remaining = mgr.stack[0].paused_remaining;
        mgr.pause_auto_dismiss(id); // second pause must not overwrite
        let second_remaining = mgr.stack[0].paused_remaining;
        assert_eq!(
            first_remaining, second_remaining,
            "double-pause must preserve the original stashed remaining"
        );
    }

    #[test]
    fn resume_on_unpaused_is_noop() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show_for(
            OverlayRequest {
                content_id: fake_id(13),
                anchor: fake_id(1),
                placement: OverlayPlacement::Centered,
                dismiss: DismissBehavior::Manual,
                layer: OverlayLayer::InTree,
                parent_overlay: None,
                on_dismiss: None,
                fade_duration: None,
            },
            Duration::from_secs(10),
        );
        let before = mgr.stack[0].auto_dismiss_after;
        mgr.resume_auto_dismiss(id); // never paused
        let after = mgr.stack[0].auto_dismiss_after;
        assert_eq!(before, after);
    }

    #[test]
    fn pause_on_persistent_overlay_is_noop() {
        let mut mgr = OverlayManager::new();
        let id = mgr.show(OverlayRequest {
            content_id: fake_id(14),
            anchor: fake_id(1),
            placement: OverlayPlacement::Centered,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        // No auto_dismiss_after — pause should be a no-op.
        mgr.pause_auto_dismiss(id);
        assert!(!mgr.is_auto_dismiss_paused(id));
        assert!(mgr.stack[0].paused_remaining.is_none());
    }

    #[test]
    fn pause_on_unknown_id_is_noop() {
        let mut mgr = OverlayManager::new();
        mgr.pause_auto_dismiss(OverlayId::new(9999)); // must not panic
        mgr.resume_auto_dismiss(OverlayId::new(9999));
    }

    #[test]
    fn viewport_corner_zero_margin_snaps_to_edge() {
        let mut mgr = OverlayManager::new();
        let id = show_corner_overlay(
            &mut mgr,
            Corner::TopLeading,
            Vec2::ZERO,
            Size::new(50.0, 50.0),
        );
        mgr.position_overlays(
            |_| Some(Rect::ZERO),
            (800.0, 600.0),
            LayoutDirection::LeftToRight,
        );
        let b = overlay_bounds(&mgr, id);
        assert_eq!((b.x, b.y), (0.0, 0.0));
    }
}