dotzuki-engine-script 0.1.0

Boa-based async JavaScript scripting runtime for the dotzuki JRPG engine
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
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;

use boa_engine::builtins::promise::PromiseState;
#[cfg(target_arch = "wasm32")]
use boa_engine::module::IdleModuleLoader;
#[cfg(not(target_arch = "wasm32"))]
use boa_engine::module::SimpleModuleLoader;
use boa_engine::object::builtins::{JsFunction, JsPromise};
use boa_engine::property::Attribute;
use boa_engine::{js_string, Context, JsArgs, JsNativeError, JsResult, JsValue, Module, NativeFunction, Source};

use crate::api_registrar::ScriptApiRegistrar;
use crate::command::{CommandResult, ScriptCommand};

#[derive(Debug, thiserror::Error)]
pub enum ScriptEngineError {
    #[error("JS error: {0}")]
    JsError(String),
    #[error("Script not found for map: {0}")]
    ScriptNotFound(String),
    #[error("Function not found: {0}")]
    FunctionNotFound(String),
    #[error("Engine not initialized")]
    NotInitialized,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EngineState {
    Idle,
    Running,
    WaitingForCommand,
    Finished,
}

struct PendingResolve {
    resolve_fn: JsFunction,
}

/// Shared state between the JS runtime and the Rust game loop.
/// Commands issued by JS `await game.showText(...)` are placed here;
/// the game loop reads them, executes the operation, then calls `signal_done`.
pub struct SharedBridge {
    pending_command: Option<ScriptCommand>,
    pending_resolve: Option<PendingResolve>,
    flags: std::collections::HashMap<String, bool>,
    /// Generic, game-agnostic seeded query state read by synchronous JS
    /// query functions (registered via `register_sync_fn`). The core engine
    /// does not know what these keys mean — the game layer seeds them and
    /// registers named query functions that interpret them.
    numbers: std::collections::HashMap<String, f64>,
    texts: std::collections::HashMap<String, String>,
    sets: std::collections::HashMap<String, std::collections::HashSet<String>>,
    player_x: u8,
    player_y: u8,
    pub lang: String,
    /// State for the script-side RNG used by `game.showRandomText(...)` (and any
    /// future `randInt`-style primitives). Game scripts have no `Math.random` /
    /// `Date.now`, so all randomness must originate on the Rust side: the game
    /// layer mixes real entropy in via [`ScriptEngine::mix_rng`], and tests can
    /// pin a deterministic stream via [`ScriptEngine::seed_rng`].
    rng_state: u64,
}

/// Non-zero default seed (a common splitmix64/golden-ratio constant). Keeping the
/// state non-zero matters because xorshift64 is stuck at 0.
const DEFAULT_RNG_SEED: u64 = 0x9E37_79B9_7F4A_7C15;

impl SharedBridge {
    fn new() -> Self {
        Self {
            pending_command: None,
            pending_resolve: None,
            flags: std::collections::HashMap::new(),
            numbers: std::collections::HashMap::new(),
            texts: std::collections::HashMap::new(),
            sets: std::collections::HashMap::new(),
            player_x: 0,
            player_y: 0,
            lang: "en".to_string(),
            rng_state: DEFAULT_RNG_SEED,
        }
    }

    /// Advance the internal xorshift64 RNG and return the next 64-bit value.
    fn next_rand(&mut self) -> u64 {
        let mut x = self.rng_state;
        if x == 0 {
            x = DEFAULT_RNG_SEED;
        }
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.rng_state = x;
        x
    }
}

/// Read-only view over the seeded query state of a [`SharedBridge`].
///
/// Passed to synchronous query closures registered via
/// [`ScriptEngine::register_sync_fn`] so they can answer `@if`-style
/// conditions without issuing a command or awaiting a promise.
pub struct BridgeView<'a> {
    inner: &'a SharedBridge,
}

impl<'a> BridgeView<'a> {
    /// Numeric seeded value (defaults to `0.0`).
    pub fn number(&self, k: &str) -> f64 {
        self.inner.numbers.get(k).copied().unwrap_or(0.0)
    }
    /// Text seeded value (defaults to empty string).
    pub fn text(&self, k: &str) -> String {
        self.inner.texts.get(k).cloned().unwrap_or_default()
    }
    /// Whether the seeded set `k` contains `v`.
    pub fn set_contains(&self, k: &str, v: &str) -> bool {
        self.inner.sets.get(k).is_some_and(|s| s.contains(v))
    }
    /// Boolean flag value (defaults to `false`).
    pub fn flag(&self, k: &str) -> bool {
        self.inner.flags.get(k).copied().unwrap_or(false)
    }
}

pub struct ScriptEngine {
    context: Context,
    bridge: Rc<RefCell<SharedBridge>>,
    state: EngineState,
    /// The currently loaded ES6 module (holds exported function bindings).
    current_module: Option<Module>,
}

impl ScriptEngine {
    pub fn new() -> Self {
        #[cfg(target_arch = "wasm32")]
        let mut context = Context::builder()
            .module_loader(Rc::new(IdleModuleLoader))
            .build()
            .expect("failed to build JS context");

        #[cfg(not(target_arch = "wasm32"))]
        let mut context = Context::builder()
            .module_loader(Rc::new(SimpleModuleLoader::new(".").expect(
                "failed to create module loader (current directory must exist)",
            )))
            .build()
            .expect("failed to build JS context");
        let bridge = Rc::new(RefCell::new(SharedBridge::new()));

        register_core_game_api(&mut context, bridge.clone());

        Self {
            context,
            bridge,
            state: EngineState::Idle,
            current_module: None,
        }
    }

