lingxia 0.11.1

LingXia - Cross-platform LxApp (lightweight application) framework for Android, iOS, macOS, HarmonyOS, and Windows
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
use lingxia_messaging::invoke_callback;
use lxapp::{
    CloseReason, CreatePageInstanceRequest, LxAppDelegate, LxAppUiEventType, OrientationConfig,
    PageInstanceEvent, PageInstanceId, PageOrientation, PageOwner, PageQueryInput, PageTarget,
    PresentationKind, SceneId,
};
#[cfg(all(target_os = "macos", feature = "browser-shell"))]
use std::sync::Arc;

/// Parses a color string (e.g., "#RRGGBB" or "transparent") into a u32 ARGB value.
fn parse_color_to_u32(color_str: &str, default_color: u32) -> u32 {
    if color_str.eq_ignore_ascii_case("transparent") {
        return 0x00000000;
    }

    if let Some(hex_part) = color_str.strip_prefix('#')
        && hex_part.len() == 6
        && let Ok(rgb) = u32::from_str_radix(hex_part, 16)
    {
        return 0xFF000000 | rgb; // Add full alpha
    }
    default_color
}

#[swift_bridge::bridge]
mod bridge {
    // LxApp basic information for Swift
    #[swift_bridge(swift_repr = "struct")]
    pub struct LxAppInfo {
        pub app_name: String,
        pub version: String,
        pub release_type: String,
        pub cache_dir: String,
        // Absolute path to the lxapp icon, or empty (host uses default mark).
        pub icon: String,
    }

    // NavigationBar state for Swift
    #[swift_bridge(swift_repr = "struct")]
    pub struct NavigationBarState {
        pub background_color: u32,
        pub text_style: String,
        pub title_text: String,
        pub show_navbar: bool,
        pub show_back_button: bool,
        pub show_home_button: bool,
    }

    // TabBar state for Swift (without items array)
    #[swift_bridge(swift_repr = "struct")]
    pub struct TabBar {
        pub color: u32,
        pub selected_color: u32,
        pub background_color: u32,
        pub border_style: u32,
        pub position: i32,
        pub dimension: i32,
        pub items_count: i32,
        pub is_visible: bool,
        /// Hidden by an explicit lx.hideTabBar() (not navigation-derived) —
        /// what desktop skins map to group collapse.
        pub is_api_hidden: bool,
        pub selected_index: i32,
        /// Which style fields the app DECLARED (bit0 color, bit1
        /// selectedColor, bit2 backgroundColor, bit3 borderStyle). The color
        /// fields above always carry effective values (mobile defaults);
        /// desktop skins use this mask to keep undeclared styles on the
        /// neutral theme instead of inheriting light mobile defaults.
        pub styled_mask: u32,
    }

    // TabBar item for Swift
    #[swift_bridge(swift_repr = "struct")]
    pub struct TabBarItem {
        pub page_path: String,
        pub text: String,
        pub icon_path: String,
        pub selected_icon_path: String,
        pub selected: bool,
        pub badge: String,
        pub has_red_dot: bool,
    }

    // Push notification trigger types
    pub enum PushTrigger {
        Background,
        Tap,
        Launch,
    }

    // lxapp-scoped UI event types.
    pub enum LxAppUiEventType {
        TabBarClick,
        CapsuleClick,
        NavigationClick,
        BackPress,
        PullDownRefresh,
    }

    // host-app scoped UI events.
    pub enum AppUiEventType {
        /// Panel icon clicked in the host app UI
        PanelIconClick,
        /// "Click to restart" callout clicked: apply the staged host-app update
        UpdateRestartClick,
        /// "Click to install" callout clicked: re-open the host-app update flow
        UpdateInstallClick,
        /// Tray icon left-clicked (delivered to `lx.tray.onClick`)
        TrayClick,
        /// Tray menu item clicked; `data` is the item index (delivered to the
        /// item's `onClick` registered by `lx.tray.setMenu`)
        TrayMenuClick,
    }

    // Current LxApp info from Rust stack
    #[swift_bridge(swift_repr = "struct")]
    pub struct CurrentLxApp {
        pub appid: String,
        pub path: String,
        pub session_id: u64,
    }

    #[swift_bridge(swift_repr = "struct")]
    pub struct CreatePageInstanceResult {
        pub ok: bool,
        pub page_instance_id: String,
        pub appid: String,
        pub resolved_path: String,
        pub query: String,
        pub error: String,
    }

    #[swift_bridge(swift_repr = "struct")]
    pub struct PageBindingResult {
        pub page_instance_id: String,
        pub webview_ptr: usize,
    }

    #[swift_bridge(swift_repr = "struct")]
    pub struct LingxiaInitResult {
        pub ok: bool,
        pub home_app_id: String,
        pub error: String,
    }

