waterui-ffi 0.3.0

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

#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
compile_error!("waterui-ffi requires the `std` feature.");
#[cfg(all(feature = "c-api", feature = "android-jni"))]
compile_error!("waterui-ffi features `c-api` and `android-jni` are mutually exclusive");
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[macro_use]
mod macros;

// JNI module for Android backend (when android-jni feature is enabled)
#[cfg(feature = "android-jni")]
pub mod jni;

mod bridge;
mod drawing;
mod events;
mod reactivity;
mod runtime;
mod ty;

/// C ABI exports for every bridged `WaterUI` component family.
pub mod components;
pub use bridge::{action, array, closure, locale};
use core::ptr::null_mut;
pub use drawing::{color, gradient, shape};
pub use events::{animation, cursor, drag_drop, event, gesture};
pub use reactivity::reactive;
pub use runtime::{app, id, safe_area, theme, views, window};
pub use ty::WuiTypeId;

use alloc::boxed::Box;
use executor_core::{init_global_executor, init_local_executor};
#[cfg(target_vendor = "apple")]
use waterkit_audio as _;
use waterui::{AnyView, Str, View};
use waterui_core::{Metadata, Native};
pub use waterui_video;

use waterui_core::metadata::MetadataKey;

use crate::array::WuiArray;

/// Reborrows a raw pointer as a shared reference.
///
/// # Safety
///
/// `ptr` must be non-null and point to a valid, initialized `T` that stays
/// alive and unaliased for the duration of the returned `'a` borrow.
#[inline]
pub const unsafe fn borrow_ffi<'a, T>(ptr: *const T) -> &'a T {
    // SAFETY: this function's own contract, stated above, is exactly the requirement
    // the dereference has: a non-null, initialized `T` alive for the returned borrow.
    unsafe { &*ptr }
}

/// Reborrows a raw pointer as an exclusive reference.
///
/// # Safety
///
/// `ptr` must be non-null and point to a valid, initialized `T` that stays
/// alive and exclusively borrowed for the duration of the returned `'a` borrow.
#[inline]
pub unsafe fn borrow_ffi_mut<'a, T>(ptr: *mut T) -> &'a mut T {
    // SAFETY: as for `borrow_ffi`, with the caller additionally promising the borrow
    // is exclusive for its lifetime.
    unsafe { &mut *ptr }
}

/// Generates the FFI entry points (`waterui_init`, `waterui_app`, and the
/// Android variants) for the application crate that calls it.
#[macro_export]
macro_rules! export {
    () => {
        const _: () = {
            /// Initializes the WaterUI runtime and creates a default environment.
            ///
            /// Native should:
            /// 1. Call this once at startup
            /// 2. Install theme settings into the returned environment
            /// 3. Pass the environment to `waterui_app()`
            ///
            /// # Safety
            /// This function must be called on main thread, once only.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn waterui_init() -> *mut $crate::WuiEnv {
                let inspector = unsafe { $crate::__init() };
                let mut env = waterui::configure_environment!(waterui::Environment::new());
                waterui::inspector::install(&mut env, inspector);
                $crate::__configure_browser_environment(&mut env);
                $crate::IntoFFI::into_ffi(env)
            }

            /// Creates the application from the user's `app(env)` function.
            ///
            /// Takes ownership of the environment (with theme already installed) from native,
            /// calls the user's `app(env: Environment) -> App` function, and returns the App.
            ///
            /// The environment is returned inside the App struct for native to use during rendering.
            ///
            /// # Safety
            /// - `env` must be a valid pointer from `waterui_init()` or native env creation
            /// - This function takes ownership of the environment
            /// - This function must be called on main thread
            #[unsafe(no_mangle)]
            #[allow(unexpected_cfgs)]
            pub unsafe extern "C" fn waterui_app(env: *mut $crate::WuiEnv) -> $crate::app::WuiApp {
                // Take ownership of the environment
                let env: waterui::Environment = unsafe { $crate::IntoRust::into_rust(env) };

                let app: waterui::app::App = app(env);

                $crate::IntoFFI::into_ffi(app)
            }

            /// Android JNI entry point with an ABI that exposes only the two
            /// opaque handles owned by the single-activity backend.
            #[cfg(target_os = "android")]
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn waterui_android_app(
                env: *mut core::ffi::c_void,
            ) -> $crate::app::WuiAndroidAppHandles {
                unsafe { waterui_app(env.cast()) }.into_android_handles()
            }

            /// Android JNI initialization entry point using an opaque handle.
            #[cfg(target_os = "android")]
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn waterui_android_init() -> *mut core::ffi::c_void {
                unsafe { waterui_init() }.cast()
            }

            #[cfg(target_os = "android")]
            #[unsafe(no_mangle)]
            extern "system" fn JNI_OnLoad(
                vm: *mut core::ffi::c_void,
                _reserved: *mut core::ffi::c_void,
            ) -> i32 {
                // Initialize JNI module (cached classes, JavaVM reference)
                // Note: We use __jni_init which is conditionally defined based on
                // the android-jni feature in waterui-ffi crate (not the calling crate).
                unsafe { $crate::__jni_init(vm) }
            }
        };
    };
}

/// Installs optional packaged browser runtimes selected by the generated FFI crate.
///
/// Not `const`: the CEF arm installs a runtime. It compiled as `const` only
/// because the CEF features were previously reached through cbindgen's macro
/// expansion, which never type-checks the body.
#[allow(
    clippy::missing_const_for_fn,
    reason = "the body is empty only in the feature configuration being linted; enabling the capability makes it install a realization"
)]
#[doc(hidden)]
#[inline]
pub fn __configure_browser_environment(env: &mut waterui::Environment) {
    #[cfg(any(feature = "cef-runtime", feature = "cef-header"))]
    components::platform::browser_cef::configure_environment(env);
    #[cfg(not(any(feature = "cef-runtime", feature = "cef-header")))]
    let _ = env;
}

/// JNI initialization helper for Android.
/// This is called from JNI_OnLoad in the export! macro.
///
/// The `android-jni` feature is mandatory for Android exports.
///
/// # Safety
/// Must only be called once from JNI_OnLoad.
#[doc(hidden)]
#[cfg(all(target_os = "android", feature = "android-jni"))]
#[inline]
pub unsafe fn __jni_init(vm: *mut core::ffi::c_void) -> i32 {
    unsafe { jni::init(vm as *mut jni::jni::sys::JavaVM) }
}

#[cfg(all(target_os = "android", not(feature = "android-jni")))]
compile_error!("waterui-ffi requires the `android-jni` feature when targeting Android");

/// JNI initialization stub for non-Android platforms.
#[doc(hidden)]
#[cfg(not(target_os = "android"))]
#[inline]
pub const unsafe fn __jni_init(_vm: *mut core::ffi::c_void) -> i32 {
    0x0001_0006
}

/// # Safety
/// You have to ensure this is only called once, and on main thread.
#[doc(hidden)]
#[inline]
#[must_use]
pub unsafe fn __init() -> Option<waterui::inspector::InspectorRuntime> {
    // SAFETY: `__init_impl` is generated by the `export!` macro in the app crate and
    // shares this entry point's contract: it runs once, on the platform main thread,
    // before any other FFI call.
    unsafe { __init_impl() }
}

/// # Safety
/// Must run on the platform main thread exactly once.
unsafe fn __init_impl() -> Option<waterui::inspector::InspectorRuntime> {
    #[cfg(target_os = "android")]
    unsafe {
        native_executor::android::register_android_main_thread()
            .expect("Failed to register Android main thread");
    }
    let inspector = waterui::inspector::maybe_init_from_env(if cfg!(target_os = "android") {
        "android"
    } else {
        "apple"
    });

    #[cfg(feature = "std")]
    {
        // Forwards panics to tracing
        std::panic::set_hook(Box::new(|info| {
            tracing_panic::panic_hook(info);
        }));

        init_tracing(
            inspector
                .as_ref()
                .map(waterui::inspector::InspectorRuntime::tracing_layer),
        );
    }

    init_global_executor(native_executor::NativeExecutor::new());
    // The FFI entry point runs under a real platform main thread (the Apple main
    // queue, or Android's looper after `register_android_main_thread`). Failing
    // here names the missing setup, instead of panicking at the first spawn.
    let main_executor = native_executor::NativeMainExecutor::new().expect(
        "waterui_init requires a platform main thread; on Android call \
         register_android_main_thread on the UI thread first, and on a host that \
         owns its own event loop install that loop's LocalExecutor instead",
    );
    init_local_executor(waterui::task::monitored_local_executor_with_probes(
        main_executor,
        inspector
            .as_ref()
            .map(waterui::inspector::InspectorRuntime::runtime_probe),
    ));

    // Locale changes reach views through a mailbox, whose pump needs the
    // executor installed just above.
    waterui_locale::start_system_locale_listener();

    inspector
}