    pub fn state(&self) -> &EngineState {
        &self.state
    }

    pub fn is_idle(&self) -> bool {
        self.state == EngineState::Idle
    }

    pub fn is_waiting(&self) -> bool {
        self.state == EngineState::WaitingForCommand
    }

    pub fn set_flag(&mut self, flag: &str, value: bool) {
        self.bridge
            .borrow_mut()
            .flags
            .insert(flag.to_string(), value);
    }

    pub fn get_flag(&self, flag: &str) -> bool {
        self.bridge
            .borrow()
            .flags
            .get(flag)
            .copied()
            .unwrap_or(false)
    }

    /// Return a snapshot of all flags currently held in the bridge.
    /// Used by the overworld to persist flags across map transitions.
    pub fn get_all_flags(&self) -> std::collections::HashMap<String, bool> {
        self.bridge.borrow().flags.clone()
    }

    /// Bulk-insert flags into the bridge (additive — does not clear existing).
    /// Called after creating a new ScriptEngine to restore persistent flags.
    pub fn seed_flags(&mut self, flags: &std::collections::HashMap<String, bool>) {
        let mut b = self.bridge.borrow_mut();
        for (k, v) in flags {
            b.flags.insert(k.clone(), *v);
        }
    }

    /// Pin the script-side RNG to a deterministic starting state. Intended for
    /// tests; a value of `0` is treated as the default non-zero seed.
    pub fn seed_rng(&mut self, seed: u64) {
        self.bridge.borrow_mut().rng_state = if seed == 0 { DEFAULT_RNG_SEED } else { seed };
    }

    /// Mix externally-sourced entropy into the script-side RNG. The game layer
    /// calls this (e.g. once per frame with a draw from the overworld RNG) so
    /// `game.showRandomText(...)` picks vary between playthroughs even though
    /// scripts themselves have no access to `Math.random`/`Date.now`.
    pub fn mix_rng(&mut self, entropy: u64) {
        let mut b = self.bridge.borrow_mut();
        b.rng_state ^= entropy.wrapping_mul(0x2545_F491_4F6C_DD1D);
        if b.rng_state == 0 {
            b.rng_state = DEFAULT_RNG_SEED;
        }
    }

    /// Seed a numeric value read by synchronous query functions.
    pub fn seed_number(&mut self, k: &str, v: f64) {
        self.bridge.borrow_mut().numbers.insert(k.into(), v);
    }

    /// Seed a text value read by synchronous query functions.
    pub fn seed_text(&mut self, k: &str, v: &str) {
        self.bridge.borrow_mut().texts.insert(k.into(), v.into());
    }

    /// Seed a string set read by synchronous query functions
    /// (e.g. the player's bag, as a set of item constant names).
    pub fn seed_set(&mut self, k: &str, vals: &[String]) {
        self.bridge
            .borrow_mut()
            .sets
            .insert(k.into(), vals.iter().cloned().collect());
    }

    pub fn set_player_position(&mut self, x: u8, y: u8) {
        self.bridge.borrow_mut().player_x = x;
        self.bridge.borrow_mut().player_y = y;
    }

    pub fn set_lang(&mut self, lang: &str) {
        self.bridge.borrow_mut().lang = lang.to_string();
    }

    pub fn load_script(&mut self, source: &str) -> Result<(), ScriptEngineError> {
        log::info!(target: "dotzuki::overworld", "[ScriptEngine] load_script: {} bytes", source.len());
        let src = Source::from_reader(source.as_bytes(), Some(Path::new("script.mjs")));
        let module = Module::parse(src, None, &mut self.context)
            .map_err(|e| {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Module parse failed: {}", e);
                ScriptEngineError::JsError(e.to_string())
            })?;

        self.context
            .module_loader()
            .register_module(js_string!("script.mjs"), module.clone());

        let promise = module.load_link_evaluate(&mut self.context);
        self.context.run_jobs();

        match promise.state() {
            PromiseState::Fulfilled(_) => {
                log::info!(target: "dotzuki::overworld", "[ScriptEngine] Module evaluated OK");
            }
            PromiseState::Rejected(err) => {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Module evaluation rejected: {:?}", err);
                return Err(ScriptEngineError::JsError(format!(
                    "Module evaluation failed: {:?}",
                    err
                )));
            }
            PromiseState::Pending => {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Module evaluation stuck pending");
                return Err(ScriptEngineError::JsError(
                    "Module evaluation stuck in pending state".to_string(),
                ));
            }
        }

        self.current_module = Some(module);

        if let Some(ref m) = self.current_module {
            for name in &["enterMap", "talkNurse", "talkLinkReceptionist", "talkGentleman"] {
                let has = m.get_value(js_string!(*name), &mut self.context)
                    .map(|v| v.is_callable())
                    .unwrap_or(false);
                log::info!(target: "dotzuki::overworld", "[ScriptEngine] Export check: {} = {}", name, has);
            }
        }

        Ok(())
    }

