oxiui 0.1.0

OxiUI — Pure-Rust GUI facade (egui + wgpu, no GTK/Qt/SDL)
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
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
//! `oxiui` — Pure-Rust GUI facade.
//!
//! **Default features:** `["gpu","egui"]` — boots an egui app rendered via wgpu.
//! GPU drivers (Vulkan/Metal/DX12) are OS-provided at runtime; they do NOT appear
//! in `cargo tree --edges normal` (GOVERNANCE §8 bullet 2).
//!
//! **Headless / ffi-audit path:** `--no-default-features --features software`
//! uses a softbuffer CPU framebuffer; no GPU stack required at build time.
//!
//! **iced backend:** Enable with `--features iced`. The iced backend wires
//! the `content` closure through `oxiui_iced::IcedUiCtx` using iced's
//! retained-mode Elm-style update/view loop. Button clicks from one frame are
//! reflected as `ButtonResponse::clicked = true` in the next frame's view call
//! (one-frame latency, inherent to the retained-mode / immediate-mode bridge).
//!
//! **slint backend:** Enable with `--features slint`. The slint backend wires
//! the `content` closure through `oxiui_slint::SlintCtx`. In M5, this operates
//! in headless collection mode (no display required). Native window rendering
//! via `slint::run_event_loop()` is deferred to M6. Note: slint 1.16.1 is
//! GPL-3.0 OR royalty-free OR commercial licensed; only pulled in under this
//! explicit feature gate.
//!
//! **dioxus backend:** Enable with `--features dioxus`. The dioxus backend wires
//! the `content` closure through `oxiui_dioxus::DioxusCtx`. In M5, this operates
//! in headless collection mode. The `minimal` dioxus feature set is used (Pure
//! Rust); the `desktop` feature (wry/tao/WebKit, C/C++ deps) is excluded.
//!
//! **GOVERNANCE §6 note:** The `default = ["gpu","egui"]` facade deviation from
//! the strict tier-1 `default = []` rule is authorized by ADAPTER_PATTERN §3
//! rule 4 (a zero-feature facade build must select at least one Pure adapter).
//! Parallel precedents: `oxicrypto`'s `default = ["pure"]`, `oxitls`'s
//! `default = ["pure","webpki-roots"]`.
//!
//! # Quick start (egui)
//!
//! ```rust,no_run
//! use oxiui::{App, AppConfig};
//! App::new(AppConfig::new().title("Hello OxiUI"))
//!     .theme(oxiui::theme::cooljapan_default())
//!     .content(|ui| {
//!         ui.heading("Hello, world!");
//!         if ui.button("Quit").clicked { /* exit logic */ }
//!     })
//!     .run()
//!     .expect("UI error");
//! ```
//!
//! # Quick start (iced backend)
//!
//! ```rust,ignore
//! use oxiui::{App, AppConfig, Backend};
//! App::new(AppConfig::new().title("Hello OxiUI (iced)"))
//!     .theme(oxiui::theme::cooljapan_default())
//!     .backend(Backend::Iced)
//!     .content(|ui| {
//!         ui.heading("Hello from iced!");
//!         if ui.button("Quit").clicked { std::process::exit(0); }
//!     })
//!     .run()
//!     .expect("UI error");
//! ```
//!
//! Or use the standalone example:
//! ```sh
//! cargo run --example hello_iced --features iced -p oxiui
//! ```

pub use oxiui_core::{ButtonResponse, Color, FontSpec, Palette, Theme, UiCtx, UiError};

/// Pluggable backend runner infrastructure.
///
/// Provides the [`BackendRunner`] trait and its built-in implementations
/// ([`EguiRunner`], `IcedRunner`) for wiring custom backend dispatchers.
pub mod runner;

#[cfg(feature = "egui")]
#[cfg_attr(docsrs, doc(cfg(feature = "egui")))]
pub use runner::EguiRunner;
#[cfg(feature = "iced")]
#[cfg_attr(docsrs, doc(cfg(feature = "iced")))]
pub use runner::IcedRunner;
pub use runner::{BackendRunner, LifecycleConfig};

/// PNG icon decoding (internal; requires `egui` feature which pulls in `png`).
#[cfg(feature = "egui")]
pub(crate) mod icon;

/// Built-in theme picker widget.
///
/// Provides `theme_picker` and [`BUILTIN_THEMES`] for constructing a simple
/// UI to switch between the OxiUI built-in themes at runtime.
pub mod theme_picker;

pub use theme_picker::{by_name as theme_by_name, theme_picker, BUILTIN_THEMES};

/// Re-exports of the COOLJAPAN theme constructors.
pub mod theme {
    pub use oxiui_theme::{cooljapan_default, dark, light};
}

/// Table widget re-exports (requires `table` feature).
#[cfg(feature = "table")]
#[cfg_attr(docsrs, doc(cfg(feature = "table")))]
pub mod table {
    pub use oxiui_table::*;
}

/// Accessibility tree builder re-exports (requires `a11y` feature).
///
/// Provides `A11yTree`, `A11yNode`, and `WidgetRole` for building
/// accesskit `TreeUpdate` objects from the OxiUI widget graph. The tree is
/// headless-testable: no display server is required to build or inspect it.
#[cfg(feature = "a11y")]
#[cfg_attr(docsrs, doc(cfg(feature = "a11y")))]
pub mod accessibility {
    pub use oxiui_accessibility::{A11yNode, A11yTree, WidgetRole};
}

/// Headless recording context for capturing widget calls as accessibility entries.
///
/// Exposes [`RecordingUiCtx`] and [`RecordingEntry`] for building an
/// [`oxiui_accessibility::A11yTree`] snapshot from a content closure without
/// opening a real window. Requires the `a11y` feature.
#[cfg(feature = "a11y")]
#[cfg_attr(docsrs, doc(cfg(feature = "a11y")))]
pub mod recording;

#[cfg(feature = "a11y")]
#[cfg_attr(docsrs, doc(cfg(feature = "a11y")))]
pub use recording::{RecordingEntry, RecordingUiCtx};

/// wasm32 web entry point re-exports (requires `web` feature).
///
/// On wasm32 targets, [`web::mount`] boots an OxiUI app on a `<canvas>` element.
/// On native targets the `mount` function returns `Err` — use this module only
/// from wasm32 binaries or from code guarded by `#[cfg(target_arch = "wasm32")]`.
#[cfg(feature = "web")]
#[cfg_attr(docsrs, doc(cfg(feature = "web")))]
pub mod web {
    pub use oxiui_web::mount;
}

/// Re-exports from `oxiui-render-soft` (requires `software` feature).
///
/// Exposes the pure-CPU headless render path: [`render::RgbaBuffer`],
/// [`render::render_headless_once`], and [`render::render_headless_scene`].
#[cfg(feature = "software")]
#[cfg_attr(docsrs, doc(cfg(feature = "software")))]
pub mod render {
    pub use oxiui_render_soft::{
        render_headless_once, render_headless_scene, Framebuffer, RgbaBuffer,
    };
}

/// Re-exports from `oxiui-core` text/font types.
///
/// Exposes [`text::FontSpec`] and [`text::FontStyle`] for convenience.
pub mod text {
    pub use oxiui_core::{FontFeature, FontSpec, FontStyle};
}

/// Constraint solver types re-exported from oxiui-core.
pub mod solver {
    pub use oxiui_core::{
        Constraint, Expression, RelOp, Solver, SolverError, Strength, Term, Variable,
    };
}

/// Prelude module — re-exports the most commonly used OxiUI types.
///
/// Add `use oxiui::prelude::*;` to get all commonly needed types in scope.
pub mod prelude {
    pub use crate::{App, AppConfig, AppExit, Backend, HotkeyConflict, Notification, Plugin};
    pub use oxiui_core::{AlignContent, FlexWrap, RichTextSpan};
    pub use oxiui_core::{ButtonResponse, Color, UiCtx, UiError};
    pub use oxiui_core::{Computed, ReactiveError, ReactiveRuntime, Signal};
    pub use oxiui_core::{Point, Rect, Size};
    pub use oxiui_theme::CooljapanTheme;
}