/// Sends `tracing` records to the platform logger, and to the inspector when one
/// is attached.
///
/// The three platform arms differ only in which logger they attach, so the
/// inspector layer is wired once here rather than in each of them.
#[cfg(feature = "std")]
fn init_tracing(inspector: Option<waterui::inspector::InspectorLayer>) {
    {
        // Forwards tracing to platform's logging system
        #[cfg(target_os = "android")]
        {
            use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

            let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
                .or_else(|_| {
                    tracing_subscriber::EnvFilter::try_new(
                        "error,wgpu_core=error,wgpu_hal=error,naga=error,jni=error",
                    )
                })
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("error"));

            tracing_subscriber::registry()
                .with(env_filter)
                .with(
                    tracing_android::layer("WaterUI").expect("Failed to create Android log layer"),
                )
                .with(inspector)
                .init();
        }

        #[cfg(target_vendor = "apple")]
        {
            use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

            let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
                .or_else(|_| {
                    tracing_subscriber::EnvFilter::try_new(
                        "error,wgpu_core=error,wgpu_hal=error,naga=error,metal=error",
                    )
                })
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("error"));

            tracing_subscriber::registry()
                .with(env_filter)
                .with(tracing_oslog::OsLogger::new("dev.waterui", "default"))
                .with(inspector)
                .init();
        }

        #[cfg(not(any(target_os = "android", target_vendor = "apple")))]
        {
            use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

            tracing_subscriber::registry()
                .with(tracing_subscriber::EnvFilter::from_default_env())
                .with(tracing_subscriber::fmt::layer())
                .with(inspector)
                .init();
        }
    }
}

/// Defines a trait for converting Rust types to FFI-compatible representations.
///
/// This trait is used to convert Rust types that are not directly FFI-compatible
/// into types that can be safely passed across the FFI boundary. Implementors
/// must specify an FFI-compatible type and provide conversion logic.
///
/// # Examples
///
/// ```
/// use waterui_ffi::IntoFFI;
///
/// struct MyStruct {
///     value: u32,
/// }
///
/// impl IntoFFI for MyStruct {
///     type FFI = *mut MyStruct;
///     fn into_ffi(self) -> Self::FFI {
///         Box::into_raw(Box::new(self))
///     }
/// }
/// ```
pub trait IntoFFI: 'static {
    /// The FFI-compatible type that this Rust type converts to.
    type FFI: 'static;

    /// Converts this Rust type into its FFI-compatible representation.
    fn into_ffi(self) -> Self::FFI;
}

/// Conversion to an FFI representation that has a dedicated null value,
/// letting `Option<T>` cross the FFI boundary without an extra wrapper.
pub trait IntoNullableFFI: 'static {
    /// The FFI-compatible type that this Rust type converts to.
    type FFI: 'static;
    /// Converts this Rust type into its FFI-compatible representation.
    fn into_ffi(self) -> Self::FFI;
    /// Returns the FFI value representing `None`.
    fn null() -> Self::FFI;
}

impl<T: IntoNullableFFI> IntoFFI for Option<T> {
    type FFI = T::FFI;

    fn into_ffi(self) -> Self::FFI {
        self.map_or_else(T::null, <T as IntoNullableFFI>::into_ffi)
    }
}

impl<T: IntoNullableFFI> IntoFFI for T {
    type FFI = T::FFI;

    fn into_ffi(self) -> Self::FFI {
        <T as IntoNullableFFI>::into_ffi(self)
    }
}

/// Types with a designated sentinel value that the C ABI treats as invalid or
/// absent.
pub trait InvalidValue {
    /// Returns the sentinel value treated as invalid/absent by the FFI.
    fn invalid() -> Self;
}

/// Defines a marker trait for types that should be treated as opaque when crossing FFI boundaries.
///
/// Opaque types are typically used when the internal structure of a type is not relevant
/// to foreign code and only the Rust side needs to understand the full implementation details.
/// This trait automatically provides implementations of `IntoFFI` and `IntoRust` for
/// any type that implements it, handling conversion to and from raw pointers.
///
/// # Examples
///
/// ```
/// use waterui_ffi::OpaqueType;
///
/// struct MyInternalStruct {
///     data: Vec<u32>,
///     state: String,
/// }
///
/// // By marking this as OpaqueType, foreign code only needs to deal with opaque pointers
/// impl OpaqueType for MyInternalStruct {}
/// ```
pub trait OpaqueType: 'static {}

impl<T: OpaqueType> IntoNullableFFI for T {
    type FFI = *mut T;
    fn into_ffi(self) -> Self::FFI {
        Box::into_raw(Box::new(self))
    }
    fn null() -> Self::FFI {
        null_mut()
    }
}

impl<T: OpaqueType> IntoRust for *mut T {
    type Rust = Option<T>;
    unsafe fn into_rust(self) -> Self::Rust {
        if self.is_null() {
            None
        } else {
            // SAFETY: the caller contract makes `self` an owning pointer from the
            // matching FFI constructor, so reclaiming the box frees it
            // exactly once.
            unsafe { Some(*Box::from_raw(self)) }
        }
    }
}
/// Defines a trait for converting FFI-compatible types back to native Rust types.
///
/// This trait is complementary to `IntoFFI` and is used to convert FFI-compatible
/// representations back into their original Rust types. This is typically used
/// when receiving data from FFI calls that need to be processed in Rust code.
///
/// # Safety
///
/// Implementations of this trait are inherently unsafe as they involve converting
/// raw pointers or other FFI-compatible types into Rust types, which requires
/// ensuring memory safety, proper ownership, and correct type interpretation.
///
/// # Examples
///
/// Shown as text rather than compiled: implementing this for `*mut MyStruct`
/// is only possible inside this crate, because the orphan rule does not treat a
/// raw pointer as a fundamental type carrying the local one.
///
/// ```text
/// impl IntoRust for *mut MyStruct {
///     type Rust = MyStruct;
///
///     unsafe fn into_rust(self) -> Self::Rust {
///         if self.is_null() {
///             panic!("Null pointer provided");
///         }
///         *Box::from_raw(self)
///     }
/// }
/// ```
pub trait IntoRust {
    /// The native Rust type that this FFI-compatible type converts to.
    type Rust;

    /// Converts this FFI-compatible type into its Rust equivalent.
    ///
    /// # Safety
    /// The caller must ensure that the FFI value being converted is valid and
    /// properly initialized. Improper use may lead to undefined behavior.
    unsafe fn into_rust(self) -> Self::Rust;
}

ffi_safe!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64, bool);

opaque!(WuiEnv, waterui::Environment, env);

opaque!(WuiAnyView, waterui::AnyView, anyview, any());

/// Visual presentation mode for the label slot of every control.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum WuiLabelDisplayMode {
    /// Use the label's own preferred presentation.
    Automatic,
    /// Show both title and icon when an icon is available.
    TitleAndIcon,
    /// Show only the title text.
    TitleOnly,
    /// Show only the icon when an icon is available.
    IconOnly,
    /// Visually hide the label entirely. The accessibility tree still
    /// announces [`WuiLabel::accessibility_label`].
    Hidden,
}

impl crate::IntoFFI for waterui_controls::label::LabelDisplayMode {
    type FFI = WuiLabelDisplayMode;
    fn into_ffi(self) -> Self::FFI {
        match self {
            Self::Automatic => WuiLabelDisplayMode::Automatic,
            Self::TitleAndIcon => WuiLabelDisplayMode::TitleAndIcon,
            Self::TitleOnly => WuiLabelDisplayMode::TitleOnly,
            Self::IconOnly => WuiLabelDisplayMode::IconOnly,
            Self::Hidden => WuiLabelDisplayMode::Hidden,
        }
    }
}

/// FFI surface for the label slot of every control.
///
/// Bundles the three pieces backends need: the visual view to render, the
/// accessibility text to announce regardless of visual mode, and the visual
/// mode itself. The `view` field is always non-null but renders to an empty
/// view when `display_mode` is [`WuiLabelDisplayMode::Hidden`].
#[repr(C)]
#[derive(Debug)]
pub struct WuiLabel {
    /// Visual chrome rendered by the backend. When `display_mode` is
    /// `Hidden` the rendered view collapses to an empty zero-size view.
    pub view: *mut WuiAnyView,
    /// Spoken accessibility text. Always non-null; backends should bind
    /// this to platform accessibility APIs (`VoiceOver`, `TalkBack`, etc.).
    pub accessibility_label: *mut crate::reactive::WuiComputed<waterui_text::styled::StyledStr>,
    /// Visual presentation mode.
    pub display_mode: WuiLabelDisplayMode,
}