    pub fn load_shared_module(
        &mut self,
        name: &str,
        source: &str,
    ) -> Result<(), ScriptEngineError> {
        log::info!(target: "dotzuki::overworld", "[ScriptEngine] load_shared_module '{}': {} bytes", name, source.len());
        let src = Source::from_reader(source.as_bytes(), Some(Path::new(name)));
        let module = Module::parse(src, None, &mut self.context)
            .map_err(|e| {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Shared module parse failed: {}", e);
                ScriptEngineError::JsError(e.to_string())
            })?;

        self.context
            .module_loader()
            .register_module(js_string!(name), module.clone());

        let promise = module.load_link_evaluate(&mut self.context);
        self.context.run_jobs();

        match promise.state() {
            PromiseState::Fulfilled(_) => {
                log::info!(target: "dotzuki::overworld", "[ScriptEngine] Shared module '{}' evaluated OK", name);
                if let Ok(val) = module.get_value(js_string!("talkNurse"), &mut self.context) {
                    log::info!(target: "dotzuki::overworld", "[ScriptEngine] Shared module talkNurse callable: {}", val.is_callable());
                }
            }
            PromiseState::Rejected(err) => {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Shared module '{}' rejected: {:?}", name, err);
                return Err(ScriptEngineError::JsError(format!(
                    "Shared module evaluation failed: {:?}",
                    err
                )));
            }
            PromiseState::Pending => {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Shared module '{}' stuck pending", name);
                return Err(ScriptEngineError::JsError(
                    "Shared module evaluation stuck in pending state".to_string(),
                ));
            }
        }
        Ok(())
    }

    /// Call a JS async function by name (e.g., "scriptDefault", "talkProf").
    /// The function must be `export`-ed from the loaded module.
    /// Returns the first ScriptCommand if the function immediately awaits one.
    pub fn call_function(
        &mut self,
        fn_name: &str,
        args: &[JsValue],
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        // Resolve `talkMom` → `storyline_talkMom` etc. (see `resolved_fn_name`).
        let resolved = self
            .resolved_fn_name(fn_name)
            .unwrap_or_else(|| fn_name.to_string());
        let fn_name = resolved.as_str();
        log::info!(target: "dotzuki::overworld", "[ScriptEngine] call_function: {}", fn_name);
        let module = self
            .current_module
            .as_ref()
            .ok_or(ScriptEngineError::NotInitialized)?;

        let func = module
            .get_value(js_string!(fn_name), &mut self.context)
            .map_err(|e| {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] get_value error for {}: {}", fn_name, e);
                ScriptEngineError::JsError(e.to_string())
            })?;

        if func.is_undefined() || func.is_null() {
            log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Function '{}' is undefined or null", fn_name);
            return Err(ScriptEngineError::FunctionNotFound(fn_name.to_string()));
        }

        let func_obj = func
            .as_callable()
            .ok_or_else(|| {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Function '{}' is not callable", fn_name);
                ScriptEngineError::FunctionNotFound(fn_name.to_string())
            })?;

        log::info!(target: "dotzuki::overworld", "[ScriptEngine] Calling function '{}'...", fn_name);
        let result = func_obj
            .call(&JsValue::undefined(), args, &mut self.context);
        
        match result {
            Ok(_) => {
                log::info!(target: "dotzuki::overworld", "[ScriptEngine] Function '{}' call succeeded", fn_name);
            }
            Err(e) => {
                log::warn!(target: "dotzuki::overworld", "[ScriptEngine] Function '{}' call failed: {}", fn_name, e);
                return Err(ScriptEngineError::JsError(e.to_string()));
            }
        }

        self.context.run_jobs();