/// Core type re-exports.
pub mod core {
    pub use oxiui_core::*;
}

/// Fine-grained reactive state primitives.
///
/// Provides `Signal`, `Computed`, `ReactiveRuntime`, and `ReactiveError`
/// from `oxiui-core`. Use these to build data-driven UI state without manually
/// tracking dirty flags.
pub mod reactive {
    pub use oxiui_core::{Computed, ReactiveError, ReactiveRuntime, Signal};
}

/// Available GUI backend choices for [`App`].
///
/// The default backend is [`Backend::Egui`]. Select `Backend::Iced` (requires
/// the `iced` feature) to use the iced retained-mode framework.
/// `Backend::Slint` and `Backend::Dioxus` are experimental adapters added in M5.
#[derive(Clone, Debug, Default)]
pub enum Backend {
    /// egui + eframe (immediate-mode, default).
    #[default]
    Egui,
    /// iced (retained-mode, Elm-style). Requires `--features iced`.
    ///
    /// The content closure is driven through `IcedUiCtx` each frame. Button
    /// clicks carry a one-frame latency (inherent to retained-mode bridging).
    #[cfg(feature = "iced")]
    Iced,
    /// slint GUI toolkit adapter. Requires `--features slint`.
    ///
    /// In M5, operates in headless collection mode. Native window rendering
    /// via `slint::run_event_loop()` is planned for M6.
    ///
    /// **License:** slint is GPL-3.0 OR royalty-free OR commercial. Enable
    /// only in projects that are compatible with one of those license options.
    #[cfg(feature = "slint")]
    Slint,
    /// Dioxus reactive UI adapter. Requires `--features dioxus`.
    ///
    /// In M5, operates in headless collection mode. Full Dioxus native rendering
    /// via `dioxus-native` (Pure Rust Blitz renderer) is planned for M6.
    #[cfg(feature = "dioxus")]
    Dioxus,
}

/// Application exit status.
///
/// Returned by [`App::run`] when the event loop terminates normally.
///
/// The `RequestedByUser` variant covers the common case of the user explicitly
/// closing the window. `Programmatic(reason)` is used when code calls a
/// controlled shutdown with an explanatory string. `Ok` is returned by the
/// headless path and by backends that do not distinguish how the loop ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppExit {
    /// The application exited normally (user closed the window or event loop drained).
    Ok,
    /// The application exited due to an error.
    Error(String),
    /// The user explicitly requested exit (e.g. clicked the close button).
    RequestedByUser,
    /// Programmatic shutdown with an explanatory reason string.
    Programmatic(String),
}

/// Error returned when two hotkeys share the same `(Modifiers, Key)` pair.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HotkeyConflict {
    /// Human-readable description of the conflicting binding.
    pub message: String,
}

impl std::fmt::Display for HotkeyConflict {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "HotkeyConflict: {}", self.message)
    }
}

impl std::error::Error for HotkeyConflict {}

/// Configuration for building an [`App`].
///
/// Use the builder methods to configure the window, then pass to [`App::new`].
///
/// # Example
///
/// ```rust,no_run
/// use oxiui::AppConfig;
/// let config = AppConfig::new()
///     .title("My App")
///     .size(1024.0, 768.0)
///     .resizable(true)
///     .decorations(true)
///     .transparent(false);
/// ```
#[derive(Debug, Clone)]
pub struct AppConfig {
    /// Window title.
    pub title: String,
    /// Initial window width in logical pixels (0.0 → use default).
    pub width: f32,
    /// Initial window height in logical pixels (0.0 → use default).
    pub height: f32,
    /// Whether the window can be resized by the user.
    pub resizable: bool,
    /// Minimum window size in logical pixels `(width, height)`.
    pub min_size: Option<(f32, f32)>,
    /// Maximum window size in logical pixels `(width, height)`.
    pub max_size: Option<(f32, f32)>,
    /// Whether the window has OS-drawn decorations (title bar, borders).
    ///
    /// Defaults to `true`.
    pub decorations: bool,
    /// Whether the window background is transparent.
    ///
    /// Defaults to `false`.
    pub transparent: bool,
    /// Whether the window is always shown above other windows.
    ///
    /// Defaults to `false`.
    pub always_on_top: bool,
    /// Optional PNG/ICO bytes for the window icon.
    ///
    /// Stored as raw bytes; decoded to RGBA when wiring into egui's
    /// `ViewportBuilder::with_icon`. Requires the `png` crate (present in
    /// `oxiui-render-soft`) — currently decoded via a small inline helper when
    /// the `software` feature is enabled. Without `software`, the icon bytes
    /// are stored but decoding is deferred (see deviation note in TODO.md).
    pub icon: Option<Vec<u8>>,
    /// Initial window position in logical pixels `(x, y)` from the top-left
    /// of the primary monitor.
    pub position: Option<(f32, f32)>,
    /// Extra font families to load at startup.
    ///
    /// Each entry is `(family_name, raw_font_bytes)`. Passed to the active
    /// backend's font loading path when [`App::run`] begins (egui path only
    /// in this release; iced font loading is deferred).
    pub extra_fonts: Vec<(String, Vec<u8>)>,
}

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

impl AppConfig {
    /// Create a new [`AppConfig`] with default settings.
    pub fn new() -> Self {
        Self {
            title: String::new(),
            width: 800.0,
            height: 600.0,
            resizable: true,
            min_size: None,
            max_size: None,
            decorations: true,
            transparent: false,
            always_on_top: false,
            icon: None,
            position: None,
            extra_fonts: Vec::new(),
        }
    }

    /// Set the window title.
    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.title = t.into();
        self
    }

    /// Set the initial window size in logical pixels.
    pub fn size(mut self, w: f32, h: f32) -> Self {
        self.width = w;
        self.height = h;
        self
    }

    /// Set whether the window can be resized.
    pub fn resizable(mut self, r: bool) -> Self {
        self.resizable = r;
        self
    }

    /// Set the minimum window size in logical pixels.
    pub fn min_size(mut self, w: f32, h: f32) -> Self {
        self.min_size = Some((w, h));
        self
    }

    /// Set the maximum window size in logical pixels.
    pub fn max_size(mut self, w: f32, h: f32) -> Self {
        self.max_size = Some((w, h));
        self
    }

    /// Set whether the window has OS-drawn decorations (title bar, borders).
    pub fn decorations(mut self, d: bool) -> Self {
        self.decorations = d;
        self
    }

    /// Set whether the window background is transparent.
    pub fn transparent(mut self, t: bool) -> Self {
        self.transparent = t;
        self
    }

    /// Set whether the window is always shown above other windows.
    pub fn always_on_top(mut self, a: bool) -> Self {
        self.always_on_top = a;
        self
    }

    /// Set the window icon from raw PNG/ICO bytes.
    pub fn icon(mut self, bytes: Vec<u8>) -> Self {
        self.icon = Some(bytes);
        self
    }

    /// Set the initial window position in logical pixels from top-left of primary monitor.
    pub fn position(mut self, x: f32, y: f32) -> Self {
        self.position = Some((x, y));
        self
    }
}

/// Boxed content closure type for an OxiUI app frame.
type ContentFn = Box<dyn FnMut(&mut dyn oxiui_core::UiCtx) + Send>;

/// Boxed lifecycle hook closure.
type HookFn = Box<dyn FnMut(&mut dyn oxiui_core::UiCtx) + Send + Sync>;

/// Type alias for an egui escape-hatch callback (avoids `type_complexity` lint).
#[cfg(feature = "egui")]
type EguiFrameHook = Box<dyn FnMut(&egui::Context) + Send>;

// ─── Plugin trait ────────────────────────────────────────────────────────────