impl crate::IntoFFI for waterui_controls::label::Label {
    type FFI = WuiLabel;
    fn into_ffi(self) -> Self::FFI {
        let accessibility_label = self.accessibility_label();
        let display_mode = self.display_mode_preference().into_ffi();
        let view = waterui::AnyView::new(self).into_ffi();
        WuiLabel {
            view,
            accessibility_label: accessibility_label.into_ffi(),
            display_mode,
        }
    }
}

/// Gets the id of the anyview type as a 128-bit value for O(1) comparison.
#[unsafe(no_mangle)]
pub extern "C" fn waterui_anyview_id() -> WuiTypeId {
    WuiTypeId::of::<AnyView>()
}

/// Clones an existing environment instance
///
/// # Safety
/// The caller must ensure that `env` is a valid pointer to a properly initialized
/// `waterui::Environment` instance and that the environment remains valid for the
/// duration of this function call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_clone_env(env: *const WuiEnv) -> *mut WuiEnv {
    // SAFETY: the caller contract requires `env` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let env = unsafe { borrow_ffi(env) };
    env.0.clone().into_ffi()
}

/// Returns the disabled state in force at this point in the view tree.
///
/// Disabled state is a scoped subtree attribute installed by `.disabled(...)`,
/// never a field on an individual control's configuration. Every interactive
/// control reads it here, from the same environment it already receives through
/// [`waterui_view_body`], and renders as inactive and ignores input while the
/// signal is `true`.
///
/// Always returns a non-null signal; it reads `false` when no `.disabled(...)`
/// scope encloses the view. Returns a new reference to the signal — the caller
/// must drop it when done.
///
/// # Safety
/// The caller must ensure that `env` is a valid pointer to a properly initialized
/// `waterui::Environment` instance and that the environment remains valid for the
/// duration of this function call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_env_disabled(
    env: *const WuiEnv,
) -> *mut crate::reactive::WuiComputed<bool> {
    // SAFETY: the caller guarantees `env` is a valid, live environment pointer
    // for the duration of this call (see the function-level safety contract).
    let env = unsafe { borrow_ffi(env) };
    env.0
        .get::<waterui_core::interaction::Disabled>()
        .map_or_else(
            || waterui::Computed::constant(false),
            |scope| scope.signal().clone(),
        )
        .into_ffi()
}

/// Gets the body of a view given the environment
///
/// # Safety
/// The caller must ensure that both `view` and `env` are valid pointers to properly
/// initialized instances and that they remain valid for the duration of this function call.
/// The `view` pointer will be consumed and should not be used after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_view_body(
    view: *mut WuiAnyView,
    env: *mut WuiEnv,
) -> *mut WuiAnyView {
    // SAFETY: the caller contract requires `env` to be a valid handle, alive and not
    // otherwise borrowed for this call; the exclusive borrow ends here.
    let env = unsafe { borrow_ffi_mut(env) };
    // SAFETY: the caller contract makes `view` an owning handle from the matching
    // FFI constructor; it is consumed here and not observed again.
    let view = unsafe { view.into_rust() };
    let body = view.body(env);
    AnyView::new(body).into_ffi()
}

/// Gets the id of a view as a 128-bit value for O(1) comparison.
///
/// Returns the view's `TypeId` (guaranteed unique within a single binary).
///
/// # Safety
/// The caller must ensure that `view` is a valid pointer to a properly
/// initialized `WuiAnyView` instance and that it remains valid for the
/// duration of this function call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_view_id(view: *const WuiAnyView) -> WuiTypeId {
    // SAFETY: the caller contract requires `view` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let view = unsafe { borrow_ffi(view) };
    WuiTypeId::from_runtime(view.type_id(), view.name())
}

/// Gets the stretch axis of a view.
///
/// Returns the `StretchAxis` that indicates how this view stretches to fill
/// available space. For native views, this returns the layout behavior defined
/// by the `NativeView` trait. For non-native views, this will panic.
///
/// # Safety
/// The caller must ensure that `view` is a valid pointer to a properly
/// initialized `WuiAnyView` instance and that it remains valid for the
/// duration of this function call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_view_stretch_axis(
    view: *const WuiAnyView,
) -> crate::components::layout::WuiStretchAxis {
    // SAFETY: the caller contract requires `view` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let view = unsafe { borrow_ffi(view) };
    view.stretch_axis().into()
}

// ============================================================================
// WuiStr - UTF-8 string for FFI
// ============================================================================

/// UTF-8 string represented as a byte array.
#[repr(C)]
#[derive(Debug, Default)]
pub struct WuiStr(WuiArray<u8>);

impl IntoFFI for Str {
    type FFI = WuiStr;
    fn into_ffi(self) -> Self::FFI {
        WuiStr(WuiArray::new(self))
    }
}

impl IntoFFI for &'static str {
    type FFI = WuiStr;
    fn into_ffi(self) -> Self::FFI {
        WuiStr(WuiArray::new(Str::from_static(self)))
    }
}

/// An optional count crosses as itself, with `0` meaning "none".
///
/// This is the convention `WuiTextField::line_limit` established: the zero a
/// `NonZeroUsize` cannot hold is exactly the wire value left over to mean
/// "no limit".
impl IntoFFI for Option<core::num::NonZeroUsize> {
    type FFI = usize;
    fn into_ffi(self) -> Self::FFI {
        self.map_or(0, core::num::NonZeroUsize::get)
    }
}

impl WuiStr {
    /// Returns the string as a `&str` without consuming the `WuiStr`.
    ///
    /// # Safety
    /// The caller must ensure the underlying bytes are valid UTF-8.
    #[must_use]
    pub unsafe fn as_str(&self) -> &str {
        // SAFETY: a `WuiStr` is only ever built from a Rust `Str`, which is UTF-8 by
        // construction, so its bytes are always valid UTF-8.
        unsafe { core::str::from_utf8_unchecked(self.0.as_slice()) }
    }
}

/// Moves an owned string into a Rust allocation for nullable FFI payloads.
///
/// The returned pointer must be consumed exactly once by the API receiving it.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub extern "C" fn waterui_str_box(value: WuiStr) -> *mut WuiStr {
    Box::into_raw(Box::new(value))
}

impl IntoRust for WuiStr {
    type Rust = Str;
    unsafe fn into_rust(self) -> Self::Rust {
        let bytes = self.0.as_slice().to_vec();
        self.0.consume();
        // Safety: We assume the input bytes are valid UTF-8
        unsafe { Str::from_utf8_unchecked(bytes) }
    }
}

/// Generic FFI payload for `Metadata<T>` views: the wrapped content plus the
/// attached metadata value.
#[repr(C)]
#[derive(Debug)]
pub struct WuiMetadata<T> {
    /// The view content wrapped by this metadata node.
    pub content: *mut WuiAnyView,
    /// The metadata value attached to `content`.
    pub value: T,
}

impl<T: IntoFFI + MetadataKey> IntoFFI for Metadata<T> {
    type FFI = WuiMetadata<T::FFI>;
    fn into_ffi(self) -> Self::FFI {
        WuiMetadata {
            content: self.content.into_ffi(),
            value: self.value.into_ffi(),
        }
    }
}

// ========== Metadata<Environment> FFI ==========
// Used by WithEnv to pass a new environment to child views

/// Type alias for `Metadata<Environment>` FFI struct
/// Layout: { content: *mut `WuiAnyView`, value: *mut `WuiEnv` }
pub type WuiMetadataEnv = WuiMetadata<*mut WuiEnv>;

// Generate waterui_metadata_env_id() and waterui_force_as_metadata_env()
ffi_metadata!(waterui::Environment, WuiMetadataEnv, env);

// ========== Navigation transition metadata FFI ==========

use crate::id::WuiId;
use waterui_navigation::{NavigationTransitionDestination, NavigationTransitionSource};

impl IntoFFI for NavigationTransitionSource {
    type FFI = WuiId;

    fn into_ffi(self) -> Self::FFI {
        self.id().into_ffi()
    }
}

impl IntoFFI for NavigationTransitionDestination {
    type FFI = WuiId;

    fn into_ffi(self) -> Self::FFI {
        self.id().into_ffi()
    }
}

/// Source geometry metadata for native navigation transitions.
pub type WuiMetadataNavigationTransitionSource = WuiMetadata<WuiId>;

/// Destination geometry metadata for native navigation transitions.
pub type WuiMetadataNavigationTransitionDestination = WuiMetadata<WuiId>;

ffi_metadata!(
    NavigationTransitionSource,
    WuiMetadataNavigationTransitionSource,
    navigation_transition_source
);
ffi_metadata!(
    NavigationTransitionDestination,
    WuiMetadataNavigationTransitionDestination,
    navigation_transition_destination
);

// ========== Metadata<Secure> FFI ==========
// Used to mark views as secure (prevent screenshots)

use waterui::metadata::secure::{HighDynamicRange, Secure, StandardDynamicRange};

