teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Toast notification — stackable, action-rich, severity-aware floating
//! notification (the "upgrade path" from [`Snackbar`](crate::snackbar)).
//!
//! Distinct from siblings:
//! - [`Snackbar`](crate::snackbar::Snackbar) — single-instance, message-only.
//!   Calling `present_snackbar` dismisses all other overlays first.
//! - [`Banner`](crate::banner::Banner) — persistent inline strip, not a floating
//!   overlay.
//! - [`MessageBox`](crate::message_box::MessageBox) — modal dialog. Blocks
//!   interaction with the rest of the UI.
//!
//! A `Toast` is built with one of the four severity constructors
//! (`info` / `success` / `warning` / `error`) plus a `loading` variant,
//! configured via builder methods, and presented with
//! `ctx.show_toast(toast)` (see
//! [`toast::ext::EventContextToastExt`](crate::toast::ext::EventContextToastExt))
//! or `toast.present(ctx)`. A [`ToastHost`]
//! installed via `TeksiloAppBuilder.install_toast(opts)` from the `teksilo`
//! umbrella accepts the request, picks a free slot from its pool, and
//! mounts a [`ToastSurface`] at the
//! configured viewport corner using the
//! [`OverlayPlacement::ViewportCorner`](teksilo_core::overlay::OverlayPlacement)
//! variant.
//!
//! ```ignore
//! ctx.show_toast(
//!     Toast::warning(tr!(unsaved_changes()))
//!         .body(tr!(close_anyway_question()))
//!         .action(ToastAction::primary(tr!(save()), |c| c.send_intent(AppIntent::Save)))
//!         .action(ToastAction::new(tr!(discard()), |c| c.send_intent(AppIntent::Discard)))
//! );
//! ```

pub mod body;
pub mod ext;
pub mod host;
pub mod registry;
pub mod surface;

use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;

use teksilo_core::widget::{EventContext, Widget};
use teksilo_core::window::TeksiloWindowId;

pub use body::TOAST_BODY_COLLAPSED_LINES;
pub use ext::EventContextToastExt;
pub use host::{ToastHost, ToastInstallOptions};
pub use registry::ToastRegistry;
pub use surface::ToastSurface;
pub use teksilo_core::styles::{ToastPriority, ToastStyleConfig};

/// Toast severity — re-export of `BannerSeverity` so apps that mix
/// `Banner` and `Toast` share one severity vocabulary. The same
/// `severity.surface()` / `severity.glyph_color(theme)` helpers apply.
pub use teksilo_core::styles::BannerSeverity as ToastSeverity;
use teksilo_i18n::LocalizedString;

/// Default auto-dismiss duration when the caller does not override
/// it (matches IntelliJ `BALLOON` and Material Snackbar maximum).
pub const DEFAULT_TOAST_AUTO_DISMISS: Duration = Duration::from_secs(10);

// =====================================================================
// ToastDismissCause
// =====================================================================

/// Why a toast was dismissed — delivered to the `on_dismiss` callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ToastDismissCause {
    /// `auto_dismiss_after` reached zero (timer expired naturally).
    Timeout,
    /// A `ToastAction` with `closes_toast(true)` (the default) fired.
    ActionInvoked,
    /// The user clicked the close (X) button.
    CloseClicked,
    /// The user pressed Escape while focus was inside the toast.
    EscapePressed,
    /// `ToastHandle::dismiss` was called from app code.
    Programmatic,
    /// The host's window is being torn down.
    HostShutdown,
    /// The host's slot pool was at `max_visible` and this toast was
    /// dropped (Normal priority overflow) or was evicted by a
    /// higher-priority arrival. Reported synthetically so `on_dismiss`
    /// always fires once per toast — apps that track outstanding
    /// toasts via the callback don't leak.
    SlotPoolFull,
}

// =====================================================================
// Routing — ToastAudience / ToastRoute
// =====================================================================

/// Opaque per-app routing token. teksilo has no notion of what an
/// "audience" means to the host app (a document, a project, a user
/// session, …) — it only ever compares and hashes this value. Apps
/// mint their own tokens (typically one per open document/window
/// group) via [`ToastAudience::new`] and pass the same value to
/// `Toast::target(...)` and `ToastRegistry::set_window_audience(...)`
/// to link the two sides of the routing decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ToastAudience(u64);

impl ToastAudience {
    /// Construct a token from an app-chosen `u64`. The app owns the
    /// meaning entirely — teksilo never inspects the value beyond
    /// equality/hash.
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// The raw numeric value, for debugging/serialization by the app.
    pub fn raw(&self) -> u64 {
        self.0
    }
}

/// Resolved delivery target for a toast (and, mirrored, its archived
/// `NotificationEntry`).
///
/// Three levels, from narrowest to widest:
/// - `Window` — exactly the window that presented the toast. This is
///   the default when a `Toast` carries no explicit `.target()` /
///   `.broadcast()` and was presented through a real `EventContext`
///   (i.e. `ctx.show_toast(...)` / `toast.present(ctx)` from an actual
///   input handler) — see `EventContextToastExt::show_toast`.
/// - `Audience` — every window currently assigned the given
///   [`ToastAudience`] via `ToastRegistry::set_window_audience`.
/// - `Broadcast` — every window, unconditionally. Also the fallback
///   when a toast is enqueued with no window AND no explicit target
///   (e.g. `ToastRegistry::show_settings_write_failed`, which fires
///   from a background `AppEvent` observer with no `EventContext` at
///   all) — an app-wide message with nothing narrower to route by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ToastRoute {
    /// Delivered only to the window with this id. Never publicly
    /// constructible from a `Toast` builder — only the framework
    /// stamps this, from a real `EventContext::window()` at present
    /// time — so an app can't accidentally fabricate a route to a
    /// window it doesn't own.
    Window(TeksiloWindowId),
    /// Delivered to every window currently assigned this audience.
    Audience(ToastAudience),
    /// Delivered to every window, unconditionally.
    Broadcast,
}

// =====================================================================
// ToastAction
// =====================================================================

/// How a [`ToastAction`] should be rendered inside the toast surface.
#[derive(Debug, Clone, Default)]
pub enum ToastActionStyle {
    /// JetBrains-style hyperlink. Rendered inline with the body row.
    /// Default — minimal visual weight, scales to many actions.
    #[default]
    Link,
    /// Material / Windows-style button. Rendered in a dedicated row
    /// below the body. Use for primary calls-to-action ("Retry",
    /// "Save", "Discard").
    Button {
        /// Variant passed to the underlying `Button`. Filled for
        /// primaries, Plain / Tinted for secondaries.
        variant: crate::button::ButtonVariant,
    },
}

/// Type-erased callback for a [`ToastAction`]. `Fn` (not `FnMut`) so
/// the same callback can be wrapped in an `Rc` and dispatched from
/// multiple paths (tap, keyboard, AT custom action).
pub type ToastActionCallback = Rc<dyn Fn(&mut EventContext)>;

/// One actionable element inside a [`Toast`] — a button or hyperlink
/// the user can click to drive a domain action.
pub struct ToastAction {
    label: LocalizedString,
    on_invoke: ToastActionCallback,
    style: ToastActionStyle,
    closes_toast: bool,
    shortcut_id: Option<String>,
    tooltip: Option<LocalizedString>,
}

impl ToastAction {
    /// Build an action with the default `Link` style and
    /// `closes_toast = true` (IntelliJ "expiring action" semantics).
    pub fn new(
        label: impl Into<LocalizedString>,
        on_invoke: impl Fn(&mut EventContext) + 'static,
    ) -> Self {
        let ls: LocalizedString = label.into();
        Self {
            label: ls,
            on_invoke: Rc::new(on_invoke),
            style: ToastActionStyle::default(),
            closes_toast: true,
            shortcut_id: None,
            tooltip: None,
        }
    }