    extern "Rust" {
        #[swift_bridge(swift_name = "lingxiaInit")]
        fn lingxia_init(data_dir: &str, cache_dir: &str, locale: &str) -> LingxiaInitResult;

        #[swift_bridge(swift_name = "getDisplayLanguage")]
        fn get_display_language() -> String;

        #[swift_bridge(swift_name = "forwardHostLog")]
        fn forward_host_log(
            level: i32,
            category: &str,
            appid: &str,
            path: &str,
            message: &str,
        ) -> bool;

        #[swift_bridge(swift_name = "setLogLevel")]
        fn set_log_level(level: i32);

        #[swift_bridge(swift_name = "hostLogEnabled")]
        fn host_log_enabled(level: i32) -> bool;

        #[swift_bridge(swift_name = "onPageShow")]
        fn on_page_show(appid: &str, path: &str);

        #[swift_bridge(swift_name = "onLxappClosed")]
        fn on_lxapp_closed(appid: &str, session_id: u64) -> bool;

        #[swift_bridge(swift_name = "onDeviceOrientationChanged")]
        fn on_device_orientation_changed(appid: &str, session_id: u64, value: &str) -> bool;

        #[swift_bridge(swift_name = "getLxAppInfo")]
        fn get_lxapp_info(appid: &str) -> LxAppInfo;

        #[swift_bridge(swift_name = "getNavigationBarState")]
        fn get_navigation_bar_state(appid: &str, path: &str) -> NavigationBarState;

        #[swift_bridge(swift_name = "getPageOrientation")]
        fn get_page_orientation(appid: &str, path: &str) -> i32;

        #[swift_bridge(swift_name = "getTabBar")]
        fn get_tab_bar(appid: &str) -> Option<TabBar>;

        #[swift_bridge(swift_name = "getTabBarItem")]
        fn get_tab_bar_item(appid: &str, index: i32) -> Option<TabBarItem>;

        // lxapp-scoped event (appid must be a real lxapp id)
        #[swift_bridge(swift_name = "onLxappEvent")]
        fn on_lxapp_event(appid: &str, event_type: LxAppUiEventType, data: &str) -> bool;

        // Host-app scoped UI event (no lxapp context; e.g. panel icon click)
        #[swift_bridge(swift_name = "onAppEvent")]
        fn on_app_event(event_type: AppUiEventType, data: &str) -> bool;

        #[swift_bridge(swift_name = "findWebViewByPageInstanceId")]
        fn find_webview_by_page_instance_id(page_instance_id: &str) -> usize;

        #[swift_bridge(swift_name = "resolvePageBinding")]
        fn resolve_page_binding(appid: &str, path: &str, session_id: u64) -> PageBindingResult;

        #[swift_bridge(swift_name = "createPageInstance")]
        fn create_page_instance_for_open(
            appid: &str,
            path: &str,
            session_id: u64,
            surface: i32,
            owner_page_instance_id: &str,
        ) -> CreatePageInstanceResult;

        #[swift_bridge(swift_name = "isLxappRestartClosing")]
        fn is_lxapp_restart_closing(appid: &str, session_id: u64) -> bool;

        #[swift_bridge(swift_name = "notifyPageInstanceMounted")]
        fn notify_page_instance_mounted(page_instance_id: &str) -> bool;

        #[swift_bridge(swift_name = "notifyPageInstanceVisible")]
        fn notify_page_instance_visible(page_instance_id: &str) -> bool;

        #[swift_bridge(swift_name = "notifyPageInstanceHidden")]
        fn notify_page_instance_hidden(page_instance_id: &str, reason: &str) -> bool;

        #[swift_bridge(swift_name = "disposePageInstance")]
        fn dispose_page_instance(page_instance_id: &str, reason: &str) -> bool;

        #[swift_bridge(swift_name = "onSurfaceClosed")]
        fn on_surface_closed(appid: &str, id: &str, reason: &str) -> bool;

        // Adaptive Surface Layout (new model): report the window's container
        // width so the shared core resolves the sizeClass (with hysteresis);
        // returns true when the sizeClass flipped. And read the resolved
        // LayoutPresentationPlan as a JSON string for the skin to bind.
        #[swift_bridge(swift_name = "setSurfaceWidth")]
        fn set_surface_width(appid: &str, width: f64) -> bool;

        #[swift_bridge(swift_name = "setSurfaceLayoutMetrics")]
        fn set_surface_layout_metrics(appid: &str, width: f64, sidebar_width: f64) -> bool;

        #[swift_bridge(swift_name = "setSurfaceViewport")]
        fn set_surface_viewport(appid: &str, width: f64, height: f64) -> bool;

        #[swift_bridge(swift_name = "surfaceDerivedLayout")]
        fn surface_derived_layout(appid: &str) -> String;

        // §11.2 Phase 1: mirror a host-declared aside into the primary lxapp's
        // surface graph so the core's DerivedLayout reflects host surfaces.
        // Drive the active-main switch through the surface graph: makes this
        // lxapp's main the active main, then commits a `present_layout` carrying
        // the new `activeMainId` for the skin reconciler to attach.
        #[swift_bridge(swift_name = "setActiveMain")]
        fn set_active_main(appid: &str) -> bool;

        // Focus a surface in the window graph (aside-slot tab switch): the
        // committed plan's slot `activeChild` follows the focus and the skin
        // reconciler swaps the slot's visible child.
        #[swift_bridge(swift_name = "focusSurface")]
        fn focus_surface(appid: &str, surface_id: &str) -> bool;

        // Runtime activator clicks hand off to the home Logic's registered
        // callback. The callback owns any resulting surface operation.
        #[swift_bridge(swift_name = "shellActivate")]
        fn shell_activate(item_id: &str) -> bool;

        // Open (or focus) an lxapp as a MAIN — the pinned-lxapp tile's click.
        #[swift_bridge(swift_name = "shellOpenLxappMain")]
        fn shell_open_lxapp_main(app_id: &str) -> bool;

        #[swift_bridge(swift_name = "shellPins")]
        fn shell_pins() -> String;

        #[swift_bridge(swift_name = "shellIsPinned")]
        fn shell_is_pinned(kind: &str, key: &str) -> bool;

        // 1 = success, -1 = shared eight-Pin limit, 0 = invalid/unavailable.
        #[swift_bridge(swift_name = "shellSetPinned")]
        fn shell_set_pinned(kind: &str, key: &str, pinned: bool) -> i32;

        #[swift_bridge(swift_name = "registerHostAside")]
        fn register_host_aside(appid: &str, surface_id: &str, edge: &str) -> bool;
        #[swift_bridge(swift_name = "registerHostAsideContent")]
        fn register_host_aside_content(
            appid: &str,
            surface_id: &str,
            content_id: &str,
            edge: &str,
        ) -> bool;

        #[swift_bridge(swift_name = "unregisterHostAside")]
        fn unregister_host_aside(appid: &str, surface_id: &str) -> bool;

        #[swift_bridge(swift_name = "openBrowserTab")]
        fn open_browser_tab(appid: &str, session_id: u64, url: &str) -> Option<String>;

        // Opens an ownerless tab in the managed browser group.
        #[swift_bridge(swift_name = "openUnownedBrowserTab")]
        fn open_unowned_browser_tab(url: &str) -> Option<String>;

        #[swift_bridge(swift_name = "configureAppleUserAgentOverride")]
        fn configure_apple_user_agent_override(
            use_default: bool,
            user_agent: &str,
            reload_existing: bool,
        ) -> bool;

        #[swift_bridge(swift_name = "openStandaloneBrowserTab")]
        fn open_standalone_browser_tab(
            appid: &str,
            session_id: u64,
            url: &str,
            ephemeral_web_data: bool,
            url_callback: bool,
        ) -> Option<String>;

        // Open an API-managed tab in the compact aside browser group.
        #[swift_bridge(swift_name = "openAsideBrowserTab")]
        fn open_aside_browser_tab(appid: &str, session_id: u64, url: &str) -> Option<String>;

        // Whether the tab belongs to the API-managed aside browser group.
        #[swift_bridge(swift_name = "browserTabIsAside")]
        fn browser_tab_is_aside(tab_id: &str) -> bool;

        #[swift_bridge(swift_name = "browserTabIdsJson")]
        fn browser_tab_ids_json() -> String;

        #[swift_bridge(swift_name = "browserCurrentTabId")]
        fn browser_current_tab_id() -> String;

        #[swift_bridge(swift_name = "urlCallbackDispatch")]
        fn url_callback_dispatch(url: &str) -> bool;

        #[swift_bridge(swift_name = "webviewLoadErrorDocument")]
        fn webview_load_error_document(url: &str) -> String;

        #[swift_bridge(swift_name = "openBrowserTabWithId")]
        fn open_browser_tab_with_id(
            appid: &str,
            session_id: u64,
            url: &str,
            tab_id: &str,
        ) -> Option<String>;

        #[swift_bridge(swift_name = "browserTabClose")]
        fn browser_tab_close(tab_id: &str) -> bool;

        // Navigate an existing browser tab to a URL through the browser runtime,
        // which swaps the lxapp start page for a web view as needed.
        #[swift_bridge(swift_name = "browserTabNavigate")]
        fn browser_tab_navigate(tab_id: &str, url: &str) -> bool;

        // Discard a background tab's WebView to free memory; keeps the entry.
        #[swift_bridge(swift_name = "browserTabDiscard")]
        fn browser_tab_discard(tab_id: &str) -> bool;

        // Recreate a discarded tab's WebView, reload its URL, and activate it.
        #[swift_bridge(swift_name = "browserTabReactivate")]
        fn browser_tab_reactivate(tab_id: &str) -> bool;

        // Sync the Rust-side active tab when switching to an already-live tab.
        #[swift_bridge(swift_name = "browserTabActivate")]
        fn browser_tab_activate(tab_id: &str);

        // Clear Rust-side active state when no browser tab is visible.
        #[swift_bridge(swift_name = "browserTabDeactivate")]
        fn browser_tab_deactivate();

        #[swift_bridge(swift_name = "getBuiltinBrowserAppId")]
        fn get_builtin_browser_app_id() -> String;

        #[swift_bridge(swift_name = "browserTabPathForId")]
        fn browser_tab_path_for_id(tab_id: &str) -> String;

        #[swift_bridge(swift_name = "updateBrowserTabInfo")]
        fn update_browser_tab_info(tab_id: &str, current_url: &str, title: &str) -> bool;

        // Whether `url` is in the browser bookmarks store (chrome star state).
        #[swift_bridge(swift_name = "browserBookmarkStatus")]
        fn browser_bookmark_status(url: &str) -> bool;

        // Bookmark state bitmask for `url`: bit 0 = bookmarked, bit 1 = pinned.
        #[swift_bridge(swift_name = "browserBookmarkState")]
        fn browser_bookmark_state(url: &str) -> u32;

        // Canonical bookmark-match key (Rust owns the normalization rules).
        #[swift_bridge(swift_name = "browserBookmarkNormalizeUrl")]
        fn browser_bookmark_normalize_url(raw: &str) -> String;

        // Toggle `url` in the bookmarks store; returns the new bookmarked state.
        #[swift_bridge(swift_name = "browserBookmarkToggle")]
        fn browser_bookmark_toggle(url: &str, title: &str) -> bool;

        // Remove `url` from bookmarks (sidebar row action).
        #[swift_bridge(swift_name = "browserBookmarkRemoveByUrl")]
        fn browser_bookmark_remove_by_url(url: &str) -> bool;

        // Full bookmarks snapshot ({groups, entries}) as JSON for the sidebar.
        #[swift_bridge(swift_name = "browserBookmarksSnapshotJson")]
        fn browser_bookmarks_snapshot_json() -> String;

        // Absolute path to Rust's cross-platform favicon cache. Empty while a
        // missing entry is being fetched.
        #[swift_bridge(swift_name = "browserBookmarkFaviconPath")]
        fn browser_bookmark_favicon_path(url: &str) -> String;

        // Store favicon bytes the webview resolved (declared icon link) into
        // the shared cache so pins/tabs/docked browser all show it.
        #[swift_bridge(swift_name = "browserFaviconStore")]
        fn browser_favicon_store(url: &str, bytes: &[u8]) -> bool;

        // One sidebar management command as JSON ({"op": "rename" | "move" |
        // "createGroupAndMove" | "renameGroup" | "deleteGroup" | "setPinned",
        // ...}).
        #[swift_bridge(swift_name = "browserBookmarksCommand")]
        fn browser_bookmarks_command(json: &str) -> bool;

        // Pin `url` to the sidebar grid, bookmarking it first when needed.
        #[swift_bridge(swift_name = "browserBookmarkPin")]
        fn browser_bookmark_pin(url: &str, title: &str) -> bool;

        #[swift_bridge(swift_name = "startBrowserTabDownload")]
        fn start_browser_tab_download(
            tab_id: &str,
            url: &str,
            user_agent: &str,
            suggested_filename: &str,
            source_page_url: &str,
            cookie: &str,
        ) -> bool;

        #[swift_bridge(swift_name = "toggleWebViewDevtoolsByPtr")]
        fn toggle_webview_devtools_by_ptr(webview_ptr: usize, detached: bool) -> bool;

        #[swift_bridge(swift_name = "onApplinkReceived")]
        fn on_applink_received(applink_path: &str) -> i32;

        #[swift_bridge(swift_name = "getCurrentLxApp")]
        fn get_current_lxapp() -> CurrentLxApp;

        #[swift_bridge(swift_name = "getLxAppSessionId")]
        fn get_lxapp_session_id(appid: &str) -> u64;

        #[swift_bridge(swift_name = "onPushlinkReceived")]
        fn on_pushlink_received(url: &str, trigger: PushTrigger) -> i32;

        #[swift_bridge(swift_name = "onPushTokenReceived")]
        fn on_push_token_received(token: &str) -> i32;

        #[swift_bridge(swift_name = "onCallback")]
        fn on_callback(id: u64, success: bool, data: &str) -> bool;

        #[swift_bridge(swift_name = "onNativeComponentEvent")]
        fn on_native_component_event(
            appid: &str,
            path: &str,
            component_id: &str,
            event_name: &str,
            payload_json: &str,
            bindings_json: &str,
        ) -> bool;

        #[swift_bridge(swift_name = "isPullDownRefreshEnabled")]
        fn is_pull_down_refresh_enabled(appid: &str, path: &str) -> bool;

        #[swift_bridge(swift_name = "resolveLxUri")]
        fn resolve_lx_uri(appid: &str, input: &str) -> Option<String>;

        #[swift_bridge(swift_name = "handleBrowserAddressInput")]
        fn handle_browser_address_input(request_json: &str) -> Option<String>;

        #[swift_bridge(swift_name = "browserUrlIsHidden")]
        fn browser_url_is_hidden(raw: &str) -> bool;

        #[swift_bridge(swift_name = "onAppShow")]
        fn on_app_show(lxappid: &str);

        #[swift_bridge(swift_name = "onAppHide")]
        fn on_app_hide(lxappid: &str);

        #[swift_bridge(swift_name = "onUserCaptureScreen")]
        fn on_user_capture_screen(lxappid: &str);

        // Returns a bitmask of enabled SDK capabilities (compile-time constant).
        // Bit 0 (0x1) = browser (tabs, downloads, settings, panels).
        #[swift_bridge(swift_name = "getAppCapabilities")]
        fn get_app_capabilities() -> u32;

        #[swift_bridge(swift_name = "shouldEnableWebViewDebugging")]
        fn should_enable_webview_debugging() -> bool;

        // Get panels config as JSON string (returns None if no panels configured)
        #[swift_bridge(swift_name = "getPanelsConfigJson")]
        fn get_panels_config_json() -> Option<String>;

        // Open a lxapp for a panel (triggers download + JS init if needed).
        // panel_id is forwarded so Swift can route the openLxApp callback to the right panel.
        #[swift_bridge(swift_name = "openPanelLxapp")]
        fn open_panel_lxapp(panel_id: &str, appid: &str, path: &str);

        #[swift_bridge(swift_name = "getTerminalBackendStatusJson")]
        fn get_terminal_backend_status_json() -> String;

        #[swift_bridge(swift_name = "terminalSessionCreate")]
        fn terminal_session_create(cols: u16, rows: u16) -> u64;

        #[swift_bridge(swift_name = "terminalSessionWrite")]
        fn terminal_session_write(id: u64, input: &str) -> bool;

        #[swift_bridge(swift_name = "terminalSessionRead")]
        fn terminal_session_read(id: u64) -> String;

        #[swift_bridge(swift_name = "terminalSessionSnapshot")]
        fn terminal_session_snapshot(id: u64) -> String;

        #[swift_bridge(swift_name = "terminalSessionExited")]
        fn terminal_session_exited(id: u64) -> bool;

        #[swift_bridge(swift_name = "terminalSessionResize")]
        fn terminal_session_resize(id: u64, cols: u16, rows: u16) -> bool;

        #[swift_bridge(swift_name = "terminalSessionScroll")]
        fn terminal_session_scroll(
            id: u64,
            delta_rows: i32,
            col: u16,
            row: u16,
            allow_application_input: bool,
        ) -> bool;

        #[swift_bridge(swift_name = "terminalSessionClose")]
        fn terminal_session_close(id: u64);
    }