/// A plugin that receives lifecycle callbacks from the [`App`] event loop.
///
/// Plugins are registered via [`App::plugin`] and called in ascending
/// [`Plugin::priority`] order (lower number = earlier call).
///
/// # Example
///
/// ```rust
/// use oxiui::{App, AppConfig};
/// use oxiui::Plugin;
/// use oxiui_core::UiCtx;
///
/// struct LogPlugin;
/// impl Plugin for LogPlugin {
///     fn init(&mut self, _ctx: &mut dyn UiCtx) {}
///     fn update(&mut self, _ctx: &mut dyn UiCtx) {}
/// }
///
/// let _app = App::new(AppConfig::new().title("test"))
///     .plugin(LogPlugin);
/// ```
pub trait Plugin: Send + Sync {
    /// Called once when the app initialises (before the first frame).
    fn init(&mut self, ctx: &mut dyn UiCtx);
    /// Called every frame after the content closure.
    fn update(&mut self, ctx: &mut dyn UiCtx);
    /// Plugin priority — lower numbers are called first. Default: `0`.
    fn priority(&self) -> i32 {
        0
    }
}

// ─── Hotkey registry ─────────────────────────────────────────────────────────

use oxiui_core::events::{Key, Modifiers};

/// A single registered hotkey binding.
pub struct HotkeyBinding {
    /// Unique identifier for this binding.
    pub id: String,
    /// Modifier keys required.
    pub modifiers: Modifiers,
    /// Logical key required.
    pub key: Key,
    /// Action to invoke when the hotkey fires.
    pub action: Box<dyn Fn() + Send + Sync>,
}

/// A registry of keyboard hotkey bindings.
///
/// Enforces that no two bindings share the same `(Modifiers, Key)` pair.
pub struct HotkeyRegistry {
    bindings: Vec<HotkeyBinding>,
}

impl HotkeyRegistry {
    /// Create an empty [`HotkeyRegistry`].
    pub fn new() -> Self {
        Self {
            bindings: Vec::new(),
        }
    }

    /// Register a hotkey binding.
    ///
    /// Returns `Err` if another binding with the same `(mods, key)` pair
    /// is already registered.
    pub fn register(
        &mut self,
        id: impl Into<String>,
        mods: Modifiers,
        key: Key,
        action: impl Fn() + Send + Sync + 'static,
    ) -> Result<(), String> {
        if self.conflict_check(mods, key.clone()) {
            return Err(format!("hotkey conflict: {mods:?}+{key:?}"));
        }
        self.bindings.push(HotkeyBinding {
            id: id.into(),
            modifiers: mods,
            key,
            action: Box::new(action),
        });
        Ok(())
    }

    /// Returns `true` if a binding with this `(mods, key)` pair is already registered.
    pub fn conflict_check(&self, mods: Modifiers, key: Key) -> bool {
        self.bindings
            .iter()
            .any(|b| b.modifiers == mods && b.key == key)
    }

    /// The number of registered bindings.
    pub fn len(&self) -> usize {
        self.bindings.len()
    }

    /// Returns `true` if no bindings are registered.
    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty()
    }
}

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

// ─── Command palette ─────────────────────────────────────────────────────────

/// A named, searchable command.
pub struct Command {
    /// Unique identifier.
    pub id: String,
    /// Display label shown in the palette.
    pub label: String,
    /// Optional keyboard shortcut hint displayed alongside the label.
    pub shortcut: Option<String>,
    /// Action to invoke when the command is selected.
    pub action: Box<dyn Fn() + Send + Sync>,
}

/// A searchable registry of [`Command`]s.
///
/// Commands are registered via [`CommandPalette::register`] and searched
/// via [`CommandPalette::search`] using a simple fuzzy-match algorithm
/// (all query characters must appear in the label in order, case-insensitive).
pub struct CommandPalette {
    commands: Vec<Command>,
}

impl CommandPalette {
    /// Create an empty [`CommandPalette`].
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
        }
    }

    /// Register a command.
    pub fn register(
        &mut self,
        id: impl Into<String>,
        label: impl Into<String>,
        action: impl Fn() + Send + Sync + 'static,
    ) {
        self.commands.push(Command {
            id: id.into(),
            label: label.into(),
            shortcut: None,
            action: Box::new(action),
        });
    }

    /// Register a command with an optional keyboard shortcut hint.
    pub fn register_with_shortcut(
        &mut self,
        id: impl Into<String>,
        label: impl Into<String>,
        shortcut: Option<String>,
        action: impl Fn() + Send + Sync + 'static,
    ) {
        self.commands.push(Command {
            id: id.into(),
            label: label.into(),
            shortcut,
            action: Box::new(action),
        });
    }

    /// Search for commands whose labels fuzzy-match `query`.
    ///
    /// The match is case-insensitive and requires that every character in
    /// `query` appear in `label` in order (subsequence matching).
    pub fn search(&self, query: &str) -> Vec<&Command> {
        let query_lc = query.to_lowercase();
        self.commands
            .iter()
            .filter(|cmd| {
                let label_lc = cmd.label.to_lowercase();
                let mut q_iter = query_lc.chars();
                let mut current = q_iter.next();
                for ch in label_lc.chars() {
                    if current == Some(ch) {
                        current = q_iter.next();
                    }
                    if current.is_none() {
                        return true;
                    }
                }
                current.is_none()
            })
            .collect()
    }

    /// The number of registered commands.
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Returns `true` if no commands are registered.
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
}

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

// ─── Notification queue ───────────────────────────────────────────────────────

/// A pending in-app toast notification.
#[derive(Debug, Clone)]
pub struct Notification {
    /// Short title line.
    pub title: String,
    /// Longer body text.
    pub body: String,
    /// How long the notification should be displayed, in milliseconds.
    pub duration_ms: u64,
    /// Urgency level: 0 = low, 1 = normal, 2 = critical.
    pub urgency: u8,
    /// When the notification was created.
    pub created_at: std::time::Instant,
}

/// A FIFO queue of pending [`Notification`]s.
///
/// Call [`NotificationQueue::push`] to enqueue notifications, and
/// [`NotificationQueue::pop_due`] each frame to drain them for display.
pub struct NotificationQueue {
    pending: std::collections::VecDeque<Notification>,
}

impl NotificationQueue {
    /// Create an empty [`NotificationQueue`].
    pub fn new() -> Self {
        Self {
            pending: std::collections::VecDeque::new(),
        }
    }

    /// Enqueue a notification.
    pub fn push(&mut self, title: impl Into<String>, body: impl Into<String>, duration_ms: u64) {
        self.pending.push_back(Notification {
            title: title.into(),
            body: body.into(),
            duration_ms,
            urgency: 1,
            created_at: std::time::Instant::now(),
        });
    }

    /// Enqueue a notification with explicit urgency (0=low, 1=normal, 2=critical).
    pub fn enqueue(&mut self, title: impl Into<String>, body: impl Into<String>, urgency: u8) {
        let duration_ms = match urgency {
            0 => 3_000,
            2 => 10_000,
            _ => 5_000,
        };
        self.pending.push_back(Notification {
            title: title.into(),
            body: body.into(),
            duration_ms,
            urgency,
            created_at: std::time::Instant::now(),
        });
    }

    /// Dequeue the next pending notification, if any.
    pub fn pop_due(&mut self) -> Option<Notification> {
        self.pending.pop_front()
    }

    /// Returns `true` if no notifications are pending.
    pub fn is_empty(&self) -> bool {
        self.pending.is_empty()
    }

    /// The number of pending notifications.
    pub fn len(&self) -> usize {
        self.pending.len()
    }
}

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

// ─── iced state types (module-level so free functions can reference them) ────
// These types are only compiled when the "iced" feature is active.
#[cfg(feature = "iced")]
mod iced_app {
    use std::cell::{Cell, RefCell};
    use std::collections::{HashMap, HashSet};

    use iced::Element;
    use iced::Task;
    use oxiui_iced::{apply_message, IcedConfig, IcedUiCtx, Message, WidgetState};

    use crate::{ContentFn, HookFn, Plugin};

    /// Application state threaded through iced's `update`/`view` loop.
    ///
    /// iced's `view(&State)` takes an immutable reference, so we use `RefCell`
    /// for interior mutability (the content closure and click/widget state).
    pub struct OxiIcedState {
        /// Window title (supplied to the `.title()` callback).
        pub title: String,
        /// The user-supplied content closure; called every `view` frame.
        pub content: RefCell<Option<ContentFn>>,
        /// Button ids whose `ButtonPressed` message was received this cycle.
        pub pending_clicks: RefCell<HashSet<usize>>,
        /// Per-widget retained state (text, checked, slider, selected index).
        pub widget_state: RefCell<HashMap<usize, WidgetState>>,
        /// Lifecycle on_init hooks; called once before the first frame.
        pub on_init: RefCell<Vec<HookFn>>,
        /// Lifecycle on_frame hooks; called every frame after content.
        pub on_frame: RefCell<Vec<HookFn>>,
        /// Registered plugins sorted by priority.
        pub plugins: RefCell<Vec<Box<dyn Plugin>>>,
        /// Whether the init phase has been completed.
        pub initialised: Cell<bool>,
    }