    /// Shorthand for `ToastAction::new(label, on_invoke).style(Button { Filled })`.
    /// The visual-weight default for primary calls-to-action.
    pub fn primary(
        label: impl Into<LocalizedString>,
        on_invoke: impl Fn(&mut EventContext) + 'static,
    ) -> Self {
        Self::new(label, on_invoke).style(ToastActionStyle::Button {
            variant: crate::button::ButtonVariant::Filled,
        })
    }

    /// Shorthand for the destructive button variant — red-tinted for
    /// confirm-style "Delete" / "Discard" actions.
    pub fn destructive(
        label: impl Into<LocalizedString>,
        on_invoke: impl Fn(&mut EventContext) + 'static,
    ) -> Self {
        Self::new(label, on_invoke).style(ToastActionStyle::Button {
            variant: crate::button::ButtonVariant::Destructive,
        })
    }

    /// Override the action's visual style. Default is `Link`.
    pub fn style(mut self, style: ToastActionStyle) -> Self {
        self.style = style;
        self
    }

    /// Whether invoking this action also dismisses the toast. Default
    /// is `true` — matches IntelliJ's "expiring action" semantics.
    /// Set to `false` for actions that toggle state without closing
    /// (e.g. "Show details" disclosure inside a sticky toast).
    pub fn closes_toast(mut self, closes: bool) -> Self {
        self.closes_toast = closes;
        self
    }

    /// Associate the action with a registered `Shortcut` id. Two
    /// effects: the keystroke label is shown as a chip on the action,
    /// and the archived form of this action (in
    /// [`NotificationLog`](crate::notification::log::NotificationLog))
    /// is re-invokable by name through the existing Intent
    /// dispatcher.
    pub fn shortcut_id(mut self, id: impl Into<String>) -> Self {
        self.shortcut_id = Some(id.into());
        self
    }

    /// Optional tooltip text shown when the pointer hovers the action.
    pub fn tooltip(mut self, text: impl Into<LocalizedString>) -> Self {
        self.tooltip = Some(text.into());
        self
    }

    /// Resolve the action label to a plain string using the current locale.
    pub fn label(&self) -> String {
        self.label.resolve_now()
    }
    /// Return the action's rendering style (link vs button variant).
    pub fn style_ref(&self) -> &ToastActionStyle {
        &self.style
    }
    /// Return `true` when invoking this action also dismisses the toast.
    pub fn closes_toast_flag(&self) -> bool {
        self.closes_toast
    }
    /// Return the associated `Shortcut` id, if any.
    pub fn shortcut_id_ref(&self) -> Option<&str> {
        self.shortcut_id.as_deref()
    }
    /// The action label as a `LocalizedString` (reactive source for
    /// the rendered Link/Button).
    pub(crate) fn label_ls(&self) -> LocalizedString {
        self.label.clone()
    }

    /// Return the optional tooltip text, if one was set via [`tooltip`](ToastAction::tooltip).
    pub fn tooltip_ref(&self) -> Option<&LocalizedString> {
        self.tooltip.as_ref()
    }
    /// Clone the invocation callback — cheap because the underlying closure is `Rc`-wrapped.
    pub fn callback(&self) -> ToastActionCallback {
        self.on_invoke.clone()
    }
}

impl std::fmt::Debug for ToastAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToastAction")
            .field("label", &self.label)
            .field("style", &self.style)
            .field("closes_toast", &self.closes_toast)
            .field("shortcut_id", &self.shortcut_id)
            .finish()
    }
}

// =====================================================================
// ToastHandle
// =====================================================================

/// Returned by [`Toast::present`] (and `ctx.show_toast(toast)`). Cheap
/// to clone (`Rc<Inner>`). Lets app code dismiss the toast
/// programmatically or check whether it is still alive.
///
/// Dropping the handle does NOT dismiss the toast — toasts have their
/// own lifecycle managed by the host (timer + manual paths). The
/// handle is the OPTIONAL "I want to control this toast later" hook.
#[derive(Clone)]
pub struct ToastHandle {
    inner: Rc<ToastHandleInner>,
}

pub(crate) struct ToastHandleInner {
    pub(crate) entry_id: u64,
    /// Marked when the host has dropped the entry (overflow at enqueue
    /// time, or any dismiss path). Cheap short-circuit for the
    /// `dismiss` / `is_alive` handle methods so they don't have to
    /// walk the registry to know "this toast is gone".
    pub(crate) dismissed: Cell<bool>,
    /// Back-reference to the registry so the handle can fire dismiss
    /// requests and check liveness.
    pub(crate) registry: registry::ToastRegistry,
}

impl ToastHandle {
    pub(crate) fn new(inner: ToastHandleInner) -> Self {
        Self {
            inner: Rc::new(inner),
        }
    }

    /// Stable per-toast id. Two `ToastHandle`s pointing at the same
    /// underlying toast share the same `entry_id`. The id is unique
    /// per `ToastRegistry` (per app) — it doesn't survive across app
    /// restarts.
    pub fn entry_id(&self) -> u64 {
        self.inner.entry_id
    }

    /// Whether the toast is still in the registry's live set (timer
    /// hasn't expired, user hasn't dismissed, host hasn't shut down).
    /// Always `false` for overflow-dropped toasts.
    pub fn is_alive(&self) -> bool {
        if self.inner.dismissed.get() {
            return false;
        }
        self.inner.registry.is_entry_alive(self.inner.entry_id)
    }

    /// Programmatically dismiss the toast with cause
    /// [`ToastDismissCause::Programmatic`]. No-op if the toast is
    /// already dismissed (timer, user, host shutdown).
    pub fn dismiss(&self, ctx: &mut EventContext) {
        if self.inner.dismissed.get() {
            return;
        }
        self.inner.registry.dismiss_entry(
            self.inner.entry_id,
            ToastDismissCause::Programmatic,
            ctx,
        );
    }
}

impl std::fmt::Debug for ToastHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToastHandle")
            .field("entry_id", &self.inner.entry_id)
            .field("dismissed", &self.inner.dismissed.get())
            .finish()
    }
}

// =====================================================================
// Toast (the present-able request)
// =====================================================================

/// Type-erased on_dismiss callback receiving the cause + context.
pub type ToastDismissCallback = Rc<dyn Fn(ToastDismissCause, &mut EventContext)>;

/// Toast — a present-able request (NOT a `Widget`). Construct with one
/// of the severity-named constructors, configure via builder methods,
/// then call `.present(ctx)` or `ctx.show_toast(self)`. Internally the
/// builder is consumed and its data is moved into a slot on the
/// installed [`ToastHost`].
///
/// See the module docs for the full conceptual overview.
pub struct Toast {
    pub(crate) severity: ToastSeverity,
    pub(crate) title: LocalizedString,
    pub(crate) body: Option<LocalizedString>,
    pub(crate) leading: Option<Box<dyn Widget>>,
    pub(crate) actions: Vec<ToastAction>,
    pub(crate) auto_dismiss_after: Option<Duration>,
    pub(crate) priority: ToastPriority,
    pub(crate) id: Option<String>,
    pub(crate) on_click: Option<Rc<dyn Fn(&mut EventContext)>>,
    pub(crate) on_dismiss: Option<ToastDismissCallback>,
    pub(crate) announcement: Option<LocalizedString>,
    pub(crate) show_close_button: bool,
    pub(crate) closable_on_escape: bool,
    pub(crate) archive: bool,
    pub(crate) style_override: Option<teksilo_core::styles::SharedToastStyle>,
    /// Resolved lazily: `None` here means "unset" — `show_toast`
    /// stamps `Some(ToastRoute::Window(origin))` from the presenting
    /// `EventContext` when the app didn't call `.target()` /
    /// `.broadcast()` explicitly. See [`ToastRoute`] for the full
    /// three-level contract.
    pub(crate) target: Option<ToastRoute>,
}

impl std::fmt::Debug for Toast {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Toast")
            .field("severity", &self.severity)
            .field("title", &self.title)
            .field("body", &self.body)
            .field("priority", &self.priority)
            .field("id", &self.id)
            .field("auto_dismiss_after", &self.auto_dismiss_after)
            .field("actions_count", &self.actions.len())
            .field("target", &self.target)
            .finish()
    }
}