    extern "Swift" {
        #[swift_bridge(swift_name = "LxApp.presentInternalBrowserTab")]
        fn present_internal_browser_tab(tab_id: &str) -> bool;

        #[swift_bridge(swift_name = "LxApp.prepareInternalBrowserTabForInput")]
        fn prepare_internal_browser_tab_for_input(tab_id: &str) -> bool;

        // Bookmarks store changed (any writer) — chrome refreshes its sidebar.
        #[swift_bridge(swift_name = "LxApp.browserBookmarksChanged")]
        fn browser_bookmarks_changed();

        // Display language changed — host-owned native chrome re-localizes.
        #[swift_bridge(swift_name = "LxApp.displayLanguageChanged")]
        fn display_language_changed();
    }
}

#[cfg(all(target_os = "macos", feature = "browser-shell"))]
struct AppleBrowserNativeInputHost;

#[cfg(all(target_os = "macos", feature = "browser-shell"))]
impl lingxia_browser::BrowserNativeInputHost for AppleBrowserNativeInputHost {
    fn prepare_for_input(&self, tab_id: &str) -> Result<(), String> {
        if self::bridge::prepare_internal_browser_tab_for_input(tab_id) {
            Ok(())
        } else {
            Err(format!("failed to prepare browser tab for input: {tab_id}"))
        }
    }
}

#[cfg(all(target_os = "macos", feature = "browser-shell"))]
fn install_browser_native_input_host() {
    let _ = lingxia_browser::register_native_input_host(Arc::new(AppleBrowserNativeInputHost));
    // Sidebar bookmarks live-refresh: any bookmarks mutation (star, sidebar
    // action, webui manager page) notifies the Swift shell.
    lingxia_browser_shell::set_bookmarks_change_listener(Box::new(|| {
        self::bridge::browser_bookmarks_changed();
    }));
    lingxia_browser_shell::set_display_language_change_listener(Box::new(|| {
        self::bridge::display_language_changed();
    }));
}

#[cfg(not(all(target_os = "macos", feature = "browser-shell")))]
fn install_browser_native_input_host() {}

/// Initialize the Lingxia SDK for iOS/macOS
pub fn lingxia_init(data_dir: &str, cache_dir: &str, locale: &str) -> bridge::LingxiaInitResult {
    crate::logging::init();
    install_browser_native_input_host();

    log::info!(
        "Initializing Lingxia SDK with data_dir: {}, cache_dir: {}",
        data_dir,
        cache_dir
    );

    let platform = match lingxia_platform::Platform::new(
        data_dir.to_string(),
        cache_dir.to_string(),
        locale.to_string(),
    ) {
        Ok(platform) => platform,
        Err(e) => {
            log::error!("Failed to create Platform: {}", e);
            return bridge::LingxiaInitResult {
                ok: false,
                home_app_id: String::new(),
                error: e.to_string(),
            };
        }
    };

    match crate::init_with_platform(platform) {
        Ok(info) => bridge::LingxiaInitResult {
            ok: true,
            home_app_id: info.into_lxapp_id().unwrap_or_default(),
            error: String::new(),
        },
        Err(error) => bridge::LingxiaInitResult {
            ok: false,
            home_app_id: String::new(),
            error: error.to_string(),
        },
    }
}