        self.state = EngineState::Running;
        let cmd = self.check_pending_command()?;
        log::info!(target: "dotzuki::overworld", "[ScriptEngine] After call_function '{}': pending_command = {:?}", fn_name, cmd.is_some());
        Ok(cmd)
    }

    /// Called each frame by the game loop.
    /// Returns the current pending command if the script is waiting.
    pub fn tick(&mut self) -> Option<ScriptCommand> {
        match self.state {
            EngineState::WaitingForCommand => self.bridge.borrow().pending_command.clone(),
            EngineState::Idle | EngineState::Finished => None,
            EngineState::Running => match self.check_pending_command() {
                Ok(cmd) => cmd,
                Err(_) => {
                    self.state = EngineState::Finished;
                    None
                }
            },
        }
    }

    /// Signal that the game has completed the pending command.
    /// Resolves the JS promise so the async function can continue.
    pub fn signal_done(
        &mut self,
        result: CommandResult,
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        if self.state != EngineState::WaitingForCommand {
            return Ok(None);
        }

        let resolve = self.bridge.borrow_mut().pending_resolve.take();
        self.bridge.borrow_mut().pending_command = None;

        if let Some(pending) = resolve {
            let js_result = command_result_to_js(&result, &mut self.context);
            pending
                .resolve_fn
                .call(&JsValue::undefined(), &[js_result], &mut self.context)
                .map_err(|e| ScriptEngineError::JsError(e.to_string()))?;

            self.context.run_jobs();
        }

        self.state = EngineState::Running;
        self.check_pending_command()
    }

    fn check_pending_command(&mut self) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        let cmd = self.bridge.borrow().pending_command.clone();
        if cmd.is_some() {
            self.state = EngineState::WaitingForCommand;
        } else if self.state == EngineState::Running {
            self.state = EngineState::Idle;
        }
        Ok(cmd)
    }

    /// Register an async command function on the `game` global JS object.
    ///
    /// The `builder` closure receives JS arguments and returns a `ScriptCommand`.
    /// The engine automatically creates a Promise, stores the command + resolve
    /// function in the bridge, and returns the Promise to JS.
    ///
    /// This is the building block for `ScriptApiRegistrar` implementations.
    pub fn register_async_fn(
        &mut self,
        name: &str,
        builder: impl Fn(&[JsValue], &mut Context) -> JsResult<ScriptCommand> + 'static,
    ) {
        let bridge = self.bridge.clone();
        let func = unsafe {
            NativeFunction::from_closure(move |_this, args, ctx| {
                let (promise, resolvers) = JsPromise::new_pending(ctx);
                let cmd = builder(args, ctx)?;
                let mut b = bridge.borrow_mut();
                b.pending_command = Some(cmd);
                b.pending_resolve = Some(PendingResolve {
                    resolve_fn: resolvers.resolve,
                });
                Ok(promise.into())
            })
        };
        let game_obj = self
            .context
            .global_object()
            .get(js_string!("game"), &mut self.context)
            .expect("game global not found")
            .to_object(&mut self.context)
            .expect("game global is not an object");
        game_obj
            .set(
                js_string!(name),
                func.to_js_function(self.context.realm()),
                true,
                &mut self.context,
            )
            .unwrap_or_else(|_| panic!("failed to register game.{}", name));
    }

    /// Register a *synchronous* query function on the `game` global JS object.
    ///
    /// Unlike [`register_async_fn`](Self::register_async_fn), the closure returns
    /// a `JsValue` directly (no promise, no pending command). It is handed a
    /// read-only [`BridgeView`] over the seeded query state so it can answer
    /// `@if`-style conditions immediately.
    pub fn register_sync_fn<F>(&mut self, name: &str, f: F)
    where
        F: Fn(&[JsValue], &mut Context, &BridgeView) -> JsResult<JsValue> + 'static,
    {
        let bridge = self.bridge.clone();
        // SAFETY: closure captures only `Rc<RefCell<SharedBridge>>` which holds no
        // GC-traced (boa `Trace`) types, so it cannot cause use-after-free.
        let func = unsafe {
            NativeFunction::from_closure(move |_this, args, ctx| {
                let b = bridge.borrow();
                let view = BridgeView { inner: &b };
                f(args, ctx, &view)
            })
        };
        let game_obj = self
            .context
            .global_object()
            .get(js_string!("game"), &mut self.context)
            .expect("game global not found")
            .to_object(&mut self.context)
            .expect("game global is not an object");
        game_obj
            .set(
                js_string!(name),
                func.to_js_function(self.context.realm()),
                true,
                &mut self.context,
            )
            .unwrap_or_else(|_| panic!("failed to register game.{}", name));
    }

    /// Construct a `ScriptEngine` with a game-specific API registrar.
    ///
    /// Core APIs (showText, moveNpc, getFlag, warpTo, playMusic, etc.) are always
    /// registered. The `registrar` adds game-specific APIs such as `giveMonster`,
    /// `startBattle`, etc.
    pub fn with_api(registrar: &dyn ScriptApiRegistrar) -> Self {
        let mut engine = Self::new();
        registrar.register_api(&mut engine);
        engine
    }
}

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

// ── Convenience call methods ─────────────────────────────────────
// These allow pokered-core to call JS functions without depending on boa_engine directly.

impl ScriptEngine {
    /// Call a JS function with no arguments.
    pub fn call_function_no_args(
        &mut self,
        fn_name: &str,
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        self.call_function(fn_name, &[])
    }

    /// Call a JS function with a single u8 argument (e.g., npc text_id lookup).
    pub fn call_function_with_u8(
        &mut self,
        fn_name: &str,
        arg: u8,
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        self.call_function(fn_name, &[JsValue::from(arg as i32)])
    }

    /// Call a JS function with two u16 arguments (e.g., coord event trigger).
    pub fn call_function_with_xy(
        &mut self,
        fn_name: &str,
        x: u16,
        y: u16,
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        self.call_function(fn_name, &[JsValue::from(x as i32), JsValue::from(y as i32)])
    }

    /// Call a JS function with a single string argument.
    pub fn call_function_with_str(
        &mut self,
        fn_name: &str,
        arg: &str,
    ) -> Result<Option<ScriptCommand>, ScriptEngineError> {
        self.call_function(fn_name, &[JsValue::from(js_string!(arg))])
    }

    /// Resolve a trigger/binding name to the exported function that actually
    /// exists in the current module. Configs bind the *bare* name (e.g.
    /// `talkMom`, `SeafoamIslandsB4FOnLoad`) but the DSL compiler exports
    /// `@storyline` blocks under a `storyline_`-prefixed name
    /// (`storyline_talkMom`). Try the exact name first (so `onLoad` names and
    /// any bare `.js` functions still win), then the `storyline_` fallback.
    fn resolved_fn_name(&mut self, fn_name: &str) -> Option<String> {
        let module = self.current_module.clone()?;
        if matches!(module.get_value(js_string!(fn_name), &mut self.context), Ok(v) if v.is_callable())
        {
            return Some(fn_name.to_string());
        }
        let prefixed = format!("storyline_{fn_name}");
        if matches!(module.get_value(js_string!(prefixed.as_str()), &mut self.context), Ok(v) if v.is_callable())
        {
            return Some(prefixed);
        }
        None
    }

    /// Check if a JS function exists in the module's exports (matching the
    /// `storyline_` resolution used by [`Self::call_function`]).
    pub fn has_function(&mut self, fn_name: &str) -> bool {
        self.resolved_fn_name(fn_name).is_some()
    }
}