    impl OxiIcedState {
        /// Create an empty fallback state (used if the boot mutex is poisoned).
        pub fn empty() -> Self {
            Self {
                title: String::new(),
                content: RefCell::new(None),
                pending_clicks: RefCell::new(HashSet::new()),
                widget_state: RefCell::new(HashMap::new()),
                on_init: RefCell::new(Vec::new()),
                on_frame: RefCell::new(Vec::new()),
                plugins: RefCell::new(Vec::new()),
                initialised: Cell::new(false),
            }
        }
    }

    /// iced update function — advances widget state and click tracking.
    pub fn update(state: &mut OxiIcedState, msg: Message) -> Task<Message> {
        let mut clicks = state.pending_clicks.borrow_mut();
        let mut widget_state = state.widget_state.borrow_mut();
        apply_message(&mut widget_state, &mut clicks, &msg);
        Task::none()
    }

    /// iced view function — drives the content closure through `IcedUiCtx`.
    ///
    /// Also fires init hooks + plugin init on the first frame, and on_frame
    /// hooks + plugin update every frame. This mirrors the pattern used by
    /// `OxiEguiApp::ui()` (egui path).
    pub fn view<'a>(state: &'a OxiIcedState) -> Element<'a, Message> {
        // Drain pending clicks for this frame.
        let clicks = {
            let mut guard = state.pending_clicks.borrow_mut();
            std::mem::take(&mut *guard)
        };
        let widget_state = state.widget_state.borrow().clone();

        let config = IcedConfig {
            pending_clicks: clicks,
            state: widget_state,
            spacing: 8.0,
            padding: 0.0,
            title: state.title.clone(),
            spec_capacity_hint: 0,
        };
        let mut ctx = IcedUiCtx::new(config);

        // Fire init hooks and plugin init exactly once.
        if !state.initialised.get() {
            state.initialised.set(true);
            if let Ok(mut hooks) = state.on_init.try_borrow_mut() {
                for hook in hooks.iter_mut() {
                    hook(&mut ctx);
                }
            }
            if let Ok(mut plugins) = state.plugins.try_borrow_mut() {
                for plugin in plugins.iter_mut() {
                    plugin.init(&mut ctx);
                }
            }
        }

        // Drive the content closure through the UiCtx bridge.
        if let Ok(mut content_guard) = state.content.try_borrow_mut() {
            if let Some(ref mut f) = *content_guard {
                f(&mut ctx);
            }
        }

        // Fire per-frame hooks and plugin updates.
        if let Ok(mut hooks) = state.on_frame.try_borrow_mut() {
            for hook in hooks.iter_mut() {
                hook(&mut ctx);
            }
        }
        if let Ok(mut plugins) = state.plugins.try_borrow_mut() {
            for plugin in plugins.iter_mut() {
                plugin.update(&mut ctx);
            }
        }

        // `into_iced_element()` returns `Element<'static, Message>`.
        // `'static: 'a` by subtyping, so the coercion is valid.
        let elem: Element<'static, Message> = ctx.into_iced_element();
        // Cast the lifetime from 'static to 'a (safe: 'static is longer).
        // SAFETY: all widget content is owned strings; no borrowed data from state.
        elem
    }

    /// Run the iced application with the given state and theme.
    pub fn run(
        state: OxiIcedState,
        iced_theme: iced::Theme,
        width: f32,
        height: f32,
    ) -> iced::Result {
        let boot_state = std::sync::Mutex::new(Some(state));

        let boot = move || {
            boot_state
                .lock()
                .ok()
                .and_then(|mut g| g.take())
                .unwrap_or_else(OxiIcedState::empty)
        };

        let title_fn = move |s: &OxiIcedState| s.title.clone();
        let theme_fn = move |_: &OxiIcedState| iced_theme.clone();
        let _ = width;
        let _ = height;

        iced::application(boot, update, view)
            .title(title_fn)
            .theme(theme_fn)
            .run()
    }
}

// ─── App builder ─────────────────────────────────────────────────────────────

/// A builder for an OxiUI application window.
///
/// Create with [`App::new`], configure with the builder methods, then call
/// [`App::run`] or [`App::run_headless_once`].
pub struct App {
    config: AppConfig,
    theme: Box<dyn oxiui_core::Theme>,
    content: Option<ContentFn>,
    backend: Backend,
    on_init: Vec<HookFn>,
    on_frame: Vec<HookFn>,
    on_close: Vec<HookFn>,
    on_resize: Vec<HookFn>,
    on_focus: Vec<HookFn>,
    plugins: Vec<Box<dyn Plugin>>,
    hotkeys: HotkeyRegistry,
    commands: CommandPalette,
    notifications: NotificationQueue,
    /// When `true`, the egui backend will yield CPU when no input events occurred.
    frame_skip: bool,
    /// Per-frame escape-hatch callbacks that receive the raw [`egui::Context`].
    #[cfg(feature = "egui")]
    egui_frame_hooks: Vec<EguiFrameHook>,
}

impl App {
    /// Create a new [`App`] with the given [`AppConfig`].
    pub fn new(config: AppConfig) -> Self {
        Self {
            config,
            theme: oxiui_theme::cooljapan_default(),
            content: None,
            backend: Backend::default(),
            on_init: Vec::new(),
            on_frame: Vec::new(),
            on_close: Vec::new(),
            on_resize: Vec::new(),
            on_focus: Vec::new(),
            plugins: Vec::new(),
            hotkeys: HotkeyRegistry::new(),
            commands: CommandPalette::new(),
            notifications: NotificationQueue::new(),
            frame_skip: false,
            #[cfg(feature = "egui")]
            egui_frame_hooks: Vec::new(),
        }
    }

    /// Set the UI theme.
    pub fn theme(mut self, theme: Box<dyn oxiui_core::Theme>) -> Self {
        self.theme = theme;
        self
    }