/// Return the effective display language selected by the runtime.
pub fn get_display_language() -> String {
    crate::app::display_language()
}

pub fn forward_host_log(
    level: i32,
    category: &str,
    appid: &str,
    path: &str,
    message: &str,
) -> bool {
    crate::logging::forward_host_log(level, category, appid, path, message)
}

/// Set the runtime log threshold (0=verbose … 4=error). See
/// [`crate::logging::set_log_level`].
pub fn set_log_level(level: i32) {
    crate::logging::set_log_level(level);
}

/// Whether a host log at `level` would be recorded. See
/// [`crate::logging::host_log_enabled`].
pub fn host_log_enabled(level: i32) -> bool {
    crate::logging::host_log_enabled(level)
}

/// Notify that a page is being shown
pub fn on_page_show(appid: &str, path: &str) {
    if let Some(lxapp) = lxapp::try_get(appid) {
        lxapp.on_page_show(path.to_string());
    }
}

pub fn resolve_lx_uri(appid: &str, input: &str) -> Option<String> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return None;
    }

    if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
        return Some(trimmed.to_string());
    }

    let lxapp = lxapp::try_get(appid)?;

    if let Some(path) = trimmed.strip_prefix("file://") {
        let resolved = lxapp.resolve_accessible_path(path).ok()?;
        return Some(format!("file://{}", resolved.to_string_lossy()));
    }

    let resolved = lxapp.resolve_accessible_path(trimmed).ok()?;
    Some(format!("file://{}", resolved.to_string_lossy()))
}

pub fn handle_browser_address_input(request_json: &str) -> Option<String> {
    crate::browser::resolve_input_json(request_json)
}

pub fn browser_url_is_hidden(raw: &str) -> bool {
    crate::browser::should_hide_url(raw)
}

/// Catch panics at FFI boundary and return a default value on failure.
macro_rules! ffi_catch_unwind {
    ($name:expr, $default:expr, $body:expr) => {
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe($body)) {
            Ok(v) => v,
            Err(_) => {
                log::error!("panic in {}", $name);
                $default
            }
        }
    };
}

/// Notify that LxApp was closed
pub fn on_lxapp_closed(appid: &str, session_id: u64) -> bool {
    ffi_catch_unwind!("on_lxapp_closed", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            if session_id == 0 || session_id != lxapp.session_id() {
                return false;
            }
            lxapp.on_lxapp_closed(session_id);
            return true;
        }
        false
    })
}