/// C-compatible empty marker struct for Secure metadata.
/// This is needed because `()` (unit type) is not representable in C.
#[repr(C)]
#[derive(Debug)]
pub struct WuiSecureMarker {
    /// Placeholder field to ensure struct has valid size in C.
    /// The actual value is meaningless - Secure is just a marker type.
    _marker: u8,
}

impl IntoFFI for Secure {
    type FFI = WuiSecureMarker;
    fn into_ffi(self) -> Self::FFI {
        WuiSecureMarker { _marker: 0 }
    }
}

/// Type alias for `Metadata<Secure>` FFI struct
/// Layout: { content: *mut `WuiAnyView`, value: `WuiSecureMarker` }
pub type WuiMetadataSecure = WuiMetadata<WuiSecureMarker>;

// Generate waterui_metadata_secure_id() and waterui_force_as_metadata_secure()
ffi_metadata!(Secure, WuiMetadataSecure, secure);

// ========== Metadata<StandardDynamicRange>/Metadata<HighDynamicRange> FFI ==========
// Used to toggle HDR color handling for a subtree.

/// C-compatible empty marker struct for dynamic range metadata.
#[repr(C)]
#[derive(Debug)]
pub struct WuiDynamicRangeMarker {
    /// Placeholder field so the struct has a valid size in C; the value is
    /// meaningless.
    _marker: u8,
}

impl IntoFFI for StandardDynamicRange {
    type FFI = WuiDynamicRangeMarker;
    fn into_ffi(self) -> Self::FFI {
        WuiDynamicRangeMarker { _marker: 0 }
    }
}

impl IntoFFI for HighDynamicRange {
    type FFI = WuiDynamicRangeMarker;
    fn into_ffi(self) -> Self::FFI {
        WuiDynamicRangeMarker { _marker: 0 }
    }
}

/// Type alias for `Metadata<StandardDynamicRange>` FFI struct.
pub type WuiMetadataStandardDynamicRange = WuiMetadata<WuiDynamicRangeMarker>;

/// Type alias for `Metadata<HighDynamicRange>` FFI struct.
pub type WuiMetadataHighDynamicRange = WuiMetadata<WuiDynamicRangeMarker>;

// Generate waterui_metadata_standard_dynamic_range_id()
// and waterui_force_as_metadata_standard_dynamic_range().
ffi_metadata!(
    StandardDynamicRange,
    WuiMetadataStandardDynamicRange,
    standard_dynamic_range
);

// Generate waterui_metadata_high_dynamic_range_id()
// and waterui_force_as_metadata_high_dynamic_range().
ffi_metadata!(
    HighDynamicRange,
    WuiMetadataHighDynamicRange,
    high_dynamic_range
);

// ========== Metadata<GestureObserver> FFI ==========
// Used to attach gesture recognizers to views

use crate::gesture::WuiGestureObserver;
use waterui::gesture::GestureObserver;

/// Type alias for `Metadata<GestureObserver>` FFI struct
pub type WuiMetadataGesture = WuiMetadata<WuiGestureObserver>;

// Generate waterui_metadata_gesture_id() and waterui_force_as_metadata_gesture()
ffi_metadata!(GestureObserver, WuiMetadataGesture, gesture);

// ========== Metadata<OnEvent> FFI ==========
// Used to attach lifecycle event handlers (appear/disappear) - one-time handlers

use crate::event::{WuiLifecycleHook, WuiOnEvent};
use waterui_core::event::{LifeCycleHook, OnEvent};

/// Type alias for `Metadata<LifeCycleHook>` FFI struct.
pub type WuiMetadataLifecycleHook = WuiMetadata<WuiLifecycleHook>;

// Generate waterui_metadata_lifecycle_hook_id() and waterui_force_as_metadata_lifecycle_hook()
ffi_metadata!(LifeCycleHook, WuiMetadataLifecycleHook, lifecycle_hook);

// Used to attach interaction event handlers (hover enter/exit) - repeatable handlers

/// Type alias for `Metadata<OnEvent>` FFI struct
pub type WuiMetadataOnEvent = WuiMetadata<WuiOnEvent>;

// Generate waterui_metadata_on_event_id() and waterui_force_as_metadata_on_event()
ffi_metadata!(OnEvent, WuiMetadataOnEvent, on_event);

// ========== Metadata<Cursor> FFI ==========
// Used to set cursor style when hovering over views

use crate::cursor::WuiCursor;
use waterui::cursor::Cursor;

/// Type alias for `Metadata<Cursor>` FFI struct
pub type WuiMetadataCursor = WuiMetadata<WuiCursor>;

// Generate waterui_metadata_cursor_id() and waterui_force_as_metadata_cursor()
ffi_metadata!(Cursor, WuiMetadataCursor, cursor);

// ========== IgnorableMetadata<AccessibilityIdentifier> FFI ==========
// A stable automation identifier: Apple maps it to `accessibilityIdentifier`,
// Android exposes it as the node's view-id resource name for UiAutomator.

use nami::{Computed, SignalExt as _};
use waterui::accessibility::{
    AccessibilityChecked, AccessibilityChildren, AccessibilityHidden, AccessibilityIdentifier,
    AccessibilityLabel, AccessibilityRole, AccessibilityState, AccessibilityStateSignal,
};

/// FFI-safe representation of `IgnorableMetadata<AccessibilityIdentifier>`
#[repr(C)]
#[derive(Debug)]
pub struct WuiIgnorableMetadataAccessibilityIdentifier {
    /// The view content wrapped by this metadata
    pub content: *mut WuiAnyView,
    /// The stable automation identifier
    pub identifier: WuiStr,
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityIdentifier> {
    type FFI = WuiIgnorableMetadataAccessibilityIdentifier;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityIdentifier {
            content: self.content.into_ffi(),
            identifier: self.value.into_str().into_ffi(),
        }
    }
}

// Generate waterui_ignorable_metadata_accessibility_identifier_id() and
// waterui_force_as_ignorable_metadata_accessibility_identifier()
ffi_ignorable_metadata!(
    AccessibilityIdentifier,
    WuiIgnorableMetadataAccessibilityIdentifier,
    accessibility_identifier
);