    /// Set the content closure that will be called every frame.
    pub fn content<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn oxiui_core::UiCtx) + Send + 'static,
    {
        self.content = Some(Box::new(f));
        self
    }

    /// Select the GUI backend.
    ///
    /// Defaults to [`Backend::Egui`]. To use iced, enable the `iced` feature
    /// and pass `Backend::Iced`.
    pub fn backend(mut self, backend: Backend) -> Self {
        self.backend = backend;
        self
    }

    // ─── Window config builder methods ───────────────────────────────────────

    /// Set the minimum window size in logical pixels.
    pub fn min_size(mut self, w: f32, h: f32) -> Self {
        self.config.min_size = Some((w, h));
        self
    }

    /// Set the maximum window size in logical pixels.
    pub fn max_size(mut self, w: f32, h: f32) -> Self {
        self.config.max_size = Some((w, h));
        self
    }

    /// Set whether the window has OS-drawn decorations (title bar, borders).
    pub fn decorations(mut self, d: bool) -> Self {
        self.config.decorations = d;
        self
    }

    /// Set whether the window background is transparent.
    pub fn transparent(mut self, t: bool) -> Self {
        self.config.transparent = t;
        self
    }

    /// Set whether the window is always shown above other windows.
    pub fn always_on_top(mut self, a: bool) -> Self {
        self.config.always_on_top = a;
        self
    }

    /// Set the window icon from raw PNG/ICO bytes.
    pub fn icon(mut self, bytes: Vec<u8>) -> Self {
        self.config.icon = Some(bytes);
        self
    }

    /// Set the initial window position in logical pixels from the primary monitor top-left.
    pub fn position(mut self, x: f32, y: f32) -> Self {
        self.config.position = Some((x, y));
        self
    }

    /// Load a custom font family into all backends.
    ///
    /// The font bytes are stored in [`AppConfig::extra_fonts`] and forwarded
    /// to the active backend's font-loading path when [`App::run`] begins.
    /// In this release, font loading is wired into the egui backend path only;
    /// the iced path stores the bytes but font registration is deferred.
    pub fn with_font(mut self, family_name: impl Into<String>, bytes: Vec<u8>) -> Self {
        self.config.extra_fonts.push((family_name.into(), bytes));
        self
    }

    /// Configure the app with a stateful content closure.
    ///
    /// The `state` value is owned by the closure and passed by mutable reference
    /// on each frame. Because `ContentFn` requires `Send`, the state must be
    /// `Send + 'static`.
    ///
    /// This replaces any previously set content closure.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxiui::{App, AppConfig};
    ///
    /// let _app = App::new(AppConfig::default())
    ///     .with_state(0i32, |ui, count| {
    ///         ui.label(&format!("Count: {count}"));
    ///         *count += 1;
    ///     });
    /// ```
    pub fn with_state<State: Send + 'static>(
        mut self,
        state: State,
        mut content: impl FnMut(&mut dyn oxiui_core::UiCtx, &mut State) + Send + 'static,
    ) -> Self {
        let mut inner_state = state;
        let content_fn = move |ui: &mut dyn oxiui_core::UiCtx| {
            content(ui, &mut inner_state);
        };
        self.content = Some(Box::new(content_fn));
        self
    }

    // ─── Frame-skipping and egui escape hatch ────────────────────────────────

    /// Enable or disable frame skipping in the egui backend.
    ///
    /// When `enabled` is `true`, the egui backend will call
    /// [`egui::Context::request_repaint_after`] with a 1-second delay whenever
    /// no input events occurred in that frame, yielding CPU time. This is a
    /// conservative "dirty flag" optimisation for apps that animate infrequently.
    ///
    /// Defaults to `false` (egui's own repaint-on-input model is sufficient for
    /// most apps without this).
    pub fn with_frame_skip(mut self, enabled: bool) -> Self {
        self.frame_skip = enabled;
        self
    }

    /// Register a per-frame callback that receives the raw [`egui::Context`].
    ///
    /// The callback is invoked once per frame from inside `OxiEguiApp::ui` after
    /// the content closure has run. This is an escape hatch for egui-specific
    /// operations (e.g., loading textures, accessing the raw style, or using
    /// egui widgets not yet exposed through [`UiCtx`]).
    ///
    /// Requires the `egui` feature.
    #[cfg(feature = "egui")]
    #[cfg_attr(docsrs, doc(cfg(feature = "egui")))]
    pub fn with_egui_ctx(mut self, f: impl FnMut(&egui::Context) + Send + 'static) -> Self {
        self.egui_frame_hooks.push(Box::new(f));
        self
    }

    // ─── Table convenience ────────────────────────────────────────────────────

    /// Embed a table view as the app's content.
    ///
    /// The table is rendered frame-by-frame through the active [`UiCtx`] by
    /// iterating the [`oxiui_table::RowSource`] and calling [`UiCtx::label`] for
    /// each cell. The source is wrapped in `Arc<Mutex<S>>` so it can be shared
    /// across frames from a `Send + 'static` closure.
    ///
    /// **Note:** For advanced table features (column sorting, resizing, filtering)
    /// use [`oxiui_table::Table`] directly inside a `content` closure with the
    /// `render_egui` / `render_iced` backend-specific methods.
    ///
    /// Requires the `table` feature.
    #[cfg(feature = "table")]
    #[cfg_attr(docsrs, doc(cfg(feature = "table")))]
    pub fn table<S: oxiui_table::RowSource + Send + 'static>(mut self, source: S) -> Self {
        let source = std::sync::Arc::new(std::sync::Mutex::new(source));
        self = self.content(move |ui| {
            if let Ok(src) = source.lock() {
                // Render column headers.
                for col in src.column_defs() {
                    ui.label(col.name.as_str());
                }
                // Render each row's cells.
                let row_count = src.row_count();
                for i in 0..row_count {
                    let cells = src.row(i);
                    for cell in &cells {
                        ui.label(&cell.to_string());
                    }
                }
            }
        });
        self
    }

    // ─── Lifecycle hooks ──────────────────────────────────────────────────────

    /// Register a closure to be called once when the app initialises.
    ///
    /// Multiple `on_init` hooks are called in registration order.
    pub fn on_init<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn UiCtx) + Send + Sync + 'static,
    {
        self.on_init.push(Box::new(f));
        self
    }

    /// Register a closure to be called every frame after the content closure.
    ///
    /// Multiple `on_frame` hooks are called in registration order.
    pub fn on_frame<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn UiCtx) + Send + Sync + 'static,
    {
        self.on_frame.push(Box::new(f));
        self
    }

    /// Register a closure to be called when the window is closed.
    ///
    /// Invoked on the egui-path inside `OxiEguiApp` (not yet on iced-path;
    /// iced has no per-close callback surface in 0.14). In headless mode this
    /// hook is never fired (there is no window to close).
    pub fn on_close<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn UiCtx) + Send + Sync + 'static,
    {
        self.on_close.push(Box::new(f));
        self
    }

    /// Register a closure to be called when the window is resized.
    ///
    /// Currently stored and available for inspection; egui and iced do not yet
    /// expose a per-resize callback in the same form — this hook is fired from
    /// the headless path for testability and will be wired into the real backends
    /// once the event surface is stable.
    pub fn on_resize<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn UiCtx) + Send + Sync + 'static,
    {
        self.on_resize.push(Box::new(f));
        self
    }

    /// Register a closure to be called when the window gains or loses focus.
    ///
    /// Same status as `on_resize` — stored, testable, not yet wired into live backends.
    pub fn on_focus<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut dyn UiCtx) + Send + Sync + 'static,
    {
        self.on_focus.push(Box::new(f));
        self
    }

    // ─── Plugin registry ──────────────────────────────────────────────────────

    /// Register a plugin.
    ///
    /// Plugins are sorted by [`Plugin::priority`] (ascending) before use, so
    /// lower-priority-number plugins are initialised and updated first.
    pub fn plugin<P: Plugin + 'static>(mut self, p: P) -> Self {
        self.plugins.push(Box::new(p));
        self
    }

    // ─── Feature APIs ─────────────────────────────────────────────────────────

    /// Enqueue an in-app toast notification.
    ///
    /// - `urgency`: 0 = low (3 s), 1 = normal (5 s), 2 = critical (10 s).
    pub fn notify(
        mut self,
        title: impl Into<String>,
        body: impl Into<String>,
        urgency: u8,
    ) -> Self {
        self.notifications.enqueue(title, body, urgency);
        self
    }

    /// Register a global hotkey binding.
    ///
    /// Returns `Err(HotkeyConflict)` if the same `(mods, key)` pair is already
    /// registered. The error is returned wrapped in the builder to allow
    /// chaining — call `.hotkey(...)` on the `Result<App, HotkeyConflict>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxiui::{App, AppConfig};
    /// use oxiui_core::events::{Key, Modifiers};
    ///
    /// let app = App::new(AppConfig::new())
    ///     .try_hotkey(Modifiers { ctrl: true, ..Modifiers::NONE }, Key::Character("s".into()), "save")
    ///     .expect("no conflict");
    /// ```
    pub fn try_hotkey(
        mut self,
        mods: Modifiers,
        key: Key,
        action: impl Into<String>,
    ) -> Result<Self, HotkeyConflict> {
        let action_str: String = action.into();
        self.hotkeys
            .register(action_str.clone(), mods, key, move || {})
            .map_err(|message| HotkeyConflict { message })?;
        Ok(self)
    }

    /// Register a searchable command in the command palette.
    ///
    /// # Example
    ///
    /// ```rust
    /// use oxiui::{App, AppConfig};
    ///
    /// let app = App::new(AppConfig::new())
    ///     .register_command("Save File", None);
    /// ```
    pub fn register_command(mut self, name: impl Into<String>, shortcut: Option<String>) -> Self {
        let name: String = name.into();
        self.commands
            .register_with_shortcut(name.clone(), name, shortcut, || {});
        self
    }

    /// Fuzzy-search the command palette and return matching command labels.
    ///
    /// Returns labels (not IDs) of commands whose label subsequence-matches `query`.
    pub fn command_matches(&self, query: &str) -> Vec<String> {
        self.commands
            .search(query)
            .into_iter()
            .map(|c| c.label.clone())
            .collect()
    }

    /// Capture a screenshot as raw PNG bytes using the software render path.
    ///
    /// When the `software` feature is enabled, this renders a headless frame at the
    /// configured window dimensions and encodes the result as PNG. When `software` is
    /// not enabled, returns `Err(UiError::Unsupported)`.
    ///
    /// # Errors
    ///
    /// - `UiError::Unsupported` when the `software` feature is not enabled.
    /// - `UiError::Backend(msg)` if PNG encoding fails.
    pub fn screenshot(&self) -> Result<Vec<u8>, UiError> {
        #[cfg(feature = "software")]
        {
            let w = if self.config.width > 0.0 {
                self.config.width as u32
            } else {
                800
            };
            let h = if self.config.height > 0.0 {
                self.config.height as u32
            } else {
                600
            };
            let buf = oxiui_render_soft::headless::render_headless_once(w, h);
            // Use RgbaBuffer::save_png to write to a temp file, then read back as bytes.
            // This avoids a direct `png` crate dependency in the oxiui facade.
            let tmp_path = std::env::temp_dir().join(format!("oxiui_screenshot_{w}x{h}.png"));
            buf.save_png(&tmp_path)
                .map_err(|e| UiError::Backend(e.to_string()))?;
            let bytes = std::fs::read(&tmp_path).map_err(|e| UiError::Backend(e.to_string()))?;
            let _ = std::fs::remove_file(&tmp_path);
            Ok(bytes)
        }
        #[cfg(not(feature = "software"))]
        Err(UiError::Unsupported(
            "App::screenshot() requires the `software` feature to be enabled.".to_string(),
        ))
    }

    /// Run one headless frame and return the value produced by `content`.
    ///
    /// This is the headless-only variant: `content` is called against a `NullUiCtx`
    /// and its return value is forwarded. The real (native-window) backends are not
    /// supported here — they return `Err(UiError::Unsupported)` with a note.
    ///
    /// # Errors
    ///
    /// - `UiError::Unsupported` when called on a non-headless app (use
    ///   [`App::run_headless_once`] + a shared-state closure for that case).
    pub fn run_with_return<T>(
        self,
        content: impl FnOnce(&mut dyn UiCtx) -> T + 'static,
    ) -> Result<T, UiError> {
        struct NullUiCtx;
        impl UiCtx for NullUiCtx {
            fn heading(&mut self, _text: &str) {}
            fn label(&mut self, _text: &str) {}
            fn button(&mut self, _label: &str) -> ButtonResponse {
                ButtonResponse::default()
            }
        }

        let mut null = NullUiCtx;
        let result = content(&mut null);
        Ok(result)
    }

    // ─── Accessors for registries (read-only borrows) ─────────────────────────

    /// Inspect the notification queue (e.g. for testing `App::notify`).
    pub fn notifications(&self) -> &NotificationQueue {
        &self.notifications
    }

    /// Inspect the hotkey registry (e.g. for testing `App::try_hotkey`).
    pub fn hotkeys(&self) -> &HotkeyRegistry {
        &self.hotkeys
    }

    /// Inspect the extra fonts registered via [`App::with_font`].
    ///
    /// Returns a slice of `(family_name, bytes)` pairs in registration order.
    pub fn extra_fonts(&self) -> &[(String, Vec<u8>)] {
        &self.config.extra_fonts
    }

    // ─── run() dispatch ───────────────────────────────────────────────────────

    /// Launch the native window and run the event loop.
    ///
    /// Requires a display at runtime. For headless / CI use, call
    /// [`App::run_headless_once`] instead.
    ///
    /// **Lazy initialisation guarantee:** `App::new()` and all builder methods
    /// store configuration only — no GPU device, OS window, or event loop is
    /// created until `run()` is called.
    ///
    /// # Errors
    ///
    /// - [`UiError::Backend`] if the backend runtime fails to initialise.
    /// - [`UiError::Unsupported`] if no UI backend is enabled.
    pub fn run(self) -> Result<AppExit, UiError> {
        #[cfg(feature = "iced")]
        if let Backend::Iced = &self.backend {
            return self.run_iced();
        }

        #[cfg(feature = "slint")]
        if let Backend::Slint = &self.backend {
            return self.run_slint_backend();
        }

        #[cfg(feature = "dioxus")]
        if let Backend::Dioxus = &self.backend {
            return self.run_dioxus_backend();
        }

        self.run_egui_or_fallback()
    }

    #[cfg(feature = "slint")]
    fn run_slint_backend(mut self) -> Result<AppExit, UiError> {
        use oxiui_slint::run_slint;

        let theme_ref = self.theme.as_ref();
        if let Some(content) = self.content.take() {
            let mut content_fn = content;
            run_slint(theme_ref, move |ui| content_fn(ui)).map(|()| AppExit::Ok)
        } else {
            run_slint(theme_ref, |_ui| {}).map(|()| AppExit::Ok)
        }
    }

    #[cfg(feature = "dioxus")]
    fn run_dioxus_backend(mut self) -> Result<AppExit, UiError> {
        use oxiui_dioxus::run_dioxus;

        let theme_ref = self.theme.as_ref();
        if let Some(content) = self.content.take() {
            let mut content_fn = content;
            run_dioxus(theme_ref, move |ui| content_fn(ui)).map(|()| AppExit::Ok)
        } else {
            run_dioxus(theme_ref, |_ui| {}).map(|()| AppExit::Ok)
        }
    }

    #[cfg(feature = "iced")]
    fn run_iced(self) -> Result<AppExit, UiError> {
        use std::cell::{Cell, RefCell};
        use std::collections::{HashMap, HashSet};

        use oxiui_iced::palette_to_iced_theme;

        let iced_theme = {
            let palette = self.theme.palette().clone();
            palette_to_iced_theme(&palette)
        };

        // Sort plugins by priority before handing off to the iced state.
        let mut plugins = self.plugins;
        plugins.sort_by_key(|p| p.priority());

        let state = iced_app::OxiIcedState {
            title: self.config.title.clone(),
            content: RefCell::new(self.content),
            pending_clicks: RefCell::new(HashSet::new()),
            widget_state: RefCell::new(HashMap::new()),
            on_init: RefCell::new(self.on_init),
            on_frame: RefCell::new(self.on_frame),
            plugins: RefCell::new(plugins),
            initialised: Cell::new(false),
        };

        iced_app::run(state, iced_theme, self.config.width, self.config.height)
            .map(|()| AppExit::Ok)
            .map_err(|e| UiError::Backend(e.to_string()))
    }

    #[cfg(all(feature = "egui", not(target_arch = "wasm32")))]
    fn run_egui_or_fallback(mut self) -> Result<AppExit, UiError> {
        use eframe::NativeOptions;
        use oxiui_egui::palette_to_egui_visuals;

        let palette = self.theme.palette().clone();
        let title = self.config.title.clone();
        let width = self.config.width;
        let height = self.config.height;
        let visuals = palette_to_egui_visuals(&palette);
        let content_fn = self.content.take();
        let extra_fonts = std::mem::take(&mut self.config.extra_fonts);

        // Sort plugins by priority (ascending).
        self.plugins.sort_by_key(|p| p.priority());

        // Decode the window icon (if provided) to egui::IconData.
        let icon_data: Option<std::sync::Arc<egui::IconData>> =
            if let Some(icon_bytes) = &self.config.icon {
                match crate::icon::decode_icon(icon_bytes) {
                    Ok(data) => Some(std::sync::Arc::new(data)),
                    Err(e) => {
                        // Non-fatal: log and continue without an icon.
                        eprintln!("oxiui: failed to decode window icon: {e}");
                        None
                    }
                }
            } else {
                None
            };

        // Build the egui ViewportBuilder with all configured props.
        let mut vp = egui::ViewportBuilder::default()
            .with_title(&title)
            .with_inner_size([width, height])
            .with_resizable(self.config.resizable)
            .with_decorations(self.config.decorations)
            .with_transparent(self.config.transparent);

        if self.config.always_on_top {
            vp = vp.with_always_on_top();
        }
        if let Some((min_w, min_h)) = self.config.min_size {
            vp = vp.with_min_inner_size([min_w, min_h]);
        }
        if let Some((max_w, max_h)) = self.config.max_size {
            vp = vp.with_max_inner_size([max_w, max_h]);
        }
        if let Some((px, py)) = self.config.position {
            vp = vp.with_position([px, py]);
        }
        if let Some(icon) = icon_data {
            vp = vp.with_icon(icon);
        }

        let native_opts = NativeOptions {
            viewport: vp,
            ..Default::default()
        };

        let frame_skip = self.frame_skip;
        let egui_frame_hooks = std::mem::take(&mut self.egui_frame_hooks);

        eframe::run_native(
            &title,
            native_opts,
            Box::new(move |cc| {
                cc.egui_ctx.set_visuals(visuals.clone());
                if !extra_fonts.is_empty() {
                    let refs: Vec<(&str, Vec<u8>)> = extra_fonts
                        .iter()
                        .map(|(n, b)| (n.as_str(), b.clone()))
                        .collect();
                    let _ = oxiui_egui::load_fonts_into_egui(&refs, &cc.egui_ctx);
                }
                Ok(Box::new(OxiEguiApp {
                    content: content_fn,
                    on_init: self.on_init,
                    on_frame: self.on_frame,
                    plugins: self.plugins,
                    initialised: false,
                    frame_skip,
                    egui_frame_hooks,
                }))
            }),
        )
        .map(|()| AppExit::Ok)
        .map_err(|e| UiError::Backend(e.to_string()))
    }

    // On wasm32 with the `egui` feature, `eframe::run_native` does not exist.
    // The wasm32 egui path uses `eframe::WebRunner` instead (wired in `oxiui-web`).
    #[cfg(all(feature = "egui", target_arch = "wasm32"))]
    fn run_egui_or_fallback(self) -> Result<AppExit, UiError> {
        let _ = &self.config;
        let _ = &self.theme;
        let _ = &self.content;
        let _ = &self.backend;
        let _ = &self.on_init;
        let _ = &self.on_frame;
        let _ = &self.plugins;
        let _ = &self.frame_skip;
        let _ = &self.egui_frame_hooks;
        Err(UiError::Unsupported(
            "On wasm32, use `oxiui_web::mount(canvas_id)` instead of App::run().".to_string(),
        ))
    }

    #[cfg(not(feature = "egui"))]
    fn run_egui_or_fallback(self) -> Result<AppExit, UiError> {
        // Reference fields to suppress dead-code diagnostics under this cfg path.
        let _ = &self.config;
        let _ = &self.theme;
        let _ = &self.content;
        let _ = &self.backend;
        let _ = &self.on_init;
        let _ = &self.on_frame;
        let _ = &self.plugins;
        let _ = &self.frame_skip;
        Err(UiError::Unsupported(
            "No UI backend enabled. Use default features or enable `egui`.".to_string(),
        ))
    }

    /// Run one synthetic UI frame without opening a real window.
    ///
    /// Calls init hooks + plugin `init`, then the content closure, then
    /// `on_frame` hooks + plugin `update`, all against a `NullUiCtx` (a no-op
    /// [`UiCtx`] that records calls but does not render). Useful for testing
    /// that content closures run without panic, and for CI environments that
    /// have no display server.
    ///
    /// # Errors
    /// Currently infallible; always returns `Ok(AppExit::Ok)`.
    pub fn run_headless_once(mut self) -> Result<AppExit, UiError> {
        struct NullUiCtx;
        impl UiCtx for NullUiCtx {
            fn heading(&mut self, _text: &str) {}
            fn label(&mut self, _text: &str) {}
            fn button(&mut self, _label: &str) -> ButtonResponse {
                ButtonResponse::default()
            }
        }

        // Sort plugins by priority.
        self.plugins.sort_by_key(|p| p.priority());

        let mut null = NullUiCtx;

        // Fire init hooks.
        for hook in self.on_init.iter_mut() {
            hook(&mut null);
        }
        // Fire plugin init.
        for plugin in self.plugins.iter_mut() {
            plugin.init(&mut null);
        }

        // Run the content closure.
        if let Some(ref mut f) = self.content {
            f(&mut null);
        }

        // Fire on_frame hooks.
        for hook in self.on_frame.iter_mut() {
            hook(&mut null);
        }
        // Fire plugin update.
        for plugin in self.plugins.iter_mut() {
            plugin.update(&mut null);
        }

        Ok(AppExit::Ok)
    }

    /// Run the app content once via [`RecordingUiCtx`] and return an accessibility tree.
    ///
    /// This is a headless operation — no event loop or real window is required.
    /// The content closure (if any) is called once through [`RecordingUiCtx`];
    /// all widget calls are captured as [`RecordingEntry`] nodes and assembled
    /// into an [`oxiui_accessibility::A11yTree`] rooted at `window_id`.
    ///
    /// Returns an empty tree (no-op root) if no content closure has been set.
    ///
    /// # Feature
    /// Requires the `a11y` feature.
    #[cfg(feature = "a11y")]
    pub fn build_a11y_snapshot(
        &mut self,
        window_id: oxiui_accessibility::WindowA11yId,
    ) -> oxiui_accessibility::A11yTree {
        let mut recorder = recording::RecordingUiCtx::new();
        if let Some(ref mut f) = self.content {
            f(&mut recorder);
        }
        recorder.build_a11y_tree(window_id)
    }
}