impl Toast {
    fn build_with_severity(severity: ToastSeverity, title: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = title.into();
        Self {
            severity,
            title: ls,
            body: None,
            leading: None,
            actions: Vec::new(),
            auto_dismiss_after: Some(DEFAULT_TOAST_AUTO_DISMISS),
            priority: ToastPriority::Normal,
            id: None,
            on_click: None,
            on_dismiss: None,
            announcement: None,
            show_close_button: true,
            closable_on_escape: true,
            archive: true,
            style_override: None,
            target: None,
        }
    }

    // ----- Constructors -----

    /// Info-severity toast (status confirmation, neutral notice).
    pub fn info(title: impl Into<LocalizedString>) -> Self {
        Self::build_with_severity(ToastSeverity::Info, title)
    }
    /// Success-severity toast ("Saved", "Connected", "Build finished").
    pub fn success(title: impl Into<LocalizedString>) -> Self {
        Self::build_with_severity(ToastSeverity::Success, title)
    }
    /// Warning-severity toast.
    pub fn warning(title: impl Into<LocalizedString>) -> Self {
        Self::build_with_severity(ToastSeverity::Warning, title)
    }
    /// Error-severity toast. Defaults to `Live::Assertive`.
    pub fn error(title: impl Into<LocalizedString>) -> Self {
        Self::build_with_severity(ToastSeverity::Error, title)
    }
    /// Loading-style toast — Info severity with a
    /// [`Spinner`](crate::spinner::Spinner) as the leading widget.
    /// Persistent by default; the app calls
    /// [`ToastHandle::dismiss`] (typically from the operation's
    /// completion callback) or replaces it with a success/error toast.
    pub fn loading(title: impl Into<LocalizedString>) -> Self {
        Self::build_with_severity(ToastSeverity::Info, title)
            .persistent()
            .leading(crate::spinner::Spinner::new(16.0))
    }

    // ----- _literal shims (permanent grep markers for untranslated strings) -----

    // ----- Body content -----

    /// Optional secondary line below the title.
    pub fn body(mut self, text: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = text.into();
        self.body = Some(ls);
        self
    }

    /// Replace the default severity glyph with a custom leading
    /// widget (spinner, app icon, avatar). Boxes the widget so the
    /// toast remains object-safe.
    pub fn leading(mut self, widget: impl Widget + 'static) -> Self {
        self.leading = Some(Box::new(widget));
        self
    }

    // ----- Actions -----

    /// Append a [`ToastAction`] (link or button) to the toast.
    pub fn action(mut self, action: ToastAction) -> Self {
        self.actions.push(action);
        self
    }
    /// Shorthand for appending a filled-button primary action — equivalent to
    /// `.action(ToastAction::primary(label, on_invoke))`.
    pub fn primary_action(
        self,
        label: impl Into<LocalizedString>,
        on_invoke: impl Fn(&mut EventContext) + 'static,
    ) -> Self {
        self.action(ToastAction::primary(label, on_invoke))
    }

    // ----- Lifetime -----

    /// Override the auto-dismiss countdown. Pass `Duration::ZERO` for immediate dismissal
    /// on the next timer tick; call [`persistent`](Toast::persistent) to disable the timer entirely.
    pub fn auto_dismiss_after(mut self, duration: Duration) -> Self {
        self.auto_dismiss_after = Some(duration);
        self
    }
    /// Disable auto-dismiss — the toast persists until the user
    /// clicks the close X, invokes a `closes_toast` action, or the
    /// app calls [`ToastHandle::dismiss`].
    pub fn persistent(mut self) -> Self {
        self.auto_dismiss_after = None;
        self
    }
    /// Set the queue priority. `High` / `Urgent` entries evict the oldest `Normal` entry
    /// when the slot pool is full; `Urgent` also forces `Live::Assertive` regardless of severity.
    pub fn priority(mut self, priority: ToastPriority) -> Self {
        self.priority = priority;
        self
    }

    // ----- Update-in-place identity -----

    /// Stable identity for the "progress toast updates in place"
    /// pattern. A subsequent `enqueue` whose `Toast` carries the same
    /// `id` as a still-live entry mutates that entry's fields
    /// (severity, title/body, route, …) in place instead of appending
    /// a new toast — see `ToastRegistry::enqueue`'s update-in-place
    /// merge for the exact behaviour.
    ///
    /// # Hazard: this id must be unique per logical operation, not just per call site
    ///
    /// The merge matches on `id` ALONE — no route/window/audience
    /// check — and then OVERWRITES the existing entry's route with
    /// the new toast's resolved target. That's intentional: it's what
    /// lets a progress toast whose audience becomes known partway
    /// through retarget itself in place. But it also means that if
    /// TWO DIFFERENT windows (or two different audiences) each
    /// present a toast using the SAME `id` for what are, to the app,
    /// two DIFFERENT operations, the second `enqueue` finds the
    /// first window's still-live entry, mutates its text/severity to
    /// the second operation's, and steals its route out from under
    /// it — the first window's toast is not dismissed, not
    /// callback'd, just silently overwritten and gone, while the
    /// second window's operation ends up displayed under the wrong
    /// route besides.
    ///
    /// teksilo deliberately does NOT make the dedup key route-aware
    /// (matching on `(id, route)` together) — that would break the
    /// intentional retargeting case above. So in a multi-window /
    /// multi-document app, do not reuse one static string id across
    /// windows for what is conceptually a per-document (or otherwise
    /// per-audience) operation — export, delete, save, etc. Fold the
    /// document/audience identity into the id yourself, e.g.
    /// `format!("export-{work_id}")` rather than a bare `"export"`
    /// constant, so two windows running the same *kind* of operation
    /// on two different documents never collide on one entry.
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    // ----- Interaction -----

    /// Treat a click on the toast body as a meaningful action — the
    /// callback fires on tap. Cursor changes to `Pointer` over the body.
    pub fn on_click(mut self, f: impl Fn(&mut EventContext) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }
    /// Notification of dismissal. Fires exactly once per toast on any
    /// dismiss path (timer, action invocation, close click, escape,
    /// programmatic, host shutdown, slot-pool overflow).
    pub fn on_dismiss(
        mut self,
        f: impl Fn(ToastDismissCause, &mut EventContext) + 'static,
    ) -> Self {
        self.on_dismiss = Some(Rc::new(f));
        self
    }
    /// Show or hide the trailing close (×) button. Default `true`.
    pub fn show_close_button(mut self, show: bool) -> Self {
        self.show_close_button = show;
        self
    }
    /// Whether pressing Escape while the toast is focused dismisses
    /// it. Default true. Set to false in apps that have a custom
    /// Escape-handling story (focus trap, modal-style toast).
    pub fn closable_on_escape(mut self, allow: bool) -> Self {
        self.closable_on_escape = allow;
        self
    }

    // ----- Accessibility -----

    /// Override the screen-reader announcement text without changing
    /// the visible title. Useful when the visible title is iconic
    /// ("3") but the spoken text needs context ("3 unread messages").
    pub fn announcement(mut self, text: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = text.into();
        self.announcement = Some(ls);
        self
    }

    // ----- Archive -----

    /// Whether this toast is added to the persistent archive that
    /// drives [`NotificationLog`](crate::notification::log::NotificationLog).
    /// Default `true`. Set `false` for noise-suppressing
    /// transient notifications like quick "Copied!" feedback.
    pub fn archive(mut self, archive: bool) -> Self {
        self.archive = archive;
        self
    }

    // ----- Style -----