/// Reactive accessibility label metadata.
#[repr(C)]
#[derive(Debug)]
pub struct WuiIgnorableMetadataAccessibilityLabel {
    /// Wrapped view content.
    pub content: *mut WuiAnyView,
    /// Resolved semantic label.
    pub label: *mut WuiComputed<StyledStr>,
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityLabel> {
    type FFI = WuiIgnorableMetadataAccessibilityLabel;

    fn into_ffi(self) -> Self::FFI {
        let label = self.value.signal().clone().map(StyledStr::from).computed();
        WuiIgnorableMetadataAccessibilityLabel {
            content: self.content.into_ffi(),
            label: label.into_ffi(),
        }
    }
}

ffi_ignorable_metadata!(
    AccessibilityLabel,
    WuiIgnorableMetadataAccessibilityLabel,
    accessibility_label
);

fn accessibility_role_code(role: &AccessibilityRole) -> i32 {
    match role {
        AccessibilityRole::Button => 0,
        AccessibilityRole::Link => 1,
        AccessibilityRole::Image => 2,
        AccessibilityRole::Text => 3,
        AccessibilityRole::Header => 4,
        AccessibilityRole::Footer => 5,
        AccessibilityRole::Navigation => 6,
        AccessibilityRole::Main => 7,
        AccessibilityRole::Search => 8,
        AccessibilityRole::Article => 9,
        AccessibilityRole::Section => 10,
        AccessibilityRole::List => 11,
        AccessibilityRole::ListItem => 12,
        AccessibilityRole::Checkbox => 13,
        AccessibilityRole::RadioButton => 14,
        AccessibilityRole::Switch => 15,
        AccessibilityRole::Slider => 16,
        AccessibilityRole::ProgressBar => 17,
        AccessibilityRole::Tab => 18,
        AccessibilityRole::TabList => 19,
        AccessibilityRole::TabPanel => 20,
        AccessibilityRole::Menu => 21,
        AccessibilityRole::MenuItem => 22,
        AccessibilityRole::MenuBar => 23,
        AccessibilityRole::MenuItemCheckbox => 24,
        AccessibilityRole::MenuItemRadio => 25,
        AccessibilityRole::Combobox => 26,
        AccessibilityRole::Option => 27,
        AccessibilityRole::Group => 28,
        _ => panic!("unsupported accessibility role in native FFI"),
    }
}

/// Accessibility metadata containing a static integer value.
#[repr(C)]
#[derive(Debug)]
pub struct WuiIgnorableMetadataAccessibilityValue {
    /// Wrapped view content.
    pub content: *mut WuiAnyView,
    /// Backend-independent semantic value.
    pub value: i32,
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityRole> {
    type FFI = WuiIgnorableMetadataAccessibilityValue;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityValue {
            content: self.content.into_ffi(),
            value: accessibility_role_code(&self.value),
        }
    }
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityHidden> {
    type FFI = WuiIgnorableMetadataAccessibilityValue;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityValue {
            content: self.content.into_ffi(),
            value: i32::from(self.value.is_hidden()),
        }
    }
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityChildren> {
    type FFI = WuiIgnorableMetadataAccessibilityValue;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityValue {
            content: self.content.into_ffi(),
            value: i32::from(self.value.excludes_descendants()),
        }
    }
}

ffi_ignorable_metadata!(
    AccessibilityRole,
    WuiIgnorableMetadataAccessibilityValue,
    accessibility_role
);
ffi_ignorable_metadata!(
    AccessibilityHidden,
    WuiIgnorableMetadataAccessibilityValue,
    accessibility_hidden
);
ffi_ignorable_metadata!(
    AccessibilityChildren,
    WuiIgnorableMetadataAccessibilityValue,
    accessibility_children
);

/// Reactive accessibility state split into primitive signals for native APIs.
#[repr(C)]
#[derive(Debug)]
pub struct WuiAccessibilityState {
    /// Whether the semantic node is disabled.
    pub disabled: *mut WuiComputed<bool>,
    /// Whether the semantic node is selected.
    pub selected: *mut WuiComputed<bool>,
    /// -1 is absent, 0 false, 1 true, and 2 mixed.
    pub checked: *mut WuiComputed<i32>,
    /// -1 is absent, 0 collapsed, and 1 expanded.
    pub expanded: *mut WuiComputed<i32>,
    /// Whether the semantic node is busy.
    pub busy: *mut WuiComputed<bool>,
    /// Whether the semantic node is hidden.
    pub hidden: *mut WuiComputed<bool>,
}

fn accessibility_state_ffi(state: &Computed<AccessibilityState>) -> WuiAccessibilityState {
    let checked = state.map(|state| match state.checked_state() {
        None => -1,
        Some(AccessibilityChecked::False) => 0,
        Some(AccessibilityChecked::True) => 1,
        Some(AccessibilityChecked::Mixed) => 2,
    });
    let expanded = state.map(|state| match state.expanded_state() {
        None => -1,
        Some(false) => 0,
        Some(true) => 1,
    });
    WuiAccessibilityState {
        disabled: state.map(|state| state.is_disabled()).computed().into_ffi(),
        selected: state.map(|state| state.is_selected()).computed().into_ffi(),
        checked: checked.computed().into_ffi(),
        expanded: expanded.computed().into_ffi(),
        busy: state.map(|state| state.is_busy()).computed().into_ffi(),
        hidden: state.map(|state| state.is_hidden()).computed().into_ffi(),
    }
}

/// Accessibility state metadata wrapper.
#[repr(C)]
#[derive(Debug)]
pub struct WuiIgnorableMetadataAccessibilityState {
    /// Wrapped view content.
    pub content: *mut WuiAnyView,
    /// Reactive semantic state.
    pub state: WuiAccessibilityState,
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityState> {
    type FFI = WuiIgnorableMetadataAccessibilityState;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityState {
            content: self.content.into_ffi(),
            state: accessibility_state_ffi(&Computed::constant(self.value)),
        }
    }
}

impl IntoFFI for waterui_core::IgnorableMetadata<AccessibilityStateSignal> {
    type FFI = WuiIgnorableMetadataAccessibilityState;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataAccessibilityState {
            content: self.content.into_ffi(),
            state: accessibility_state_ffi(self.value.state()),
        }
    }
}

ffi_ignorable_metadata!(
    AccessibilityState,
    WuiIgnorableMetadataAccessibilityState,
    accessibility_state
);
ffi_ignorable_metadata!(
    AccessibilityStateSignal,
    WuiIgnorableMetadataAccessibilityState,
    accessibility_state_signal
);

// ========== Common imports for metadata FFI ==========
use crate::color::WuiColor;
use crate::reactive::WuiComputed;

// ========== WuiMaterial FFI ==========
// Used for material blur effects (window backgrounds, etc.)

use waterui::background::Material;

/// FFI-safe representation of a material blur style.
///
/// Maps to `SwiftUI`'s Material types on Apple platforms.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub enum WuiMaterial {
    /// Ultra-thin blur, most transparent.
    UltraThin = 0,
    /// Thin blur.
    Thin = 1,
    /// Regular blur (default).
    Regular = 2,
    /// Thick blur.
    Thick = 3,
    /// Ultra-thick blur, most opaque.
    UltraThick = 4,
}

impl IntoFFI for Material {
    type FFI = WuiMaterial;
    fn into_ffi(self) -> Self::FFI {
        match self {
            Self::UltraThin => WuiMaterial::UltraThin,
            Self::Thin => WuiMaterial::Thin,
            Self::Regular => WuiMaterial::Regular,
            Self::Thick => WuiMaterial::Thick,
            Self::UltraThick => WuiMaterial::UltraThick,
        }
    }
}

// ========== Metadata<Shadow> FFI ==========
// Used to apply shadow effects to views

use waterui::style::Shadow;

/// FFI-safe representation of a shadow.
#[repr(C)]
#[derive(Debug)]
pub struct WuiShadow {
    /// Shadow color (as opaque pointer - needs environment to resolve).
    pub color: *mut WuiColor,
    /// Horizontal offset.
    pub offset_x: f32,
    /// Vertical offset.
    pub offset_y: f32,
    /// Blur radius.
    pub radius: f32,
}

impl IntoFFI for Shadow {
    type FFI = WuiShadow;
    fn into_ffi(self) -> Self::FFI {
        WuiShadow {
            color: self.color.into_ffi(),
            offset_x: self.offset.x,
            offset_y: self.offset.y,
            radius: self.radius,
        }
    }
}

/// Type alias for `Metadata<Shadow>` FFI struct
pub type WuiMetadataShadow = WuiMetadata<WuiShadow>;

// Generate waterui_metadata_shadow_id() and waterui_force_as_metadata_shadow()
ffi_metadata!(Shadow, WuiMetadataShadow, shadow);

// ========== Metadata<Border> FFI ==========
// Used to apply border effects to views

use waterui::border::Border;

/// FFI-safe representation of a border.
#[repr(C)]
#[derive(Debug)]
pub struct WuiBorder {
    /// Border color (as opaque pointer - needs environment to resolve).
    pub color: *mut WuiColor,
    /// Border width in points.
    pub width: f32,
    /// Corner radius in points (0 = square corners).
    pub corner_radius: f32,
    /// Which edges to draw the border on.
    pub edges: WuiEdgeSet,
}