/// Notify device orientation changes from host platform.
pub fn on_device_orientation_changed(appid: &str, session_id: u64, value: &str) -> bool {
    let Some(lxapp) = lxapp::try_get(appid) else {
        return false;
    };

    if session_id == 0 || session_id != lxapp.session_id() {
        return false;
    }

    let normalized = match value {
        "portrait" => "portrait",
        "landscape" => "landscape",
        _ => return false,
    };

    let payload = format!(r#"{{"value":"{}"}}"#, normalized);
    lxapp::publish_app_event(appid, "DeviceOrientationChange", Some(payload))
}

/// Handle lxapp-scoped UI events from Swift. `appid` must be a real lxapp id.
pub fn on_lxapp_event(appid: &str, event_type: self::bridge::LxAppUiEventType, data: &str) -> bool {
    let ui_event_type = match event_type {
        self::bridge::LxAppUiEventType::TabBarClick => LxAppUiEventType::TabBarClick,
        self::bridge::LxAppUiEventType::CapsuleClick => LxAppUiEventType::CapsuleClick,
        self::bridge::LxAppUiEventType::NavigationClick => LxAppUiEventType::NavigationClick,
        self::bridge::LxAppUiEventType::BackPress => LxAppUiEventType::BackPress,
        self::bridge::LxAppUiEventType::PullDownRefresh => LxAppUiEventType::PullDownRefresh,
    };

    lxapp::try_get(appid)
        .map(|lxapp| lxapp.on_lxapp_event(ui_event_type, data.to_string()))
        .unwrap_or(false)
}

/// Handle host-app scoped UI events from Swift (no lxapp context).
pub fn on_app_event(event_type: self::bridge::AppUiEventType, data: &str) -> bool {
    match event_type {
        self::bridge::AppUiEventType::PanelIconClick => {
            // data = panelId; look up config and ask Rust to load the lxapp if needed
            if let Some((app_id, path)) = crate::browser::panel_item_for_id(data) {
                crate::browser::open_panel_lxapp(data, &app_id, &path);
                true
            } else {
                false
            }
        }
        self::bridge::AppUiEventType::UpdateRestartClick => {
            // The sidebar "ready to update" callout was clicked: swap the
            // staged bundle and quit so it relaunches into the new version.
            lingxia_platform::apply_staged_macos_update()
        }
        self::bridge::AppUiEventType::UpdateInstallClick => {
            // The "update available" reminder was clicked: re-run the update
            // flow, which re-presents the card and downloads on confirm.
            crate::task::spawn(async {
                let _ = crate::update::host_app::check().await;
            });
            true
        }
        self::bridge::AppUiEventType::TrayClick => {
            // `data` is the tray-owning lxapp id. Deliver `lx.tray.onClick` only to
            // that app, not every loaded lxapp.
            if !data.is_empty() {
                lxapp::publish_app_event(data, "lx.tray.click", None);
            }
            true
        }
        self::bridge::AppUiEventType::TrayMenuClick => {
            // `data` is "<appid>:<index>" — deliver to the owning app's handler that
            // `lx.tray.setMenu` registered for that index (split on the last ':' so
            // an appid containing ':' is tolerated).
            if let Some((appid, index)) = data.rsplit_once(':')
                && !appid.is_empty()
            {
                let event = format!("lx.tray.menu:{index}");
                lxapp::publish_app_event(appid, &event, None);
            }
            true
        }
    }
}

pub fn on_native_component_event(
    appid: &str,
    path: &str,
    component_id: &str,
    event_name: &str,
    payload_json: &str,
    bindings_json: &str,
) -> bool {
    lxapp::on_native_component_event(
        appid,
        path,
        component_id,
        event_name,
        payload_json,
        bindings_json,
    )
}

pub fn open_browser_tab(appid: &str, session_id: u64, url: &str) -> Option<String> {
    ffi_catch_unwind!("open_browser_tab", None, || {
        match crate::browser::open_for_app(appid, session_id, url, None) {
            Ok(tab_id) => Some(tab_id),
            Err(e) => {
                log::error!("open_browser_tab failed: {}", e);
                None
            }
        }
    })
}

pub fn open_unowned_browser_tab(url: &str) -> Option<String> {
    ffi_catch_unwind!("open_unowned_browser_tab", None, || {
        match crate::browser::open(url, None) {
            Ok(tab_id) => Some(tab_id),
            Err(error) => {
                log::error!("open_unowned_browser_tab failed: {error}");
                None
            }
        }
    })
}

pub fn configure_apple_user_agent_override(
    use_default: bool,
    user_agent: &str,
    reload_existing: bool,
) -> bool {
    ffi_catch_unwind!("configure_apple_user_agent_override", false, || {
        let user_agent = if use_default {
            lingxia_webview::UserAgentOverride::Default
        } else {
            lingxia_webview::UserAgentOverride::Custom(user_agent.to_string())
        };
        lingxia_webview::platform::apple::configure_user_agent_override_for_webviews(
            user_agent,
            true,
            reload_existing,
        )
        .map_err(|err| log::error!("configure Apple user agent failed: {err}"))
        .is_ok()
    })
}
/// Offer a navigation URL from a native (non-managed) WebView to the
/// URL-callback registry. `true` means a channel consumed it and the native
/// side must cancel the navigation.
pub fn url_callback_dispatch(url: &str) -> bool {
    ffi_catch_unwind!("url_callback_dispatch", false, || {
        lingxia_webview::url_callback::dispatch(url)
    })
}

pub fn webview_load_error_document(url: &str) -> String {
    crate::webview_error::load_error_document(url)
}

pub fn open_standalone_browser_tab(
    appid: &str,
    session_id: u64,
    url: &str,
    ephemeral_web_data: bool,
    url_callback: bool,
) -> Option<String> {
    ffi_catch_unwind!("open_standalone_browser_tab", None, || {
        let data_mode = if ephemeral_web_data {
            lingxia_webview::WebViewDataMode::Ephemeral
        } else {
            lingxia_webview::WebViewDataMode::ProfileDefault
        };
        match crate::browser::open_standalone_for_app(
            appid,
            session_id,
            url,
            None,
            data_mode,
            url_callback,
        ) {
            Ok(tab_id) => Some(tab_id),
            Err(e) => {
                log::error!("open_standalone_browser_tab failed: {}", e);
                None
            }
        }
    })
}

pub fn open_aside_browser_tab(appid: &str, session_id: u64, url: &str) -> Option<String> {
    ffi_catch_unwind!("open_aside_browser_tab", None, || {
        match crate::browser::open_aside_for_app(appid, session_id, url, None) {
            Ok(tab_id) => Some(tab_id),
            Err(e) => {
                log::error!("open_aside_browser_tab failed: {}", e);
                None
            }
        }
    })
}

pub fn browser_tab_is_aside(tab_id: &str) -> bool {
    ffi_catch_unwind!("browser_tab_is_aside", false, || {
        crate::browser::tab_is_aside(tab_id)
    })
}

pub fn browser_tab_ids_json() -> String {
    ffi_catch_unwind!("browser_tab_ids_json", "[]".to_string(), || {
        #[cfg(feature = "browser-runtime")]
        {
            let ids = lingxia_browser::tabs()
                .into_iter()
                .filter(|tab| {
                    !lingxia_browser::tab_is_aside(&tab.tab_id)
                        && !lingxia_browser::tab_is_standalone(&tab.tab_id)
                })
                .map(|tab| tab.tab_id)
                .collect::<Vec<_>>();
            serde_json::to_string(&ids).unwrap_or_else(|_| "[]".to_string())
        }
        #[cfg(not(feature = "browser-runtime"))]
        "[]".to_string()
    })
}

pub fn browser_current_tab_id() -> String {
    ffi_catch_unwind!("browser_current_tab_id", String::new(), || {
        #[cfg(feature = "browser-runtime")]
        {
            lingxia_browser::current_tab()
                .filter(|tab| {
                    !lingxia_browser::tab_is_aside(&tab.tab_id)
                        && !lingxia_browser::tab_is_standalone(&tab.tab_id)
                })
                .map(|tab| tab.tab_id)
                .unwrap_or_default()
        }
        #[cfg(not(feature = "browser-runtime"))]
        String::new()
    })
}

pub fn open_browser_tab_with_id(
    appid: &str,
    session_id: u64,
    url: &str,
    tab_id: &str,
) -> Option<String> {
    ffi_catch_unwind!("open_browser_tab_with_id", None, || {
        match crate::browser::open_for_app(appid, session_id, url, Some(tab_id)) {
            Ok(tab_id) => Some(tab_id),
            Err(e) => {
                log::error!("open_browser_tab_with_id failed: {}", e);
                None
            }
        }
    })
}

pub fn browser_tab_close(tab_id: &str) -> bool {
    ffi_catch_unwind!("browser_tab_close", false, || {
        crate::browser::close(tab_id).is_ok()
    })
}

pub fn browser_tab_navigate(tab_id: &str, url: &str) -> bool {
    ffi_catch_unwind!("browser_tab_navigate", false, || {
        crate::browser::navigate(tab_id, url).is_ok()
    })
}

pub fn browser_tab_discard(tab_id: &str) -> bool {
    ffi_catch_unwind!("browser_tab_discard", false, || {
        crate::browser::discard(tab_id).is_ok()
    })
}

pub fn browser_tab_reactivate(tab_id: &str) -> bool {
    ffi_catch_unwind!("browser_tab_reactivate", false, || {
        crate::browser::reactivate(tab_id).is_ok()
    })
}

pub fn browser_tab_activate(tab_id: &str) {
    ffi_catch_unwind!("browser_tab_activate", (), || {
        crate::browser::mark_active(tab_id)
    })
}

pub fn browser_tab_deactivate() {
    ffi_catch_unwind!("browser_tab_deactivate", (), || {
        crate::browser::clear_active()
    })
}

pub fn get_builtin_browser_app_id() -> String {
    crate::browser::APP_ID.to_string()
}

pub fn browser_bookmark_status(url: &str) -> bool {
    ffi_catch_unwind!("browser_bookmark_status", false, || {
        crate::browser::bookmark_status(url)
    })
}

pub fn browser_bookmark_state(url: &str) -> u32 {
    ffi_catch_unwind!("browser_bookmark_state", 0, || {
        crate::browser::bookmark_state(url)
    })
}

pub fn browser_bookmark_normalize_url(raw: &str) -> String {
    ffi_catch_unwind!("browser_bookmark_normalize_url", String::new(), || {
        crate::browser::normalize_bookmark_url(raw)
    })
}

pub fn browser_bookmark_toggle(url: &str, title: &str) -> bool {
    ffi_catch_unwind!("browser_bookmark_toggle", false, || {
        crate::browser::bookmark_toggle(url, title)
    })
}

pub fn browser_bookmark_remove_by_url(url: &str) -> bool {
    ffi_catch_unwind!("browser_bookmark_remove_by_url", false, || {
        crate::browser::bookmark_remove_by_url(url)
    })
}

pub fn browser_bookmarks_snapshot_json() -> String {
    ffi_catch_unwind!("browser_bookmarks_snapshot_json", String::new(), || {
        crate::browser::bookmarks_snapshot_json()
    })
}

pub fn browser_bookmark_favicon_path(url: &str) -> String {
    ffi_catch_unwind!("browser_bookmark_favicon_path", String::new(), || {
        crate::browser::bookmark_favicon_path(url)
    })
}

pub fn browser_favicon_store(url: &str, bytes: &[u8]) -> bool {
    ffi_catch_unwind!("browser_favicon_store", false, || {
        crate::browser::store_favicon(url, bytes)
    })
}

pub fn browser_bookmarks_command(json: &str) -> bool {
    ffi_catch_unwind!("browser_bookmarks_command", false, || {
        crate::browser::bookmarks_command_json(json)
    })
}

pub fn browser_bookmark_pin(url: &str, title: &str) -> bool {
    ffi_catch_unwind!("browser_bookmark_pin", false, || {
        crate::browser::bookmark_pin(url, title)
    })
}

pub fn browser_tab_path_for_id(tab_id: &str) -> String {
    crate::browser::tab_path(tab_id)
}

pub fn present_internal_browser_tab(tab_id: &str) -> bool {
    ffi_catch_unwind!("present_internal_browser_tab", false, || {
        self::bridge::present_internal_browser_tab(tab_id)
    })
}

pub fn set_surface_width(appid: &str, width: f64) -> bool {
    ffi_catch_unwind!("set_surface_width", false, || {
        lxapp::try_get(appid)
            .map(|lxapp| lxapp.set_surface_width(width))
            .unwrap_or(false)
    })
}

pub fn set_surface_layout_metrics(appid: &str, width: f64, sidebar_width: f64) -> bool {
    ffi_catch_unwind!("set_surface_layout_metrics", false, || {
        lxapp::try_get(appid)
            .map(|lxapp| lxapp.set_surface_layout_metrics(width, sidebar_width))
            .unwrap_or(false)
    })
}

pub fn set_surface_viewport(appid: &str, width: f64, height: f64) -> bool {
    ffi_catch_unwind!("set_surface_viewport", false, || {
        lxapp::try_get(appid)
            .map(|lxapp| lxapp.set_surface_viewport(width, height))
            .unwrap_or(false)
    })
}

pub fn surface_derived_layout(appid: &str) -> String {
    ffi_catch_unwind!("surface_derived_layout", "null".to_string(), || {
        lxapp::try_get(appid)
            .and_then(|lxapp| lxapp.surface_derived_layout())
            .and_then(|layout| serde_json::to_string(&layout).ok())
            .unwrap_or_else(|| "null".to_string())
    })
}

pub fn set_active_main(appid: &str) -> bool {
    ffi_catch_unwind!("set_active_main", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            lxapp.set_active_main();
            true
        } else {
            false
        }
    })
}