    /// Override the visual chrome for this toast instance. Takes precedence over the
    /// theme-wide `style_slots.toast` slot and the built-in `RecipeToastStyle` default.
    pub fn style(mut self, style: impl teksilo_core::styles::ToastStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    // ----- Routing -----

    /// Route this toast to every window currently assigned `audience`
    /// (via `ToastRegistry::set_window_audience`), instead of the
    /// default origin-window. Overrides any previous `.target()` /
    /// `.broadcast()` call — last setter wins.
    pub fn target(mut self, audience: ToastAudience) -> Self {
        self.target = Some(ToastRoute::Audience(audience));
        self
    }

    /// Route this toast to every window, unconditionally — for
    /// genuinely app-wide messages (a data-loss warning, an update
    /// available notice) rather than one window's concern. Overrides
    /// any previous `.target()` call — last setter wins.
    pub fn broadcast(mut self) -> Self {
        self.target = Some(ToastRoute::Broadcast);
        self
    }

    // ----- Present -----

    /// Submit the toast through the installed
    /// [`ToastHost`]. Equivalent to
    /// `ctx.show_toast(self)`. Returns a [`ToastHandle`] for
    /// programmatic control. If `install_toast` was not called the
    /// returned handle is in the "dropped" state (`is_alive` returns
    /// `false`) and a one-shot stderr warning fires explaining the omission.
    pub fn present(self, ctx: &mut EventContext) -> ToastHandle {
        EventContextToastExt::show_toast(ctx, self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use teksilo_i18n::lit;

    #[test]
    fn severity_constructors_round_trip() {
        assert_eq!(Toast::info(lit!("x")).severity, ToastSeverity::Info);
        assert_eq!(Toast::success(lit!("x")).severity, ToastSeverity::Success);
        assert_eq!(Toast::warning(lit!("x")).severity, ToastSeverity::Warning);
        assert_eq!(Toast::error(lit!("x")).severity, ToastSeverity::Error);
    }

    #[test]
    fn defaults_match_documented_values() {
        let t = Toast::info(lit!("hello"));
        assert_eq!(t.auto_dismiss_after, Some(DEFAULT_TOAST_AUTO_DISMISS));
        assert_eq!(t.priority, ToastPriority::Normal);
        assert!(t.show_close_button);
        assert!(t.closable_on_escape);
        assert!(t.archive);
        assert!(t.body.is_none());
        assert!(t.actions.is_empty());
        assert!(t.on_dismiss.is_none());
        assert!(t.on_click.is_none());
    }

    #[test]
    fn persistent_clears_auto_dismiss() {
        let t = Toast::error(lit!("boom")).persistent();
        assert!(t.auto_dismiss_after.is_none());
    }

    #[test]
    fn loading_is_info_persistent() {
        let t = Toast::loading(lit!("Uploading"));
        assert_eq!(t.severity, ToastSeverity::Info);
        assert!(
            t.auto_dismiss_after.is_none(),
            "loading is persistent by default"
        );
        assert!(t.leading.is_some(), "loading sets a Spinner leading widget");
    }

    #[test]
    fn action_primary_uses_filled_button() {
        let a = ToastAction::primary(lit!("Retry"), |_| {}).style(ToastActionStyle::Button {
            variant: crate::button::ButtonVariant::Filled,
        });
        match a.style_ref() {
            ToastActionStyle::Button {
                variant: crate::button::ButtonVariant::Filled,
            } => {}
            other => panic!("expected Button {{ Filled }}, got {other:?}"),
        }
        assert!(a.closes_toast_flag(), "actions close the toast by default");
    }

    #[test]
    fn action_closes_toast_can_be_disabled() {
        let a = ToastAction::new(lit!("Toggle"), |_| {}).closes_toast(false);
        assert!(!a.closes_toast_flag());
    }

    // -----------------------------------------------------------------
    // Registry tests
    // -----------------------------------------------------------------

    fn fresh_registry() -> ToastRegistry {
        ToastRegistry::new(host::ToastInstallOptions::default())
    }

    fn small_registry(max_visible: usize) -> ToastRegistry {
        ToastRegistry::new(host::ToastInstallOptions {
            max_visible,
            ..host::ToastInstallOptions::default()
        })
    }

    #[test]
    fn enqueue_creates_live_entry() {
        let r = fresh_registry();
        let (h, _overflow) = r.enqueue(Toast::info(lit!("Saved")));
        assert!(h.entry_id() > 0);
        assert_eq!(r.live_count(), 1);
    }

    #[test]
    fn enqueue_returns_distinct_ids() {
        let r = fresh_registry();
        let (h1, _) = r.enqueue(Toast::info(lit!("a")));
        let (h2, _) = r.enqueue(Toast::info(lit!("b")));
        let (h3, _) = r.enqueue(Toast::info(lit!("c")));
        assert!(h1.entry_id() != h2.entry_id());
        assert!(h2.entry_id() != h3.entry_id());
        assert_eq!(r.live_count(), 3);
    }

    #[test]
    fn slot_pool_overflow_drops_normal_priority() {
        let r = small_registry(2);
        let (_h1, _) = r.enqueue(Toast::info(lit!("a")));
        let (_h2, _) = r.enqueue(Toast::info(lit!("b")));
        assert_eq!(r.live_count(), 2);
        let (h3, overflow) = r.enqueue(Toast::info(lit!("c")));
        assert_eq!(
            r.live_count(),
            2,
            "third Normal-priority toast must be dropped when pool is full"
        );
        // Returned handle is in the "dropped" state — `is_alive` is
        // the public surface for this check.
        assert!(!h3.is_alive(), "overflow handle should not be alive");
        // overflow callback is None because we didn't attach on_dismiss
        assert!(overflow.is_none());
    }

    #[test]
    fn slot_pool_overflow_fires_on_dismiss_for_normal_drop() {
        use std::cell::Cell;
        let r = small_registry(2);
        let (_h1, _) = r.enqueue(Toast::info(lit!("a")));
        let (_h2, _) = r.enqueue(Toast::info(lit!("b")));
        let fired = Rc::new(Cell::new(false));
        let fired_clone = fired.clone();
        let (_h3, overflow) = r.enqueue(Toast::info(lit!("c")).on_dismiss(move |cause, _ctx| {
            assert_eq!(cause, ToastDismissCause::SlotPoolFull);
            fired_clone.set(true);
        }));
        // The registry returns the overflow callback to the caller —
        // the ext's `show_toast` then invokes it synchronously with
        // its `EventContext`. Simulate that here by just calling it.
        let (_cause, cb) = overflow.expect("overflow callback present");
        // We don't have a real EventContext in unit tests, but the
        // callback signature is `(cause, &mut EventContext)`. Need
        // to construct one — skip this part; the registry mechanism
        // (correctly returning the callback) is what we're verifying.
        let _ = cb;
        // The actual user-callback invocation is exercised in the
        // ext + WidgetTree integration tests below.
        assert!(!fired.get(), "callback fires only when ext invokes it");
    }

    #[test]
    fn high_priority_evicts_oldest_normal_when_full() {
        let r = small_registry(2);
        let (h_a, _) = r.enqueue(Toast::info(lit!("a")));
        let (h_b, _) = r.enqueue(Toast::info(lit!("b")));
        let oldest_normal_id = h_a.entry_id();
        let newer_normal_id = h_b.entry_id();
        let (h_high, _) = r.enqueue(Toast::info(lit!("urgent")).priority(ToastPriority::High));
        let live_ids = r.live_entry_ids();
        assert!(
            !live_ids.contains(&oldest_normal_id),
            "oldest Normal must be evicted to make room for High"
        );
        assert!(live_ids.contains(&newer_normal_id));
        assert!(live_ids.contains(&h_high.entry_id()));
        assert_eq!(r.live_count(), 2);
    }

    #[test]
    fn tick_timers_decrements_and_dismisses_on_expiry() {
        let r = fresh_registry();
        let (h, _) =
            r.enqueue(Toast::info(lit!("fast")).auto_dismiss_after(Duration::from_millis(500)));
        let id = h.entry_id();

        // Tick 200ms — entry still alive.
        let any_expired = r.tick_timers(Duration::from_millis(200), false);
        assert!(!any_expired);
        assert!(r.live_entry_ids().contains(&id));

        // Tick another 350ms (total > 500) — entry expires.
        let any_expired = r.tick_timers(Duration::from_millis(350), false);
        assert!(any_expired);
        assert!(!r.live_entry_ids().contains(&id));
    }

    #[test]
    fn paused_tick_does_not_decrement() {
        let r = fresh_registry();
        let (h, _) =
            r.enqueue(Toast::info(lit!("slow")).auto_dismiss_after(Duration::from_millis(300)));
        // 10 ticks of 100ms (total 1s, well past 300ms) with paused=true.
        for _ in 0..10 {
            let any_expired = r.tick_timers(Duration::from_millis(100), true);
            assert!(!any_expired);
        }
        assert!(r.live_entry_ids().contains(&h.entry_id()));
    }

    #[test]
    fn persistent_toast_never_expires() {
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::error(lit!("sticky")).persistent());
        for _ in 0..50 {
            let any_expired = r.tick_timers(Duration::from_secs(1), false);
            assert!(!any_expired);
        }
        assert!(r.live_entry_ids().contains(&h.entry_id()));
    }

    #[test]
    fn has_running_timers_gates_the_idle_frame_loop() {
        // Regression: an empty toast host used to keep a permanent
        // `frame_tick` subscription, waking the event loop at ~60 fps
        // forever (a steady idle-CPU drain on any app that called
        // `install_toast_default()`). The host now arms its per-frame
        // timer only while `has_running_timers()` is true.
        let r = fresh_registry();

        // Empty queue: nothing to decrement → no subscription.
        assert!(!r.has_running_timers());

        // A sticky / persistent toast has no finite timer → still no tick.
        let (sticky, _) = r.enqueue(Toast::error(lit!("sticky")).persistent());
        assert!(!r.has_running_timers());

        // A timed toast arms the timer → host subscribes.
        let (timed, _) =
            r.enqueue(Toast::info(lit!("timed")).auto_dismiss_after(Duration::from_millis(500)));
        assert!(r.has_running_timers());

        // Expire it: the only running timer is gone, so the host drops
        // the subscription again even though the sticky toast remains.
        let expired = r.tick_timers(Duration::from_millis(600), false);
        assert!(expired);
        assert!(!r.live_entry_ids().contains(&timed.entry_id()));
        assert!(r.live_entry_ids().contains(&sticky.entry_id()));
        assert!(!r.has_running_timers());
    }

    #[test]
    fn loading_constructor_is_persistent_with_spinner_leading() {
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::loading(lit!("Uploading")));
        r.with_entry(h.entry_id(), |e| {
            assert!(e.time_left.is_none(), "loading toasts are persistent");
            assert!(
                e.leading.is_some(),
                "loading toasts carry a Spinner leading"
            );
            assert_eq!(e.severity, ToastSeverity::Info);
        })
        .unwrap();
    }

    #[test]
    fn version_signal_bumps_on_enqueue_and_dismiss() {
        let r = fresh_registry();
        let initial = r.version_signal().get();
        let (_h1, _) = r.enqueue(Toast::info(lit!("a")));
        let after_show = r.version_signal().get();
        assert_ne!(initial, after_show, "version bumps on enqueue");

        r.tick_timers(Duration::ZERO, false); // no-op, no expiry
        // Expire one with a fast timer.
        let (h2, _) =
            r.enqueue(Toast::info(lit!("b")).auto_dismiss_after(Duration::from_millis(1)));
        let _ = h2;
        let pre_dismiss = r.version_signal().get();
        r.tick_timers(Duration::from_millis(10), false);
        let post_dismiss = r.version_signal().get();
        assert_ne!(pre_dismiss, post_dismiss, "version bumps on timer dismiss");
    }

    #[test]
    fn registry_with_archive_mirrors_pushes() {
        use crate::notification::NotificationArchiveModel;
        let archive = std::rc::Rc::new(NotificationArchiveModel::in_memory());
        let registry =
            ToastRegistry::with_archive(host::ToastInstallOptions::default(), archive.clone());
        let (_h1, _) = registry.enqueue(Toast::error(lit!("Build failed")));
        let (_h2, _) = registry.enqueue(Toast::success(lit!("Deploy ok")));
        // Both toasts mirrored.
        assert_eq!(archive.entries().len(), 2);
        // Newest first (the archive inserts at index 0).
        assert_eq!(
            archive.entries().with_item(0, |e| e.title.clone()),
            Some("Deploy ok".into())
        );
        assert_eq!(archive.unread_count().get(), 2);
    }

    #[test]
    fn registry_archive_false_skips_mirroring() {
        use crate::notification::NotificationArchiveModel;
        let archive = std::rc::Rc::new(NotificationArchiveModel::in_memory());
        let registry =
            ToastRegistry::with_archive(host::ToastInstallOptions::default(), archive.clone());
        // Default toast is archived.
        let (_archived, _) = registry.enqueue(Toast::info(lit!("logged")));
        // Opt-out toast is NOT archived.
        let (_silent, _) = registry.enqueue(Toast::info(lit!("Copied!")).archive(false));
        assert_eq!(archive.entries().len(), 1);
        assert_eq!(
            archive.entries().with_item(0, |e| e.title.clone()),
            Some("logged".into())
        );
    }

    #[test]
    fn registry_with_id_updates_live_entry_in_place_keeping_entry_id() {
        let r = fresh_registry();
        let (first, _) = r.enqueue(Toast::loading(lit!("Uploading 1 of 7…")).id("upload"));
        assert_eq!(r.live_count(), 1);
        let first_entry_id = first.entry_id();

        let (second, _) = r.enqueue(Toast::loading(lit!("Uploading 4 of 7…")).id("upload"));
        // Same entry, NOT a new one.
        assert_eq!(r.live_count(), 1, "live entry count stays at 1");
        assert_eq!(
            second.entry_id(),
            first_entry_id,
            "update returns the same entry_id — the original handle stays valid"
        );

        // The first handle is still alive (still points at the same
        // entry that's still live).
        assert!(first.is_alive());
        assert!(second.is_alive());
    }

    #[test]
    fn registry_in_place_update_reflects_new_title_body() {
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::info(lit!("Saving")).id("save"));
        let _ = r.enqueue(
            Toast::success(lit!("Saved!"))
                .id("save")
                .body(lit!("Written 1.2 MB to disk.")),
        );
        r.with_entry(h.entry_id(), |e| {
            assert_eq!(e.title.resolve_now(), "Saved!", "title updated in place");
            assert_eq!(
                e.body.as_ref().map(|b| b.resolve_now()).as_deref(),
                Some("Written 1.2 MB to disk."),
                "body updated in place"
            );
            assert_eq!(e.severity, ToastSeverity::Success, "severity updated");
        })
        .unwrap();
    }

