oxide-sdk 0.4.0

Guest SDK for building .wasm applications that run inside the Oxide browser
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
//! # Oxide SDK
//!
//! Guest-side SDK for building WebAssembly applications that run inside the
//! [Oxide browser](https://github.com/niklabh/oxide). This crate provides
//! safe Rust wrappers around the raw host-imported functions exposed by the
//! `"oxide"` wasm import module.
//!
//! ## Quick Start
//!
//! Add `oxide-sdk` to your `Cargo.toml` and set `crate-type = ["cdylib"]`:
//!
//! ```toml
//! [lib]
//! crate-type = ["cdylib"]
//!
//! [dependencies]
//! oxide-sdk = "0.2"
//! ```
//!
//! Then write your app:
//!
//! ```rust,ignore
//! use oxide_sdk::*;
//!
//! #[no_mangle]
//! pub extern "C" fn start_app() {
//!     log("Hello from Oxide!");
//!     canvas_clear(30, 30, 46, 255);
//!     canvas_text(20.0, 40.0, 28.0, 255, 255, 255, "Welcome to Oxide");
//! }
//! ```
//!
//! Build with `cargo build --target wasm32-unknown-unknown --release`.
//!
//! ## Interactive Apps
//!
//! For apps that need a render loop, export `on_frame`:
//!
//! ```rust,ignore
//! use oxide_sdk::*;
//!
//! #[no_mangle]
//! pub extern "C" fn start_app() {
//!     log("Interactive app started");
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn on_frame(_dt_ms: u32) {
//!     canvas_clear(30, 30, 46, 255);
//!     let (mx, my) = mouse_position();
//!     canvas_circle(mx, my, 20.0, 255, 100, 100, 255);
//!
//!     if ui_button(1, 20.0, 20.0, 100.0, 30.0, "Click me!") {
//!         log("Button was clicked!");
//!     }
//! }
//! ```
//!
//! ## API Categories
//!
//! | Category | Functions |
//! |----------|-----------|
//! | **Canvas** | [`canvas_clear`], [`canvas_rect`], [`canvas_circle`], [`canvas_text`], [`canvas_line`], [`canvas_image`], [`canvas_dimensions`] |
//! | **Console** | [`log`], [`warn`], [`error`] |
//! | **HTTP** | [`fetch`], [`fetch_get`], [`fetch_post`], [`fetch_post_proto`], [`fetch_put`], [`fetch_delete`] |
//! | **Protobuf** | [`proto::ProtoEncoder`], [`proto::ProtoDecoder`] |
//! | **Storage** | [`storage_set`], [`storage_get`], [`storage_remove`], [`kv_store_set`], [`kv_store_get`], [`kv_store_delete`] |
//! | **Audio** | [`audio_play`], [`audio_play_url`], [`audio_detect_format`], [`audio_play_with_format`], [`audio_last_url_content_type`], [`audio_pause`], [`audio_channel_play`] |
//! | **Video** | [`video_load`], [`video_load_url`], [`video_render`], [`video_play`], [`video_hls_open_variant`], [`subtitle_load_srt`] |
//! | **Media capture** | [`camera_open`], [`camera_capture_frame`], [`microphone_open`], [`microphone_read_samples`], [`screen_capture`], [`media_pipeline_stats`] |
//! | **Timers** | [`set_timeout`], [`set_interval`], [`clear_timer`], [`time_now_ms`] |
//! | **Navigation** | [`navigate`], [`push_state`], [`replace_state`], [`get_url`], [`history_back`], [`history_forward`] |
//! | **Input** | [`mouse_position`], [`mouse_button_down`], [`key_down`], [`key_pressed`], [`scroll_delta`] |
//! | **Widgets** | [`ui_button`], [`ui_checkbox`], [`ui_slider`], [`ui_text_input`] |
//! | **Crypto** | [`hash_sha256`], [`hash_sha256_hex`], [`base64_encode`], [`base64_decode`] |
//! | **Other** | [`clipboard_write`], [`clipboard_read`], [`random_u64`], [`random_f64`], [`notify`], [`upload_file`], [`load_module`] |
//!
//! ## Full API Documentation
//!
//! See <https://docs.oxide.foundation/oxide_sdk/> for the complete API
//! reference, or browse the individual function documentation below.

pub mod proto;

// ─── Raw FFI imports from the host ──────────────────────────────────────────

#[link(wasm_import_module = "oxide")]
extern "C" {
    #[link_name = "api_log"]
    fn _api_log(ptr: u32, len: u32);

    #[link_name = "api_warn"]
    fn _api_warn(ptr: u32, len: u32);

    #[link_name = "api_error"]
    fn _api_error(ptr: u32, len: u32);

    #[link_name = "api_get_location"]
    fn _api_get_location(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_upload_file"]
    fn _api_upload_file(name_ptr: u32, name_cap: u32, data_ptr: u32, data_cap: u32) -> u64;

    #[link_name = "api_canvas_clear"]
    fn _api_canvas_clear(r: u32, g: u32, b: u32, a: u32);

    #[link_name = "api_canvas_rect"]
    fn _api_canvas_rect(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32);

    #[link_name = "api_canvas_circle"]
    fn _api_canvas_circle(cx: f32, cy: f32, radius: f32, r: u32, g: u32, b: u32, a: u32);

    #[link_name = "api_canvas_text"]
    fn _api_canvas_text(x: f32, y: f32, size: f32, r: u32, g: u32, b: u32, ptr: u32, len: u32);

    #[link_name = "api_canvas_line"]
    fn _api_canvas_line(x1: f32, y1: f32, x2: f32, y2: f32, r: u32, g: u32, b: u32, thickness: f32);

    #[link_name = "api_canvas_dimensions"]
    fn _api_canvas_dimensions() -> u64;

    #[link_name = "api_canvas_image"]
    fn _api_canvas_image(x: f32, y: f32, w: f32, h: f32, data_ptr: u32, data_len: u32);

    #[link_name = "api_storage_set"]
    fn _api_storage_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32);

    #[link_name = "api_storage_get"]
    fn _api_storage_get(key_ptr: u32, key_len: u32, out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_storage_remove"]
    fn _api_storage_remove(key_ptr: u32, key_len: u32);

    #[link_name = "api_clipboard_write"]
    fn _api_clipboard_write(ptr: u32, len: u32);

    #[link_name = "api_clipboard_read"]
    fn _api_clipboard_read(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_time_now_ms"]
    fn _api_time_now_ms() -> u64;

    #[link_name = "api_set_timeout"]
    fn _api_set_timeout(callback_id: u32, delay_ms: u32) -> u32;

    #[link_name = "api_set_interval"]
    fn _api_set_interval(callback_id: u32, interval_ms: u32) -> u32;

    #[link_name = "api_clear_timer"]
    fn _api_clear_timer(timer_id: u32);

    #[link_name = "api_random"]
    fn _api_random() -> u64;

    #[link_name = "api_notify"]
    fn _api_notify(title_ptr: u32, title_len: u32, body_ptr: u32, body_len: u32);

    #[link_name = "api_fetch"]
    fn _api_fetch(
        method_ptr: u32,
        method_len: u32,
        url_ptr: u32,
        url_len: u32,
        ct_ptr: u32,
        ct_len: u32,
        body_ptr: u32,
        body_len: u32,
        out_ptr: u32,
        out_cap: u32,
    ) -> i64;

    #[link_name = "api_load_module"]
    fn _api_load_module(url_ptr: u32, url_len: u32) -> i32;

    #[link_name = "api_hash_sha256"]
    fn _api_hash_sha256(data_ptr: u32, data_len: u32, out_ptr: u32) -> u32;

    #[link_name = "api_base64_encode"]
    fn _api_base64_encode(data_ptr: u32, data_len: u32, out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_base64_decode"]
    fn _api_base64_decode(data_ptr: u32, data_len: u32, out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_kv_store_set"]
    fn _api_kv_store_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32) -> i32;

    #[link_name = "api_kv_store_get"]
    fn _api_kv_store_get(key_ptr: u32, key_len: u32, out_ptr: u32, out_cap: u32) -> i32;

    #[link_name = "api_kv_store_delete"]
    fn _api_kv_store_delete(key_ptr: u32, key_len: u32) -> i32;

    // ── Navigation ──────────────────────────────────────────────────

    #[link_name = "api_navigate"]
    fn _api_navigate(url_ptr: u32, url_len: u32) -> i32;

    #[link_name = "api_push_state"]
    fn _api_push_state(
        state_ptr: u32,
        state_len: u32,
        title_ptr: u32,
        title_len: u32,
        url_ptr: u32,
        url_len: u32,
    );

    #[link_name = "api_replace_state"]
    fn _api_replace_state(
        state_ptr: u32,
        state_len: u32,
        title_ptr: u32,
        title_len: u32,
        url_ptr: u32,
        url_len: u32,
    );

    #[link_name = "api_get_url"]
    fn _api_get_url(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_get_state"]
    fn _api_get_state(out_ptr: u32, out_cap: u32) -> i32;

    #[link_name = "api_history_length"]
    fn _api_history_length() -> u32;

    #[link_name = "api_history_back"]
    fn _api_history_back() -> i32;

    #[link_name = "api_history_forward"]
    fn _api_history_forward() -> i32;

    // ── Hyperlinks ──────────────────────────────────────────────────

    #[link_name = "api_register_hyperlink"]
    fn _api_register_hyperlink(x: f32, y: f32, w: f32, h: f32, url_ptr: u32, url_len: u32) -> i32;

    #[link_name = "api_clear_hyperlinks"]
    fn _api_clear_hyperlinks();

    // ── Input Polling ────────────────────────────────────────────────

    #[link_name = "api_mouse_position"]
    fn _api_mouse_position() -> u64;

    #[link_name = "api_mouse_button_down"]
    fn _api_mouse_button_down(button: u32) -> u32;

    #[link_name = "api_mouse_button_clicked"]
    fn _api_mouse_button_clicked(button: u32) -> u32;

    #[link_name = "api_key_down"]
    fn _api_key_down(key: u32) -> u32;

    #[link_name = "api_key_pressed"]
    fn _api_key_pressed(key: u32) -> u32;

    #[link_name = "api_scroll_delta"]
    fn _api_scroll_delta() -> u64;

    #[link_name = "api_modifiers"]
    fn _api_modifiers() -> u32;

    // ── Interactive Widgets ─────────────────────────────────────────

    #[link_name = "api_ui_button"]
    fn _api_ui_button(
        id: u32,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
        label_ptr: u32,
        label_len: u32,
    ) -> u32;

    #[link_name = "api_ui_checkbox"]
    fn _api_ui_checkbox(
        id: u32,
        x: f32,
        y: f32,
        label_ptr: u32,
        label_len: u32,
        initial: u32,
    ) -> u32;

    #[link_name = "api_ui_slider"]
    fn _api_ui_slider(id: u32, x: f32, y: f32, w: f32, min: f32, max: f32, initial: f32) -> f32;

    #[link_name = "api_ui_text_input"]
    fn _api_ui_text_input(
        id: u32,
        x: f32,
        y: f32,
        w: f32,
        init_ptr: u32,
        init_len: u32,
        out_ptr: u32,
        out_cap: u32,
    ) -> u32;

    // ── Audio Playback ──────────────────────────────────────────────

    #[link_name = "api_audio_play"]
    fn _api_audio_play(data_ptr: u32, data_len: u32) -> i32;

    #[link_name = "api_audio_play_url"]
    fn _api_audio_play_url(url_ptr: u32, url_len: u32) -> i32;

    #[link_name = "api_audio_detect_format"]
    fn _api_audio_detect_format(data_ptr: u32, data_len: u32) -> u32;

    #[link_name = "api_audio_play_with_format"]
    fn _api_audio_play_with_format(data_ptr: u32, data_len: u32, format_hint: u32) -> i32;

    #[link_name = "api_audio_last_url_content_type"]
    fn _api_audio_last_url_content_type(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_audio_pause"]
    fn _api_audio_pause();

    #[link_name = "api_audio_resume"]
    fn _api_audio_resume();

    #[link_name = "api_audio_stop"]
    fn _api_audio_stop();

    #[link_name = "api_audio_set_volume"]
    fn _api_audio_set_volume(level: f32);

    #[link_name = "api_audio_get_volume"]
    fn _api_audio_get_volume() -> f32;

    #[link_name = "api_audio_is_playing"]
    fn _api_audio_is_playing() -> u32;

    #[link_name = "api_audio_position"]
    fn _api_audio_position() -> u64;

    #[link_name = "api_audio_seek"]
    fn _api_audio_seek(position_ms: u64) -> i32;

    #[link_name = "api_audio_duration"]
    fn _api_audio_duration() -> u64;

    #[link_name = "api_audio_set_loop"]
    fn _api_audio_set_loop(enabled: u32);

    #[link_name = "api_audio_channel_play"]
    fn _api_audio_channel_play(channel: u32, data_ptr: u32, data_len: u32) -> i32;

    #[link_name = "api_audio_channel_play_with_format"]
    fn _api_audio_channel_play_with_format(
        channel: u32,
        data_ptr: u32,
        data_len: u32,
        format_hint: u32,
    ) -> i32;

    #[link_name = "api_audio_channel_stop"]
    fn _api_audio_channel_stop(channel: u32);

    #[link_name = "api_audio_channel_set_volume"]
    fn _api_audio_channel_set_volume(channel: u32, level: f32);

    // ── Video ─────────────────────────────────────────────────────────

    #[link_name = "api_video_detect_format"]
    fn _api_video_detect_format(data_ptr: u32, data_len: u32) -> u32;

    #[link_name = "api_video_load"]
    fn _api_video_load(data_ptr: u32, data_len: u32, format_hint: u32) -> i32;

    #[link_name = "api_video_load_url"]
    fn _api_video_load_url(url_ptr: u32, url_len: u32) -> i32;

    #[link_name = "api_video_last_url_content_type"]
    fn _api_video_last_url_content_type(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_video_hls_variant_count"]
    fn _api_video_hls_variant_count() -> u32;

    #[link_name = "api_video_hls_variant_url"]
    fn _api_video_hls_variant_url(index: u32, out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_video_hls_open_variant"]
    fn _api_video_hls_open_variant(index: u32) -> i32;

    #[link_name = "api_video_play"]
    fn _api_video_play();

    #[link_name = "api_video_pause"]
    fn _api_video_pause();

    #[link_name = "api_video_stop"]
    fn _api_video_stop();

    #[link_name = "api_video_seek"]
    fn _api_video_seek(position_ms: u64) -> i32;

    #[link_name = "api_video_position"]
    fn _api_video_position() -> u64;

    #[link_name = "api_video_duration"]
    fn _api_video_duration() -> u64;

    #[link_name = "api_video_render"]
    fn _api_video_render(x: f32, y: f32, w: f32, h: f32) -> i32;

    #[link_name = "api_video_set_volume"]
    fn _api_video_set_volume(level: f32);

    #[link_name = "api_video_get_volume"]
    fn _api_video_get_volume() -> f32;

    #[link_name = "api_video_set_loop"]
    fn _api_video_set_loop(enabled: u32);

    #[link_name = "api_video_set_pip"]
    fn _api_video_set_pip(enabled: u32);

    #[link_name = "api_subtitle_load_srt"]
    fn _api_subtitle_load_srt(ptr: u32, len: u32) -> i32;

    #[link_name = "api_subtitle_load_vtt"]
    fn _api_subtitle_load_vtt(ptr: u32, len: u32) -> i32;

    #[link_name = "api_subtitle_clear"]
    fn _api_subtitle_clear();

    // ── Media capture ─────────────────────────────────────────────────

    #[link_name = "api_camera_open"]
    fn _api_camera_open() -> i32;

    #[link_name = "api_camera_close"]
    fn _api_camera_close();

    #[link_name = "api_camera_capture_frame"]
    fn _api_camera_capture_frame(out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_camera_frame_dimensions"]
    fn _api_camera_frame_dimensions() -> u64;

    #[link_name = "api_microphone_open"]
    fn _api_microphone_open() -> i32;

    #[link_name = "api_microphone_close"]
    fn _api_microphone_close();

    #[link_name = "api_microphone_sample_rate"]
    fn _api_microphone_sample_rate() -> u32;

    #[link_name = "api_microphone_read_samples"]
    fn _api_microphone_read_samples(out_ptr: u32, max_samples: u32) -> u32;

    #[link_name = "api_screen_capture"]
    fn _api_screen_capture(out_ptr: u32, out_cap: u32) -> i32;

    #[link_name = "api_screen_capture_dimensions"]
    fn _api_screen_capture_dimensions() -> u64;

    #[link_name = "api_media_pipeline_stats"]
    fn _api_media_pipeline_stats() -> u64;

    // ── URL Utilities ───────────────────────────────────────────────

    #[link_name = "api_url_resolve"]
    fn _api_url_resolve(
        base_ptr: u32,
        base_len: u32,
        rel_ptr: u32,
        rel_len: u32,
        out_ptr: u32,
        out_cap: u32,
    ) -> i32;

    #[link_name = "api_url_encode"]
    fn _api_url_encode(input_ptr: u32, input_len: u32, out_ptr: u32, out_cap: u32) -> u32;

    #[link_name = "api_url_decode"]
    fn _api_url_decode(input_ptr: u32, input_len: u32, out_ptr: u32, out_cap: u32) -> u32;
}

// ─── Console API ────────────────────────────────────────────────────────────

/// Print a message to the browser console (log level).
pub fn log(msg: &str) {
    unsafe { _api_log(msg.as_ptr() as u32, msg.len() as u32) }
}

/// Print a warning to the browser console.
pub fn warn(msg: &str) {
    unsafe { _api_warn(msg.as_ptr() as u32, msg.len() as u32) }
}

/// Print an error to the browser console.
pub fn error(msg: &str) {
    unsafe { _api_error(msg.as_ptr() as u32, msg.len() as u32) }
}

// ─── Geolocation API ────────────────────────────────────────────────────────

/// Get the device's mock geolocation as a `"lat,lon"` string.
pub fn get_location() -> String {
    let mut buf = [0u8; 128];
    let len = unsafe { _api_get_location(buf.as_mut_ptr() as u32, buf.len() as u32) };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

// ─── File Upload API ────────────────────────────────────────────────────────

/// File returned from the native file picker.
pub struct UploadedFile {
    pub name: String,
    pub data: Vec<u8>,
}

/// Opens the native OS file picker and returns the selected file.
/// Returns `None` if the user cancels.
pub fn upload_file() -> Option<UploadedFile> {
    let mut name_buf = [0u8; 256];
    let mut data_buf = vec![0u8; 1024 * 1024]; // 1MB max

    let result = unsafe {
        _api_upload_file(
            name_buf.as_mut_ptr() as u32,
            name_buf.len() as u32,
            data_buf.as_mut_ptr() as u32,
            data_buf.len() as u32,
        )
    };

    if result == 0 {
        return None;
    }

    let name_len = (result >> 32) as usize;
    let data_len = (result & 0xFFFF_FFFF) as usize;

    Some(UploadedFile {
        name: String::from_utf8_lossy(&name_buf[..name_len]).to_string(),
        data: data_buf[..data_len].to_vec(),
    })
}

// ─── Canvas API ─────────────────────────────────────────────────────────────

/// Clear the canvas with a solid RGBA color.
pub fn canvas_clear(r: u8, g: u8, b: u8, a: u8) {
    unsafe { _api_canvas_clear(r as u32, g as u32, b as u32, a as u32) }
}

/// Draw a filled rectangle.
pub fn canvas_rect(x: f32, y: f32, w: f32, h: f32, r: u8, g: u8, b: u8, a: u8) {
    unsafe { _api_canvas_rect(x, y, w, h, r as u32, g as u32, b as u32, a as u32) }
}

/// Draw a filled circle.
pub fn canvas_circle(cx: f32, cy: f32, radius: f32, r: u8, g: u8, b: u8, a: u8) {
    unsafe { _api_canvas_circle(cx, cy, radius, r as u32, g as u32, b as u32, a as u32) }
}

/// Draw text on the canvas.
pub fn canvas_text(x: f32, y: f32, size: f32, r: u8, g: u8, b: u8, text: &str) {
    unsafe {
        _api_canvas_text(
            x,
            y,
            size,
            r as u32,
            g as u32,
            b as u32,
            text.as_ptr() as u32,
            text.len() as u32,
        )
    }
}

/// Draw a line between two points.
pub fn canvas_line(x1: f32, y1: f32, x2: f32, y2: f32, r: u8, g: u8, b: u8, thickness: f32) {
    unsafe { _api_canvas_line(x1, y1, x2, y2, r as u32, g as u32, b as u32, thickness) }
}

/// Returns `(width, height)` of the canvas in pixels.
pub fn canvas_dimensions() -> (u32, u32) {
    let packed = unsafe { _api_canvas_dimensions() };
    ((packed >> 32) as u32, (packed & 0xFFFF_FFFF) as u32)
}

/// Draw an image on the canvas from encoded image bytes (PNG, JPEG, GIF, WebP).
/// The browser decodes the image and renders it at the given rectangle.
pub fn canvas_image(x: f32, y: f32, w: f32, h: f32, data: &[u8]) {
    unsafe { _api_canvas_image(x, y, w, h, data.as_ptr() as u32, data.len() as u32) }
}

// ─── Local Storage API ──────────────────────────────────────────────────────

/// Store a key-value pair in sandboxed local storage.
pub fn storage_set(key: &str, value: &str) {
    unsafe {
        _api_storage_set(
            key.as_ptr() as u32,
            key.len() as u32,
            value.as_ptr() as u32,
            value.len() as u32,
        )
    }
}

/// Retrieve a value from local storage. Returns empty string if not found.
pub fn storage_get(key: &str) -> String {
    let mut buf = [0u8; 4096];
    let len = unsafe {
        _api_storage_get(
            key.as_ptr() as u32,
            key.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

/// Remove a key from local storage.
pub fn storage_remove(key: &str) {
    unsafe { _api_storage_remove(key.as_ptr() as u32, key.len() as u32) }
}

// ─── Clipboard API ──────────────────────────────────────────────────────────

/// Copy text to the system clipboard.
pub fn clipboard_write(text: &str) {
    unsafe { _api_clipboard_write(text.as_ptr() as u32, text.len() as u32) }
}

/// Read text from the system clipboard.
pub fn clipboard_read() -> String {
    let mut buf = [0u8; 4096];
    let len = unsafe { _api_clipboard_read(buf.as_mut_ptr() as u32, buf.len() as u32) };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

// ─── Timer / Clock API ─────────────────────────────────────────────────────

/// Get the current time in milliseconds since the UNIX epoch.
pub fn time_now_ms() -> u64 {
    unsafe { _api_time_now_ms() }
}

/// Schedule a one-shot timer that fires after `delay_ms` milliseconds.
/// When it fires the host calls your exported `on_timer(callback_id)`.
/// Returns a timer ID that can be passed to [`clear_timer`].
pub fn set_timeout(callback_id: u32, delay_ms: u32) -> u32 {
    unsafe { _api_set_timeout(callback_id, delay_ms) }
}

/// Schedule a repeating timer that fires every `interval_ms` milliseconds.
/// When it fires the host calls your exported `on_timer(callback_id)`.
/// Returns a timer ID that can be passed to [`clear_timer`].
pub fn set_interval(callback_id: u32, interval_ms: u32) -> u32 {
    unsafe { _api_set_interval(callback_id, interval_ms) }
}

/// Cancel a timer previously created with [`set_timeout`] or [`set_interval`].
pub fn clear_timer(timer_id: u32) {
    unsafe { _api_clear_timer(timer_id) }
}

// ─── Random API ─────────────────────────────────────────────────────────────

/// Get a random u64 from the host.
pub fn random_u64() -> u64 {
    unsafe { _api_random() }
}

/// Get a random f64 in [0, 1).
pub fn random_f64() -> f64 {
    (random_u64() >> 11) as f64 / (1u64 << 53) as f64
}

// ─── Notification API ───────────────────────────────────────────────────────

/// Send a notification to the user (rendered in the browser console).
pub fn notify(title: &str, body: &str) {
    unsafe {
        _api_notify(
            title.as_ptr() as u32,
            title.len() as u32,
            body.as_ptr() as u32,
            body.len() as u32,
        )
    }
}

// ─── Audio Playback API ─────────────────────────────────────────────────────

/// Detected or hinted audio container (host codes: 0 unknown, 1 WAV, 2 MP3, 3 Ogg, 4 FLAC).
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioFormat {
    /// Could not classify from bytes (try decode anyway).
    Unknown = 0,
    Wav = 1,
    Mp3 = 2,
    Ogg = 3,
    Flac = 4,
}

impl From<u32> for AudioFormat {
    fn from(code: u32) -> Self {
        match code {
            1 => AudioFormat::Wav,
            2 => AudioFormat::Mp3,
            3 => AudioFormat::Ogg,
            4 => AudioFormat::Flac,
            _ => AudioFormat::Unknown,
        }
    }
}

impl From<AudioFormat> for u32 {
    fn from(f: AudioFormat) -> u32 {
        f as u32
    }
}

/// Play audio from encoded bytes (WAV, MP3, OGG, FLAC).
/// The host decodes and plays the audio. Returns 0 on success, negative on error.
pub fn audio_play(data: &[u8]) -> i32 {
    unsafe { _api_audio_play(data.as_ptr() as u32, data.len() as u32) }
}

/// Sniff the container/codec from raw bytes (magic bytes / MP3 sync). Does not decode audio.
pub fn audio_detect_format(data: &[u8]) -> AudioFormat {
    let code = unsafe { _api_audio_detect_format(data.as_ptr() as u32, data.len() as u32) };
    AudioFormat::from(code)
}

/// Play with an optional format hint (`AudioFormat::Unknown` = same as [`audio_play`]).
/// If the hint disagrees with what the host sniffs from the bytes, the host logs a warning but still decodes.
pub fn audio_play_with_format(data: &[u8], format: AudioFormat) -> i32 {
    unsafe {
        _api_audio_play_with_format(data.as_ptr() as u32, data.len() as u32, u32::from(format))
    }
}

/// Fetch audio from a URL and play it.
/// The host sends an `Accept` header listing supported codecs, records the response `Content-Type`,
/// and rejects obvious HTML/JSON error bodies when no audio signature is found (`-4`).
/// Returns 0 on success, negative on error.
pub fn audio_play_url(url: &str) -> i32 {
    unsafe { _api_audio_play_url(url.as_ptr() as u32, url.len() as u32) }
}

/// `Content-Type` header from the last successful [`audio_play_url`] response (may be empty).
pub fn audio_last_url_content_type() -> String {
    let mut buf = [0u8; 512];
    let len =
        unsafe { _api_audio_last_url_content_type(buf.as_mut_ptr() as u32, buf.len() as u32) };
    let n = (len as usize).min(buf.len());
    String::from_utf8_lossy(&buf[..n]).to_string()
}

/// Pause audio playback.
pub fn audio_pause() {
    unsafe { _api_audio_pause() }
}

/// Resume paused audio playback.
pub fn audio_resume() {
    unsafe { _api_audio_resume() }
}

/// Stop audio playback and clear the queue.
pub fn audio_stop() {
    unsafe { _api_audio_stop() }
}

/// Set audio volume. 1.0 is normal, 0.0 is silent, up to 2.0 for boost.
pub fn audio_set_volume(level: f32) {
    unsafe { _api_audio_set_volume(level) }
}

/// Get the current audio volume.
pub fn audio_get_volume() -> f32 {
    unsafe { _api_audio_get_volume() }
}

/// Returns `true` if audio is currently playing (not paused and not empty).
pub fn audio_is_playing() -> bool {
    unsafe { _api_audio_is_playing() != 0 }
}

/// Get the current playback position in milliseconds.
pub fn audio_position() -> u64 {
    unsafe { _api_audio_position() }
}

/// Seek to a position in milliseconds. Returns 0 on success, negative on error.
pub fn audio_seek(position_ms: u64) -> i32 {
    unsafe { _api_audio_seek(position_ms) }
}

/// Get the total duration of the currently loaded track in milliseconds.
/// Returns 0 if unknown or nothing is loaded.
pub fn audio_duration() -> u64 {
    unsafe { _api_audio_duration() }
}

/// Enable or disable looping on the default channel.
/// When enabled, subsequent `audio_play` calls will loop indefinitely.
pub fn audio_set_loop(enabled: bool) {
    unsafe { _api_audio_set_loop(if enabled { 1 } else { 0 }) }
}

// ─── Multi-Channel Audio API ────────────────────────────────────────────────

/// Play audio on a specific channel. Multiple channels play simultaneously.
/// Channel 0 is the default used by `audio_play`. Use channels 1+ for layered
/// sound effects, background music, etc.
pub fn audio_channel_play(channel: u32, data: &[u8]) -> i32 {
    unsafe { _api_audio_channel_play(channel, data.as_ptr() as u32, data.len() as u32) }
}

/// Like [`audio_channel_play`] with an optional [`AudioFormat`] hint.
pub fn audio_channel_play_with_format(channel: u32, data: &[u8], format: AudioFormat) -> i32 {
    unsafe {
        _api_audio_channel_play_with_format(
            channel,
            data.as_ptr() as u32,
            data.len() as u32,
            u32::from(format),
        )
    }
}

/// Stop playback on a specific channel.
pub fn audio_channel_stop(channel: u32) {
    unsafe { _api_audio_channel_stop(channel) }
}

/// Set volume for a specific channel (0.0 silent, 1.0 normal, up to 2.0 boost).
pub fn audio_channel_set_volume(channel: u32, level: f32) {
    unsafe { _api_audio_channel_set_volume(channel, level) }
}

// ─── Video API ─────────────────────────────────────────────────────────────

/// Container or hint for [`video_load_with_format`] (host codes: 0 unknown, 1 MP4, 2 WebM, 3 AV1).
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoFormat {
    Unknown = 0,
    Mp4 = 1,
    Webm = 2,
    Av1 = 3,
}

impl From<u32> for VideoFormat {
    fn from(code: u32) -> Self {
        match code {
            1 => VideoFormat::Mp4,
            2 => VideoFormat::Webm,
            3 => VideoFormat::Av1,
            _ => VideoFormat::Unknown,
        }
    }
}

impl From<VideoFormat> for u32 {
    fn from(f: VideoFormat) -> u32 {
        f as u32
    }
}

/// Sniff container from leading bytes (magic only; does not decode).
pub fn video_detect_format(data: &[u8]) -> VideoFormat {
    let code = unsafe { _api_video_detect_format(data.as_ptr() as u32, data.len() as u32) };
    VideoFormat::from(code)
}

/// Load video from encoded bytes (MP4, WebM, etc.). Requires FFmpeg on the host.
/// Returns 0 on success, negative on error.
pub fn video_load(data: &[u8]) -> i32 {
    unsafe {
        _api_video_load(
            data.as_ptr() as u32,
            data.len() as u32,
            VideoFormat::Unknown as u32,
        )
    }
}

/// Load with a [`VideoFormat`] hint (unknown = same as [`video_load`]).
pub fn video_load_with_format(data: &[u8], format: VideoFormat) -> i32 {
    unsafe { _api_video_load(data.as_ptr() as u32, data.len() as u32, u32::from(format)) }
}

/// Open a progressive or adaptive (HLS) URL. The host uses FFmpeg; master playlists may list variants.
pub fn video_load_url(url: &str) -> i32 {
    unsafe { _api_video_load_url(url.as_ptr() as u32, url.len() as u32) }
}

/// `Content-Type` from the last successful [`video_load_url`] (may be empty).
pub fn video_last_url_content_type() -> String {
    let mut buf = [0u8; 512];
    let len =
        unsafe { _api_video_last_url_content_type(buf.as_mut_ptr() as u32, buf.len() as u32) };
    let n = (len as usize).min(buf.len());
    String::from_utf8_lossy(&buf[..n]).to_string()
}

/// Number of variant stream URIs parsed from the last HLS master playlist (0 if not a master).
pub fn video_hls_variant_count() -> u32 {
    unsafe { _api_video_hls_variant_count() }
}

/// Resolved variant URL for `index`, written into `buf`-style API (use fixed buffer).
pub fn video_hls_variant_url(index: u32) -> String {
    let mut buf = [0u8; 2048];
    let len =
        unsafe { _api_video_hls_variant_url(index, buf.as_mut_ptr() as u32, buf.len() as u32) };
    let n = (len as usize).min(buf.len());
    String::from_utf8_lossy(&buf[..n]).to_string()
}

/// Open a variant playlist by index (after loading a master with [`video_load_url`]).
pub fn video_hls_open_variant(index: u32) -> i32 {
    unsafe { _api_video_hls_open_variant(index) }
}

pub fn video_play() {
    unsafe { _api_video_play() }
}

pub fn video_pause() {
    unsafe { _api_video_pause() }
}

pub fn video_stop() {
    unsafe { _api_video_stop() }
}

pub fn video_seek(position_ms: u64) -> i32 {
    unsafe { _api_video_seek(position_ms) }
}

pub fn video_position() -> u64 {
    unsafe { _api_video_position() }
}

pub fn video_duration() -> u64 {
    unsafe { _api_video_duration() }
}

/// Draw the current video frame into the given rectangle (same coordinate space as canvas).
pub fn video_render(x: f32, y: f32, w: f32, h: f32) -> i32 {
    unsafe { _api_video_render(x, y, w, h) }
}

/// Volume multiplier for the video track (0.0–2.0; embedded audio mixing may follow in future hosts).
pub fn video_set_volume(level: f32) {
    unsafe { _api_video_set_volume(level) }
}

pub fn video_get_volume() -> f32 {
    unsafe { _api_video_get_volume() }
}

pub fn video_set_loop(enabled: bool) {
    unsafe { _api_video_set_loop(if enabled { 1 } else { 0 }) }
}

/// Floating picture-in-picture preview (host mirrors the last rendered frame).
pub fn video_set_pip(enabled: bool) {
    unsafe { _api_video_set_pip(if enabled { 1 } else { 0 }) }
}

/// Load SubRip subtitles (cues rendered on [`video_render`]).
pub fn subtitle_load_srt(text: &str) -> i32 {
    unsafe { _api_subtitle_load_srt(text.as_ptr() as u32, text.len() as u32) }
}

/// Load WebVTT subtitles.
pub fn subtitle_load_vtt(text: &str) -> i32 {
    unsafe { _api_subtitle_load_vtt(text.as_ptr() as u32, text.len() as u32) }
}

pub fn subtitle_clear() {
    unsafe { _api_subtitle_clear() }
}

// ─── Media capture API ─────────────────────────────────────────────────────

/// Opens the default camera after a host permission dialog.
///
/// Returns `0` on success. Negative codes: `-1` user denied, `-2` no camera, `-3` open failed.
pub fn camera_open() -> i32 {
    unsafe { _api_camera_open() }
}

/// Stops the camera stream opened by [`camera_open`].
pub fn camera_close() {
    unsafe { _api_camera_close() }
}

/// Captures one RGBA8 frame into `out`. Returns the number of bytes written (`0` if the camera
/// is not open or capture failed). Query [`camera_frame_dimensions`] after a successful write.
pub fn camera_capture_frame(out: &mut [u8]) -> u32 {
    unsafe { _api_camera_capture_frame(out.as_mut_ptr() as u32, out.len() as u32) }
}

/// Width and height in pixels of the last [`camera_capture_frame`] buffer.
pub fn camera_frame_dimensions() -> (u32, u32) {
    let packed = unsafe { _api_camera_frame_dimensions() };
    let w = (packed >> 32) as u32;
    let h = packed as u32;
    (w, h)
}

/// Starts microphone capture (mono `f32` ring buffer) after a host permission dialog.
///
/// Returns `0` on success. Negative codes: `-1` denied, `-2` no input device, `-3` stream error.
pub fn microphone_open() -> i32 {
    unsafe { _api_microphone_open() }
}

pub fn microphone_close() {
    unsafe { _api_microphone_close() }
}

/// Sample rate of the opened input stream in Hz (`0` if the microphone is not open).
pub fn microphone_sample_rate() -> u32 {
    unsafe { _api_microphone_sample_rate() }
}

/// Dequeues up to `out.len()` mono `f32` samples from the microphone ring buffer.
/// Returns how many samples were written.
pub fn microphone_read_samples(out: &mut [f32]) -> u32 {
    unsafe { _api_microphone_read_samples(out.as_mut_ptr() as u32, out.len() as u32) }
}

/// Captures the primary display as RGBA8 after permission dialogs (OS may prompt separately).
///
/// Returns `Ok(bytes_written)` or an error code: `-1` denied, `-2` no display, `-3` capture failed, `-4` buffer error.
pub fn screen_capture(out: &mut [u8]) -> Result<usize, i32> {
    let n = unsafe { _api_screen_capture(out.as_mut_ptr() as u32, out.len() as u32) };
    if n >= 0 {
        Ok(n as usize)
    } else {
        Err(n)
    }
}

/// Width and height of the last [`screen_capture`] image.
pub fn screen_capture_dimensions() -> (u32, u32) {
    let packed = unsafe { _api_screen_capture_dimensions() };
    let w = (packed >> 32) as u32;
    let h = packed as u32;
    (w, h)
}

/// Host-side pipeline counters: total camera frames captured (high 32 bits) and current microphone
/// ring depth in samples (low 32 bits).
pub fn media_pipeline_stats() -> (u64, u32) {
    let packed = unsafe { _api_media_pipeline_stats() };
    let camera_frames = packed >> 32;
    let mic_ring = packed as u32;
    (camera_frames, mic_ring)
}

// ─── HTTP Fetch API ─────────────────────────────────────────────────────────

/// Response from an HTTP fetch call.
pub struct FetchResponse {
    pub status: u32,
    pub body: Vec<u8>,
}

impl FetchResponse {
    /// Interpret the response body as UTF-8 text.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).to_string()
    }
}

/// Perform an HTTP request.  Returns the status code and response body.
///
/// `content_type` sets the `Content-Type` header (pass `""` to omit).
/// Protobuf is the native format — use `"application/protobuf"` for binary
/// payloads.
pub fn fetch(
    method: &str,
    url: &str,
    content_type: &str,
    body: &[u8],
) -> Result<FetchResponse, i64> {
    let mut out_buf = vec![0u8; 4 * 1024 * 1024]; // 4 MB response buffer
    let result = unsafe {
        _api_fetch(
            method.as_ptr() as u32,
            method.len() as u32,
            url.as_ptr() as u32,
            url.len() as u32,
            content_type.as_ptr() as u32,
            content_type.len() as u32,
            body.as_ptr() as u32,
            body.len() as u32,
            out_buf.as_mut_ptr() as u32,
            out_buf.len() as u32,
        )
    };
    if result < 0 {
        return Err(result);
    }
    let status = (result >> 32) as u32;
    let body_len = (result & 0xFFFF_FFFF) as usize;
    Ok(FetchResponse {
        status,
        body: out_buf[..body_len].to_vec(),
    })
}

/// HTTP GET request.
pub fn fetch_get(url: &str) -> Result<FetchResponse, i64> {
    fetch("GET", url, "", &[])
}

/// HTTP POST with raw bytes.
pub fn fetch_post(url: &str, content_type: &str, body: &[u8]) -> Result<FetchResponse, i64> {
    fetch("POST", url, content_type, body)
}

/// HTTP POST with protobuf body (sets `Content-Type: application/protobuf`).
pub fn fetch_post_proto(url: &str, msg: &proto::ProtoEncoder) -> Result<FetchResponse, i64> {
    fetch("POST", url, "application/protobuf", msg.as_bytes())
}

/// HTTP PUT with raw bytes.
pub fn fetch_put(url: &str, content_type: &str, body: &[u8]) -> Result<FetchResponse, i64> {
    fetch("PUT", url, content_type, body)
}

/// HTTP DELETE.
pub fn fetch_delete(url: &str) -> Result<FetchResponse, i64> {
    fetch("DELETE", url, "", &[])
}

// ─── Dynamic Module Loading ─────────────────────────────────────────────────

/// Fetch and execute another `.wasm` module from a URL.
/// The loaded module shares the same canvas, console, and storage context.
/// Returns 0 on success, negative error code on failure.
pub fn load_module(url: &str) -> i32 {
    unsafe { _api_load_module(url.as_ptr() as u32, url.len() as u32) }
}

// ─── Crypto / Hash API ─────────────────────────────────────────────────────

/// Compute the SHA-256 hash of the given data. Returns 32 bytes.
pub fn hash_sha256(data: &[u8]) -> [u8; 32] {
    let mut out = [0u8; 32];
    unsafe {
        _api_hash_sha256(
            data.as_ptr() as u32,
            data.len() as u32,
            out.as_mut_ptr() as u32,
        );
    }
    out
}

/// Return SHA-256 hash as a lowercase hex string.
pub fn hash_sha256_hex(data: &[u8]) -> String {
    let hash = hash_sha256(data);
    let mut hex = String::with_capacity(64);
    for byte in &hash {
        hex.push(HEX_CHARS[(*byte >> 4) as usize]);
        hex.push(HEX_CHARS[(*byte & 0x0F) as usize]);
    }
    hex
}

const HEX_CHARS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];

// ─── Base64 API ─────────────────────────────────────────────────────────────

/// Base64-encode arbitrary bytes.
pub fn base64_encode(data: &[u8]) -> String {
    let mut buf = vec![0u8; data.len() * 4 / 3 + 8];
    let len = unsafe {
        _api_base64_encode(
            data.as_ptr() as u32,
            data.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

/// Decode a base64-encoded string back to bytes.
pub fn base64_decode(encoded: &str) -> Vec<u8> {
    let mut buf = vec![0u8; encoded.len()];
    let len = unsafe {
        _api_base64_decode(
            encoded.as_ptr() as u32,
            encoded.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    buf[..len as usize].to_vec()
}

// ─── Persistent Key-Value Store API ─────────────────────────────────────────

/// Store a key-value pair in the persistent on-disk KV store.
/// Returns `true` on success.
pub fn kv_store_set(key: &str, value: &[u8]) -> bool {
    let rc = unsafe {
        _api_kv_store_set(
            key.as_ptr() as u32,
            key.len() as u32,
            value.as_ptr() as u32,
            value.len() as u32,
        )
    };
    rc == 0
}

/// Convenience wrapper: store a UTF-8 string value.
pub fn kv_store_set_str(key: &str, value: &str) -> bool {
    kv_store_set(key, value.as_bytes())
}

/// Retrieve a value from the persistent KV store.
/// Returns `None` if the key does not exist.
pub fn kv_store_get(key: &str) -> Option<Vec<u8>> {
    let mut buf = vec![0u8; 64 * 1024]; // 64 KB read buffer
    let rc = unsafe {
        _api_kv_store_get(
            key.as_ptr() as u32,
            key.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    if rc < 0 {
        return None;
    }
    Some(buf[..rc as usize].to_vec())
}

/// Convenience wrapper: retrieve a UTF-8 string value.
pub fn kv_store_get_str(key: &str) -> Option<String> {
    kv_store_get(key).map(|v| String::from_utf8_lossy(&v).into_owned())
}

/// Delete a key from the persistent KV store. Returns `true` on success.
pub fn kv_store_delete(key: &str) -> bool {
    let rc = unsafe { _api_kv_store_delete(key.as_ptr() as u32, key.len() as u32) };
    rc == 0
}

// ─── Navigation API ─────────────────────────────────────────────────────────

/// Navigate to a new URL.  The URL can be absolute or relative to the current
/// page.  Navigation happens asynchronously after the current `start_app`
/// returns.  Returns 0 on success, negative on invalid URL.
pub fn navigate(url: &str) -> i32 {
    unsafe { _api_navigate(url.as_ptr() as u32, url.len() as u32) }
}

/// Push a new entry onto the browser's history stack without triggering a
/// module reload.  This is analogous to `history.pushState()` in web browsers.
///
/// - `state`:  Opaque binary data retrievable later via [`get_state`].
/// - `title`:  Human-readable title for the history entry.
/// - `url`:    The URL to display in the address bar (relative or absolute).
///             Pass `""` to keep the current URL.
pub fn push_state(state: &[u8], title: &str, url: &str) {
    unsafe {
        _api_push_state(
            state.as_ptr() as u32,
            state.len() as u32,
            title.as_ptr() as u32,
            title.len() as u32,
            url.as_ptr() as u32,
            url.len() as u32,
        )
    }
}

/// Replace the current history entry (no new entry is pushed).
/// Analogous to `history.replaceState()`.
pub fn replace_state(state: &[u8], title: &str, url: &str) {
    unsafe {
        _api_replace_state(
            state.as_ptr() as u32,
            state.len() as u32,
            title.as_ptr() as u32,
            title.len() as u32,
            url.as_ptr() as u32,
            url.len() as u32,
        )
    }
}

/// Get the URL of the currently loaded page.
pub fn get_url() -> String {
    let mut buf = [0u8; 4096];
    let len = unsafe { _api_get_url(buf.as_mut_ptr() as u32, buf.len() as u32) };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

/// Retrieve the opaque state bytes attached to the current history entry.
/// Returns `None` if no state has been set.
pub fn get_state() -> Option<Vec<u8>> {
    let mut buf = vec![0u8; 64 * 1024]; // 64 KB
    let rc = unsafe { _api_get_state(buf.as_mut_ptr() as u32, buf.len() as u32) };
    if rc < 0 {
        return None;
    }
    Some(buf[..rc as usize].to_vec())
}

/// Return the total number of entries in the history stack.
pub fn history_length() -> u32 {
    unsafe { _api_history_length() }
}

/// Navigate backward in history.  Returns `true` if a navigation was queued.
pub fn history_back() -> bool {
    unsafe { _api_history_back() == 1 }
}

/// Navigate forward in history.  Returns `true` if a navigation was queued.
pub fn history_forward() -> bool {
    unsafe { _api_history_forward() == 1 }
}

// ─── Hyperlink API ──────────────────────────────────────────────────────────

/// Register a rectangular region on the canvas as a clickable hyperlink.
///
/// When the user clicks inside the rectangle the browser navigates to `url`.
/// Coordinates are in the same canvas-local space used by the drawing APIs.
/// Returns 0 on success.
pub fn register_hyperlink(x: f32, y: f32, w: f32, h: f32, url: &str) -> i32 {
    unsafe { _api_register_hyperlink(x, y, w, h, url.as_ptr() as u32, url.len() as u32) }
}

/// Remove all previously registered hyperlinks.
pub fn clear_hyperlinks() {
    unsafe { _api_clear_hyperlinks() }
}

// ─── URL Utility API ────────────────────────────────────────────────────────

/// Resolve a relative URL against a base URL (WHATWG algorithm).
/// Returns `None` if either URL is invalid.
pub fn url_resolve(base: &str, relative: &str) -> Option<String> {
    let mut buf = [0u8; 4096];
    let rc = unsafe {
        _api_url_resolve(
            base.as_ptr() as u32,
            base.len() as u32,
            relative.as_ptr() as u32,
            relative.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    if rc < 0 {
        return None;
    }
    Some(String::from_utf8_lossy(&buf[..rc as usize]).to_string())
}

/// Percent-encode a string for safe inclusion in URL components.
pub fn url_encode(input: &str) -> String {
    let mut buf = vec![0u8; input.len() * 3 + 4];
    let len = unsafe {
        _api_url_encode(
            input.as_ptr() as u32,
            input.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

/// Decode a percent-encoded string.
pub fn url_decode(input: &str) -> String {
    let mut buf = vec![0u8; input.len() + 4];
    let len = unsafe {
        _api_url_decode(
            input.as_ptr() as u32,
            input.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}

// ─── Input Polling API ──────────────────────────────────────────────────────

/// Get the mouse position in canvas-local coordinates.
pub fn mouse_position() -> (f32, f32) {
    let packed = unsafe { _api_mouse_position() };
    let x = f32::from_bits((packed >> 32) as u32);
    let y = f32::from_bits((packed & 0xFFFF_FFFF) as u32);
    (x, y)
}

/// Returns `true` if the given mouse button is currently held down.
/// Button 0 = primary (left), 1 = secondary (right), 2 = middle.
pub fn mouse_button_down(button: u32) -> bool {
    unsafe { _api_mouse_button_down(button) != 0 }
}

/// Returns `true` if the given mouse button was clicked this frame.
pub fn mouse_button_clicked(button: u32) -> bool {
    unsafe { _api_mouse_button_clicked(button) != 0 }
}

/// Returns `true` if the given key is currently held down.
/// See `KEY_*` constants for key codes.
pub fn key_down(key: u32) -> bool {
    unsafe { _api_key_down(key) != 0 }
}

/// Returns `true` if the given key was pressed this frame.
pub fn key_pressed(key: u32) -> bool {
    unsafe { _api_key_pressed(key) != 0 }
}

/// Get the scroll wheel delta for this frame.
pub fn scroll_delta() -> (f32, f32) {
    let packed = unsafe { _api_scroll_delta() };
    let x = f32::from_bits((packed >> 32) as u32);
    let y = f32::from_bits((packed & 0xFFFF_FFFF) as u32);
    (x, y)
}

/// Returns modifier key state as a bitmask: bit 0 = Shift, bit 1 = Ctrl, bit 2 = Alt.
pub fn modifiers() -> u32 {
    unsafe { _api_modifiers() }
}

/// Returns `true` if Shift is held.
pub fn shift_held() -> bool {
    modifiers() & 1 != 0
}

/// Returns `true` if Ctrl (or Cmd on macOS) is held.
pub fn ctrl_held() -> bool {
    modifiers() & 2 != 0
}

/// Returns `true` if Alt is held.
pub fn alt_held() -> bool {
    modifiers() & 4 != 0
}

// ─── Key Constants ──────────────────────────────────────────────────────────

pub const KEY_A: u32 = 0;
pub const KEY_B: u32 = 1;
pub const KEY_C: u32 = 2;
pub const KEY_D: u32 = 3;
pub const KEY_E: u32 = 4;
pub const KEY_F: u32 = 5;
pub const KEY_G: u32 = 6;
pub const KEY_H: u32 = 7;
pub const KEY_I: u32 = 8;
pub const KEY_J: u32 = 9;
pub const KEY_K: u32 = 10;
pub const KEY_L: u32 = 11;
pub const KEY_M: u32 = 12;
pub const KEY_N: u32 = 13;
pub const KEY_O: u32 = 14;
pub const KEY_P: u32 = 15;
pub const KEY_Q: u32 = 16;
pub const KEY_R: u32 = 17;
pub const KEY_S: u32 = 18;
pub const KEY_T: u32 = 19;
pub const KEY_U: u32 = 20;
pub const KEY_V: u32 = 21;
pub const KEY_W: u32 = 22;
pub const KEY_X: u32 = 23;
pub const KEY_Y: u32 = 24;
pub const KEY_Z: u32 = 25;
pub const KEY_0: u32 = 26;
pub const KEY_1: u32 = 27;
pub const KEY_2: u32 = 28;
pub const KEY_3: u32 = 29;
pub const KEY_4: u32 = 30;
pub const KEY_5: u32 = 31;
pub const KEY_6: u32 = 32;
pub const KEY_7: u32 = 33;
pub const KEY_8: u32 = 34;
pub const KEY_9: u32 = 35;
pub const KEY_ENTER: u32 = 36;
pub const KEY_ESCAPE: u32 = 37;
pub const KEY_TAB: u32 = 38;
pub const KEY_BACKSPACE: u32 = 39;
pub const KEY_DELETE: u32 = 40;
pub const KEY_SPACE: u32 = 41;
pub const KEY_UP: u32 = 42;
pub const KEY_DOWN: u32 = 43;
pub const KEY_LEFT: u32 = 44;
pub const KEY_RIGHT: u32 = 45;
pub const KEY_HOME: u32 = 46;
pub const KEY_END: u32 = 47;
pub const KEY_PAGE_UP: u32 = 48;
pub const KEY_PAGE_DOWN: u32 = 49;

// ─── Interactive Widget API ─────────────────────────────────────────────────

/// Render a button at the given position. Returns `true` if it was clicked
/// on the previous frame.
///
/// Must be called from `on_frame()` — widgets are only rendered for
/// interactive applications that export a frame loop.
pub fn ui_button(id: u32, x: f32, y: f32, w: f32, h: f32, label: &str) -> bool {
    unsafe { _api_ui_button(id, x, y, w, h, label.as_ptr() as u32, label.len() as u32) != 0 }
}

/// Render a checkbox. Returns the current checked state.
///
/// `initial` sets the value the first time this ID is seen.
pub fn ui_checkbox(id: u32, x: f32, y: f32, label: &str, initial: bool) -> bool {
    unsafe {
        _api_ui_checkbox(
            id,
            x,
            y,
            label.as_ptr() as u32,
            label.len() as u32,
            if initial { 1 } else { 0 },
        ) != 0
    }
}

/// Render a slider. Returns the current value.
///
/// `initial` sets the value the first time this ID is seen.
pub fn ui_slider(id: u32, x: f32, y: f32, w: f32, min: f32, max: f32, initial: f32) -> f32 {
    unsafe { _api_ui_slider(id, x, y, w, min, max, initial) }
}

/// Render a single-line text input. Returns the current text content.
///
/// `initial` sets the text the first time this ID is seen.
pub fn ui_text_input(id: u32, x: f32, y: f32, w: f32, initial: &str) -> String {
    let mut buf = [0u8; 4096];
    let len = unsafe {
        _api_ui_text_input(
            id,
            x,
            y,
            w,
            initial.as_ptr() as u32,
            initial.len() as u32,
            buf.as_mut_ptr() as u32,
            buf.len() as u32,
        )
    };
    String::from_utf8_lossy(&buf[..len as usize]).to_string()
}