fn command_result_to_js(result: &CommandResult, _context: &mut Context) -> JsValue {
    match result {
        CommandResult::Void => JsValue::undefined(),
        CommandResult::Bool(b) => JsValue::from(*b),
        CommandResult::Number(n) => JsValue::from(*n),
        CommandResult::Text(s) => JsValue::from(js_string!(s.as_str())),
    }
}

fn register_core_game_api(context: &mut Context, bridge: Rc<RefCell<SharedBridge>>) {
    let mut game_obj = boa_engine::object::ObjectInitializer::new(context);
    let game_obj = game_obj.build();

    let lang_bridge = bridge.clone();
    let lang_fn = unsafe {
        NativeFunction::from_closure(move |_this: &JsValue, _args: &[JsValue], _ctx: &mut Context| -> JsResult<JsValue> {
            Ok(JsValue::from(js_string!(lang_bridge.borrow().lang.as_str())))
        })
    };
    game_obj
        .set(js_string!("lang"), lang_fn.to_js_function(context.realm()), true, context)
        .expect("failed to register game.lang");

    let t_bridge = bridge.clone();
    let t_fn = unsafe {
        NativeFunction::from_closure(move |_this: &JsValue, args: &[JsValue], ctx: &mut Context| -> JsResult<JsValue> {
        let en = args.get_or_undefined(0).to_string(ctx).map_or(String::new(), |s| s.to_std_string_lossy());
        let zh = args.get_or_undefined(1).to_string(ctx).map_or(String::new(), |s| s.to_std_string_lossy());
        let result = if t_bridge.borrow().lang == "zh" { zh } else { en };
            Ok(JsValue::from(js_string!(result)))
        })
    };
    game_obj
        .set(js_string!("t"), t_fn.to_js_function(context.realm()), true, context)
        .expect("failed to register game.t");

    // game.showRandomText(a, b, c, ...) OR game.showRandomText([a, b, c])
    //   -> Promise<void>
    // Picks one line at random (Rust-side RNG) and shows it, exactly like
    // game.showText. Used for original flavor-text pools where an NPC/sign picks
    // a line from a set each interaction (e.g. gossip NPCs, the cruise ship
    // chefs). Resolves like showText once the box is dismissed.
    let rand_text_bridge = bridge.clone();
    // SAFETY: captures only `Rc<RefCell<SharedBridge>>`, which holds no
    // GC-traced (boa `Trace`) types, so it cannot cause use-after-free.
    let rand_text_fn = unsafe {
        NativeFunction::from_closure(
            move |_this: &JsValue, args: &[JsValue], ctx: &mut Context| -> JsResult<JsValue> {
                // Accept a single array argument, or a variadic list of strings.
                let mut options: Vec<String> = Vec::new();
                if args.len() == 1 && args[0].is_object() {
                    let obj = args[0].to_object(ctx)?;
                    let len = obj.get(js_string!("length"), ctx)?.to_u32(ctx)?;
                    for i in 0..len {
                        options.push(obj.get(i, ctx)?.to_string(ctx)?.to_std_string_lossy());
                    }
                } else {
                    for a in args {
                        options.push(a.to_string(ctx)?.to_std_string_lossy());
                    }
                }

                let (promise, resolvers) = JsPromise::new_pending(ctx);

                let mut b = rand_text_bridge.borrow_mut();
                let text = if options.is_empty() {
                    String::new()
                } else {
                    let idx = (b.next_rand() % options.len() as u64) as usize;
                    options.swap_remove(idx)
                };
                b.pending_command = Some(ScriptCommand::ShowText { text });
                b.pending_resolve = Some(PendingResolve {
                    resolve_fn: resolvers.resolve,
                });

                Ok(promise.into())
            },
        )
    };
    game_obj
        .set(
            js_string!("showRandomText"),
            rand_text_fn.to_js_function(context.realm()),
            true,
            context,
        )
        .expect("failed to register game.showRandomText");

    macro_rules! register_async_command {
        ($name:expr, $bridge:expr, $context:expr, $game_obj:expr, $cmd_builder:expr) => {{
            let bridge = $bridge.clone();
            // SAFETY: The closure captures only `Rc<RefCell<SharedBridge>>` which contains no
            // GC-traced (boa `Trace`) types, so it cannot cause use-after-free with the GC.
            let func = unsafe {
                NativeFunction::from_closure(move |_this, args, ctx| {
                    let (promise, resolvers) = JsPromise::new_pending(ctx);

                    let cmd = ($cmd_builder)(args, ctx)?;

                    let mut b = bridge.borrow_mut();
                    b.pending_command = Some(cmd);
                    b.pending_resolve = Some(PendingResolve {
                        resolve_fn: resolvers.resolve,
                    });

                    Ok(promise.into())
                })
            };
            $game_obj
                .set(
                    js_string!($name),
                    func.to_js_function($context.realm()),
                    true,
                    $context,
                )
                .expect(concat!("failed to register game.", $name));
        }};
    }

    // game.showText(text: string) -> Promise<void>
    register_async_command!(
        "showText",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let text = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::ShowText { text })
        }
    );

    // game.showChoice(options: string[]) -> Promise<number>
    register_async_command!(
        "showChoice",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arr = args.get_or_undefined(0).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut options = Vec::new();
            for i in 0..len {
                let val = arr.get(i, ctx)?;
                options.push(val.to_string(ctx)?.to_std_string_lossy());
            }
            Ok(ScriptCommand::ShowChoice { options })
        }
    );

    // game.moveNpc(npcId: string, path: [number, number][]) -> Promise<void>
    register_async_command!(
        "moveNpc",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let arr = args.get_or_undefined(1).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut path = Vec::new();
            for i in 0..len {
                let point = arr.get(i, ctx)?.to_object(ctx)?;
                let x = point.get(0, ctx)?.to_u32(ctx)? as u8;
                let y = point.get(1, ctx)?.to_u32(ctx)? as u8;
                path.push((x, y));
            }
            Ok(ScriptCommand::MoveNpc { npc_id, path })
        }
    );

    // game.startNpcMove(npcId: string, path: [number, number][]) -> Promise<void>
    // Fire-and-forget: starts NPC moving along path, resolves immediately.
    register_async_command!(
        "startNpcMove",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let arr = args.get_or_undefined(1).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut path = Vec::new();
            for i in 0..len {
                let point = arr.get(i, ctx)?.to_object(ctx)?;
                let x = point.get(0, ctx)?.to_u32(ctx)? as u8;
                let y = point.get(1, ctx)?.to_u32(ctx)? as u8;
                path.push((x, y));
            }
            Ok(ScriptCommand::StartNpcMove { npc_id, path })
        }
    );

    // game.awaitNpcMove(npcId: string) -> Promise<void>
    // Blocks until the NPC's scripted path is complete.
    register_async_command!(
        "awaitNpcMove",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::AwaitNpcMove { npc_id })
        }
    );

    // game.movePlayer(path: [number, number][]) -> Promise<void>
    // Blocks until the player finishes walking the path.
    register_async_command!(
        "movePlayer",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arr = args.get_or_undefined(0).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut path = Vec::new();
            for i in 0..len {
                let point = arr.get(i, ctx)?.to_object(ctx)?;
                let x = point.get(0, ctx)?.to_u32(ctx)? as u8;
                let y = point.get(1, ctx)?.to_u32(ctx)? as u8;
                path.push((x, y));
            }
            Ok(ScriptCommand::MovePlayer { path })
        }
    );

    // game.movePlayerRelative(steps: ([number, number] | DirectionString)[]) -> Promise<void>
    // Each entry is a (dx, dy) delta (or a direction string) applied
    // cumulatively from the player's current position; the deltas are
    // resolved to absolute waypoints by the game core when the command
    // runs. Blocks until the player finishes walking.
    register_async_command!(
        "movePlayerRelative",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arr = args.get_or_undefined(0).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut steps = Vec::new();
            for i in 0..len {
                let entry = arr.get(i, ctx)?;
                if entry.is_string() {
                    let dir = entry.to_string(ctx)?.to_std_string_lossy();
                    let delta = match dir.to_ascii_lowercase().as_str() {
                        "up" | "north" => (0i16, -1i16),
                        "down" | "south" => (0, 1),
                        "left" | "west" => (-1, 0),
                        "right" | "east" => (1, 0),
                        other => {
                            return Err(JsNativeError::typ()
                                .with_message(format!(
                                    "movePlayerRelative: unknown direction '{other}'"
                                ))
                                .into())
                        }
                    };
                    steps.push(delta);
                } else {
                    let point = entry.to_object(ctx)?;
                    let dx = point.get(0, ctx)?.to_i32(ctx)? as i16;
                    let dy = point.get(1, ctx)?.to_i32(ctx)? as i16;
                    steps.push((dx, dy));
                }
            }
            Ok(ScriptCommand::MovePlayerRelative { steps })
        }
    );

    // game.moveNpcTo(npcId: string, x: number, y: number) -> Promise<void>
    // Plans a terrain-aware path and resolves when movement is done.
    register_async_command!(
        "moveNpcTo",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let x = args.get_or_undefined(1).to_u32(ctx)? as u8;
            let y = args.get_or_undefined(2).to_u32(ctx)? as u8;
            Ok(ScriptCommand::MoveNpcTo { npc_id, x, y })
        }
    );

    // game.startNpcMoveTo(npcId: string, x: number, y: number) -> Promise<void>
    // Plans a terrain-aware path, starts movement immediately and resolves at once.
    register_async_command!(
        "startNpcMoveTo",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let x = args.get_or_undefined(1).to_u32(ctx)? as u8;
            let y = args.get_or_undefined(2).to_u32(ctx)? as u8;
            Ok(ScriptCommand::StartNpcMoveTo { npc_id, x, y })
        }
    );

    // game.movePlayerTo(x: number, y: number) -> Promise<void>
    // Plans a terrain-aware path and resolves when movement is done.
    register_async_command!(
        "movePlayerTo",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let x = args.get_or_undefined(0).to_u32(ctx)? as u8;
            let y = args.get_or_undefined(1).to_u32(ctx)? as u8;
            Ok(ScriptCommand::MovePlayerTo { x, y })
        }
    );

    // game.faceNpc(npcId: string, direction: string) -> Promise<void>
    register_async_command!(
        "faceNpc",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let direction = args
                .get_or_undefined(1)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::FaceNpc { npc_id, direction })
        }
    );

    // game.facePlayer(direction: string) -> Promise<void>
    register_async_command!(
        "facePlayer",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let direction = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::FacePlayer { direction })
        }
    );

    // game.setNpcFrame(npcId: string, frame: number) -> Promise<void>
    register_async_command!(
        "setNpcFrame",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let frame = args
                .get_or_undefined(1)
                .to_number(ctx)? as u8;
            Ok(ScriptCommand::SetNpcFrame { npc_id, frame })
        }
    );

    // game.playMusic(musicId: string) -> Promise<void>
    register_async_command!(
        "playMusic",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let music_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::PlayMusic { music_id })
        }
    );

    // game.playSound(soundId: string) -> Promise<void>
    register_async_command!(
        "playSound",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let sound_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::PlaySound { sound_id })
        }
    );

    // game.stopMusic() -> Promise<void>
    register_async_command!(
        "stopMusic",
        bridge,
        context,
        game_obj,
        |_args: &[JsValue], _ctx: &mut Context| -> JsResult<ScriptCommand> {
            Ok(ScriptCommand::StopMusic)
        }
    );

    // game.fadeOutMusic() -> Promise<void>
    register_async_command!(
        "fadeOutMusic",
        bridge,
        context,
        game_obj,
        |_args: &[JsValue], _ctx: &mut Context| -> JsResult<ScriptCommand> {
            Ok(ScriptCommand::FadeOutMusic)
        }
    );

    // game.delay(frames: number) -> Promise<void>
    register_async_command!("delay", bridge, context, game_obj, |args: &[JsValue],
                                                                 ctx: &mut Context|
     -> JsResult<
        ScriptCommand,
    > {
        let frames = args.get_or_undefined(0).to_u32(ctx)? as u16;
        Ok(ScriptCommand::Delay { frames })
    });

    // game.warpTo(map: string, x: number, y: number) -> Promise<void>
    register_async_command!("warpTo", bridge, context, game_obj, |args: &[JsValue],
                                                                  ctx: &mut Context|
     -> JsResult<
        ScriptCommand,
    > {
        let map = args
            .get_or_undefined(0)
            .to_string(ctx)?
            .to_std_string_lossy();
        let x = args.get_or_undefined(1).to_u32(ctx)? as u8;
        let y = args.get_or_undefined(2).to_u32(ctx)? as u8;
        Ok(ScriptCommand::WarpTo { map, x, y })
    });

    // game.heal() -> Promise<void>
    register_async_command!("heal", bridge, context, game_obj, |_args: &[JsValue],
                                                                 _ctx: &mut Context|
     -> JsResult<
        ScriptCommand,
    > {
        Ok(ScriptCommand::Heal)
    });

    // game.fadeScreen(fadeType: string) -> Promise<void>
    register_async_command!(
        "fadeScreen",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let fade_type = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::FadeScreen { fade_type })
        }
    );

    // game.showObject(objectIndexOrToggleId: number | string) -> Promise<void>
    register_async_command!(
        "showObject",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arg = args.get_or_undefined(0);
            if arg.is_string() {
                let toggle_id = arg.to_string(ctx)?.to_std_string_lossy();
                Ok(ScriptCommand::ShowObjectByName { toggle_id })
            } else {
                let object_index = arg.to_u32(ctx)? as u8;
                Ok(ScriptCommand::ShowObject { object_index })
            }
        }
    );

    // game.hideObject(objectIndexOrToggleId: number | string) -> Promise<void>
    register_async_command!(
        "hideObject",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arg = args.get_or_undefined(0);
            if arg.is_string() {
                let toggle_id = arg.to_string(ctx)?.to_std_string_lossy();
                Ok(ScriptCommand::HideObjectByName { toggle_id })
            } else {
                let object_index = arg.to_u32(ctx)? as u8;
                Ok(ScriptCommand::HideObject { object_index })
            }
        }
    );

    // game.showObjectByName(toggleId: string) -> Promise<void>
    // Explicit string-only alias used by many .scene files (e.g. `@load` guards).
    // Without this the call is `undefined` and the handler throws before the
    // object is ever toggled.
    register_async_command!(
        "showObjectByName",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let toggle_id = args.get_or_undefined(0).to_string(ctx)?.to_std_string_lossy();
            Ok(ScriptCommand::ShowObjectByName { toggle_id })
        }
    );

    // game.hideObjectByName(toggleId: string) -> Promise<void>
    register_async_command!(
        "hideObjectByName",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let toggle_id = args.get_or_undefined(0).to_string(ctx)?.to_std_string_lossy();
            Ok(ScriptCommand::HideObjectByName { toggle_id })
        }
    );

    // game.setJoyIgnore(mask: number) -> Promise<void>
    register_async_command!(
        "setJoyIgnore",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let mask = args.get_or_undefined(0).to_u32(ctx)? as u8;
            Ok(ScriptCommand::SetJoyIgnore { mask })
        }
    );

    // game.clearJoyIgnore() -> Promise<void>
    register_async_command!(
        "clearJoyIgnore",
        bridge,
        context,
        game_obj,
        |_args: &[JsValue], _ctx: &mut Context| -> JsResult<ScriptCommand> {
            Ok(ScriptCommand::ClearJoyIgnore)
        }
    );

    // game.followNpc(npcId: string, targetX: number, targetY: number) -> Promise<void>
    register_async_command!(
        "followNpc",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let target_x = args.get_or_undefined(1).to_u32(ctx)? as u8;
            let target_y = args.get_or_undefined(2).to_u32(ctx)? as u8;
            Ok(ScriptCommand::FollowNpc {
                npc_id,
                target_x,
                target_y,
            })
        }
    );

    // game.openShop(items: string[]) -> Promise<void>
    register_async_command!(
        "openShop",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let arr = args.get_or_undefined(0).to_object(ctx)?;
            let len = arr.get(js_string!("length"), ctx)?.to_u32(ctx)?;
            let mut items = Vec::new();
            for i in 0..len {
                let val = arr.get(i, ctx)?;
                items.push(val.to_string(ctx)?.to_std_string_lossy());
            }
            Ok(ScriptCommand::OpenShop { items })
        }
    );

    // game.showEmotionBubble(npcId: string, emotion: string) -> Promise<void>
    register_async_command!(
        "showEmotionBubble",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let emotion = args
                .get_or_undefined(1)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::ShowEmotionBubble { npc_id, emotion })
        }
    );

    // game.setNpcPosition(npcId: string, x: number, y: number) -> Promise<void>
    register_async_command!(
        "setNpcPosition",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let npc_id = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let x = args.get_or_undefined(1).to_u32(ctx)? as u8;
            let y = args.get_or_undefined(2).to_u32(ctx)? as u8;
            Ok(ScriptCommand::SetNpcPosition { npc_id, x, y })
        }
    );

    // game.showScene(sceneName: string) -> Promise<void>
    register_async_command!(
        "showScene",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let scene_name = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::ShowScene {
                scene_name,
                layout_json: None,
            })
        }
    );

    // game.hideScene(sceneName: string) -> Promise<void>
    register_async_command!(
        "hideScene",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let scene_name = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            Ok(ScriptCommand::HideScene { scene_name })
        }
    );

    // game.updateUI(sceneName: string, data: any) -> Promise<void>
    register_async_command!(
        "updateUI",
        bridge,
        context,
        game_obj,
        |args: &[JsValue], ctx: &mut Context| -> JsResult<ScriptCommand> {
            let scene_name = args
                .get_or_undefined(0)
                .to_string(ctx)?
                .to_std_string_lossy();
            let data_val = args.get_or_undefined(1);
            let json_val = data_val.to_json(ctx)?;
            let data_json = json_val.to_string();
            Ok(ScriptCommand::UpdateUI {
                scene_name,
                data_json,
            })
        }
    );

    // game.getFlag(flag: string) -> boolean
    {
        let bridge = bridge.clone();
        // SAFETY: closure captures Rc<RefCell<SharedBridge>> — no GC-traced types.
        let func = unsafe {
            NativeFunction::from_closure(move |_this, args, ctx| {
                let flag = args
                    .get_or_undefined(0)
                    .to_string(ctx)?
                    .to_std_string_lossy();
                let val = bridge.borrow().flags.get(&flag).copied().unwrap_or(false);
                Ok(JsValue::from(val))
            })
        };
        game_obj
            .set(
                js_string!("getFlag"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.getFlag");
    }

    // game.setFlag(flag: string) -> void
    {
        let bridge = bridge.clone();
        // SAFETY: closure captures Rc<RefCell<SharedBridge>> — no GC-traced types.
        let func = unsafe {
            NativeFunction::from_closure(move |_this, args, ctx| {
                let flag = args
                    .get_or_undefined(0)
                    .to_string(ctx)?
                    .to_std_string_lossy();
                bridge.borrow_mut().flags.insert(flag, true);
                Ok(JsValue::undefined())
            })
        };
        game_obj
            .set(
                js_string!("setFlag"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.setFlag");
    }

    // game.resetFlag(flag: string) -> void
    {
        let bridge = bridge.clone();
        // SAFETY: closure captures Rc<RefCell<SharedBridge>> — no GC-traced types.
        let func = unsafe {
            NativeFunction::from_closure(move |_this, args, ctx| {
                let flag = args
                    .get_or_undefined(0)
                    .to_string(ctx)?
                    .to_std_string_lossy();
                bridge.borrow_mut().flags.insert(flag, false);
                Ok(JsValue::undefined())
            })
        };
        game_obj
            .set(
                js_string!("resetFlag"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.resetFlag");
    }

    // game.getPlayerPosition() -> {x: number, y: number}
    {
        let bridge = bridge.clone();
        let func = unsafe {
            NativeFunction::from_closure(move |_this, _args, ctx| {
                let b = bridge.borrow();
                let pos = boa_engine::object::ObjectInitializer::new(ctx)
                    .property(
                        js_string!("x"),
                        JsValue::from(b.player_x as i32),
                        Attribute::all(),
                    )
                    .property(
                        js_string!("y"),
                        JsValue::from(b.player_y as i32),
                        Attribute::all(),
                    )
                    .build();
                Ok(pos.into())
            })
        };
        game_obj
            .set(
                js_string!("getPlayerPosition"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.getPlayerPosition");
    }

    // game.getPlayerX() -> number
    {
        let bridge = bridge.clone();
        let func = unsafe {
            NativeFunction::from_closure(move |_this, _args, _ctx| {
                Ok(JsValue::from(bridge.borrow().player_x as i32))
            })
        };
        game_obj
            .set(
                js_string!("getPlayerX"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.getPlayerX");
    }

    // game.getPlayerY() -> number
    {
        let bridge = bridge.clone();
        let func = unsafe {
            NativeFunction::from_closure(move |_this, _args, _ctx| {
                Ok(JsValue::from(bridge.borrow().player_y as i32))
            })
        };
        game_obj
            .set(
                js_string!("getPlayerY"),
                func.to_js_function(context.realm()),
                true,
                context,
            )
            .expect("failed to register game.getPlayerY");
    }

    context
        .register_global_property(js_string!("game"), game_obj, Attribute::all())
        .expect("failed to register global game object");
}