    #[test]
    fn registry_in_place_update_resets_auto_dismiss_timer() {
        let r = fresh_registry();
        let (h, _) = r.enqueue(
            Toast::info(lit!("slow"))
                .id("ticker")
                .auto_dismiss_after(Duration::from_millis(500)),
        );
        // Tick almost to expiry on the first entry.
        r.tick_timers(Duration::from_millis(450), false);
        // Update: resets time_left to a fresh 500 ms.
        let _ = r.enqueue(
            Toast::info(lit!("slow #2"))
                .id("ticker")
                .auto_dismiss_after(Duration::from_millis(500)),
        );
        // A 100 ms tick should NOT dismiss it (timer was reset).
        let any_expired = r.tick_timers(Duration::from_millis(100), false);
        assert!(
            !any_expired,
            "timer reset on update — entry must survive a tick that would have expired the original"
        );
        assert!(h.is_alive());
    }

    #[test]
    fn registry_in_place_update_preserves_leading_when_not_provided() {
        // The first call carries a Spinner via Toast::loading().
        // The second call has no `.leading(...)` — the spinner must
        // survive (so the demo's "Uploading 1 of 7" → "Uploading
        // 4 of 7" pattern keeps showing a spinner).
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::loading(lit!("step 1")).id("upload"));
        // Probe: first build will take_leading; we test the registry's
        // intent (no take here, just verify it's still Some before the
        // update so we have a baseline).
        let has_spinner_initially = r.with_entry(h.entry_id(), |e| e.leading.is_some()).unwrap();
        assert!(has_spinner_initially, "loading toast carries a Spinner");