// ─── OxiEguiApp (native egui integration) ────────────────────────────────────

// OxiEguiApp is only used by `run_native`, which only exists on non-wasm32 targets.
#[cfg(all(feature = "egui", not(target_arch = "wasm32")))]
struct OxiEguiApp {
    content: Option<ContentFn>,
    on_init: Vec<HookFn>,
    on_frame: Vec<HookFn>,
    plugins: Vec<Box<dyn Plugin>>,
    initialised: bool,
    /// If true, yield CPU when no input events occurred this frame.
    frame_skip: bool,
    /// Raw egui::Context escape-hatch callbacks.
    egui_frame_hooks: Vec<EguiFrameHook>,
}

#[cfg(all(feature = "egui", not(target_arch = "wasm32")))]
impl eframe::App for OxiEguiApp {
    /// Called each frame with the root [`egui::Ui`].
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        // Clone the context now (cheap Arc clone) so we can pass it to hooks
        // without conflicting with the EguiUiCtx borrow below.
        let egui_ctx = ui.ctx().clone();

        let mut ctx_bridge = oxiui_egui::EguiUiCtx::new(ui);

        // Fire init hooks exactly once.
        if !self.initialised {
            self.initialised = true;
            for hook in self.on_init.iter_mut() {
                hook(&mut ctx_bridge);
            }
            for plugin in self.plugins.iter_mut() {
                plugin.init(&mut ctx_bridge);
            }
        }