impl IntoFFI for Border {
    type FFI = WuiBorder;
    fn into_ffi(self) -> Self::FFI {
        WuiBorder {
            color: self.color.into_ffi(),
            width: self.width,
            corner_radius: self.corner_radius,
            edges: self.edges.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Border>` FFI struct
pub type WuiMetadataBorder = WuiMetadata<WuiBorder>;

// Generate waterui_metadata_border_id() and waterui_force_as_metadata_border()
ffi_metadata!(Border, WuiMetadataBorder, border);

use waterui::style::{Anchor, Offset, Rotation, Scale};
// ========== Metadata<Scale> FFI ==========
// Used to apply scale transforms to views

/// FFI-safe representation of an anchor point.
/// Normalized coordinates: (0.0, 0.0) = top-left, (0.5, 0.5) = center, (1.0, 1.0) = bottom-right.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct WuiAnchor {
    /// X coordinate (0.0 = left, 0.5 = center, 1.0 = right)
    pub x: f32,
    /// Y coordinate (0.0 = top, 0.5 = center, 1.0 = bottom)
    pub y: f32,
}

impl IntoFFI for Anchor {
    type FFI = WuiAnchor;
    fn into_ffi(self) -> Self::FFI {
        WuiAnchor {
            x: self.x,
            y: self.y,
        }
    }
}

/// FFI-safe representation of a scale transform.
/// All values are reactive (Computed) and can be animated.
#[repr(C)]
#[derive(Debug)]
pub struct WuiScale {
    /// Scale factor along X axis (1.0 = no scale)
    pub x: *mut WuiComputed<f32>,
    /// Scale factor along Y axis (1.0 = no scale)
    pub y: *mut WuiComputed<f32>,
    /// Anchor point for the scale transform
    pub anchor: WuiAnchor,
}

impl IntoFFI for Scale {
    type FFI = WuiScale;
    fn into_ffi(self) -> Self::FFI {
        WuiScale {
            x: self.x.into_ffi(),
            y: self.y.into_ffi(),
            anchor: self.anchor.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Scale>` FFI struct
pub type WuiMetadataScale = WuiMetadata<WuiScale>;

// Generate waterui_metadata_scale_id() and waterui_force_as_metadata_scale()
ffi_metadata!(Scale, WuiMetadataScale, scale);

// ========== Metadata<Rotation> FFI ==========
// Used to apply rotation transforms to views

/// FFI-safe representation of a rotation transform.
/// All values are reactive (Computed) and can be animated.
#[repr(C)]
#[derive(Debug)]
pub struct WuiRotation {
    /// Rotation angle in degrees (positive = clockwise)
    pub angle: *mut WuiComputed<f32>,
    /// Anchor point for the rotation transform
    pub anchor: WuiAnchor,
}

impl IntoFFI for Rotation {
    type FFI = WuiRotation;
    fn into_ffi(self) -> Self::FFI {
        WuiRotation {
            angle: self.angle.into_ffi(),
            anchor: self.anchor.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Rotation>` FFI struct
pub type WuiMetadataRotation = WuiMetadata<WuiRotation>;

// Generate waterui_metadata_rotation_id() and waterui_force_as_metadata_rotation()
ffi_metadata!(Rotation, WuiMetadataRotation, rotation);

// ========== Metadata<Offset> FFI ==========
// Used to apply offset (translation) transforms to views

/// FFI-safe representation of an offset transform.
/// All values are reactive (Computed) and can be animated.
#[repr(C)]
#[derive(Debug)]
pub struct WuiOffset {
    /// Offset along X axis in points
    pub x: *mut WuiComputed<f32>,
    /// Offset along Y axis in points
    pub y: *mut WuiComputed<f32>,
}

impl IntoFFI for Offset {
    type FFI = WuiOffset;
    fn into_ffi(self) -> Self::FFI {
        WuiOffset {
            x: self.x.into_ffi(),
            y: self.y.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Offset>` FFI struct
pub type WuiMetadataOffset = WuiMetadata<WuiOffset>;

// Generate waterui_metadata_offset_id() and waterui_force_as_metadata_offset()
ffi_metadata!(Offset, WuiMetadataOffset, offset);

use waterui::filter::Opacity;

// ========== Metadata<Opacity> FFI ==========
// Used to apply compositor opacity metadata to views

/// FFI-safe representation of compositor opacity metadata.
/// All values are reactive (`Computed`) and can be animated.
#[repr(C)]
#[derive(Debug)]
pub struct WuiOpacity {
    /// Opacity value (0 = transparent, 1 = opaque).
    pub value: *mut WuiComputed<f32>,
}

impl IntoFFI for Opacity {
    type FFI = WuiOpacity;
    fn into_ffi(self) -> Self::FFI {
        WuiOpacity {
            value: self.value.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Opacity>` FFI struct
pub type WuiMetadataOpacity = WuiMetadata<WuiOpacity>;

// Generate waterui_metadata_opacity_id() and waterui_force_as_metadata_opacity()
ffi_metadata!(Opacity, WuiMetadataOpacity, opacity);

// ========== Metadata<Focused> FFI ==========
// Used to track focus state for views

use crate::reactive::WuiBinding;
use waterui::component::focus::Focused;

/// FFI-safe representation of focused state.
#[repr(C)]
#[derive(Debug)]
pub struct WuiFocused {
    /// Binding to the focus state (true = focused).
    pub binding: *mut WuiBinding<bool>,
}

impl IntoFFI for Focused {
    type FFI = WuiFocused;
    fn into_ffi(self) -> Self::FFI {
        WuiFocused {
            binding: self.0.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Focused>` FFI struct
pub type WuiMetadataFocused = WuiMetadata<WuiFocused>;

// Generate waterui_metadata_focused_id() and waterui_force_as_metadata_focused()
ffi_metadata!(Focused, WuiMetadataFocused, focused);

// ========== Metadata<IgnoreSafeArea> FFI ==========
// Used to extend views beyond safe area insets

use waterui_layout::IgnoreSafeArea;

/// FFI-safe representation of edge set for safe area.
#[repr(C)]
#[derive(Debug)]
pub struct WuiEdgeSet {
    /// Ignore safe area on top edge.
    pub top: bool,
    /// Ignore safe area on leading edge.
    pub leading: bool,
    /// Ignore safe area on bottom edge.
    pub bottom: bool,
    /// Ignore safe area on trailing edge.
    pub trailing: bool,
}

impl IntoFFI for waterui_layout::EdgeSet {
    type FFI = WuiEdgeSet;
    fn into_ffi(self) -> Self::FFI {
        WuiEdgeSet {
            top: self.top,
            leading: self.leading,
            bottom: self.bottom,
            trailing: self.trailing,
        }
    }
}

/// FFI-safe representation of `IgnoreSafeArea`.
#[repr(C)]
#[derive(Debug)]
pub struct WuiIgnoreSafeArea {
    /// Which edges should ignore safe area.
    pub edges: WuiEdgeSet,
}

impl IntoFFI for IgnoreSafeArea {
    type FFI = WuiIgnoreSafeArea;
    fn into_ffi(self) -> Self::FFI {
        WuiIgnoreSafeArea {
            edges: self.edges.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<IgnoreSafeArea>` FFI struct
pub type WuiMetadataIgnoreSafeArea = WuiMetadata<WuiIgnoreSafeArea>;

// Generate waterui_metadata_ignore_safe_area_id() and waterui_force_as_metadata_ignore_safe_area()
ffi_metadata!(IgnoreSafeArea, WuiMetadataIgnoreSafeArea, ignore_safe_area);

// ========== Metadata<Retain> FFI ==========
// Used to keep values alive for the lifetime of a view (e.g., watcher guards)

use waterui_core::Retain;

/// FFI-safe representation of Retain metadata.
/// The actual retained value is opaque - renderers just need to keep it alive.
#[repr(C)]
#[derive(Debug)]
pub struct WuiRetain {
    /// Opaque pointer to the retained value (`Box<dyn Any>`).
    /// This must be kept alive and dropped when the view is disposed.
    _opaque: *mut (),
}

#[cfg(feature = "android-jni")]
impl WuiRetain {
    pub(crate) fn opaque_ptr(&self) -> *mut () {
        self._opaque
    }

    pub(crate) fn from_ptr(ptr: *mut ()) -> Self {
        Self { _opaque: ptr }
    }
}

impl IntoFFI for Retain {
    type FFI = WuiRetain;
    fn into_ffi(self) -> Self::FFI {
        // Leak the Retain to keep the inner value alive
        // The native side will call waterui_drop_retain to clean up
        let boxed = Box::new(self);
        WuiRetain {
            _opaque: Box::into_raw(boxed).cast::<()>(),
        }
    }
}

/// Type alias for `Metadata<Retain>` FFI struct
pub type WuiMetadataRetain = WuiMetadata<WuiRetain>;

// Generate waterui_metadata_retain_id() and waterui_force_as_metadata_retain()
ffi_metadata!(Retain, WuiMetadataRetain, retain);

/// Drops the retained value.
///
/// # Safety
/// The caller must ensure that `retain` is a valid pointer returned from
/// `waterui_force_as_metadata_retain` and has not been dropped before.
#[unsafe(no_mangle)]
#[expect(
    clippy::used_underscore_binding,
    reason = "the `_opaque` field name is part of the checked-in C ABI; the underscore signals native code must treat it as opaque"
)]
pub unsafe extern "C" fn waterui_drop_retain(retain: WuiRetain) {
    // SAFETY: the caller contract makes `_opaque` the boxed `Retain` handed out by the
    // matching constructor, released exactly once here.
    unsafe {
        drop(Box::from_raw(retain._opaque.cast::<Retain>()));
    }
}

// ========== Metadata<ClipShape> FFI ==========
// Used to clip views to shapes

use waterui::shape::{ClipShape, PathCommand};

/// FFI-safe representation of a path command.
/// All coordinates are normalized (0.0-1.0) and scale with view bounds.
#[repr(C)]
#[derive(Debug)]
pub enum WuiPathCommand {
    /// Move to a position without drawing.
    MoveTo {
        /// Target X coordinate.
        x: f32,
        /// Target Y coordinate.
        y: f32,
    },
    /// Draw a straight line to a position.
    LineTo {
        /// Target X coordinate.
        x: f32,
        /// Target Y coordinate.
        y: f32,
    },
    /// Draw a quadratic bezier curve.
    QuadTo {
        /// Control point X coordinate.
        cx: f32,
        /// Control point Y coordinate.
        cy: f32,
        /// End point X coordinate.
        x: f32,
        /// End point Y coordinate.
        y: f32,
    },
    /// Draw a cubic bezier curve.
    CubicTo {
        /// First control point X coordinate.
        c1x: f32,
        /// First control point Y coordinate.
        c1y: f32,
        /// Second control point X coordinate.
        c2x: f32,
        /// Second control point Y coordinate.
        c2y: f32,
        /// End point X coordinate.
        x: f32,
        /// End point Y coordinate.
        y: f32,
    },
    /// Draw an arc.
    Arc {
        /// Center X coordinate.
        cx: f32,
        /// Center Y coordinate.
        cy: f32,
        /// Radius along the X axis.
        rx: f32,
        /// Radius along the Y axis.
        ry: f32,
        /// Start angle in radians.
        start: f32,
        /// Sweep angle in radians.
        sweep: f32,
    },
    /// Close the current subpath.
    Close,
}

impl IntoFFI for PathCommand {
    type FFI = WuiPathCommand;
    fn into_ffi(self) -> Self::FFI {
        match self {
            Self::MoveTo { x, y } => WuiPathCommand::MoveTo { x, y },
            Self::LineTo { x, y } => WuiPathCommand::LineTo { x, y },
            Self::QuadTo { cx, cy, x, y } => WuiPathCommand::QuadTo { cx, cy, x, y },
            Self::CubicTo {
                c1x,
                c1y,
                c2x,
                c2y,
                x,
                y,
            } => WuiPathCommand::CubicTo {
                c1x,
                c1y,
                c2x,
                c2y,
                x,
                y,
            },
            Self::Arc {
                cx,
                cy,
                rx,
                ry,
                start,
                sweep,
            } => WuiPathCommand::Arc {
                cx,
                cy,
                rx,
                ry,
                start,
                sweep,
            },
            Self::Close => WuiPathCommand::Close,
        }
    }
}

/// FFI-safe representation of a clip shape.
/// Contains the structured kind plus the path commands defining the mask.
#[repr(C)]
#[derive(Debug)]
pub struct WuiClipShape {
    /// Shape kind for backend-side rendering. Prefer this over `commands`:
    /// the commands are in unit space, where a corner radius stretches with
    /// the clipped rect's aspect ratio.
    pub kind: crate::shape::WuiShapeKind,
    /// Array of path commands defining the shape.
    pub commands: WuiArray<WuiPathCommand>,
}

impl IntoFFI for ClipShape {
    type FFI = WuiClipShape;
    fn into_ffi(self) -> Self::FFI {
        let commands: alloc::vec::Vec<WuiPathCommand> =
            self.commands().iter().map(|cmd| cmd.into_ffi()).collect();
        WuiClipShape {
            kind: self.kind().into_ffi(),
            commands: WuiArray::new(commands),
        }
    }
}

/// Type alias for `Metadata<ClipShape>` FFI struct
pub type WuiMetadataClipShape = WuiMetadata<WuiClipShape>;

// Generate waterui_metadata_clip_shape_id() and waterui_force_as_metadata_clip_shape()
ffi_metadata!(ClipShape, WuiMetadataClipShape, clip_shape);

// Filled shapes are represented by `ResolvedShape` raw views via ffi/src/shape.rs.

// ========== Metadata<ContextMenu> FFI ==========
// Used to attach context menus to views

use crate::components::icon::WuiSystemIcon;
use crate::components::text::WuiText;
use crate::views::{WuiAnyViews, signal_vec_views};
use waterui::metadata::context_menu::ResolvedContextMenu;
use waterui_controls::menu::{ResolvedMenu, ResolvedMenuItem, Shortcut, ShortcutModifiers};
use waterui_core::handler::SharedAction;
use waterui_icon::SystemIcon;
use waterui_text::styled::StyledStr;

opaque!(WuiSharedAction, SharedAction<()>, shared_action);

/// Call a shared action with the given environment.
///
/// # Safety
/// * `action` must be a valid pointer to a `WuiSharedAction`.
/// * `env` must be a valid pointer to a `WuiEnv`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_call_shared_action(
    action: *const WuiSharedAction,
    env: *const WuiEnv,
) {
    // SAFETY: the caller contract requires `action` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let action = unsafe { borrow_ffi(action) }.0.clone();
    // SAFETY: the caller contract requires `env` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let env = unsafe { borrow_ffi(env) }.0.clone();
    action.call(&env);
}

/// FFI-safe menu item tag.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WuiMenuItemTag {
    /// A leaf command.
    Command = 0,
    /// A divider separating adjacent items.
    Divider = 1,
    /// A nested menu.
    Menu = 2,
}

ffi_safe!(WuiMenuItemTag);

/// FFI-safe shortcut modifier flags.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WuiShortcutModifiers {
    /// Command modifier on Apple platforms.
    pub command: bool,
    /// Shift modifier.
    pub shift: bool,
    /// Option/alt modifier.
    pub option: bool,
    /// Control modifier.
    pub control: bool,
}

ffi_safe!(WuiShortcutModifiers);

impl IntoFFI for ShortcutModifiers {
    type FFI = WuiShortcutModifiers;

    fn into_ffi(self) -> Self::FFI {
        WuiShortcutModifiers {
            command: self.command(),
            shift: self.shift(),
            option: self.option(),
            control: self.control(),
        }
    }
}

/// FFI-safe keyboard shortcut payload.
#[repr(C)]
#[derive(Debug)]
pub struct WuiShortcut {
    /// The key equivalent.
    pub key: WuiStr,
    /// The shortcut modifiers.
    pub modifiers: WuiShortcutModifiers,
}

impl IntoFFI for Shortcut {
    type FFI = WuiShortcut;

    fn into_ffi(self) -> Self::FFI {
        WuiShortcut {
            key: self.key.into_ffi(),
            modifiers: self.modifiers.into_ffi(),
        }
    }
}

/// FFI-safe representation of a menu item.
#[repr(C)]
#[derive(Debug)]
pub struct WuiMenuItem {
    /// The menu node kind.
    pub tag: WuiMenuItemTag,
    /// The resolved label for commands and nested menus.
    pub label: *mut WuiText,
    /// Optional icon shown alongside the label.
    pub icon: *mut WuiSystemIcon,
    /// The action handler pointer for commands.
    pub action: *mut WuiSharedAction,
    /// Reactive disabled state for commands.
    pub disabled: *mut WuiComputed<bool>,
    /// Reactive selected/checkmark state for commands.
    pub selected: *mut WuiComputed<bool>,
    /// Optional keyboard shortcut metadata for commands.
    pub shortcut: *mut WuiShortcut,
    /// Nested menu items.
    pub items: *mut WuiAnyViews,
}

/// Takes the label value from an owned menu-item label allocation.
///
/// # Safety
///
/// `label` must be consumed exactly once.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_menu_item_take_label(label: *mut WuiText) -> WuiText {
    // SAFETY: the caller contract makes `label` an owning pointer from the matching
    // FFI constructor, so reclaiming the box frees it exactly once.
    unsafe { *Box::from_raw(label) }
}

/// Takes the icon value from an owned menu-item icon allocation.
///
/// # Safety
///
/// `icon` must be consumed exactly once.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_menu_item_take_icon(icon: *mut WuiSystemIcon) -> WuiSystemIcon {
    // SAFETY: the caller contract makes `icon` an owning pointer from the matching
    // FFI constructor, so reclaiming the box frees it exactly once.
    unsafe { *Box::from_raw(icon) }
}

/// Takes the shortcut value from an owned menu-item shortcut allocation.
///
/// # Safety
///
/// `shortcut` must be consumed exactly once.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_menu_item_take_shortcut(
    shortcut: *mut WuiShortcut,
) -> WuiShortcut {
    // SAFETY: the caller contract makes `shortcut` an owning pointer from the
    // matching FFI constructor, so reclaiming the box frees it exactly once.
    unsafe { *Box::from_raw(shortcut) }
}

#[inline]
fn menu_text(label: waterui_text::TextConfig) -> *mut WuiText {
    Box::into_raw(Box::new(label.into_ffi()))
}

#[inline]
fn optional_menu_icon(icon: Option<SystemIcon>) -> *mut WuiSystemIcon {
    icon.map_or_else(null_mut, |icon| Box::into_raw(Box::new(icon.into_ffi())))
}

#[inline]
fn optional_shortcut(shortcut: Option<Shortcut>) -> *mut WuiShortcut {
    shortcut.map_or_else(null_mut, |shortcut| {
        Box::into_raw(Box::new(shortcut.into_ffi()))
    })
}

/// Raw semantic menu item stored in the framework's identity-aware collection.
#[doc(hidden)]
#[derive(Debug)]
pub struct ResolvedMenuItemView(ResolvedMenuItem);

waterui_core::raw_view!(ResolvedMenuItemView);

impl IntoFFI for ResolvedMenuItemView {
    type FFI = WuiMenuItem;

    fn into_ffi(self) -> Self::FFI {
        match self.0 {
            ResolvedMenuItem::Command(command) => WuiMenuItem {
                tag: WuiMenuItemTag::Command,
                label: menu_text(command.label),
                icon: optional_menu_icon(command.icon),
                action: command.action.into_ffi(),
                disabled: command.disabled.into_ffi(),
                selected: command.selected.into_ffi(),
                shortcut: optional_shortcut(command.shortcut),
                items: null_mut(),
            },
            ResolvedMenuItem::Divider => WuiMenuItem {
                tag: WuiMenuItemTag::Divider,
                label: null_mut(),
                icon: null_mut(),
                action: null_mut(),
                disabled: null_mut(),
                selected: null_mut(),
                shortcut: null_mut(),
                items: null_mut(),
            },
            ResolvedMenuItem::Menu(menu) => WuiMenuItem {
                tag: WuiMenuItemTag::Menu,
                label: menu_text(menu.label),
                icon: optional_menu_icon(menu.icon),
                action: null_mut(),
                disabled: null_mut(),
                selected: null_mut(),
                shortcut: null_mut(),
                items: menu_items_views(menu.items),
            },
        }
    }
}

ffi_view!(ResolvedMenuItemView, WuiMenuItem, menu_item);

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum MenuItemIdentity {
    Semantic(usize),
    Divider(usize),
}

fn menu_item_identity(items: &[ResolvedMenuItem], index: usize) -> MenuItemIdentity {
    match &items[index] {
        ResolvedMenuItem::Command(command) => MenuItemIdentity::Semantic(command.semantic_id()),
        ResolvedMenuItem::Menu(menu) => MenuItemIdentity::Semantic(menu.semantic_id()),
        ResolvedMenuItem::Divider => MenuItemIdentity::Divider(
            items[..=index]
                .iter()
                .filter(|item| matches!(item, ResolvedMenuItem::Divider))
                .count(),
        ),
    }
}

pub(crate) fn menu_items_views(
    items: nami::Computed<alloc::vec::Vec<ResolvedMenuItem>>,
) -> *mut WuiAnyViews {
    signal_vec_views(items, menu_item_identity, |item| {
        AnyView::new(Native::new(ResolvedMenuItemView(item)))
    })
}

/// FFI-safe representation of a context menu.
#[repr(C)]
#[derive(Debug)]
pub struct WuiContextMenu {
    /// Identity-aware reactive menu items.
    pub items: *mut WuiAnyViews,
}

impl IntoFFI for ResolvedContextMenu {
    type FFI = WuiContextMenu;
    fn into_ffi(self) -> Self::FFI {
        WuiContextMenu {
            items: menu_items_views(self.items),
        }
    }
}

/// Type alias for `Metadata<ContextMenu>` FFI struct
pub type WuiMetadataContextMenu = WuiMetadata<WuiContextMenu>;

// Generate waterui_metadata_context_menu_id() and waterui_force_as_metadata_context_menu()
ffi_metadata!(ResolvedContextMenu, WuiMetadataContextMenu, context_menu);

// ========== Menu FFI ==========
// Menu component that displays a dropdown menu when tapped

/// FFI-safe representation of a Menu component.
#[repr(C)]
#[derive(Debug)]
pub struct WuiMenu {
    /// The label view displayed on the menu button.
    pub label: *mut WuiAnyView,
    /// Identity-aware reactive menu items.
    pub items: *mut WuiAnyViews,
    /// Semantic accessibility label for the menu trigger.
    pub accessibility_label: *mut WuiComputed<StyledStr>,
}

impl IntoFFI for ResolvedMenu {
    type FFI = WuiMenu;
    fn into_ffi(self) -> Self::FFI {
        WuiMenu {
            label: self.label.into_ffi(),
            items: menu_items_views(self.items),
            accessibility_label: self.accessibility_label.into_ffi(),
        }
    }
}

// Generate waterui_menu_id() and waterui_force_as_menu()
ffi_view!(ResolvedMenu, WuiMenu, menu);

// ========== Drag and Drop FFI ==========

// Used to make views draggable or drop destinations

use crate::drag_drop::{WuiDraggable, WuiDropDestination};
#[cfg(feature = "c-api")]
use waterui::drag_drop::{Draggable, DropDestination};

/// Type alias for `Metadata<Draggable>` FFI struct
pub type WuiMetadataDraggable = WuiMetadata<WuiDraggable>;

// Generate waterui_metadata_draggable_id() and waterui_force_as_metadata_draggable()
#[cfg(feature = "c-api")]
ffi_metadata!(Draggable, WuiMetadataDraggable, draggable);

/// Type alias for `Metadata<DropDestination>` FFI struct
pub type WuiMetadataDropDestination = WuiMetadata<WuiDropDestination>;

// Generate waterui_metadata_drop_destination_id() and waterui_force_as_metadata_drop_destination()
#[cfg(feature = "c-api")]
ffi_metadata!(
    DropDestination,
    WuiMetadataDropDestination,
    drop_destination
);

// ========== IgnorableMetadata<MaterialBackground> FFI ==========
// Used to apply native blur effects on supported platforms (Apple)

#[cfg(feature = "c-api")]
use waterui::background::MaterialBackground;

/// FFI-safe representation of `IgnorableMetadata<MaterialBackground>`
#[repr(C)]
#[derive(Debug)]
#[cfg(feature = "c-api")]
pub struct WuiIgnorableMetadataMaterialBackground {
    /// The view content wrapped by this metadata
    pub content: *mut WuiAnyView,
    /// The material type for the blur effect
    pub material: WuiMaterial,
}

#[cfg(feature = "c-api")]
impl IntoFFI for waterui_core::IgnorableMetadata<MaterialBackground> {
    type FFI = WuiIgnorableMetadataMaterialBackground;

    fn into_ffi(self) -> Self::FFI {
        WuiIgnorableMetadataMaterialBackground {
            content: self.content.into_ffi(),
            material: self.value.0.into_ffi(),
        }
    }
}

// Generate waterui_ignorable_metadata_material_background_id() and
// waterui_force_as_ignorable_metadata_material_background()
#[cfg(feature = "c-api")]
ffi_ignorable_metadata!(
    MaterialBackground,
    WuiIgnorableMetadataMaterialBackground,
    material_background
);

// ========== Metadata<Hittable> FFI ==========
// Controls whether a view responds to hit testing (touch/click events)

use waterui::interaction::Hittable;

/// FFI-safe representation of Hittable metadata.
#[repr(C)]
#[derive(Debug)]
pub struct WuiHittable {
    /// Whether hit testing is enabled (reactive).
    pub enabled: *mut WuiComputed<bool>,
}

impl IntoFFI for Hittable {
    type FFI = WuiHittable;
    fn into_ffi(self) -> Self::FFI {
        WuiHittable {
            enabled: self.enabled.into_ffi(),
        }
    }
}

/// Type alias for `Metadata<Hittable>` FFI struct
pub type WuiMetadataHittable = WuiMetadata<WuiHittable>;

// Generate waterui_metadata_hittable_id() and waterui_force_as_metadata_hittable()
ffi_metadata!(Hittable, WuiMetadataHittable, hittable);

#[cfg(all(test, feature = "c-api"))]
mod tests {
    use alloc::rc::Rc;
    use alloc::sync::Arc;
    use core::cell::Cell;
    use core::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use waterui_core::handler::SharedAction;

    #[test]
    fn shared_action_callback_executes() {
        let hits = Arc::new(AtomicUsize::new(0));
        let hits_for_action = Arc::clone(&hits);
        let action_ptr = SharedAction::new(move || {
            hits_for_action.fetch_add(1, Ordering::SeqCst);
        })
        .into_ffi();
        let env_ptr = waterui::Environment::new().into_ffi();

        // SAFETY: both pointers are the live handles this test created above.
        unsafe {
            waterui_call_shared_action(action_ptr, env_ptr);
        }

        assert_eq!(hits.load(Ordering::SeqCst), 1);
        // SAFETY: both handles are still live and are each released once here.
        unsafe {
            waterui_drop_shared_action(action_ptr);
            let _: waterui::Environment = IntoRust::into_rust(env_ptr);
        }
    }

    #[test]
    fn shared_action_survives_reentrant_native_drop_until_callback_returns() {
        let action_ptr = Rc::new(Cell::new(core::ptr::null_mut::<WuiSharedAction>()));
        let callback_finished = Rc::new(Cell::new(false));
        let action_ptr_for_callback = Rc::clone(&action_ptr);
        let callback_finished_for_callback = Rc::clone(&callback_finished);
        let action = SharedAction::new(move || {
            // SAFETY: the cell holds the action handle the test installed before
            // invoking this callback, and the callback runs once.
            unsafe { waterui_drop_shared_action(action_ptr_for_callback.get()) };
            callback_finished_for_callback.set(true);
        })
        .into_ffi();
        action_ptr.set(action);
        let env = WuiEnv(waterui::Environment::new());

        // SAFETY: `action` is the handle built just above and `env` a live local.
        unsafe { waterui_call_shared_action(action, &raw const env) };

        assert!(callback_finished.get());
    }
}