        // Update with no leading set — preserves existing.
        let _ = r.enqueue(Toast::info(lit!("step 2")).id("upload"));
        let still_has_spinner = r.with_entry(h.entry_id(), |e| e.leading.is_some()).unwrap();
        assert!(
            still_has_spinner,
            "in-place update with no .leading(...) preserves the existing leading widget"
        );
    }

    #[test]
    fn registry_in_place_update_preserves_on_dismiss_when_not_provided() {
        // Mirrors the leading-widget preservation test:
        // First toast attaches an on_dismiss callback; the update
        // has none, so the original callback must survive on the
        // live entry. (We can't easily simulate the callback firing
        // without a real EventContext, but the entry inspection
        // proves the preservation behaviour up to the fire point.)
        let r = fresh_registry();
        let (h, _) = r.enqueue(
            Toast::info(lit!("step 1"))
                .id("preserve-on-dismiss")
                .on_dismiss(|_cause, _ctx| {}),
        );
        // Sanity: the callback is attached.
        assert!(
            r.with_entry(h.entry_id(), |e| e.on_dismiss.is_some())
                .unwrap(),
            "original entry has on_dismiss attached"
        );

        // Update with no on_dismiss — original must survive.
        let _ = r.enqueue(Toast::success(lit!("step 2")).id("preserve-on-dismiss"));
        assert!(
            r.with_entry(h.entry_id(), |e| e.on_dismiss.is_some())
                .unwrap(),
            "in-place update with no .on_dismiss(...) preserves the existing callback"
        );

        // Update WITH a new on_dismiss replaces (we just verify the
        // field stays Some — the OLD callback gets dropped silently,
        // per the documented contract).
        let _ = r.enqueue(
            Toast::info(lit!("step 3"))
                .id("preserve-on-dismiss")
                .on_dismiss(|_cause, _ctx| {}),
        );
        assert!(
            r.with_entry(h.entry_id(), |e| e.on_dismiss.is_some())
                .unwrap(),
            "in-place update WITH new on_dismiss installs the replacement"
        );
    }

    #[test]
    fn registry_in_place_update_without_id_appends_normally() {
        let r = fresh_registry();
        let _ = r.enqueue(Toast::info(lit!("a")));
        let _ = r.enqueue(Toast::info(lit!("b")));
        // No id on either — both appear as distinct entries.
        assert_eq!(r.live_count(), 2);
    }

    #[test]
    fn registry_in_place_update_distinct_ids_do_not_collide() {
        let r = fresh_registry();
        let _ = r.enqueue(Toast::info(lit!("upload")).id("upload"));
        let _ = r.enqueue(Toast::info(lit!("download")).id("download"));
        // Different ids → two live entries.
        assert_eq!(r.live_count(), 2);
        // Updates target each independently.
        let _ = r.enqueue(Toast::success(lit!("Uploaded!")).id("upload"));
        assert_eq!(
            r.live_count(),
            2,
            "still two entries after upload-only update"
        );
    }

    #[test]
    fn registry_with_id_merges_into_archive_in_place() {
        use crate::notification::NotificationArchiveModel;
        let archive = std::rc::Rc::new(NotificationArchiveModel::in_memory());
        let registry =
            ToastRegistry::with_archive(host::ToastInstallOptions::default(), archive.clone());
        let (_a, _) = registry.enqueue(Toast::info(lit!("Uploading 1 of 7")).id("upload"));
        assert_eq!(archive.entries().len(), 1);
        let (_b, _) = registry.enqueue(Toast::info(lit!("Uploading 4 of 7")).id("upload"));
        // No new entry — the existing one was updated.
        assert_eq!(archive.entries().len(), 1);
        let merged = archive.entries().with_item(0, |e| e.clone()).unwrap();
        assert_eq!(merged.title, "Uploading 4 of 7");
        assert_eq!(merged.updates.len(), 1);
    }

    #[test]
    fn registry_without_archive_does_not_panic() {
        // No archive configured — pushes still succeed; archive lookup
        // is just None.
        let registry = ToastRegistry::new(host::ToastInstallOptions::default());
        let (_h, _) = registry.enqueue(Toast::info(lit!("no archive here")));
        assert!(registry.archive().is_none());
    }

    #[test]
    fn registry_archive_intent_name_survives_on_action() {
        use crate::notification::{ArchivedActionStyle, NotificationArchiveModel};
        let archive = std::rc::Rc::new(NotificationArchiveModel::in_memory());
        let registry =
            ToastRegistry::with_archive(host::ToastInstallOptions::default(), archive.clone());
        let (_h, _) = registry
            .enqueue(Toast::error(lit!("Build failed")).action(
                ToastAction::primary(lit!("Retry"), |_| {}).shortcut_id("app.build.retry"),
            ));
        let entry = archive.entries().with_item(0, |e| e.clone()).unwrap();
        assert_eq!(entry.actions.len(), 1);
        assert_eq!(entry.actions[0].label, "Retry");
        assert_eq!(
            entry.actions[0].intent_name.as_deref(),
            Some("app.build.retry")
        );
        assert_eq!(entry.actions[0].style, ArchivedActionStyle::PrimaryButton);
        assert!(entry.actions[0].closes_on_invoke);
    }

    #[test]
    fn archive_flag_is_captured_on_entry() {
        let r = fresh_registry();
        let (h_noarchive, _) = r.enqueue(Toast::info(lit!("Copied!")).archive(false));
        let archived = r.with_entry(h_noarchive.entry_id(), |e| e.archive).unwrap();
        assert!(!archived);

        let (h_archived, _) = r.enqueue(Toast::error(lit!("Build failed")));
        let archived = r.with_entry(h_archived.entry_id(), |e| e.archive).unwrap();
        assert!(archived, "archive defaults to true");
    }

    #[test]
    fn registry_mirrors_the_resolved_route_onto_the_archived_entry() {
        // Both the render-side host filter (`ToastHost::build`) and
        // the bell/log scoping filter (`notification::route_visible`)
        // trust `NotificationEntry::route` to match the LIVE entry's
        // resolved `ToastRoute`. Every existing scoped-bell test
        // (`notification::center_button`'s `scoped_bell_*` tests)
        // proves the FILTER is correct by hand-building a
        // `NotificationEntry` with an explicit route — none of them go
        // through the real `enqueue` → `entry_to_archive` mirror, so
        // none of them would notice if that mirror stopped copying the
        // route (e.g. a refactor that hardcoded `Broadcast` at the
        // mirror site, or dropped the field). This is that missing
        // link: enqueue through the real pipeline and check the
        // archived copy.
        use crate::notification::NotificationArchiveModel;
        let archive = std::rc::Rc::new(NotificationArchiveModel::in_memory());
        let registry =
            ToastRegistry::with_archive(host::ToastInstallOptions::default(), archive.clone());

        let audience = ToastAudience::new(99);
        let (h, _) = registry.enqueue(Toast::info(lit!("scoped")).target(audience));
        let live_route = registry.with_entry(h.entry_id(), |e| e.route).unwrap();
        assert_eq!(live_route, ToastRoute::Audience(audience));

        let archived_route = archive.entries().with_item(0, |e| e.route).unwrap();
        assert_eq!(
            archived_route,
            ToastRoute::Audience(audience),
            "the archived NotificationEntry must carry the SAME route as the live \
             entry it was mirrored from"
        );
    }

    // -----------------------------------------------------------------
    // AT role/live mapping (via ToastSurface)
    // -----------------------------------------------------------------

    /// Build an `AccessNodeBuilder` directly from a `ToastSurface` so
    /// we can probe `role` AND `live` (the public `accessibility_node`
    /// helper only surfaces `role` + `name` + `actions`).
    fn surface_node(
        severity: ToastSeverity,
        priority: ToastPriority,
    ) -> teksilo_core::accessibility::AccessNodeBuilder {
        use crate::toast::surface::{ToastSurface, ToastSurfaceData};
        use teksilo_core::accessibility::AccessNodeBuilder;
        use teksilo_core::widget::Widget;
        let data = ToastSurfaceData {
            entry_id: 1,
            severity,
            priority,
            title: teksilo_i18n::lit!("x"),
            body: None,
            announcement: None,
            actions: Rc::new(Vec::new()),
            show_close_button: false,
            on_click: None,
            style_override: None,
            body_state: teksilo_core::signal::Signal::new(0),
        };
        let surface = ToastSurface::new(data, None, fresh_registry(), false);
        let mut builder = AccessNodeBuilder::new();
        surface.accessibility(&mut builder);
        builder
    }

    fn surface_role_for(
        severity: ToastSeverity,
        priority: ToastPriority,
    ) -> teksilo_core::accesskit::Role {
        surface_node(severity, priority).role()
    }

    fn surface_live_for(
        severity: ToastSeverity,
        priority: ToastPriority,
    ) -> teksilo_core::accesskit::Live {
        let mut node = surface_node(severity, priority);
        node.inner_mut()
            .live()
            .unwrap_or(teksilo_core::accesskit::Live::Off)
    }

    #[test]
    fn at_role_status_for_info_success_warning_normal() {
        use teksilo_core::accesskit::Role;
        assert_eq!(
            surface_role_for(ToastSeverity::Info, ToastPriority::Normal),
            Role::Status
        );
        assert_eq!(
            surface_role_for(ToastSeverity::Success, ToastPriority::Normal),
            Role::Status
        );
        assert_eq!(
            surface_role_for(ToastSeverity::Warning, ToastPriority::Normal),
            Role::Status
        );
    }

    #[test]
    fn at_role_alert_for_error_and_warning_high() {
        use teksilo_core::accesskit::Role;
        assert_eq!(
            surface_role_for(ToastSeverity::Error, ToastPriority::Normal),
            Role::Alert
        );
        assert_eq!(
            surface_role_for(ToastSeverity::Error, ToastPriority::High),
            Role::Alert
        );
        assert_eq!(
            surface_role_for(ToastSeverity::Warning, ToastPriority::High),
            Role::Alert
        );
        assert_eq!(
            surface_role_for(ToastSeverity::Warning, ToastPriority::Urgent),
            Role::Alert
        );
    }

    #[test]
    fn at_live_polite_for_status_assertive_for_alert() {
        use teksilo_core::accesskit::Live;
        assert_eq!(
            surface_live_for(ToastSeverity::Info, ToastPriority::Normal),
            Live::Polite
        );
        assert_eq!(
            surface_live_for(ToastSeverity::Error, ToastPriority::Normal),
            Live::Assertive
        );
        assert_eq!(
            surface_live_for(ToastSeverity::Warning, ToastPriority::High),
            Live::Assertive
        );
    }

    #[test]
    fn urgent_priority_forces_assertive_regardless_of_severity() {
        use teksilo_core::accesskit::Live;
        // Info + Urgent = Assertive even though Info would normally be Polite.
        assert_eq!(
            surface_live_for(ToastSeverity::Info, ToastPriority::Urgent),
            Live::Assertive
        );
        assert_eq!(
            surface_live_for(ToastSeverity::Success, ToastPriority::Urgent),
            Live::Assertive
        );
    }

    // -----------------------------------------------------------------
    // End-to-end: WidgetTree + ToastHost + ToastRegistry
    // -----------------------------------------------------------------

    use crate::primitives::TextWidget as TestLeaf; // any layout-only widget works as user_root

    fn setup_host_tree(
        opts: host::ToastInstallOptions,
    ) -> (teksilo_core::widget_tree::WidgetTree, ToastRegistry) {
        use std::any::{Any, TypeId};
        use std::collections::HashMap;

        let registry = ToastRegistry::new(opts.clone());
        let mut app_state: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        app_state.insert(TypeId::of::<ToastRegistry>(), Box::new(registry.clone()));

        let mut tree = teksilo_core::widget_tree::WidgetTree::new()
            .with_theme(teksilo_core::presets::intui::light());
        tree.set_app_context(Rc::new(
            teksilo_core::event_source::TreeAppContext::empty().with_app_state(app_state),
        ));
        let user_root = tree.add(TestLeaf::new(lit!("user content")));
        let host = ToastHost::wrapping(user_root, registry.clone(), opts);
        tree.add(host);
        tree.layout(teksilo_canvas::SizeProposal::exact(800.0, 600.0));
        (tree, registry)
    }

    #[test]
    fn host_renders_a_toast_surface_for_each_live_entry() {
        use std::any::{Any, TypeId};
        use std::collections::HashMap;

        // Pre-populate the registry with a toast BEFORE the host is
        // added, so the host's first build sees the entry. (The
        // version-binding rebuild path requires a fresh dirty-flush
        // pass which is exercised in `dismiss_clears_surface` below.)
        let opts = host::ToastInstallOptions::default();
        let registry = ToastRegistry::new(opts.clone());
        let _h = registry.enqueue(Toast::success(lit!("Saved")));
        assert_eq!(registry.live_count(), 1);

        let mut app_state: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        app_state.insert(TypeId::of::<ToastRegistry>(), Box::new(registry.clone()));

        let mut tree = teksilo_core::widget_tree::WidgetTree::new()
            .with_theme(teksilo_core::presets::intui::light());
        tree.set_app_context(Rc::new(
            teksilo_core::event_source::TreeAppContext::empty().with_app_state(app_state),
        ));
        let user_root = tree.add(TestLeaf::new(lit!("user content")));
        tree.add(ToastHost::wrapping(user_root, registry.clone(), opts));
        tree.layout(teksilo_canvas::SizeProposal::exact(800.0, 600.0));

        assert!(
            tree.find_by_role(teksilo_core::accesskit::Role::Status)
                .is_some(),
            "Success toast renders a Role::Status surface in the host"
        );
    }

    #[test]
    fn host_promotes_error_toast_to_role_alert() {
        use std::any::{Any, TypeId};
        use std::collections::HashMap;
        let opts = host::ToastInstallOptions::default();
        let registry = ToastRegistry::new(opts.clone());
        let _h = registry.enqueue(Toast::error(lit!("Build failed")).persistent());

        let mut app_state: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        app_state.insert(TypeId::of::<ToastRegistry>(), Box::new(registry.clone()));
        let mut tree = teksilo_core::widget_tree::WidgetTree::new()
            .with_theme(teksilo_core::presets::intui::light());
        tree.set_app_context(Rc::new(
            teksilo_core::event_source::TreeAppContext::empty().with_app_state(app_state),
        ));
        let user_root = tree.add(TestLeaf::new(lit!("root")));
        tree.add(ToastHost::wrapping(user_root, registry.clone(), opts));
        tree.layout(teksilo_canvas::SizeProposal::exact(800.0, 600.0));
        assert!(
            tree.find_by_role(teksilo_core::accesskit::Role::Alert)
                .is_some(),
            "Error toast emits Role::Alert via the surface widget"
        );
    }

    #[test]
    fn hover_count_flips_paused_state_observed_by_host_tick() {
        // Direct test of the contract between the surface (which writes
        // to hover_count) and the host tick (which reads it). We don't
        // need a full WidgetTree — the registry is the integration
        // surface.
        let r = fresh_registry();
        let (h, _) =
            r.enqueue(Toast::info(lit!("hover me")).auto_dismiss_after(Duration::from_millis(200)));
        // Simulate pointer-enter on the surface: hover_count = 1.
        r.hover_count_signal().set(1);
        // 10 ticks of 100 ms each (total 1 s, well past 200 ms) with
        // paused=hover_count>0 → entry survives.
        for _ in 0..10 {
            let hover = r.hover_count_signal().get() > 0;
            r.tick_timers(Duration::from_millis(100), hover);
        }
        assert!(
            r.live_entry_ids().contains(&h.entry_id()),
            "hover-paused entry must survive past its auto-dismiss window"
        );
        // Pointer-leave: hover_count = 0, timer resumes.
        r.hover_count_signal().set(0);
        let hover = r.hover_count_signal().get() > 0;
        r.tick_timers(Duration::from_millis(250), hover);
        assert!(
            !r.live_entry_ids().contains(&h.entry_id()),
            "after un-hover, entry expires"
        );
    }

    // -----------------------------------------------------------------
    // Routing — origin window default / .target() / .broadcast()
    // -----------------------------------------------------------------

    /// A toast presented through a real `EventContext` (an actual
    /// input handler, not a bare `enqueue` call) with no explicit
    /// `.target()` / `.broadcast()` must be tagged with the
    /// *presenting window's* id — the whole point of the "default =
    /// origin window" design is that existing single-window apps get
    /// correct routing for free.
    #[test]
    fn show_toast_default_targets_the_originating_window() {
        use crate::button::Button;
        use std::any::{Any, TypeId};
        use std::collections::HashMap;

        use teksilo_core::window::state::WindowStateInit;
        use teksilo_core::window::{TeksiloWindowId, WindowPlacement, WindowState};

        let registry = fresh_registry();
        let mut app_state: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
        app_state.insert(TypeId::of::<ToastRegistry>(), Box::new(registry.clone()));

        let mut tree = teksilo_core::widget_tree::WidgetTree::new()
            .with_theme(teksilo_core::presets::intui::light());
        tree.set_app_context(Rc::new(
            teksilo_core::event_source::TreeAppContext::empty().with_app_state(app_state),
        ));
        tree.set_window_state(WindowState::new(WindowStateInit {
            id: TeksiloWindowId::new(1),
            string_id: Some("test".to_string()),
            placement: WindowPlacement::Floating,
            title: "Test".to_string(),
            size: (800, 600),
            position: (0, 0),
            focused: false,
            resizable: true,
            always_on_top: false,
        }));

        let btn = tree.add(Button::new(lit!("Save")).on_activate_fn(|ctx| {
            let _ = Toast::info(lit!("Saved")).present(ctx);
        }));
        tree.layout(teksilo_canvas::SizeProposal::exact(400.0, 300.0));

        tree.click(btn);

        assert_eq!(
            registry.live_count(),
            1,
            "the click must have enqueued a toast"
        );
        let eid = registry.live_entry_ids()[0];
        registry
            .with_entry(eid, |e| {
                assert_eq!(
                    e.route,
                    ToastRoute::Window(TeksiloWindowId::new(1)),
                    "no explicit target + a real window at present time → origin-window route"
                );
            })
            .unwrap();
    }

    #[test]
    fn target_routes_to_the_matching_audience_only() {
        let r = fresh_registry();
        let audience = ToastAudience::new(42);
        let (h, _) = r.enqueue(Toast::info(lit!("scoped")).target(audience));
        r.with_entry(h.entry_id(), |e| {
            assert_eq!(e.route, ToastRoute::Audience(audience));
        })
        .unwrap();
    }

    #[test]
    fn broadcast_routes_regardless_of_window_or_audience() {
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::warning(lit!("everyone")).broadcast());
        r.with_entry(h.entry_id(), |e| {
            assert_eq!(e.route, ToastRoute::Broadcast);
        })
        .unwrap();
    }

    #[test]
    fn no_window_no_target_falls_back_to_broadcast() {
        // Mirrors `show_settings_write_failed`'s call path: `enqueue`
        // called directly, no `EventContext`, no explicit `.target()`.
        // The only sensible default for a routeless, contextless toast
        // is app-wide, not "nowhere".
        let r = fresh_registry();
        let (h, _) = r.enqueue(Toast::error(lit!("no context here")));
        r.with_entry(h.entry_id(), |e| {
            assert_eq!(e.route, ToastRoute::Broadcast);
        })
        .unwrap();
    }

    #[test]
    fn per_audience_admission_one_burst_does_not_starve_another_audience() {
        // Decision 1: `max_visible` is enforced PER routing bucket.
        // A burst of audience A's toasts past the pool size must not
        // touch audience B's slots at all.
        let r = small_registry(2);
        let audience_a = ToastAudience::new(1);
        let audience_b = ToastAudience::new(2);

        let (a1, _) = r.enqueue(Toast::info(lit!("a1")).target(audience_a));
        let (a2, _) = r.enqueue(Toast::info(lit!("a2")).target(audience_a));
        // A's bucket is now full (max_visible = 2). A third A toast
        // must be dropped exactly like the single-bucket overflow test.
        let (a3, _) = r.enqueue(Toast::info(lit!("a3")).target(audience_a));
        assert!(
            !a3.is_alive(),
            "audience A's third toast overflows its own bucket"
        );
        assert!(a1.is_alive() && a2.is_alive());

        // Audience B has its own, untouched pool of 2 slots.
        let (b1, _) = r.enqueue(Toast::info(lit!("b1")).target(audience_b));
        let (b2, _) = r.enqueue(Toast::info(lit!("b2")).target(audience_b));
        assert!(
            b1.is_alive() && b2.is_alive(),
            "audience B's own admission must be unaffected by A's burst"
        );
        assert_eq!(
            r.live_count(),
            4,
            "2 live A entries + 2 live B entries — B was never starved"
        );

        // A third B toast still overflows B's own bucket (proves the
        // bucketing is real, not just "everything fits because global
        // max_visible was raised somewhere").
        let (b3, _) = r.enqueue(Toast::info(lit!("b3")).target(audience_b));
        assert!(!b3.is_alive());
        assert_eq!(r.live_count(), 4);
    }

    #[test]
    fn per_audience_high_priority_evicts_oldest_normal_within_the_same_bucket_only() {
        let r = small_registry(2);
        let audience_a = ToastAudience::new(1);
        let audience_b = ToastAudience::new(2);

        let (a_old, _) = r.enqueue(Toast::info(lit!("a-old")).target(audience_a));
        let (a_new, _) = r.enqueue(Toast::info(lit!("a-new")).target(audience_a));
        let (b1, _) = r.enqueue(Toast::info(lit!("b1")).target(audience_b));
        let (b2, _) = r.enqueue(Toast::info(lit!("b2")).target(audience_b));

        // A High-priority arrival targeting audience A must evict only
        // the oldest Normal entry WITHIN audience A's bucket — B's
        // entries must survive untouched.
        let (a_high, _) = r.enqueue(
            Toast::info(lit!("a-urgent"))
                .target(audience_a)
                .priority(ToastPriority::High),
        );
        let live_ids = r.live_entry_ids();
        assert!(
            !live_ids.contains(&a_old.entry_id()),
            "oldest Normal within audience A's bucket is evicted"
        );
        assert!(live_ids.contains(&a_new.entry_id()));
        assert!(live_ids.contains(&a_high.entry_id()));
        assert!(
            live_ids.contains(&b1.entry_id()) && live_ids.contains(&b2.entry_id()),
            "audience B's entries must be untouched by A's High-priority eviction"
        );
        assert_eq!(r.live_count(), 4);
    }

    #[test]
    fn host_renders_no_surfaces_when_registry_empty() {
        // Inverse of the above: with no live entries the host has no
        // toast surfaces in the AT tree.
        let (tree, registry) = setup_host_tree(host::ToastInstallOptions::default());
        assert_eq!(registry.live_count(), 0);
        assert!(
            tree.find_by_role(teksilo_core::accesskit::Role::Status)
                .is_none()
        );
        assert!(
            tree.find_by_role(teksilo_core::accesskit::Role::Alert)
                .is_none()
        );
    }
}