        // Content closure.
        if let Some(ref mut f) = self.content {
            f(&mut ctx_bridge);
        }

        // Per-frame hooks and plugin updates.
        for hook in self.on_frame.iter_mut() {
            hook(&mut ctx_bridge);
        }
        for plugin in self.plugins.iter_mut() {
            plugin.update(&mut ctx_bridge);
        }

        // egui escape-hatch callbacks.
        for hook in &mut self.egui_frame_hooks {
            hook(&egui_ctx);
        }

        // Frame-skip: if no input events occurred this frame, defer the next repaint.
        if self.frame_skip && egui_ctx.input(|i| i.events.is_empty()) {
            egui_ctx.request_repaint_after(std::time::Duration::from_secs(1));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxiui_core::events::{Key, Modifiers};

    // ─── STEP 1: Iced plugin init wiring (backend-agnostic proxy via headless) ──

    /// Plugins registered on a headless app fire init+update in priority order.
    /// This indirectly proves OxiIcedState::empty() and the priority sort compile.
    #[test]
    fn test_iced_plugin_init_called() {
        use std::sync::{Arc, Mutex};

        struct SpyPlugin {
            counter: Arc<Mutex<u32>>,
        }
        impl Plugin for SpyPlugin {
            fn init(&mut self, _ctx: &mut dyn UiCtx) {
                *self.counter.lock().unwrap() += 1;
            }
            fn update(&mut self, _ctx: &mut dyn UiCtx) {}
        }

        let counter = Arc::new(Mutex::new(0u32));
        let counter_c = Arc::clone(&counter);

        App::new(AppConfig::new())
            .plugin(SpyPlugin { counter: counter_c })
            .run_headless_once()
            .unwrap();

        assert_eq!(
            *counter.lock().unwrap(),
            1,
            "plugin init must be called once"
        );
    }

    // ─── STEP 2: Window config props ─────────────────────────────────────────

    /// All seven new AppConfig fields round-trip through the builder correctly.
    #[test]
    fn test_app_config_window_props_set() {
        let cfg = AppConfig::new()
            .min_size(400.0, 300.0)
            .max_size(1920.0, 1080.0)
            .decorations(false)
            .transparent(true)
            .always_on_top(true)
            .icon(vec![0u8, 1, 2, 3])
            .position(100.0, 200.0);

        assert_eq!(cfg.min_size, Some((400.0, 300.0)));
        assert_eq!(cfg.max_size, Some((1920.0, 1080.0)));
        assert!(!cfg.decorations);
        assert!(cfg.transparent);
        assert!(cfg.always_on_top);
        assert_eq!(cfg.icon, Some(vec![0u8, 1, 2, 3]));
        assert_eq!(cfg.position, Some((100.0, 200.0)));
    }

    /// AppConfig default values are correct (decorations=true, transparent=false, etc.).
    #[test]
    fn test_app_config_defaults() {
        let cfg = AppConfig::new();
        assert!(cfg.decorations, "decorations defaults to true");
        assert!(!cfg.transparent, "transparent defaults to false");
        assert!(!cfg.always_on_top, "always_on_top defaults to false");
        assert!(cfg.min_size.is_none());
        assert!(cfg.max_size.is_none());
        assert!(cfg.icon.is_none());
        assert!(cfg.position.is_none());
    }

    // ─── STEP 3a: App::notify enqueues ───────────────────────────────────────

    #[test]
    fn test_app_notify_enqueues() {
        let app = App::new(AppConfig::new()).notify("Alert", "Something happened", 1);
        assert_eq!(
            app.notifications().len(),
            1,
            "one notification must be enqueued"
        );
        let n = app.notifications.pending.iter().next().unwrap();
        assert_eq!(n.title, "Alert");
        assert_eq!(n.body, "Something happened");
        assert_eq!(n.urgency, 1);
    }

    // ─── STEP 3b: App::hotkey conflict detection ──────────────────────────────

    #[test]
    fn test_app_hotkey_conflict_detection() {
        let mods = Modifiers {
            ctrl: true,
            ..Modifiers::NONE
        };
        let key = Key::Character("s".into());

        let app = App::new(AppConfig::new())
            .try_hotkey(mods, key.clone(), "save")
            .expect("first registration must succeed");

        let result = app.try_hotkey(mods, key, "save-duplicate");
        assert!(result.is_err(), "duplicate hotkey must return Err");
    }

    #[test]
    fn test_hotkey_conflict_error_type() {
        let mods = Modifiers::NONE;
        let key = Key::Escape;

        let app = App::new(AppConfig::new())
            .try_hotkey(mods, key.clone(), "esc")
            .unwrap();

        match app.try_hotkey(mods, key, "esc2") {
            Err(err) => assert!(!err.message.is_empty()),
            Ok(_) => panic!("expected HotkeyConflict error"),
        }
    }

    // ─── STEP 3c: Command palette fuzzy match ────────────────────────────────

    #[test]
    fn test_command_palette_fuzzy_match() {
        let app = App::new(AppConfig::new())
            .register_command("Save File", None)
            .register_command("Open File", None)
            .register_command("Quit", None);

        let matches = app.command_matches("save");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0], "Save File");
    }

    #[test]
    fn test_command_palette_empty_query_matches_all() {
        let app = App::new(AppConfig::new())
            .register_command("Alpha", None)
            .register_command("Beta", None);

        let matches = app.command_matches("");
        assert_eq!(matches.len(), 2);
    }

    // ─── STEP 3d: Screenshot ─────────────────────────────────────────────────

    #[test]
    fn test_screenshot_returns_nonempty_or_unsupported() {
        let app = App::new(AppConfig::new().size(64.0, 48.0));
        let result = app.screenshot();
        match result {
            Ok(bytes) => assert!(!bytes.is_empty(), "screenshot bytes must be non-empty"),
            Err(UiError::Unsupported(_)) => {
                // expected when `software` feature is not enabled
            }
            Err(e) => panic!("unexpected screenshot error: {e:?}"),
        }
    }

    // ─── STEP 3e: run_with_return ─────────────────────────────────────────────

    #[test]
    fn test_run_with_return_headless() {
        let app = App::new(AppConfig::new());
        let result = app.run_with_return(|_ui| 42u32);
        assert_eq!(result.unwrap(), 42u32);
    }

    #[test]
    fn test_run_with_return_string_value() {
        let app = App::new(AppConfig::new());
        let result = app.run_with_return(|_ui| "hello".to_string());
        assert_eq!(result.unwrap(), "hello");
    }

    // ─── STEP 3f: Lifecycle on_close/on_resize/on_focus registered ───────────

    #[test]
    fn test_lifecycle_on_close_registered() {
        // on_close hooks are stored and survive the builder chain (not fired in headless).
        let _app = App::new(AppConfig::new()).on_close(|_ui| {});
        // If this compiles, the hook is accepted.
    }

    #[test]
    fn test_lifecycle_on_resize_registered() {
        let _app = App::new(AppConfig::new()).on_resize(|_ui| {});
    }

    #[test]
    fn test_lifecycle_on_focus_registered() {
        let _app = App::new(AppConfig::new()).on_focus(|_ui| {});
    }

    // ─── STEP 3g: Richer AppExit ─────────────────────────────────────────────

    #[test]
    fn test_app_exit_richer_reason() {
        let r1 = AppExit::RequestedByUser;
        let r2 = AppExit::Programmatic("deliberate shutdown".into());
        let r3 = AppExit::Ok;

        assert_eq!(r1, AppExit::RequestedByUser);
        assert_eq!(r2, AppExit::Programmatic("deliberate shutdown".into()));
        assert_ne!(r1, r3);
        assert_ne!(r2, AppExit::Programmatic("other".into()));
    }

    // ─── STEP 3h: Prelude exports UiCtx ──────────────────────────────────────

    #[test]
    fn test_prelude_exports_uictx() {
        // Verifying at compile-time that `UiCtx` is in the prelude.
        use crate::prelude::*;
        // If this compiles, UiCtx is re-exported.
        fn _accepts_ctx(_: &dyn UiCtx) {}
    }

    // ─── Integration: headless smoke (equivalent to test_every_example_compiles) ──

    #[test]
    fn test_headless_smoke_all_apis() {
        // Exercise all new APIs in a single headless run.
        use std::sync::{Arc, Mutex};

        struct CountPlugin(Arc<Mutex<u32>>);
        impl Plugin for CountPlugin {
            fn init(&mut self, _: &mut dyn UiCtx) {
                *self.0.lock().unwrap() += 10;
            }
            fn update(&mut self, _: &mut dyn UiCtx) {
                *self.0.lock().unwrap() += 1;
            }
        }

        let counter = Arc::new(Mutex::new(0u32));

        App::new(
            AppConfig::new()
                .title("smoke")
                .min_size(100.0, 100.0)
                .decorations(true)
                .transparent(false),
        )
        .plugin(CountPlugin(Arc::clone(&counter)))
        .on_init(|_| {})
        .on_frame(|_| {})
        .notify("Test", "body", 0)
        .content(|ui| {
            ui.heading("h");
        })
        .run_headless_once()
        .unwrap();

        let c = *counter.lock().unwrap();
        assert_eq!(c, 11, "init=10, update=1");
    }
}