pub fn shell_activate(item_id: &str) -> bool {
    ffi_catch_unwind!("shell_activate", false, || {
        lingxia_shell::activate(item_id).is_ok()
    })
}

pub fn shell_open_lxapp_main(app_id: &str) -> bool {
    ffi_catch_unwind!("shell_open_lxapp_main", false, || {
        let app_id = app_id.trim().to_string();
        if app_id.is_empty() {
            return false;
        }
        // One lxapp, one region: refuse to pull an aside into the main.
        if lxapp::open_region(&app_id) == Some(lxapp::LxAppOpenRegion::Aside) {
            log::warn!("pin open refused: {app_id} is open as an aside");
            return false;
        }
        std::mem::drop(rong_rt::RongExecutor::global().spawn(async move {
            if let Err(err) = lxapp::prepare_lxapp_open(&app_id, lxapp::ReleaseType::Release).await
            {
                log::error!("pin open failed for {app_id}: {err}");
                return;
            }
            if let Err(err) = lxapp::open_lxapp(&app_id, lxapp::LxAppStartupOptions::default()) {
                log::error!("pin open failed for {app_id}: {err}");
                return;
            }
            lxapp::schedule_lxapp_update_check(&app_id, lxapp::ReleaseType::Release);
        }));
        true
    })
}

pub fn shell_pins() -> String {
    ffi_catch_unwind!("shell_pins", String::new(), || {
        lingxia_shell::pins()
            .ok()
            .map(|pins| crate::shell::visible_shell_pins(&pins, lingxia_app_context::home_app_id()))
            .and_then(|pins| serde_json::to_string(&pins).ok())
            .unwrap_or_default()
    })
}

pub fn shell_is_pinned(kind: &str, key: &str) -> bool {
    ffi_catch_unwind!("shell_is_pinned", false, || {
        if shell_pin_is_home_lxapp(kind, key) {
            return false;
        }
        shell_pin_target(kind, key)
            .and_then(|target| lingxia_shell::is_pinned(&target).ok())
            .unwrap_or(false)
    })
}

pub fn shell_set_pinned(kind: &str, key: &str, pinned: bool) -> i32 {
    ffi_catch_unwind!("shell_set_pinned", 0, || {
        if pinned && shell_pin_is_home_lxapp(kind, key) {
            return 0;
        }
        let Some(target) = shell_pin_target(kind, key) else {
            return 0;
        };
        match lingxia_shell::set_pinned(target, pinned) {
            Ok(_) => 1,
            Err(lingxia_shell::ShellError::LimitReached { .. }) => -1,
            Err(error) => {
                log::warn!("failed to update shell Pin: {error}");
                0
            }
        }
    })
}

fn shell_pin_is_home_lxapp(kind: &str, key: &str) -> bool {
    kind == "lxapp" && lingxia_app_context::home_app_id().is_some_and(|home| home == key.trim())
}

fn shell_pin_target(kind: &str, key: &str) -> Option<lingxia_shell::ShellPinTarget> {
    let key = key.trim();
    if key.is_empty() {
        return None;
    }
    match kind {
        "lxapp" => Some(lingxia_shell::ShellPinTarget::Lxapp {
            key: key.to_string(),
        }),
        "bookmark" => Some(lingxia_shell::ShellPinTarget::Bookmark {
            key: key.to_string(),
        }),
        _ => None,
    }
}

pub fn focus_surface(appid: &str, surface_id: &str) -> bool {
    ffi_catch_unwind!("focus_surface", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            lxapp.focus_shell_surface(surface_id)
        } else {
            false
        }
    })
}

pub fn register_host_aside(appid: &str, surface_id: &str, edge: &str) -> bool {
    ffi_catch_unwind!("register_host_aside", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            lxapp.register_host_aside(surface_id, edge);
            true
        } else {
            false
        }
    })
}

pub fn register_host_aside_content(
    appid: &str,
    surface_id: &str,
    content_id: &str,
    edge: &str,
) -> bool {
    ffi_catch_unwind!("register_host_aside_content", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            lxapp.register_host_aside_content(surface_id, content_id, edge);
            true
        } else {
            false
        }
    })
}

pub fn unregister_host_aside(appid: &str, surface_id: &str) -> bool {
    ffi_catch_unwind!("unregister_host_aside", false, || {
        if let Some(lxapp) = lxapp::try_get(appid) {
            lxapp.unregister_host_aside(surface_id);
            true
        } else {
            false
        }
    })
}

pub fn update_browser_tab_info(tab_id: &str, current_url: &str, title: &str) -> bool {
    ffi_catch_unwind!("update_browser_tab_info", false, || {
        let current_url = if current_url.trim().is_empty() {
            None
        } else {
            Some(current_url)
        };
        let title = if title.trim().is_empty() {
            None
        } else {
            Some(title)
        };
        crate::browser::update_tab(tab_id, current_url, title)
    })
}

pub fn start_browser_tab_download(
    tab_id: &str,
    url: &str,
    user_agent: &str,
    suggested_filename: &str,
    source_page_url: &str,
    cookie: &str,
) -> bool {
    ffi_catch_unwind!("start_browser_tab_download", false, || {
        match crate::browser::download(
            tab_id,
            url,
            Some(user_agent),
            Some(suggested_filename),
            Some(source_page_url),
            Some(cookie),
        ) {
            Ok(()) => {
                log::info!(
                    "start_browser_tab_download accepted tab_id={} url={}",
                    tab_id,
                    url
                );
                true
            }
            Err(err) => {
                log::warn!(
                    "start_browser_tab_download failed tab_id={} url={} error={}",
                    tab_id,
                    url,
                    err
                );
                false
            }
        }
    })
}

pub fn toggle_webview_devtools_by_ptr(webview_ptr: usize, detached: bool) -> bool {
    if webview_ptr == 0 {
        return false;
    }
    #[cfg(target_os = "macos")]
    {
        lingxia_webview::platform::apple::toggle_webview_devtools_by_swift_ptr(
            webview_ptr,
            detached,
        )
    }
    #[cfg(not(target_os = "macos"))]
    {
        let _ = detached;
        false
    }
}

/// Get current active LxApp ID and path from Rust stack
pub fn get_current_lxapp() -> self::bridge::CurrentLxApp {
    let (current_appid, current_path, current_session_id) = lxapp::get_current_lxapp();
    self::bridge::CurrentLxApp {
        appid: current_appid,
        path: current_path,
        session_id: current_session_id,
    }
}

/// Get runtime session id for a specific lxapp.
pub fn get_lxapp_session_id(appid: &str) -> u64 {
    lxapp::try_get(appid)
        .map(|lxapp| lxapp.session_id())
        .unwrap_or(0)
}

pub fn find_webview_by_page_instance_id(page_instance_id: &str) -> usize {
    let page_instance_id = page_instance_id.trim();
    if page_instance_id.is_empty() {
        return 0;
    }
    let _ = lxapp::touch_page_instance_by_id(page_instance_id);

    lxapp::find_page_by_instance_id(page_instance_id)
        .and_then(|page| page.webview())
        .map(|webview| webview.get_swift_webview_ptr())
        .unwrap_or(0)
}

fn resolve_page_instance_id(appid: &str, path: &str, session_id: u64) -> String {
    if session_id == 0 {
        return String::new();
    }

    fn normalize_lookup_path(path: &str) -> &str {
        let path = path.split('?').next().unwrap_or(path);
        path.split('#').next().unwrap_or(path)
    }

    let Some(lxapp) = lxapp::try_get(appid) else {
        return String::new();
    };
    if lxapp.session_id() != session_id {
        return String::new();
    }

    let normalized_path = normalize_lookup_path(path);
    let resolved_path = lxapp
        .find_page_path(normalized_path)
        .unwrap_or_else(|| normalized_path.to_string());
    let page_instance_id = lxapp
        .page_instance_id_for_path(&resolved_path)
        .unwrap_or_default();
    if !page_instance_id.is_empty() {
        let _ = lxapp::touch_page_instance_by_id(&page_instance_id);
    }
    page_instance_id
}

pub fn resolve_page_binding(
    appid: &str,
    path: &str,
    session_id: u64,
) -> self::bridge::PageBindingResult {
    let page_instance_id = resolve_page_instance_id(appid, path, session_id);
    let mut webview_ptr = if page_instance_id.is_empty() {
        0
    } else {
        find_webview_by_page_instance_id(&page_instance_id)
    };
    if webview_ptr == 0 {
        // Browser tabs showing external documents have no bound lxapp
        // PageInstance — the WebView belongs to the tab, not a page.
        // Resolve it directly from the webview registry by webtag.
        let webtag = lingxia_webview::WebTag::new(appid, path, Some(session_id));
        if let Some(webview) = lingxia_webview::runtime::find_webview(&webtag) {
            webview_ptr = webview.get_swift_webview_ptr();
        }
    }
    self::bridge::PageBindingResult {
        page_instance_id,
        webview_ptr,
    }
}

/// True while `session_id` is being torn down for a restart — lets the shell skip
/// its post-close "reveal next app" for a restart (the runtime reopens it itself).
pub fn is_lxapp_restart_closing(appid: &str, session_id: u64) -> bool {
    lxapp::try_get(appid)
        .map(|app| app.is_restart_closing_session(session_id))
        .unwrap_or(false)
}

fn parse_close_reason(reason: &str) -> CloseReason {
    match reason.trim().to_ascii_lowercase().as_str() {
        "user" => CloseReason::User,
        "owner_closed" => CloseReason::OwnerClosed,
        "app_closed" | "appclose" | "close" => CloseReason::AppClosed,
        "programmatic" => CloseReason::Programmatic,
        "failed" | "presentation_failed" => CloseReason::Unknown,
        _ => CloseReason::Unknown,
    }
}

fn map_presentation_kind(surface: i32) -> PresentationKind {
    match surface {
        1 => PresentationKind::Panel,
        3 => PresentationKind::Overlay,
        _ => PresentationKind::Window,
    }
}

pub fn create_page_instance_for_open(
    appid: &str,
    path: &str,
    session_id: u64,
    surface: i32,
    owner_page_instance_id: &str,
) -> self::bridge::CreatePageInstanceResult {
    if session_id == 0 {
        return self::bridge::CreatePageInstanceResult {
            ok: false,
            page_instance_id: String::new(),
            appid: appid.to_string(),
            resolved_path: String::new(),
            query: String::new(),
            error: "invalid session_id".to_string(),
        };
    }

    let Some(lxapp_instance) = lxapp::try_get(appid) else {
        return self::bridge::CreatePageInstanceResult {
            ok: false,
            page_instance_id: String::new(),
            appid: appid.to_string(),
            resolved_path: String::new(),
            query: String::new(),
            error: "lxapp not found".to_string(),
        };
    };

    if lxapp_instance.session_id() != session_id {
        return self::bridge::CreatePageInstanceResult {
            ok: false,
            page_instance_id: String::new(),
            appid: appid.to_string(),
            resolved_path: String::new(),
            query: String::new(),
            error: "stale session".to_string(),
        };
    }

    // Reject page creation on the old session being restart-closed, so a premature
    // reopen can't pre-create its pages on the dying worker (recreate's instance is unmarked).
    if lxapp_instance.is_restart_closing_session(session_id) {
        return self::bridge::CreatePageInstanceResult {
            ok: false,
            page_instance_id: String::new(),
            appid: appid.to_string(),
            resolved_path: String::new(),
            query: String::new(),
            error: "restart closing session".to_string(),
        };
    }

    let owner = if let Some(owner_id) = PageInstanceId::parse(owner_page_instance_id.to_string()) {
        PageOwner::Page(owner_id)
    } else {
        PageOwner::Scene(SceneId("system".to_string()))
    };

    match lxapp::create_page_instance(CreatePageInstanceRequest {
        owner,
        appid: appid.to_string(),
        target: PageTarget::Path(path.to_string()),
        query: None::<PageQueryInput>,
        surface: map_presentation_kind(surface),
    }) {
        Ok(created) => self::bridge::CreatePageInstanceResult {
            ok: true,
            page_instance_id: created.page_instance_id.to_string(),
            appid: created.appid,
            resolved_path: created.resolved_path,
            query: created.query,
            error: String::new(),
        },
        Err(err) => self::bridge::CreatePageInstanceResult {
            ok: false,
            page_instance_id: String::new(),
            appid: appid.to_string(),
            resolved_path: String::new(),
            query: String::new(),
            error: err.to_string(),
        },
    }
}

pub fn notify_page_instance_mounted(page_instance_id: &str) -> bool {
    lxapp::notify_page_instance_by_id(page_instance_id, PageInstanceEvent::Mounted).is_ok()
}

pub fn notify_page_instance_visible(page_instance_id: &str) -> bool {
    lxapp::notify_page_instance_by_id(page_instance_id, PageInstanceEvent::Visible).is_ok()
}

pub fn notify_page_instance_hidden(page_instance_id: &str, reason: &str) -> bool {
    lxapp::notify_page_instance_by_id(
        page_instance_id,
        PageInstanceEvent::Hidden {
            reason: parse_close_reason(reason),
        },
    )
    .is_ok()
}

pub fn dispose_page_instance(page_instance_id: &str, reason: &str) -> bool {
    lxapp::dispose_page_instance_by_id(page_instance_id, parse_close_reason(reason)).is_ok()
}

pub fn on_surface_closed(appid: &str, id: &str, reason: &str) -> bool {
    if let Some(lxapp) = lxapp::try_get(appid) {
        let _ = lxapp.forget_surface(id);
    }
    #[cfg(feature = "standard")]
    {
        lingxia_logic::notify_surface_closed(id, reason)
    }
    #[cfg(not(feature = "standard"))]
    {
        let _ = reason;
        false
    }
}

/// Get LxApp information
/// Returns default empty values if app not found.
///
/// This works around a swift-bridge `Option<struct with String>` limitation.
pub fn get_lxapp_info(appid: &str) -> self::bridge::LxAppInfo {
    if let Some(lxapp) = lxapp::try_get(appid) {
        let lxapp_info = lxapp.get_lxapp_info();
        self::bridge::LxAppInfo {
            app_name: lxapp_info.app_name,
            version: lxapp_info.version,
            release_type: lxapp_info.release_type,
            cache_dir: lxapp.user_cache_dir.to_string_lossy().into_owned(),
            icon: lxapp_info.icon,
        }
    } else {
        self::bridge::LxAppInfo {
            app_name: String::new(),
            version: String::new(),
            release_type: String::new(),
            cache_dir: String::new(),
            icon: String::new(),
        }
    }
}

/// Get NavigationBar state
/// Returns default values if app not found.
///
/// This works around a swift-bridge `Option<struct with String>` limitation.
pub fn get_navigation_bar_state(appid: &str, path: &str) -> self::bridge::NavigationBarState {
    if let Some(lxapp) = lxapp::try_get(appid) {
        let nav_state = lxapp.get_navbar_state(path);
        let bg_color = parse_color_to_u32(&nav_state.navigationBarBackgroundColor, 0xFFFFFFFF);

        self::bridge::NavigationBarState {
            background_color: bg_color,
            text_style: nav_state.navigationBarTextStyle,
            title_text: nav_state.navigationBarTitleText,
            show_navbar: nav_state.show_navbar,
            show_back_button: nav_state.show_back_button,
            show_home_button: nav_state.show_home_button,
        }
    } else {
        self::bridge::NavigationBarState {
            background_color: 0,
            text_style: String::new(),
            title_text: String::new(),
            show_navbar: false,
            show_back_button: false,
            show_home_button: false,
        }
    }
}

/// Get page orientation for a specific page path.
/// Returns: 0=auto, 1=portrait, 2=landscape, 3=reverse-portrait, 4=reverse-landscape
pub fn get_page_orientation(appid: &str, path: &str) -> i32 {
    let Some(lxapp_instance) = lxapp::try_get(appid) else {
        return 0;
    };

    let orientation = lxapp_instance.get_page_orientation(path);
    orientation_to_value(orientation)
}

fn orientation_to_value(orientation: OrientationConfig) -> i32 {
    match (orientation.mode, orientation.rotation) {
        (PageOrientation::Auto, _) => 0,
        (PageOrientation::Portrait, 180) => 3,
        (PageOrientation::Portrait, _) => 1,
        (PageOrientation::Landscape, 180) => 4,
        (PageOrientation::Landscape, _) => 2,
    }
}

/// Get TabBar state
pub fn get_tab_bar(appid: &str) -> Option<self::bridge::TabBar> {
    lxapp::try_get(appid).and_then(|lxapp| {
        lxapp.get_tabbar().map(|tabbar| self::bridge::TabBar {
            color: parse_color_to_u32(&tabbar.color, 0xFF666666),
            selected_color: parse_color_to_u32(&tabbar.selectedColor, 0xFF1677FF),
            background_color: parse_color_to_u32(&tabbar.backgroundColor, 0xFFFFFFFF),
            border_style: parse_color_to_u32(&tabbar.borderStyle, 0xFFF0F0F0),
            position: tabbar.position.to_i32(),
            dimension: tabbar.dimension,
            items_count: tabbar.list.len() as i32,
            is_visible: tabbar.is_visible,
            is_api_hidden: tabbar.api_hidden,
            selected_index: tabbar.selected_index,
            styled_mask: (!tabbar.color.is_empty() as u32)
                | ((!tabbar.selectedColor.is_empty() as u32) << 1)
                | ((!tabbar.backgroundColor.is_empty() as u32) << 2)
                | ((!tabbar.borderStyle.is_empty() as u32) << 3),
        })
    })
}

/// Get TabBar item by index
pub fn get_tab_bar_item(appid: &str, index: i32) -> Option<self::bridge::TabBarItem> {
    lxapp::try_get(appid)
        .and_then(|lxapp| lxapp.get_tabbar())
        .and_then(|tabbar| {
            tabbar.get_item(index).map(|item| self::bridge::TabBarItem {
                page_path: item.pagePath.clone(),
                text: item.text.clone().unwrap_or_default(),
                icon_path: item.iconPath.clone().unwrap_or_default(),
                selected_icon_path: item.selectedIconPath.clone().unwrap_or_default(),
                selected: item.selected,
                badge: item.badge.clone().unwrap_or_default(),
                has_red_dot: item.has_red_dot,
            })
        })
}

/// Handle AppLink URL by processing the path (Universal Link)
pub fn on_applink_received(url: &str) -> i32 {
    lingxia_service::applink::handle(url)
}

/// Handle Push Notification Link with trigger context
pub fn on_pushlink_received(url: &str, trigger: self::bridge::PushTrigger) -> i32 {
    let trigger_name = match trigger {
        self::bridge::PushTrigger::Background => "Background",
        self::bridge::PushTrigger::Tap => "Tap",
        self::bridge::PushTrigger::Launch => "Launch",
    };

    log::info!(
        "[Apple] Push Link received: {} (trigger: {})",
        url,
        trigger_name
    );

    lingxia_service::applink::handle(url)
}

/// Handle push notification device token
pub fn on_push_token_received(token: &str) -> i32 {
    crate::push::bind_push_token_for_ffi(token.to_string())
}

/// Callback from platform (called from Swift/Objective-C)
///
/// # Parameters
/// - `id`: Callback ID for correlating with pending operation
/// - `success`: Whether the operation completed successfully
/// - `data`: When `success=true`, contains JSON payload; when `success=false`, contains error code string (see i18n/err_code)
pub fn on_callback(id: u64, success: bool, data: &str) -> bool {
    let result = if success {
        Ok(data.to_string())
    } else {
        // Parse data as u32 error code, default to 1000 (unknown error) if failed
        Err(data.parse::<u32>().unwrap_or(1000))
    };

    if invoke_callback(id, result) {
        true
    } else {
        log::warn!("[Apple] Callback not found for id={}", id);
        false
    }
}

/// Check if pull-down refresh is enabled for a specific page
pub fn is_pull_down_refresh_enabled(appid: &str, path: &str) -> bool {
    lxapp::is_pull_down_refresh_enabled(appid, path)
}

/// Notify that app entered foreground
/// Called from Swift when UIApplication receives willEnterForeground notification
pub fn on_app_show(lxappid: &str) {
    if let Some(lxapp) = lxapp::try_get(lxappid) {
        let args = lxapp::AppServiceEventArgs {
            source: lxapp::AppServiceEventSource::Host,
            reason: lxapp::AppServiceEventReason::Foreground,
        }
        .to_json_string();
        let _ = lxapp.appservice_notify(lxapp::AppServiceEvent::OnShow, Some(args));
    }
}

/// Notify that app entered background
/// Called from Swift when UIApplication receives didEnterBackground notification
pub fn on_app_hide(lxappid: &str) {
    if let Some(lxapp) = lxapp::try_get(lxappid) {
        let args = lxapp::AppServiceEventArgs {
            source: lxapp::AppServiceEventSource::Host,
            reason: lxapp::AppServiceEventReason::Background,
        }
        .to_json_string();
        let _ = lxapp.appservice_notify(lxapp::AppServiceEvent::OnHide, Some(args));
    }
}

/// Notify that user captured a screenshot
/// Called from Swift when UIApplication receives userDidTakeScreenshot notification
pub fn on_user_capture_screen(lxappid: &str) {
    if let Some(lxapp) = lxapp::try_get(lxappid) {
        let args = lxapp::AppServiceEventArgs {
            source: lxapp::AppServiceEventSource::Host,
            reason: lxapp::AppServiceEventReason::Screenshot,
        }
        .to_json_string();
        let _ = lxapp.appservice_notify(lxapp::AppServiceEvent::OnUserCaptureScreen, Some(args));
    }
}

pub fn get_app_capabilities() -> u32 {
    crate::capabilities::app_capabilities()
}

pub fn should_enable_webview_debugging() -> bool {
    crate::should_enable_webview_debugging()
}

/// Get panels config as a JSON string.
/// Returns None if no panels are configured in app.json.
pub fn get_panels_config_json() -> Option<String> {
    crate::browser::panels_config_json()
}

/// Open a lxapp for a panel without pushing it to the navigation stack.
/// panel_id is used by Rust as the panel slot context for surface routing.
pub fn open_panel_lxapp(panel_id: &str, appid: &str, path: &str) {
    crate::browser::open_panel_lxapp(panel_id, appid, path);
}

pub fn get_terminal_backend_status_json() -> String {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::ghostty_status_json();
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        r#"{"backend":"ghostty","available":false,"status":"terminal runtime disabled","sourceDir":null,"libDir":null}"#.to_string()
    }
}

pub fn terminal_session_create(cols: u16, rows: u16) -> u64 {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_create(cols, rows);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = (cols, rows);
        0
    }
}

pub fn terminal_session_write(id: u64, input: &str) -> bool {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_write(id, input);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = (id, input);
        false
    }
}

pub fn terminal_session_read(id: u64) -> String {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_read(id);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = id;
        String::new()
    }
}

pub fn terminal_session_snapshot(id: u64) -> String {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_snapshot(id);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = id;
        r#"{"cols":0,"rows":0,"lines":[],"cells":[],"cursor_row":0,"cursor_col":0,"cursor_visible":false,"application_cursor":false,"bracketed_paste":false,"alternate_screen":false,"scrollbar":null,"title":null,"generation":0,"exited":true}"#.to_string()
    }
}

pub fn terminal_session_exited(id: u64) -> bool {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_exited(id);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = id;
        true
    }
}

pub fn terminal_session_resize(id: u64, cols: u16, rows: u16) -> bool {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_resize(id, cols, rows);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = (id, cols, rows);
        false
    }
}

pub fn terminal_session_scroll(
    id: u64,
    delta_rows: i32,
    col: u16,
    row: u16,
    allow_application_input: bool,
) -> bool {
    #[cfg(feature = "terminal-runtime")]
    {
        return crate::terminal::terminal_scroll(id, delta_rows, col, row, allow_application_input);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = (id, delta_rows, col, row, allow_application_input);
        false
    }
}

pub fn terminal_session_close(id: u64) {
    #[cfg(feature = "terminal-runtime")]
    {
        crate::terminal::terminal_close(id);
    }

    #[cfg(not(feature = "terminal-runtime"))]
    {
        let _ = id;
    }
}