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

 * MuJoCo PlayEngine: Interactive Cockpit & Game Loop Controller

 * Style: Fall Guys & Party Animals Jelly Bean Pop Edition

 * Features:

 *   - Real-time DeepMind MuJoCo v3.3.0 WebAssembly Physics (60 FPS WebGL)

 *   - 3-Way Camera Perspective Switcher ('cam_front', 'cam_quarter', 'cam_topdown') + [C] shortcut

 *   - Kawaii 8-Bit Chiptune Procedural BGM (0 Bytes asset, pure Web Audio API)

 *   - Victory & Goal Clear Banners across all 10 Mini-Games

 *   - Coin Collection Sound FX & Star Coin Tracker (5/5)

 *   - Full 10 Games Contextual Action Buttons & Keypad Visualizer

 *   - 100% English Default with Korean Toggle

 */

// โ˜… ROOT-CAUSE FIX (HF Private Space): NO static import here.
// A static import chain (app.js โ†’ mujoco_wasm_player.js โ†’ mujoco.js) means that if ANY
// sub-module fails to load (e.g. private-Space auth token `__sign` not forwarded to
// sub-resource requests), the browser aborts app.js entirely โ†’ empty game list & dead
// START button. The physics engine is now lazily imported inside initWasmEngine().
let MujocoWasmPlayer = null;

// Forward HF private-Space auth query (`__sign`) to every sub-resource URL.
function withSign(url) {
  try {
    const sign = new URLSearchParams(window.location.search).get("__sign");
    if (!sign) return url;
    return url + (url.includes("?") ? "&" : "?") + "__sign=" + encodeURIComponent(sign);
  } catch (e) {
    return url;
  }
}
window.__withSign = withSign;

const I18N = {
  en: {
    brand_subtitle: "๐Ÿฌ Physical AI Sandbox & Arcade | HWIHWA LAB",
    menu_title: "10 Jelly Bricks",
    menu_desc: "Select a jelly brick to play in the sweet bouncy arena!",
    hud_score: "Survival Time",
    hud_best: "Best Record",
    hud_angle: "Pole Angle",
    hud_coins: "Star Coins",
    hud_demo: "Demolition Rate",
    hud_race: "Race Leader",
    hud_swing: "Swing Angle",
    hud_beans: "Beans Landed",
    hud_pinball: "Pinball Score",
    hud_domino: "Target Status",
    hud_acro: "Backflip Combo",
    hud_claw: "Rescue Height",
    keypad_title: "๐ŸŽฎ Real-time Keyboard Visualizer",
    cam_label: "๐ŸŽฅ View:",
    cam_front: "๐ŸŽฅ Front",
    cam_quarter: "๐Ÿ“ 45ยฐ Quarter",
    cam_topdown: "๐Ÿš Top-Down",
    cam_tip: "Press <strong>[C]</strong> to switch view",
    control_title: "Control Deck",
    control_mode_label: "Controller Mode",
    mode_manual: "๐ŸŽฎ Human Play",
    mode_ai: "๐Ÿค– Smart AI",
    mode_help_manual: "Use โ† and โ†’ arrow keys to balance the lollipop! (Survive 15s to Win ๐Ÿ†)",
    mode_help_ai: "AI PD Controller automatically maintains balance.",
    action_btn_label: "Quick Actions",
    cannon_power_label: "๐Ÿ’ฃ Cannon Power",
    cannon_preset_soft: "Soft (0.6x)",
    cannon_preset_normal: "Normal (1.0x)",
    cannon_preset_heavy: "Heavy (1.6x)",
    cannon_preset_mega: "MEGA (2.0x)",
    gravity_label: "Bouncy Gravity",
    gravity_zero: "Floating (0G)",
    gravity_moon: "Moon (-1.6)",
    gravity_earth: "Earth (-9.8)",
    gravity_heavy: "Heavy (-24.8)",
    btn_start_game: "โ–ถ START GAME (SPACE)",
    btn_playing: "โธ PLAYING (R to Reset)",
    btn_retry: "๐Ÿ”„ RETRY (R)",
    btn_play_again: "๐Ÿ”„ PLAY AGAIN (R)",
    btn_reset_toy: "๐Ÿ”„ RESET TOY (R)",
    btn_export_code: "๐Ÿ“‹ COPY PYTHON / XML CODE",
    ready_title: "READY TO PLAY!",
    ready_sub: "Press [SPACE] or Click [START] to Play!",
    overlay_btn_start: "โ–ถ START GAME",
    gameover_title: "OOPS! TOPPLED!",
    gameover_sub: "Oops! Toppled! Press [R] key to Retry",
    label_survived: "SURVIVED:",
    label_grade: "GRADE:",
    overlay_btn_retry: "๐Ÿ”„ RETRY (R)",
    overlay_btn_watch_ai: "๐Ÿค– WATCH SMART AI",
    overlay_btn_play_again: "๐Ÿ”„ PLAY AGAIN (R)",
    overlay_btn_next: "โฉ NEXT GAME",
    mentor_quote: "๐ŸŸข ENGINE LIVE ยท MuJoCo v3.3.0 (500Hz) ยท 30 FPS Stream ยท Zero Assets (100% Procedural) ยท Built with โค๏ธ by HWIHWA LAB",
    banner_badge: "ENGINE LIVE",
    modal_desc: "This code is a 100% standalone executable MuJoCo brick. Copy and paste it into Antigravity or Python to build games and AI agents!",
    modal_tab_py: "Python Script",
    modal_tab_xml: "MuJoCo XML (Blueprint)",
    modal_btn_copy: "๐Ÿ“‹ Copy to Clipboard",
    modal_btn_close: "Close",
    engine_loading_msg: "๐Ÿฌ Loading 3D Physics Engine... Please wait!"
  },
  ko: {
    brand_subtitle: "๐Ÿฌ Physical AI Sandbox & Arcade | HWIHWA LAB",
    menu_title: "10๋Œ€ ์ ค๋ฆฌ ๋ฌผ๋ฆฌ ์›์ž",
    menu_desc: "ํด๋ฆญํ•˜์—ฌ ํ†ตํ†ต ํŠ€๋Š” ์Šค์œ„ํŠธ ์•„๋ ˆ๋‚˜์—์„œ ํ”Œ๋ ˆ์ดํ•˜์„ธ์š”.",
    hud_score: "๋ฒ„ํ‹ด ์‹œ๊ฐ„ (์ ์ˆ˜)",
    hud_best: "์ตœ๊ณ  ๊ธฐ๋ก",
    hud_angle: "๊ธฐ์šธ๊ธฐ ๊ฐ๋„",
    hud_coins: "ํ™ฉ๊ธˆ ์ฝ”์ธ",
    hud_demo: "ํƒ€์›Œ ๋ถ•๊ดด์œจ",
    hud_race: "์„ ๋‘ ์ฃผ์ž",
    hud_swing: "์Šค์œ™ ๊ฐ๋„",
    hud_beans: "์•ˆ์ฐฉํ•œ ์ ค๋ฆฌ",
    hud_pinball: "ํ•€๋ณผ ์ ์ˆ˜",
    hud_domino: "ํ™ฉ๊ธˆ๋ณ„ ์ƒํƒœ",
    hud_acro: "๋ฐฑํ…€๋ธ”๋ง ์ฝค๋ณด",
    hud_claw: "์ธํ˜• ๊ตฌ์ถœ ๋†’์ด",
    keypad_title: "๐ŸŽฎ ์‹ค์‹œ๊ฐ„ ํ‚ค๋ณด๋“œ ์ž…๋ ฅ ์‹œ๊ฐํ™”",
    cam_label: "๐ŸŽฅ ์นด๋ฉ”๋ผ ๋ทฐ:",
    cam_front: "๐ŸŽฅ ์ •๋ฉด ๋ทฐ",
    cam_quarter: "๐Ÿ“ 45ยฐ ์ฟผํ„ฐ ๋ทฐ",
    cam_topdown: "๐Ÿš ํƒ‘๋‹ค์šด ๋ทฐ",
    cam_tip: "<strong>[C]</strong> ํ‚ค๋กœ ์นด๋ฉ”๋ผ ๋ทฐ ์ฆ‰์‹œ ์ „ํ™˜",
    control_title: "์ปจํŠธ๋กค ๋ฐํฌ",
    control_mode_label: "์กฐ์ž‘ ๋ชจ๋“œ ์„ ํƒ",
    mode_manual: "๐ŸŽฎ ์ธ๊ฐ„ ํ”Œ๋ ˆ์ด",
    mode_ai: "๐Ÿค– ์Šค๋งˆํŠธ AI",
    mode_help_manual: "โ†, โ†’ ๋ฐฉํ–ฅํ‚ค๋กœ ์นดํŠธ๋ฅผ ๋ฐ€์–ด ๋กค๋ฆฌํŒ์˜ ๊ท ํ˜•์„ ์„ธ์›Œ๋ณด์„ธ์š”! (15์ดˆ ์ƒ์กด ์‹œ ๐Ÿ† ๊ณจ๋“  ๋ฐธ๋Ÿฐ์„œ ์Šน๋ฆฌ)",
    mode_help_ai: "AI(PD ์ปจํŠธ๋กค๋Ÿฌ)๊ฐ€ ๋ชจํ„ฐ๋ฅผ ์ž๋™ ์ œ์–ดํ•˜์—ฌ ์™„๋ฒฝํ•œ ๊ท ํ˜•์„ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค.",
    action_btn_label: "์ฆ‰๊ฐ ์‹คํ–‰ ์•ก์…˜",
    cannon_power_label: "๐Ÿ’ฃ ๋Œ€ํฌ ํ™”๋ ฅ ํŒŒ์›Œ",
    cannon_preset_soft: "์•ฝํ•˜๊ฒŒ (0.6x)",
    cannon_preset_normal: "๋ณดํ†ต (1.0x)",
    cannon_preset_heavy: "๊ฐ•ํ•˜๊ฒŒ (1.6x)",
    cannon_preset_mega: "์ดˆ๊ฐ•๋ ฅ MEGA (2.0x)",
    gravity_label: "์ค‘๋ ฅ ๊ฐ€์†๋„ ์กฐ์ ˆ (Gravity)",
    gravity_zero: "๋ฌด์ค‘๋ ฅ (0G)",
    gravity_moon: "๋‹ฌ ํ‘œ๋ฉด (-1.6)",
    gravity_earth: "์ง€๊ตฌ (-9.8)",
    gravity_heavy: "์ดˆ์ค‘๋ ฅ (-24.8)",
    btn_start_game: "โ–ถ ๊ฒŒ์ž„ ์‹œ์ž‘ (SPACE)",
    btn_playing: "โธ ํ”Œ๋ ˆ์ด ์ค‘ (Rํ‚ค๋กœ ๋ฆฌ์…‹)",
    btn_retry: "๐Ÿ”„ ์žฌ๋„์ „ํ•˜๊ธฐ (Rํ‚ค)",
    btn_play_again: "๐Ÿ”„ ๋‹ค์‹œ ํ”Œ๋ ˆ์ด (Rํ‚ค)",
    btn_reset_toy: "๐Ÿ”„ ์›์œ„์น˜ ๋ฆฌ์…‹ (R)",
    btn_export_code: "๐Ÿ“‹ ํŒŒ์ด์ฌ / XML ์ฝ”๋“œ ๋ณต์‚ฌ",
    ready_title: "ํ”Œ๋ ˆ์ด ์ค€๋น„ ์™„๋ฃŒ!",
    ready_sub: "[SPACE] ํ‚ค ๋˜๋Š” [์‹œ์ž‘] ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ ํ”Œ๋ ˆ์ดํ•˜์„ธ์š”!",
    overlay_btn_start: "โ–ถ ๊ฒŒ์ž„ ์‹œ์ž‘",
    gameover_title: "์™€๋ฅด๋ฅด! ์“ฐ๋Ÿฌ์กŒ์Šต๋‹ˆ๋‹ค!",
    gameover_sub: "์™€๋ฅด๋ฅด ์“ฐ๋Ÿฌ์กŒ์Šต๋‹ˆ๋‹ค! [R] ํ‚ค๋กœ ์žฌ๋„์ „ํ•˜์„ธ์š”.",
    label_survived: "๋ฒ„ํ‹ด ์‹œ๊ฐ„:",
    label_grade: "๋„์ „ ๋“ฑ๊ธ‰:",
    overlay_btn_retry: "๐Ÿ”„ ์žฌ๋„์ „ (R)",
    overlay_btn_watch_ai: "๐Ÿค– ๋˜‘๋˜‘ํ•œ AI ๊ด€์ „ํ•˜๊ธฐ",
    overlay_btn_play_again: "๐Ÿ”„ ๋‹ค์‹œ ํ”Œ๋ ˆ์ด (R)",
    overlay_btn_next: "โฉ ๋‹ค์Œ ๊ฒŒ์ž„",
    mentor_quote: "๐ŸŸข ENGINE LIVE ยท MuJoCo v3.3.0 (500Hz) ยท 30 FPS Stream ยท Zero Assets (100% Procedural) ยท Built with โค๏ธ by HWIHWA LAB",
    banner_badge: "์—”์ง„ ๊ตฌ๋™ ์ค‘",
    modal_desc: "์ด ์ฝ”๋“œ๋Š” ์™„์ „ํžˆ ๋…๋ฆฝ ์‹คํ–‰ ๊ฐ€๋Šฅํ•œ MuJoCo ๋ฌผ๋ฆฌ ๋ฒฝ๋Œ์ž…๋‹ˆ๋‹ค. ๋ณต์‚ฌํ•ด์„œ ์•ˆํ‹ฐ๊ทธ๋ž˜๋น„ํ‹ฐ๋‚˜ ๋กœ์ปฌ ํŒŒ์ด์ฌ์— ๋ถ™์—ฌ๋„ฃ์–ด ๋‚˜๋งŒ์˜ ์›น๊ฒŒ์ž„์ด๋‚˜ AI ์‹œ๋ฎฌ๋ ˆ์ดํ„ฐ๋กœ ํ™•์žฅํ•˜์„ธ์š”!",
    modal_tab_py: "ํŒŒ์ด์ฌ ์‹คํ–‰ ์Šคํฌ๋ฆฝํŠธ",
    modal_tab_xml: "MuJoCo XML ์„ค๊ณ„๋„",
    modal_btn_copy: "๐Ÿ“‹ ํด๋ฆฝ๋ณด๋“œ์— ๋ณต์‚ฌ",
    modal_btn_close: "๋‹ซ๊ธฐ",
    engine_loading_msg: "๐Ÿฌ 3D ๋ฌผ๋ฆฌ ์—”์ง„ ๋กœ๋”ฉ ์ค‘... ์ž ์‹œ๋งŒ ๊ธฐ๋‹ค๋ ค ์ฃผ์„ธ์š”!"
  }
};

// 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„๋ณ„ ๋งž์ถคํ˜• ์ธ๊ฐ„ ์ˆ˜๋™ vs ์Šค๋งˆํŠธ AI ์•ˆ๋‚ด ๋ฌธ๊ตฌ
const GAME_MODE_HELP = {
  1: {
    ko: {
      manual: "์ŠคํŽ˜์ด์Šค๋ฐ”๋ฅผ ๋ˆŒ๋Ÿฌ ์ ค๋ฆฌ๋นˆ์„ ํƒ€์ด๋ฐ์— ๋งž์ถฐ ๋ฐ”๋‹ฅ ๋งคํŠธ๋กœ ์•ˆ์ „ํ•˜๊ฒŒ ๋‚™ํ•˜์‹œํ‚ค์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ 1.6์ดˆ๋งˆ๋‹ค ์ตœ์ ์˜ ๋ฆฌ๋“ฌ์œผ๋กœ ์ ค๋ฆฌ๋นˆ์„ ๊ณต์ค‘ ํˆฌํ•˜ํ•˜์—ฌ ๋งคํŠธ ํŒŒํ‹ฐ๋ฅผ ์™„์„ฑํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [Space] to drop cute jelly beans safely onto the bouncy foam pit!",
      ai: "Smart AI drops jelly beans in a rhythmic sequence every 1.6s to create a sweet pile!"
    }
  },
  2: {
    ko: {
      manual: "A / D ํ‚ค๋กœ ์ขŒ์šฐ ํ”Œ๋ฆฌํผ๋ฅผ ์ณ์˜ฌ๋ ค ์ ค๋ฆฌ๋ณผ๋“ค์ด ๋ฐ”๋‹ฅ์œผ๋กœ ๋–จ์–ด์ง€์ง€ ์•Š๊ฒŒ ํŠ•๊ฒจ๋‚ด์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ 10๊ฐœ ๊ตฌ์Šฌ์˜ ์‹ค์‹œ๊ฐ„ ๊ถค์ ์„ ์ถ”์ ํ•˜์—ฌ ํ”Œ๋ฆฌํผ ๋‚™ํ•˜ ๊ตฌ์—ญ ์ง„์ž… ์‹œ ์ดˆ๊ณ ์† ๋ฐ˜์‚ฌ ๋ฐ˜๊ฒฉํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [A] / [D] to flap left and right flippers and keep the gumballs bouncing!",
      ai: "Smart AI tracks all gumballs in real time and triggers reflex flaps whenever a ball enters the danger zone!"
    }
  },
  3: {
    ko: {
      manual: "์ŠคํŽ˜์ด์Šค๋ฐ”๋ฅผ ๋ˆŒ๋Ÿฌ ์ ค๋ฆฌ๋นˆ ์ŠคํŠธ๋ผ์ด์ปค๋กœ 1๋ฒˆ ๋„๋ฏธ๋…ธ๋ฅผ ํƒ€๊ฒฉํ•˜๊ณ  ํ™ฉ๊ธˆ๋ณ„์„ ์“ฐ๋Ÿฌ๋œจ๋ฆฌ์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ๋ฌผ๋ฆฌ ์—”์ง„ ์—ฐ์‡„ ๋ฐ˜๊ฒฝ์„ ๊ณ„์‚ฐํ•˜์—ฌ ๋„๋ฏธ๋…ธ ์—ฐ์‡„ ์ „๋„๋ฅผ ์ผ์œผํ‚ค๋Š” ์ž„ํŽ„์Šค ๋Œ์ง„์„ ์ž๋™ ์ง‘ํ–‰ํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [Space] to launch the jelly striker, topple the sweet dominoes, and hit the Gold Star!",
      ai: "Smart AI calculates optimal impulse physics to trigger a domino chain reaction toppling the Gold Star!"
    }
  },
  4: {
    ko: {
      manual: "W ๋˜๋Š” โ†‘ ํ‚ค๋ฅผ ์Šค์œ™ ํƒ€์ด๋ฐ์— ๋งž์ถฐ ๋ˆŒ๋Ÿฌ ๋ฐ˜๋™์„ ๊ฐ€์†ํ•˜๊ณ  360๋„ ํšŒ์ „์„ ๋‹ฌ์„ฑํ•˜์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ๊ฐ์†๋„ ๋ถ€ํ˜ธ์™€ ๋™๊ธฐํ™”๋œ ์ตœ์  ๊ณต์ง„ ํŽŒํ•‘(Resonance Pumping) ํ† ํฌ๋ฅผ ์ž๋™ ์ธ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [W] / [โ†‘] in sync with the swing rhythm to pump momentum and achieve a 360ยฐ full loop!",
      ai: "Smart AI applies optimal resonance pumping torque synchronized with angular velocity to conquer the 360ยฐ loop!"
    }
  },
  5: {
    ko: {
      manual: "์ŠคํŽ˜์ด์Šค๋ฐ”๋กœ 2๋‹จ ๊ด€์ ˆ์— ์˜ˆ์ธก ๋ถˆ๊ฐ€๋Šฅํ•œ ์นด์˜ค์Šค ํ† ํฌ๋ฅผ ์ฃผ์ž…ํ•˜์—ฌ 3ํšŒ์ „ ๊ณต์ค‘์ œ๋น„๋ฅผ ์„ฑ๊ณต์‹œํ‚ค์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ์ด์ค‘ ์ง„์ž์˜ ๋น„์„ ํ˜• ์œ„์ƒ ๊ณต๊ฐ„์„ ๋ถ„์„ํ•˜์—ฌ ํ™”๋ คํ•œ ๊ณต์ค‘์ œ๋น„ ์ฝค๋ณด๋ฅผ ์œ ๋„ํ•˜๋Š” ์œ„์ƒ ๊ฒฐํ•ฉ ํ† ํฌ๋ฅผ ๋ถ„์‚ฌํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [Space] to inject chaotic torque into the double pendulum and complete 3 acrobatic somersaults!",
      ai: "Smart AI drives non-linear phase-coupled sinusoidal torques to execute thrilling multi-rotation somersault combos!"
    }
  },
  6: {
    ko: {
      manual: "์ŠคํŽ˜์ด์Šค๋ฐ”๋กœ ํ•‘ํฌ๋นˆ๊ณผ ๋ฏผํŠธ๋นˆ์˜ ๋ ˆ์ธ๋ณด์šฐ ์›Œํ„ฐ์Šฌ๋ผ์ด๋“œ ๋ ˆ์ด์Šค๋ฅผ ์‹œ์ž‘ํ•˜์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ์–‘ ๋ ˆ์ด์„œ ๊ฐ„์˜ ๊ฑฐ๋ฆฌ ์ฐจ์ด๋ฅผ ๊ฐ์ง€ํ•˜์—ฌ ๋’ค์ฒ˜์ง„ ์ฃผ์ž์—๊ฒŒ ์Šฌ๋ฆฝ์ŠคํŠธ๋ฆผ ๋ถ€์ŠคํŠธ๋ฅผ ์ฃผ์–ด ๊ทน์ ์ธ ๋ฐ•๋น™ ์Šน๋ถ€๋ฅผ ์—ฐ์ถœํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Press [Space] to unleash the thrilling rainbow water slide race between Pink Bean and Mint Bean!",
      ai: "Smart AI monitors the lead gap and applies dynamic slipstream catch-up boost for a thrilling photo-finish showdown!"
    }
  },
  7: {
    ko: {
      manual: "โ†, โ†’ ๋ฐฉํ–ฅํ‚ค๋กœ ์นดํŠธ๋ฅผ ๋ฐ€์–ด ๋กค๋ฆฌํŒ์˜ ๊ท ํ˜•์„ ์„ธ์›Œ๋ณด์„ธ์š”! (15์ดˆ ์ƒ์กด ์‹œ ๐Ÿ† ๊ณจ๋“  ๋ฐธ๋Ÿฐ์„œ ์Šน๋ฆฌ)",
      ai: "[์‚ด์•„ ์ˆจ ์‰ฌ๋Š” ์„œ์ปค์Šค AI] ๋ฏธํ’์— ํ”๋“ค๋ฆฌ๋Š” ๋กค๋ฆฌํŒ์„ ์‹ค์‹œ๊ฐ„ LQR ์ œ์–ด๋กœ ์ขŒ์šฐ 3~4cm์”ฉ ํ†ก! ํ†ก! ์น˜๋ฉฐ ์ค‘์•™ ๊ท ํ˜•์„ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค."
    },
    en: {
      manual: "Use โ† and โ†’ arrow keys to balance the lollipop! (Survive 15s to Win ๐Ÿ†)",
      ai: "[Living Circus AI] Performs real-time LQR balancing, dynamically micro-tapping 3~4cm to hold the center against carnival breezes."
    }
  },
  8: {
    ko: {
      manual: "W / A / S / D ํ‚ค๋กœ ๋‹ฌ์ฝคํ•œ ๋ฒ”ํผ์นด๋ฅผ ์กฐ์ข…ํ•˜์—ฌ ์•„๋ ˆ๋‚˜ ๊ณณ๊ณณ์˜ 5๋Œ€ ํ™ฉ๊ธˆ ๋งˆ์นด๋กฑ ๋ณ„ ์ฝ”์ธ์„ ๋ชจ๋‘ ์ˆ˜์ง‘ํ•˜์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ Pure Pursuit ์ž์œจ์ฃผํ–‰๊ณผ ์žฅ์• ๋ฌผ ํƒˆ์ถœ ๋ฆฌํ”Œ๋ ‰์Šค๋กœ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฏธ์ˆ˜์ง‘ ํ™ฉ๊ธˆ ์ฝ”์ธ์„ ์ˆœ์ฐจ ํƒ์ƒ‰ํ•˜์—ฌ ์™„๋ฒฝ ์ฃผํ–‰ํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Drive the sweet bumper car with W / A / S / D to collect all 5 Golden Macaron Star Coins across the arena!",
      ai: "Smart AI executes a Pure Pursuit autonomous waypoint navigation algorithm with obstacle avoidance to hunt all 5 coins!"
    }
  },
  9: {
    ko: {
      manual: "W / S (์–ด๊นจ), A / D (ํŒ”๊ฟˆ์น˜), ์ŠคํŽ˜์ด์Šค๋ฐ” (์ž์„ ์˜จ/์˜คํ”„)๋กœ ์ ค๋ฆฌ๋นˆ ์ธํ˜•์„ ์กฐ์ค€ํ•˜์—ฌ ๊ตฌ์ถœํ•˜์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ์—ญ๊ธฐ๊ตฌํ•™ 3๋‹จ๊ณ„ ์‹œํ€€์Šค(์ ‘๊ทผ โž” ํ•˜๊ฐ• & ์ž์„ ํก์ฐฉ โž” ์ƒ์Šน)๋ฅผ ์ˆ˜ํ–‰ํ•˜์—ฌ ์ ค๋ฆฌ๋นˆ ์ธํ˜•์„ ์ž๋™ ๊ตฌ์ถœํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Control shoulder (W/S), elbow (A/D), and spacebar (magnet toggle) to rescue the Jelly Bean plushie!",
      ai: "Smart AI executes a 3-stage Inverse Kinematics pick-and-place sequence (approach โž” descend & magnet on โž” lift) to rescue the plushie!"
    }
  },
  10: {
    ko: {
      manual: "์šฐ์ธก ์Šฌ๋ผ์ด๋”๋กœ ๋Œ€ํฌ ํŒŒ์›Œ๋ฅผ ์กฐ์ ˆํ•˜๊ณ , ์ŠคํŽ˜์ด์Šค๋ฐ”๋ฅผ ๋ˆŒ๋Ÿฌ 9๋‹จ ๋งˆ์นด๋กฑ ํƒ€์›Œ๋ฅผ ์ผ๊ฒฉ์— ๋ถ•๊ดด์‹œํ‚ค์„ธ์š”!",
      ai: "์Šค๋งˆํŠธ AI๊ฐ€ ๋งˆ์นด๋กฑ ํƒ€์›Œ์˜ ์งˆ๋Ÿ‰ ์ค‘์‹ฌ(CoM)๊ณผ ํƒ„๋„ํ•™์„ ๊ณ„์‚ฐํ•˜์—ฌ 80% ์ด์ƒ ์ „๋ณต์„ ์œ ๋„ํ•˜๋Š” ์ตœ์ ์˜ ์ €๊ฒฉ ์‚ฌ๊ฒฉ์„ ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค!"
    },
    en: {
      manual: "Adjust cannon power with the right slider, then press [Space] to demolish the 9-story macaron tower in one shot!",
      ai: "Smart AI computes tower center-of-mass and projectile ballistics, automatically firing an optimal sniper shot for total demolition!"
    }
  }
};

function updateModeHelpText() {
  const modeHelp = document.getElementById("modeHelpText");
  if (!modeHelp) return;
  const gameHelp = GAME_MODE_HELP[currentExampleId];
  if (gameHelp && gameHelp[currentLang] && gameHelp[currentLang][currentControlMode]) {
    modeHelp.textContent = gameHelp[currentLang][currentControlMode];
  } else {
    modeHelp.textContent = currentControlMode === "ai"
      ? (I18N[currentLang]?.mode_help_ai || I18N.en.mode_help_ai)
      : (I18N[currentLang]?.mode_help_manual || I18N.en.mode_help_manual);
  }
}

// ์ „์—ญ ์ƒํƒœ ๋ณ€์ˆ˜: ๊ธ€๋กœ๋ฒŒ ํ—ˆ๊น…ํŽ˜์ด์Šค(Hugging Face) ๋ฐ ํ•ด์™ธ ์‚ฌ์šฉ์ž ํ‘œ์ค€ 100% ์˜๋ฌธ(en) ๊ธฐ๋ณธ ์‹œ์ž‘
let currentLang = (function() {
  try {
    const urlParams = new URLSearchParams(window.location.search);
    const paramLang = urlParams.get("lang");
    if (paramLang && (paramLang === "ko" || paramLang === "en")) {
      return paramLang;
    }
    // ๊ณผ๊ฑฐ ๋กœ์ปฌ์Šคํ† ๋ฆฌ์ง€์— ko๊ฐ€ ๋‚จ์•„์žˆ๋”๋ผ๋„ ํ”„๋กœ๊ทธ๋žจ ์ฒซ ์‹คํ–‰์€ ํ•ญ์ƒ ์˜๋ฌธ ๊ธฐ๋ณธ์œผ๋กœ ์‹œ์ž‘
    // ํ˜„์žฌ ๋ธŒ๋ผ์šฐ์ € ํƒญ ์„ธ์…˜ ๋‚ด์—์„œ๋งŒ ํ† ๊ธ€ ์ƒํƒœ ์œ ์ง€
    const sess = sessionStorage.getItem("jelly_lang_sess");
    if (sess && (sess === "ko" || sess === "en")) {
      return sess;
    }
  } catch (e) {}
  return "en";
})();
let currentExampleId = 7;
let currentControlMode = "manual";
let currentGameState = "ready";
let currentCamera = "cam_front";
let currentCodeData = null;
let currentCodeTab = "py";
let examplesData = (typeof window !== "undefined" && window.EMBEDDED_EXAMPLES) ? window.EMBEDDED_EXAMPLES : {};
let activeKeySet = new Set();
let soundEnabled = true;
let bgmEnabled = false;
let audioCtx = null;
let bgmTimer = null;
let bgmStep = 0;

// WebAssembly Physics Engine (1st-Class Core Engine for Static Space & Web)
let wasmPlayer = null;
let useWasm = true;


// 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ ์Šน๋ฆฌ ์ถ•ํ•˜ ๋ฐฐ๋„ˆ ํ…์ŠคํŠธ ํ”„๋ฆฌ์…‹
const VICTORY_BANNERS = {
  1: { icon: "๐ŸŽˆ", title: "SKYDIVING PARTY CLEARED!", sub: "All Jelly Beans landed safely on the carnival floor!" },
  2: { icon: "๐ŸŽ‰", title: "PINBALL JACKPOT!", sub: "Gumballs cascade through candy bumpers in high-score style!" },
  3: { icon: "๐ŸŒŸ", title: "DOMINO CLEARED!", sub: "All 7 Dominos Knocked Down & Golden Star Hit! (0.83s)" },
  4: { icon: "๐ŸŽก", title: "360ยฐ SWING COMPLETED!", sub: "Full kinetic somersault loop achieved in carnival sky!" },
  5: { icon: "๐Ÿคธ", title: "ACROBATIC COMBO!", sub: "Twin Gymnast Beans performed 3 consecutive backflips!" },
  6: { icon: "๐Ÿ", title: "PINK BEAN WINS! ๐Ÿ†", sub: "Champion of the Rainbow Waterpark Slide! Splash pool reached!" },
  7: { icon: "โญ", title: "GOLDEN BALANCER MASTER!", sub: "15 seconds balanced on pudding cart! Flawless control!" },
  8: { icon: "๐Ÿ†", title: "COIN DASH MASTER!", sub: "All 5 Golden Star Coins Collected! Master Bumper Driver!" },
  9: { icon: "๐Ÿงธ", title: "PLUSHIE RESCUED!", sub: "Magnetic Crane lifted the plushie bean safely out of the box!" },
  10: { icon: "๐Ÿ’ฅ", title: "TOWER ANNIHILATED!", sub: "9-Story Macaron Tower 100% Demolished! Direct cannon hit!" }
};

const VICTORY_BANNERS_KR = {
  1: { icon: "๐ŸŽˆ", title: "์Šค์นด์ด๋‹ค์ด๋น™ ํŒŒํ‹ฐ ์„ฑ๊ณต!", sub: "๋ชจ๋“  ์ ค๋ฆฌ๋นˆ์ด ํญ์‹ ํ•œ ์ถ•์ œ ๋ฐ”๋‹ฅ์— ์•ˆ์ „ํ•˜๊ฒŒ ์ฐฉ์ง€ํ–ˆ์Šต๋‹ˆ๋‹ค!" },
  2: { icon: "๐ŸŽ‰", title: "ํ•€๋ณผ ์žญํŒŸ ๋‹ฌ์„ฑ!", sub: "๋‹ฌ์ฝคํ•œ ์บ”๋”” ๋ฒ”ํผ๋ฅผ ํ†ต๊ณผํ•˜๋ฉฐ ์ ค๋ฆฌ๋ณผ ํญํฌ์ˆ˜๊ฐ€ ์Ÿ์•„์ง‘๋‹ˆ๋‹ค!" },
  3: { icon: "๐ŸŒŸ", title: "๋„๋ฏธ๋…ธ ์ „๋„ ์™„๋ฒฝ ์„ฑ๊ณต!", sub: "7์—ฐ์† ๋„๋ฏธ๋…ธ ์ „๋„ & ํ™ฉ๊ธˆ๋ณ„ ๋ช…์ค‘! 0.83์ดˆ ํด๋ฆฌ์–ด" },
  4: { icon: "๐ŸŽก", title: "360๋„ ์ž์ด์–ธํŠธ ์Šค์œ™ ์„ฑ๊ณต!", sub: "์ถ•์ œ ํ•˜๋Š˜์„ ๊ฐ€๋ฅด๋Š” ์™„๋ฒฝํ•œ 360๋„ ๊ณต์ง„ ํšŒ์ „ ๋ฃจํ”„ ๋‹ฌ์„ฑ!" },
  5: { icon: "๐Ÿคธ", title: "์•„ํฌ๋กœ๋ฐ”ํ‹ฑ 3์—ฐ์† ํ‚ฅ!", sub: "์Œ๋‘ฅ์ด ์ ค๋ฆฌ๋นˆ์˜ ๊ณต์ค‘ 3์—ฐ์† ๋ฐฑํ…€๋ธ”๋ง ์„œ์ปค์Šค ์„ฑ๊ณต!" },
  6: { icon: "๐Ÿ", title: "ํ•‘ํฌ๋นˆ 1์œ„ ๊ณจ์ธ! ๐Ÿ†", sub: "๋ฌด์ง€๊ฐœ ์›Œํ„ฐ ์Šฌ๋ผ์ด๋“œ ์ œํŒจ! ์ฒจ๋ฒ™ ํ’€์žฅ ๊ณจ์ธ ์„ฑ๊ณต!" },
  7: { icon: "โญ", title: "15์ดˆ ๊ณจ๋“  ๋ฐธ๋Ÿฐ์„œ ๋‹ฌ์„ฑ!", sub: "ํ‘ธ๋”ฉ ์นดํŠธ ์œ„์—์„œ ์•„์Šฌ์•„์Šฌ 15์ดˆ ๊ท ํ˜• ์œ ์ง€ ์„ฑ๊ณต!" },
  8: { icon: "๐Ÿ†", title: "5๋Œ€ ํ™ฉ๊ธˆ ์ฝ”์ธ ์ „์ฒด ์ˆ˜์ง‘!", sub: "์ถ•์ œ ๋ฒ”ํผ์นด ๋งˆ์Šคํ„ฐ ๋“œ๋ผ์ด๋ฒ„ ๋“ฑ๊ทน! ๋ชจ๋“  ์Šคํƒ€ ์ฝ”์ธ ํš๋“!" },
  9: { icon: "๐Ÿงธ", title: "์ ค๋ฆฌ๋นˆ ์ธํ˜• ๊ตฌ์ถœ ์„ฑ๊ณต!", sub: "์ž์„ ํฌ๋ ˆ์ธ ํก์ฐฉ์œผ๋กœ ํ‘น์‹ ํ•œ ์ธํ˜•๋นˆ์„ ์•ˆ์ „ํ•˜๊ฒŒ ๊ตฌ์ถœํ–ˆ์Šต๋‹ˆ๋‹ค!" },
  10: { icon: "๐Ÿ’ฅ", title: "๋งˆ์นด๋กฑ ํƒ€์›Œ 100% ์™„ํŒŒ!", sub: "9์ธต ๋งˆ์นด๋กฑ ํƒ€์›Œ ํ†ต์พŒํ•œ ์ „๋„ ์™„ํŒŒ ์„ฑ๊ณต! ๋Œ€ํฌ์•Œ ๋ช…์ค‘!" }
};

// ์Šคํƒ ๋“œ์–ผ๋ก  / ์ŠคํŽ˜์ด์Šค ์ธํ„ฐ๋ž™ํ‹ฐ๋ธŒ ์ƒํƒœ ๋จธ์‹  ์ œ์–ด ํƒ€์ด๋จธ & ์Šค์ฝ”์–ด ์นด์šดํ„ฐ
let staticLifecycleTimer = null;
let staticBalanceInterval = null;
let staticBeanCounter = 0;
let staticPinballScore = 0;
let staticSwingLoops = 0;
let staticAcroCombo = 0;
let staticCoinCounter = 0;
let staticClawMagnet = false;
let staticSurvivalTime = 0.0;

// ============================================================================
// ๐Ÿš€ WASM Real-Time Physics Engine Controller (Singleton Promise)
// ============================================================================
class EngineLoadingManager {
  constructor() {
    this.currentVal = 6;
    this.targetVal = 20;
    this.isSceneStable = false;
    this.isUiReady = false;
    this.isFontsReady = false;
    this.isReady = false;
    this.isDismissed = false;
    this.startTime = performance.now();
    this.minDurationMs = 1600; // Pacing so users can comfortably perceive milestones
    this.holdDurationMs = 500; // Hold at 100% for 500ms so user clearly perceives completion
    this.timer = null;
    this.overlay = null;

    // Web Fonts loading check
    if (typeof document !== "undefined" && document.fonts && document.fonts.ready) {
      document.fonts.ready.then(() => {
        this.isFontsReady = true;
        this._checkReadiness();
      }).catch(() => {
        this.isFontsReady = true;
        this._checkReadiness();
      });
    } else {
      this.isFontsReady = true;
    }

    this._startTicker();
  }

  getOverlay() {
    if (!this.overlay) this.overlay = document.getElementById("engineLoadingOverlay");
    return this.overlay;
  }

  setMessage(msgKo, msgEn) {
    const el = document.getElementById("engineLoadingMsg");
    if (!el) return;
    const isKo = (typeof currentLang !== "undefined" ? currentLang : "ko") === "ko";
    el.textContent = isKo ? msgKo : msgEn;
  }

  setProgress(target, msgKo = null, msgEn = null) {
    if (this.isReady) return;
    this.targetVal = Math.max(this.targetVal, Math.min(95, target));
    if (msgKo && msgEn) {
      this.setMessage(msgKo, msgEn);
    }
  }

  notifyUiReady() {
    this.isUiReady = true;
    this.setProgress(70, "๐ŸŽจ UI ๋ฐ ๊ฒŒ์ž„ ํŒŒ๋ผ๋ฏธํ„ฐ ๋กœ๋”ฉ ์™„๋ฃŒ", "๐ŸŽจ UI & Parameters Initialized");
    this._checkReadiness();
  }

  notifySceneStable() {
    this.isSceneStable = true;
    this.setProgress(96, "โœจ 3D ๊ทธ๋ž˜ํ”ฝ ๋ฐ ๋ฌผ๋ฆฌ ๋ Œ๋”๋ง ๊ฒ€์ฆ ์™„๋ฃŒ", "โœจ 3D Graphics & Physics Verified");
    this._checkReadiness();
  }

  _checkReadiness() {
    if (this.isReady) return;

    // Check all physical and visual DOM criteria
    const listEl = document.getElementById("brickList");
    const hasGameList = listEl && listEl.children.length >= 10;
    const titleEl = document.getElementById("activeTitle");
    const hasHeader = titleEl && titleEl.textContent.trim().length > 0;
    const canvas = document.querySelector(".screen-wrapper canvas.wasm-canvas");
    const hasCanvas = canvas && canvas.clientWidth > 0 && canvas.clientHeight > 0;
    const isPlayerReady = typeof wasmPlayer !== "undefined" && wasmPlayer && wasmPlayer.isReady && wasmPlayer.isGameLoaded && wasmPlayer.geomMeshes && wasmPlayer.geomMeshes.length > 0;

    // All screen elements, web fonts, and 3D frames must be 100% verified!
    if (this.isSceneStable && this.isFontsReady && hasGameList && hasHeader && hasCanvas && isPlayerReady) {
      this.complete();
    }
  }

  _startTicker() {
    if (this.timer) return;
    this.timer = setInterval(() => {
      const elapsed = performance.now() - this.startTime;
      const timeRatio = Math.min(1.0, elapsed / this.minDurationMs);

      // Desired progress based on minimum pacing and actual milestone
      let desired = this.targetVal;
      if (!this.isReady) {
        // Smoothly pace progress up to 88% while WASM module downloads and compiles
        desired = Math.min(88, Math.max(this.targetVal, timeRatio * 85));
      } else {
        // Once engine and all elements are ready, glide smoothly all the way to 100%
        desired = 100;
      }

      if (this.currentVal < desired) {
        // Steady, comfortable step so numbers are clearly readable (never jump wildly)
        const step = Math.min(1.8, Math.max(0.4, (desired - this.currentVal) * 0.12));
        this.currentVal = Math.min(desired, this.currentVal + step);
      }

      const bar = document.getElementById("miniProgressBar");
      const pct = document.getElementById("loadingPercent");
      const rounded = Math.round(this.currentVal);

      if (bar) bar.style.width = `${rounded}%`;
      if (pct) pct.textContent = `${rounded}%`;

      // When reaching 100% after readiness signal
      if (this.isReady && this.currentVal >= 99.5) {
        this.currentVal = 100;
        if (bar) bar.style.width = "100%";
        if (pct) {
          pct.textContent = "100%";
          pct.style.color = "#10b981"; // Vibrant Emerald Green
          pct.style.transform = "scale(1.12)";
        }
        this.setMessage("๐ŸŽ‰ 100% ์ค€๋น„ ์™„๋ฃŒ! ๊ฒŒ์ž„์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค!", "๐ŸŽ‰ 100% Ready! Starting 3D Arena!");
        clearInterval(this.timer);
        this.timer = null;
        this._dismissWithHold();
      }
    }, 25);
  }

  complete() {
    if (this.isReady) return;
    this.isReady = true;
    this.targetVal = 100;
    this._startTicker();
  }

  _dismissWithHold() {
    if (this.isDismissed) return;
    this.isDismissed = true;

    // Hold at 100% for 500ms so user perceives completion before fade-out begins
    setTimeout(() => {
      const ov = this.getOverlay();
      if (!ov) return;

      // Step 1: Smooth opacity fade-out (0.4s ease)
      ov.classList.add("fade-out");

      // Step 2: Clean DOM removal after fade-out transition finishes
      setTimeout(() => {
        ov.classList.add("is-hidden");
        ov.style.setProperty("display", "none", "important");
        ov.style.setProperty("opacity", "0", "important");
        ov.style.setProperty("visibility", "hidden", "important");
        ov.style.setProperty("pointer-events", "none", "important");
        try { ov.remove(); } catch (e) {}

        // Ensure 3D canvas and viewport dimensions are perfectly synchronized
        if (typeof wasmPlayer !== "undefined" && wasmPlayer && typeof wasmPlayer.handleResize === "function") {
          wasmPlayer.handleResize();
        }
      }, 420);
    }, this.holdDurationMs);
  }
}

const engineLoadingMgr = new EngineLoadingManager();
window.__engineLoadingMgr = engineLoadingMgr;
function dismissEngineLoadingOverlay() {
  engineLoadingMgr.complete();
}
window.__dismissLoadingOverlay = dismissEngineLoadingOverlay;


// ============================================================================
// ๐Ÿ”Š Kawaii Web Audio API Synthesizer (0 ๋ฐ”์ดํŠธ ๋‹ค์šด๋กœ๋“œ, ๋ธŒ๋ผ์šฐ์ € ์ˆœ์ˆ˜ ํ•ฉ์„ฑ์Œ)
// ============================================================================
function initAudio() {
  if (!audioCtx) {
    const AudioContextClass = window.AudioContext || window.webkitAudioContext;
    if (AudioContextClass) {
      audioCtx = new AudioContextClass();
    }
  }
  if (audioCtx && audioCtx.state === "suspended") {
    audioCtx.resume();
  }
}

function playBoing() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const now = audioCtx.currentTime;
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = "sine";
    osc.frequency.setValueAtTime(220, now);
    osc.frequency.exponentialRampToValueAtTime(560, now + 0.12);
    osc.frequency.exponentialRampToValueAtTime(280, now + 0.24);
    gain.gain.setValueAtTime(0.3, now);
    gain.gain.exponentialRampToValueAtTime(0.01, now + 0.24);
    osc.connect(gain);
    gain.connect(audioCtx.destination);
    osc.start(now);
    osc.stop(now + 0.24);
  } catch (e) {}
}

function playPop() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const now = audioCtx.currentTime;
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = "sine";
    osc.frequency.setValueAtTime(540, now);
    osc.frequency.exponentialRampToValueAtTime(140, now + 0.08);
    gain.gain.setValueAtTime(0.25, now);
    gain.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
    osc.connect(gain);
    gain.connect(audioCtx.destination);
    osc.start(now);
    osc.stop(now + 0.08);
  } catch (e) {}
}

function playCoinSound() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const now = audioCtx.currentTime;
    const notes = [987.77, 1318.51]; // B5 -> E6 ์พŒํ™œํ•œ 1-up ์ฝ”์ธ ํš๋“์Œ
    notes.forEach((freq, idx) => {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      const t = now + idx * 0.08;
      osc.type = "sine";
      osc.frequency.setValueAtTime(freq, t);
      gain.gain.setValueAtTime(0.25, t);
      gain.gain.exponentialRampToValueAtTime(0.01, t + 0.18);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start(t);
      osc.stop(t + 0.18);
    });
  } catch (e) {}
}

function playStart() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const notes = [261.63, 329.63, 392.00, 523.25]; // C4 -> E4 -> G4 -> C5
    notes.forEach((freq, idx) => {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      const now = audioCtx.currentTime + idx * 0.07;
      osc.type = "triangle";
      osc.frequency.setValueAtTime(freq, now);
      gain.gain.setValueAtTime(0.2, now);
      gain.gain.exponentialRampToValueAtTime(0.01, now + 0.18);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start(now);
      osc.stop(now + 0.18);
    });
  } catch (e) {}
}

function playGameOver() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const notes = [440.00, 392.00, 349.23, 261.63]; // A4 -> G4 -> F4 -> C4
    notes.forEach((freq, idx) => {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      const now = audioCtx.currentTime + idx * 0.11;
      osc.type = "sawtooth";
      osc.frequency.setValueAtTime(freq, now);
      gain.gain.setValueAtTime(0.18, now);
      gain.gain.exponentialRampToValueAtTime(0.01, now + 0.22);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start(now);
      osc.stop(now + 0.22);
    });
  } catch (e) {}
}

function playCheer() {
  if (!soundEnabled) return;
  initAudio();
  if (!audioCtx) return;
  try {
    const notes = [523.25, 659.25, 783.99, 1046.50, 1318.51]; // C5 -> E5 -> G5 -> C6 -> E6
    notes.forEach((freq, idx) => {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      const now = audioCtx.currentTime + idx * 0.07;
      osc.type = "triangle";
      osc.frequency.setValueAtTime(freq, now);
      gain.gain.setValueAtTime(0.28, now);
      gain.gain.exponentialRampToValueAtTime(0.01, now + 0.28);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start(now);
      osc.stop(now + 0.28);
    });
  } catch (e) {}
}

// ============================================================================
// ๐ŸŽต Procedural 8-Bit Chiptune Kawaii BGM (์ˆœ์ˆ˜ Web Audio API ์ฝ”๋“œ ์ƒ์„ฑ)
// ============================================================================
const MELODY = [
  523.25, 659.25, 783.99, 1046.50, 880.00, 783.99, 659.25, 523.25,
  587.33, 659.25, 783.99, 880.00, 783.99, 659.25, 587.33, 523.25
];
const BASS = [
  130.81, 130.81, 164.81, 164.81, 220.00, 220.00, 174.61, 196.00
];

function startBgm() {
  initAudio();
  if (!audioCtx) return;
  if (bgmTimer) clearInterval(bgmTimer);

  bgmStep = 0;
  const stepInterval = 140; // ~107 BPM 16๋น„ํŠธ

  bgmTimer = setInterval(() => {
    if (!bgmEnabled || !audioCtx) return;
    try {
      const now = audioCtx.currentTime;
      
      // 1. ๋ฉœ๋กœ๋”” (๋ฆฌ๋“œ ์‚ฌ๊ฐํŒŒ)
      const noteFreq = MELODY[bgmStep % MELODY.length];
      if (noteFreq) {
        const lead = audioCtx.createOscillator();
        const leadGain = audioCtx.createGain();
        lead.type = "square";
        lead.frequency.setValueAtTime(noteFreq, now);
        leadGain.gain.setValueAtTime(0.035, now);
        leadGain.gain.exponentialRampToValueAtTime(0.002, now + 0.12);
        lead.connect(leadGain);
        leadGain.connect(audioCtx.destination);
        lead.start(now);
        lead.stop(now + 0.12);
      }

      // 2. ๋ฒ ์ด์Šค (ํ†ตํ†ต ํŠ€๋Š” ์‚ผ๊ฐํŒŒ)
      if (bgmStep % 2 === 0) {
        const bassFreq = BASS[(bgmStep / 2) % BASS.length];
        const bass = audioCtx.createOscillator();
        const bassGain = audioCtx.createGain();
        bass.type = "triangle";
        bass.frequency.setValueAtTime(bassFreq, now);
        bassGain.gain.setValueAtTime(0.08, now);
        bassGain.gain.exponentialRampToValueAtTime(0.005, now + 0.22);
        bass.connect(bassGain);
        bassGain.connect(audioCtx.destination);
        bass.start(now);
        bass.stop(now + 0.22);
      }

      bgmStep++;
    } catch (e) {}
  }, stepInterval);
}

function stopBgm() {
  if (bgmTimer) {
    clearInterval(bgmTimer);
    bgmTimer = null;
  }
}

function toggleBgm() {
  initAudio();
  bgmEnabled = !bgmEnabled;
  const btn = document.getElementById("bgmToggleBtn");
  const txt = document.getElementById("bgmText");
  if (btn) btn.classList.toggle("playing", bgmEnabled);
  if (txt) txt.textContent = bgmEnabled ? "BGM ON" : "BGM OFF";

  if (bgmEnabled) {
    playPop();
    startBgm();
  } else {
    stopBgm();
  }
}

// ============================================================================
// ๐ŸŽ‰ Confetti Particle System
// ============================================================================
function triggerConfetti() {
  const canvas = document.getElementById("confettiCanvas");
  if (!canvas) return;
  const ctx = canvas.getContext("2d");
  canvas.width = canvas.clientWidth || 640;
  canvas.height = canvas.clientHeight || 480;

  const colors = ["#ff477e", "#06d6a0", "#ffd166", "#118ab2", "#9d4edd", "#ff7b00"];
  const particles = [];
  for (let i = 0; i < 60; i++) {
    particles.push({
      x: canvas.width * 0.5 + (Math.random() - 0.5) * 80,
      y: canvas.height * 0.45,
      vx: (Math.random() - 0.5) * 16,
      vy: -Math.random() * 12 - 6,
      size: Math.random() * 9 + 4,
      color: colors[Math.floor(Math.random() * colors.length)],
      rot: Math.random() * 360,
      vrot: (Math.random() - 0.5) * 15,
      alpha: 1.0
    });
  }

  let start = null;
  function render(ts) {
    if (!start) start = ts;
    const progress = ts - start;
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    let active = false;
    particles.forEach(p => {
      p.x += p.vx;
      p.y += p.vy;
      p.vy += 0.38;
      p.rot += p.vrot;
      p.alpha = Math.max(0, 1 - progress / 1500);

      if (p.alpha > 0) {
        active = true;
        ctx.save();
        ctx.translate(p.x, p.y);
        ctx.rotate((p.rot * Math.PI) / 180);
        ctx.fillStyle = p.color;
        ctx.globalAlpha = p.alpha;
        ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size * 0.6);
        ctx.restore();
      }
    });

    if (active && progress < 1600) {
      requestAnimationFrame(render);
    } else {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  }
  requestAnimationFrame(render);
}

// ============================================================================
// ๐Ÿš€ DOM Initialization
// ============================================================================
// CRITICAL FIX: <script type="module"> is deferred โ€” DOMContentLoaded may have
// already fired before module evaluation. Use readyState check to guarantee init.
function safeStep(name, fn) {
  try {
    return fn();
  } catch (e) {
    console.error(`[initApp] step '${name}' failed:`, e);
    if (window.__bootError) window.__bootError(`${name}: ${e && e.message ? e.message : e}`);
  }
}

let __appInitStarted = false;
async function initApp() {
  if (__appInitStarted) return;
  __appInitStarted = true;
  // Each step isolated: one failure can never block the game list from rendering.
  safeStep("language", setupLanguageToggle);
  safeStep("sound", setupSoundToggle);
  safeStep("bgm", setupBgmToggle);
  safeStep("fullscreen", setupFullscreenToggle);
  safeStep("keyboard", setupKeyboardListeners);
  safeStep("widescreen", setupAutoWidescreen);
  try {
    await loadExamples();
  } catch (e) {
    console.error("[initApp] loadExamples failed:", e);
    if (window.__bootError) window.__bootError("loadExamples: " + (e && e.message ? e.message : e));
  }
  safeStep("translations", applyTranslations);
  safeStep("actionButtons", updateActionButtons);
  safeStep("gameStateUI", () => updateGameStateUI());
  if (typeof window !== 'undefined' && window.__engineLoadingMgr) {
    window.__engineLoadingMgr.notifyUiReady();
  }
  // Catastrophic 40s timeout: warn user rather than abruptly hiding loading screen while elements are missing
  setTimeout(() => {
    if (typeof window !== 'undefined' && window.__engineLoadingMgr && !window.__engineLoadingMgr.isReady) {
      console.warn("[initApp] 40s timeout reached without stable scene rendering.");
      engineLoadingMgr.setMessage("โš ๏ธ ๋„คํŠธ์›Œํฌ ๋กœ๋”ฉ ์ง€์—ฐ ์ค‘... ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”.", "โš ๏ธ Network delay... Please refresh if needed.");
    }
  }, 40000);
}
window.__jellyInitApp = initApp;

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initApp);
} else {
  // DOM already parsed (module deferred execution) โ€” init immediately
  initApp();
}

function setupAutoWidescreen() {
  try {
    if (window.resizeTo && screen.availWidth && screen.availHeight) {
      if (window.outerWidth < screen.availWidth * 0.8) {
        window.moveTo(0, 0);
        window.resizeTo(screen.availWidth, screen.availHeight);
      }
    }
  } catch (e) {}
}

function setupFullscreenToggle() {
  const fsBtn = document.getElementById("fullscreenBtn");
  const fsText = document.getElementById("fsText");
  if (!fsBtn) return;

  function updateFsText() {
    if (document.fullscreenElement) {
      if (fsText) fsText.textContent = "NORMAL";
      fsBtn.title = currentLang === "ko" ? "์ผ๋ฐ˜ ํ™”๋ฉด์œผ๋กœ ๋ณต๊ท€ [F]" : "Exit Widescreen Fullscreen [F]";
    } else {
      if (fsText) fsText.textContent = "WIDE";
      fsBtn.title = currentLang === "ko" ? "16:9 ์™€์ด๋“œ ์ „์ฒดํ™”๋ฉด ์ „ํ™˜ [F]" : "Toggle 16:9 Widescreen Fullscreen [F]";
    }
  }

  fsBtn.addEventListener("click", () => {
    playPop();
    if (!document.fullscreenElement) {
      if (document.documentElement.requestFullscreen) {
        document.documentElement.requestFullscreen().catch(() => {});
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen().catch(() => {});
      }
    }
  });

  document.addEventListener("fullscreenchange", updateFsText);
  updateFsText();
}


function setupLanguageToggle() {
  const toggleBtn = document.getElementById("langToggleBtn");
  if (!toggleBtn) return;
  const langText = document.getElementById("langText");
  if (langText) langText.textContent = currentLang.toUpperCase();
  toggleBtn.title = currentLang === "en" ? "ํ•œ๊ตญ์–ด๋กœ ๋ณ€๊ฒฝ (Switch to Korean)" : "Switch to English";

  toggleBtn.addEventListener("click", () => {
    currentLang = currentLang === "en" ? "ko" : "en";
    try {
      sessionStorage.setItem("jelly_lang_sess", currentLang);
      localStorage.removeItem("jelly_lang"); // ๊ธฐ์กด ko ๊ณ ์ • ์บ์‹œ ์ •๋ฆฌ
    } catch (e) {}
    if (langText) langText.textContent = currentLang.toUpperCase();
    toggleBtn.title = currentLang === "en" ? "ํ•œ๊ตญ์–ด๋กœ ๋ณ€๊ฒฝ (Switch to Korean)" : "Switch to English";
    applyTranslations();
    renderExampleList();
    updateUIHeader();
    updateActionButtons();
    updateGameStateUI();
    playPop();
  });
}

function setupSoundToggle() {
  const toggleBtn = document.getElementById("soundToggleBtn");
  if (!toggleBtn) return;
  toggleBtn.addEventListener("click", () => {
    initAudio();
    soundEnabled = !soundEnabled;
    toggleBtn.classList.toggle("muted", !soundEnabled);
    toggleBtn.innerHTML = soundEnabled ? '๐Ÿ”Š <span id="soundText">SFX ON</span>' : '๐Ÿ”‡ <span id="soundText">SFX OFF</span>';
    if (soundEnabled) playPop();
  });
}

function setupBgmToggle() {
  const toggleBtn = document.getElementById("bgmToggleBtn");
  if (!toggleBtn) return;
  toggleBtn.addEventListener("click", () => {
    toggleBgm();
  });
}

function applyTranslations() {
  const dict = I18N[currentLang] || I18N.en;
  document.querySelectorAll("[data-i18n]").forEach(elem => {
    const key = elem.getAttribute("data-i18n");
    if (dict[key]) {
      if (dict[key].includes("<")) {
        elem.innerHTML = dict[key];
      } else {
        elem.textContent = dict[key];
      }
    }
  });

  // ๋ชจ๋“œ ๋„์›€๋ง ๋ฐ ์ธ๋””์ผ€์ดํ„ฐ ์ฆ‰์‹œ ๊ฐฑ์‹  (๋‹จ์ผ ์ด๋ชจ์ง€ ์•„์ด์ฝ˜ ์ ์šฉ)
  updateModeHelpText();
  const indicatorIcon = document.getElementById("indicatorIcon");
  const indicatorText = document.getElementById("indicatorText");
  if (indicatorIcon) {
    indicatorIcon.textContent = currentControlMode === "ai" ? "๐Ÿค–" : "๐ŸŽฎ";
  }
  if (indicatorText) {
    indicatorText.textContent = currentControlMode === "ai"
      ? (currentLang === "ko" ? "AI ์ž์œจ ์ œ์–ด ๋ชจ๋“œ" : "Autonomous AI Mode")
      : (currentLang === "ko" ? "์ธ๊ฐ„ ์ˆ˜๋™ ์กฐ์ž‘ ๋ชจ๋“œ" : "Human Manual Mode");
  }
}

// ============================================================================
// ๐ŸŽฅ 3-Way Camera Controller
// ============================================================================
async function setCamera(camName) {
  playPop();
  currentCamera = camName;
  document.getElementById("btnCamFront")?.classList.toggle("active", camName === "cam_front");
  document.getElementById("btnCamQuarter")?.classList.toggle("active", camName === "cam_quarter");
  document.getElementById("btnCamTopdown")?.classList.toggle("active", camName === "cam_topdown");

  if (useWasm && wasmPlayer) {
    wasmPlayer.setCamera(camName);
    return;
  }

  try {
    await fetch("/api/camera", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ camera: camName })
    });
  } catch (err) {
    console.error("Camera switch error:", err);
  }
}

function cycleCamera() {
  const order = ["cam_front", "cam_quarter", "cam_topdown"];
  const curIdx = order.indexOf(currentCamera);
  const nextCam = order[(curIdx + 1) % order.length];
  setCamera(nextCam);
}

// ============================================================================
// ๐Ÿš€ WASM Real-Time Physics Engine Controller (Singleton Promise)
// ============================================================================

let wasmInitPromise = null;
async function initWasmEngine() {
  if (wasmPlayer && wasmPlayer.isReady) {
    return wasmPlayer;
  }
  if (wasmInitPromise) return wasmInitPromise;
  wasmInitPromise = (async () => {
    const container = document.querySelector('.screen-wrapper');
    const streamImg = document.getElementById("mjpegStream");
    if (streamImg) streamImg.style.display = "none";

    const statusLabel = document.getElementById("streamStatus");
    if (statusLabel) statusLabel.textContent = "WASM 60FPS";

    engineLoadingMgr.setProgress(25, "๐Ÿฌ 3D ๋ฌผ๋ฆฌ ์—”์ง„ ์ปค๋„ ์ดˆ๊ธฐํ™” ์ค‘...", "๐Ÿฌ Initializing 3D Physics Engine...");

    try {
      if (!MujocoWasmPlayer) {
        engineLoadingMgr.setProgress(50, "๐Ÿ“ฆ MuJoCo WebAssembly ๋ชจ๋“ˆ ๋กœ๋”ฉ ์ค‘...", "๐Ÿ“ฆ Loading MuJoCo WASM Module...");
        const mod = await import(withSign("./mujoco_wasm_player.js?v=20261107_v30"));
        MujocoWasmPlayer = mod.MujocoWasmPlayer;
      }
      wasmPlayer = new MujocoWasmPlayer(container);
      engineLoadingMgr.setProgress(75, "โš™๏ธ 60FPS ๋ฌผ๋ฆฌ ์—ฐ์‚ฐ ์ฝ”์–ด ์ปดํŒŒ์ผ ์ค‘...", "โš™๏ธ Compiling 60FPS Physics Core...");
      await wasmPlayer.init();
      engineLoadingMgr.setProgress(92, "๐ŸŽจ 3D ์นด๋‹ˆ๋ฐœ ํ…Œ๋งˆํŒŒํฌ ํ™˜๊ฒฝ ๋นŒ๋“œ ์ค‘...", "๐ŸŽจ Building 3D Carnival Arena...");

      wasmPlayer.onTelemetryUpdate = (t) => {
        updateHUD(t);
        if (t.victory_banner && currentGameState !== "victory") {
          currentGameState = "victory";
          playCheer();
          triggerConfetti();
          updateGameStateUI(t);
        }
      };

      wasmPlayer.onCoinCollected = (coins) => {
        playCoinSound();
        triggerConfetti();
        const el = document.getElementById("hudCoins");
        if (el) el.textContent = coins;
      };

      wasmPlayer.onStateChange = (state, data) => {
        currentGameState = state;
        updateGameStateUI(data);
        if (state === "victory") {
          playCheer();
          triggerConfetti();
        } else if (state === "gameover") {
          playGameOver();
        }
      };

      console.log("๐Ÿš€ MujocoWasmPlayer successfully initialized!");
      return wasmPlayer;
    } catch (err) {
      console.error("โŒ Failed to initialize MujocoWasmPlayer:", err);
      if (window.__bootError) window.__bootError("Physics engine: " + (err && err.message ? err.message : err));
      throw err;
    }
  })();
  return wasmInitPromise;
}

function updateHUD(t) {
  if (!t) return;
  if (t.survival_time !== undefined) {
    const el = document.getElementById("hudScore");
    if (el) el.textContent = `${t.survival_time.toFixed(2)}s`;
  }
  if (t.best_score !== undefined) {
    const el = document.getElementById("hudBest");
    if (el) el.textContent = `${t.best_score.toFixed(2)}s`;
  }
  if (t.pole_angle_deg !== undefined) {
    const el = document.getElementById("hudAngle");
    if (el) el.textContent = `${t.pole_angle_deg}ยฐ`;
  }
  if (t.coins_collected !== undefined) {
    const el = document.getElementById("hudCoins");
    if (el) el.textContent = t.coins_collected;
  }
  if (t.demolition_rate !== undefined) {
    const el = document.getElementById("hudDemo");
    if (el) el.textContent = t.demolition_rate.toFixed(1);
  }
  if (t.beans_landed !== undefined) {
    const el = document.getElementById("hudBeansLanded");
    if (el) el.textContent = `${t.beans_landed} (${t.beans_dropped || 4} drops)`;
  }
  if (t.pinball_score !== undefined) {
    const el = document.getElementById("hudPinballScore");
    if (el) el.textContent = t.pinball_score;
  }
  if (t.domino_cleared !== undefined) {
    const el = document.getElementById("hudDominoStatus");
    if (el) el.textContent = t.domino_cleared ? "Cleared! (0.83s) ๐ŸŒŸ" : "Standing ๐ŸŒŸ";
  }
  if (t.swing_angle_deg !== undefined) {
    const el = document.getElementById("hudSwingAngle");
    if (el) el.textContent = `${t.swing_angle_deg}ยฐ (Loops: ${t.swing_loops || 0})`;
  }
  if (t.somersault_count !== undefined) {
    const el = document.getElementById("hudAcroCombo");
    if (el) el.textContent = `${Math.min(3, t.somersault_count)} / 3 ๐Ÿคธ`;
  }
  if (t.race_leader !== undefined) {
    const el = document.getElementById("hudRaceLeader");
    if (el) el.textContent = t.race_winner ? `${t.race_winner} Won! ๐Ÿ†` : t.race_leader;
  }
  if (t.claw_height !== undefined) {
    const el = document.getElementById("hudClawHeight");
    if (el) el.textContent = `${t.claw_height.toFixed(2)}m`;
  }
}

// ============================================================================
// ๐ŸŽฎ ์˜ˆ์ œ ๊ด€๋ฆฌ & ์„ ํƒ (100% ๋กœ์ปฌ ๋™๋“ฑ ๋ฌผ๋ฆฌ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ์ง๊ฒฐ)
// ============================================================================
async function loadExamples() {
  // 1. EMBEDDED_EXAMPLES ๋™๊ธฐ ๋กœ๋“œ ๋ฐ ์ดˆ๊ธฐ UI ์„ธํŒ…
  if (typeof window.EMBEDDED_EXAMPLES !== "undefined" && Object.keys(window.EMBEDDED_EXAMPLES).length > 0) {
    examplesData = window.EMBEDDED_EXAMPLES;
  }

  // ๊ธฐ๋ณธ ๊ฒŒ์ž„ ID ๊ฒฐ์ • (์œ ์ € ํด๋ฆญ ๋Œ€๊ธฐ๊ฐ’ ๋˜๋Š” ํ”Œ๋ž˜๊ทธ์‹ญ 7๋ฒˆ)
  const pending = Number(window.__pendingSelect) || 7;
  currentExampleId = pending;

  // ์ขŒ์ธก ๊ฒŒ์ž„ ๋ฆฌ์ŠคํŠธ ๋ฐ UI ํ—ค๋” ๋™๊ธฐ ์ฆ‰๊ฐ ๋ Œ๋”๋ง
  renderExampleList();
  updateUIHeader();
  updateActionButtons();
  updateGameStateUI();

  if (typeof window !== 'undefined' && window.__engineLoadingMgr) {
    window.__engineLoadingMgr.notifyUiReady();
  }

  // 2. ๐Ÿš€ MuJoCo WebAssembly ์‹ค์‹œ๊ฐ„ ๋ฌผ๋ฆฌ ์—”์ง„ ์ฆ‰์‹œ ๊ฐ€๋™
  useWasm = true;
  try {
    await initWasmEngine();
    if (wasmPlayer) {
      wasmPlayer.loadGame(currentExampleId);
    }
  } catch (err) {
    console.error("WASM startup error:", err);
    if (window.__engineLoadingMgr) {
      window.__engineLoadingMgr.setMessage("โš ๏ธ WASM ๋ฌผ๋ฆฌ ์—”์ง„ ๋กœ๋”ฉ ์˜ค๋ฅ˜", "โš ๏ธ WASM Loading Error");
      window.__engineLoadingMgr.complete();
    }
  }
}

function renderExampleList() {
  const listEl = document.getElementById("brickList");
  if (!listEl) return;
  listEl.innerHTML = "";

  for (let i = 1; i <= 10; i++) {
    const meta = examplesData[i];
    if (!meta) continue;

    const item = document.createElement("div");
    item.className = `brick-item ${i === currentExampleId ? "active" : ""}`;
    item.onclick = () => {
      playPop();
      selectExample(i);
    };

    const title = currentLang === "ko" ? meta.title_kr : `${i.toString().padStart(2, "0")} ยท ${meta.title}`;

    item.innerHTML = `

      <div class="brick-item-top">

        <span class="brick-num">#${i.toString().padStart(2, "0")}</span>

        <span class="brick-category-tag">${meta.badge}</span>

      </div>

      <div class="brick-title">${title}</div>

    `;

    listEl.appendChild(item);
  }
}

async function selectExample(id) {
  currentExampleId = id;
  renderExampleList();
  updateUIHeader();
  updateActionButtons();

  currentGameState = "ready";
  currentControlMode = "manual";
  document.getElementById("btnModeManual")?.classList.add("active");
  document.getElementById("btnModeAI")?.classList.remove("active");
  const indicatorIcon = document.getElementById("indicatorIcon");
  const indicatorText = document.getElementById("indicatorText");
  if (indicatorIcon) indicatorIcon.textContent = "๐ŸŽฎ";
  if (indicatorText) {
    indicatorText.textContent = currentLang === "ko" ? "์ธ๊ฐ„ ์ˆ˜๋™ ์กฐ์ž‘ ๋ชจ๋“œ" : "Human Manual Mode";
  }
  updateModeHelpText();
  updateGameStateUI();

  // ๐Ÿš€ WASM ๋ฌผ๋ฆฌ ์—”์ง„์œผ๋กœ ์ง๊ฒฐ (์ง€์—ฐ ์ œ๋กœ, 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ 3D ๋ฌผ๋ฆฌ ์ฆ‰์‹œ ๋กœ๋“œ)
  if (useWasm) {
    if (wasmPlayer && wasmPlayer.isReady) {
      wasmPlayer.loadGame(id);
    } else {
      initWasmEngine().then(player => {
        if (player && player.isReady) player.loadGame(id);
      }).catch(err => {
        console.error("selectExample wasm load error:", err);
      });
    }
    return;
  }
}

function nextExample() {
  const nextId = currentExampleId >= 10 ? 1 : currentExampleId + 1;
  selectExample(nextId);
}

function updateUIHeader() {
  const meta = examplesData[currentExampleId];
  if (!meta) return;

  const title = currentLang === "ko" ? meta.title_kr : `${currentExampleId.toString().padStart(2, "0")} ยท ${meta.title}`;
  document.getElementById("activeTitle").textContent = title;
  document.getElementById("activeBadge").textContent = meta.badge;

  // 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ ์ „์šฉ HUD ์œ„์ ฏ ๊ฐ€์‹œ์„ฑ ์ œ์–ด
  const setHudDisplay = (id, show) => {
    const el = document.getElementById(id);
    if (el) el.style.display = show ? "flex" : "none";
  };

  const isCartpole = currentExampleId === 7;
  setHudDisplay("scoreHud", isCartpole);
  setHudDisplay("bestHud", isCartpole);
  setHudDisplay("angleHud", isCartpole);
  setHudDisplay("beanHud", currentExampleId === 1);
  setHudDisplay("pinballHud", currentExampleId === 2);
  setHudDisplay("dominoHud", currentExampleId === 3);
  setHudDisplay("swingHud", currentExampleId === 4);
  setHudDisplay("acroHud", currentExampleId === 5);
  setHudDisplay("raceHud", currentExampleId === 6);
  setHudDisplay("coinHud", currentExampleId === 8);
  setHudDisplay("clawHud", currentExampleId === 9);
  setHudDisplay("demoHud", currentExampleId === 10);

  // ๋ชจ๋“œ ์นด๋“œ ์ƒ์‹œ ํ™œ์„ฑํ™” (10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ ์ „์ฒด ์Šค๋งˆํŠธ AI ์ž์œจ์ฃผํ–‰/์˜คํ† ํ”Œ๋ ˆ์ด ์ง€์›)
  document.getElementById("modeCard").style.display = "flex";
  document.getElementById("cannonCard").style.display = currentExampleId === 10 ? "flex" : "none";
  updateModeHelpText();
}

// ============================================================================
// ๐ŸŽ›๏ธ ์ƒํ™ฉ๋ณ„ 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ ์กฐ์ž‘ ๋ฒ„ํŠผ ๋ฐ”์ธ๋”
// ============================================================================
function updateActionButtons() {
  const grid = document.getElementById("actionBtnGrid");
  if (!grid) return;
  grid.innerHTML = "";
  const isKo = currentLang === "ko";

  if (currentExampleId === 1) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('drop_bean')">

        ๐ŸŽˆ ${isKo ? "์ ค๋ฆฌ๋นˆ ๊ณต์ค‘ ํˆฌํ•˜! (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Drop Extra Bean! (Space)"}

      </button>

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 6px;">

        <button class="btn-action-trigger" onclick="sendAction('bounce_cushion', -1)">

          โ—€ ${isKo ? "์ขŒ์ธก ํŠ•๊ธฐ๊ธฐ (โ† / A)" : "Bounce Left (โ† / A)"}

        </button>

        <button class="btn-action-trigger" onclick="sendAction('bounce_cushion', 1)">

          ${isKo ? "์šฐ์ธก ํŠ•๊ธฐ๊ธฐ โ–ถ (โ†’ / D)" : "Bounce Right โ–ถ (โ†’ / D)"}

        </button>

      </div>

    `;
  } else if (currentExampleId === 2) {
    grid.innerHTML = `

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">

        <button class="btn-action-trigger" onmousedown="sendAction('flip_left')" onmouseup="sendAction('flip_stop')">

          โ—€ ${isKo ? "์ขŒ์ธก ํ”Œ๋ฆฌํผ (A)" : "Left Flipper (A)"}

        </button>

        <button class="btn-action-trigger" onmousedown="sendAction('flip_right')" onmouseup="sendAction('flip_stop')">

          ${isKo ? "์šฐ์ธก ํ”Œ๋ฆฌํผ โ–ถ (D)" : "Right Flipper โ–ถ (D)"}

        </button>

      </div>

      <button class="btn-action-trigger" style="margin-top: 6px;" onclick="sendAction('ball_rain')">

        โ˜” ${isKo ? "์ ค๋ฆฌ๋ณผ ํญํฌ์ˆ˜ (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Gumball Rain (Space)"}

      </button>

    `;
  } else if (currentExampleId === 3) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('push_domino')">

        ๐Ÿ‘‰ ${isKo ? "1๋ฒˆ ๋„๋ฏธ๋…ธ ๋ฐ€๊ธฐ! (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Strike 1st Domino! (Space)"}

      </button>

    `;
  } else if (currentExampleId === 4) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('swing_pump')">

        ๐ŸŽก ${isKo ? "๊ทธ๋„ค ๋ฐ˜๋™ ๊ฐ€์† (W / โ†‘ / ์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Pump Momentum (W / โ†‘ / Space)"}

      </button>

    `;
  } else if (currentExampleId === 5) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('acrobatic_flip')">

        ๐Ÿคธ ${isKo ? "์•„ํฌ๋กœ๋ฐ”ํ‹ฑ ํ‚ฅ (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Acrobatic Kick (Space)"}

      </button>

    `;
  } else if (currentExampleId === 6) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('start_race')">

        ๐Ÿ ${isKo ? "์›Œํ„ฐ ์Šฌ๋ผ์ด๋“œ ์ถœ๋ฐœ! (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Start Slide Race! (Space)"}

      </button>

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 6px;">

        <button class="btn-action-trigger" onclick="sendAction('slide_boost_pink')">${isKo ? "๐Ÿš€ ํ•‘ํฌ๋นˆ ๋ถ€์Šคํ„ฐ (A / โ†)" : "๐Ÿš€ Pink Turbo Boost (A / โ†)"}</button>

        <button class="btn-action-trigger" onclick="sendAction('slide_boost_mint')">${isKo ? "๐Ÿš€ ๋ฏผํŠธ๋นˆ ๋ถ€์Šคํ„ฐ (D / โ†’)" : "๐Ÿš€ Mint Turbo Boost (D / โ†’)"}</button>

      </div>

    `;
  } else if (currentExampleId === 7) {
    grid.innerHTML = `

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">

        <button class="btn-action-trigger" onmousedown="sendAction('cart_left')" onmouseup="sendAction('cart_stop')">

          โ—€ ${isKo ? "์ขŒ์ธก ์ด๋™ (A / โ†)" : "Push Left (A / โ†)"}

        </button>

        <button class="btn-action-trigger" onmousedown="sendAction('cart_right')" onmouseup="sendAction('cart_stop')">

          ${isKo ? "์šฐ์ธก ์ด๋™ โ–ถ (D / โ†’)" : "Push Right โ–ถ (D / โ†’)"}

        </button>

      </div>

    `;
  } else if (currentExampleId === 8) {
    grid.innerHTML = `

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">

        <button class="btn-action-trigger" onmousedown="sendAction('car_forward')" onmouseup="sendAction('car_stop')">

          โ–ฒ ${isKo ? "์ „์ง„ (W / โ†‘)" : "Throttle (W / โ†‘)"}

        </button>

        <button class="btn-action-trigger" onmousedown="sendAction('car_backward')" onmouseup="sendAction('car_stop')">

          โ–ผ ${isKo ? "ํ›„์ง„ (S / โ†“)" : "Reverse (S / โ†“)"}

        </button>

        <button class="btn-action-trigger" onmousedown="sendAction('car_left')" onmouseup="sendAction('car_stop')">

          โ—€ ${isKo ? "์ขŒํšŒ์ „ (A / โ†)" : "Steer Left (A / โ†)"}

        </button>

        <button class="btn-action-trigger" onmousedown="sendAction('car_right')" onmouseup="sendAction('car_stop')">

          ${isKo ? "์šฐํšŒ์ „ โ–ถ (D / โ†’)" : "Steer Right โ–ถ (D / โ†’)"}

        </button>

      </div>

      <p style="font-size: 11px; color: var(--candy-yellow); font-weight: 700; margin-top: 6px; text-align: center;">

        โญ ${isKo ? "5๋Œ€ ํ™ฉ๊ธˆ ์ฝ”์ธ์„ ๋ชจ๋‘ ํš๋“ํ•˜์„ธ์š”!" : "Collect all 5 Golden Star Coins!"}

      </p>

    `;
  } else if (currentExampleId === 9) {
    grid.innerHTML = `

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">

        <button class="btn-action-trigger" onclick="sendAction('arm_shoulder_up')">${isKo ? "์–ด๊นจ ๊ด€์ ˆ โ†‘ (W / โ†‘)" : "Shoulder โ†‘ (W / โ†‘)"}</button>

        <button class="btn-action-trigger" onclick="sendAction('arm_shoulder_down')">${isKo ? "์–ด๊นจ ๊ด€์ ˆ โ†“ (S / โ†“)" : "Shoulder โ†“ (S / โ†“)"}</button>

        <button class="btn-action-trigger" onclick="sendAction('arm_elbow_up')">${isKo ? "ํŒ”๊ฟˆ์น˜ โ†— (D / โ†’)" : "Elbow โ†— (D / โ†’)"}</button>

        <button class="btn-action-trigger" onclick="sendAction('arm_elbow_down')">${isKo ? "ํŒ”๊ฟˆ์น˜ โ†˜ (A / โ†)" : "Elbow โ†˜ (A / โ†)"}</button>

      </div>

      <button class="btn-action-trigger" style="margin-top: 6px;" onclick="sendAction('claw_magnet_toggle')">

        ๐Ÿงฒ ${isKo ? "์ž์„ ํฌ๋ ˆ์ธ ํก์ฐฉ ON/OFF (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Magnet Grip Suction (Space)"}

      </button>

    `;
  } else if (currentExampleId === 10) {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('fire_cannon')">

        ๐Ÿš€ ${isKo ? "์ ค๋ฆฌ๋นˆ ๋Œ€ํฌ ๋ฐœ์‚ฌ! (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "FIRE CANNONBALL! (Space)"}

      </button>

    `;
  } else {
    grid.innerHTML = `

      <button class="btn-action-trigger" onclick="sendAction('start')">

        โ–ถ ${isKo ? "๋ฌผ๋ฆฌ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ์‹œ์ž‘ (์ŠคํŽ˜์ด์Šค๋ฐ”)" : "Trigger Physics (Space)"}

      </button>

    `;
  }
}

function triggerStaticVictory(exampleId) {
  currentGameState = "victory";
  playCheer();
  triggerConfetti();

  const banner = (currentLang === "ko" ? VICTORY_BANNERS_KR[exampleId] : VICTORY_BANNERS[exampleId]) || {
    icon: "๐ŸŒŸ",
    title: "VICTORY!",
    sub: "Stage Cleared!"
  };
  const iconEl = document.getElementById("vicIcon");
  const titleEl = document.getElementById("vicTitle");
  const subEl = document.getElementById("vicSub");
  if (iconEl) iconEl.textContent = banner.icon;
  if (titleEl) titleEl.textContent = banner.title;
  if (subEl) subEl.textContent = banner.sub;
  updateGameStateUI();
}

function startStaticAISimulation(exampleId) {
  if (staticLifecycleTimer) {
    clearTimeout(staticLifecycleTimer);
    staticLifecycleTimer = null;
  }
  if (staticBalanceInterval) {
    clearInterval(staticBalanceInterval);
    staticBalanceInterval = null;
  }
  const screenImg = document.getElementById("mjpegStream");

  // 01 ์Šค์นด์ด๋‹ค์ด๋น™ AI ๋ฆฌ๋“ฌ ํˆฌํ•˜ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ (1.2์ดˆ ๊ฐ„๊ฒฉ 4ํšŒ ํˆฌํ•˜ ํ›„ ์Šน๋ฆฌ)
  if (exampleId === 1) {
    let aiLanded = 0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 1) {
        clearInterval(staticBalanceInterval);
        return;
      }
      aiLanded++;
      const beanEl = document.getElementById("hudBeansLanded");
      if (beanEl) beanEl.textContent = `${aiLanded} / 4 ๐ŸŽˆ`;
      playBoing();
      if (aiLanded >= 4) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(1);
      }
    }, 700);
  }
  // 02 ์บ”๋”” ํ•€๋ณผ ๋ณผํ’€์žฅ AI ์ž๋™ ํ”Œ๋ฆฌํ•‘ ๋ฐ 1000์  ๋ŒํŒŒ
  else if (exampleId === 2) {
    staticPinballScore = 0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 2) {
        clearInterval(staticBalanceInterval);
        return;
      }
      staticPinballScore += Math.floor(Math.random() * 60) + 120;
      const pinEl = document.getElementById("hudPinballScore");
      if (pinEl) pinEl.textContent = staticPinballScore;
      playBoing();
      if (staticPinballScore >= 1000) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(2);
      }
    }, 320);
  }
  // 03 ๋„๋ฏธ๋…ธ ์ŠคํŠธ๋ผ์ดํฌ AI ํƒ„๋„ ์ž„ํŽ„์Šค ๊ฒฉ๋ฐœ
  else if (exampleId === 3) {
    staticLifecycleTimer = setTimeout(() => {
      if (currentGameState !== "playing" || currentExampleId !== 3) return;
      if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[3]) {
        screenImg.src = EMBEDDED_CLEARED[3];
      }
      const domEl = document.getElementById("hudDominoStatus");
      if (domEl) domEl.textContent = "AI Cleared! (0.83s) ๐ŸŒŸ";
      triggerStaticVictory(3);
    }, 2400);
  }
  // 04 ์ž์ด์–ธํŠธ ๊ทธ๋„ค AI ๊ณต์ง„ ํŽŒํ•‘ 360๋„ ๋ฃจํ”„
  else if (exampleId === 4) {
    let aiAngle = 0.0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 4) {
        clearInterval(staticBalanceInterval);
        return;
      }
      aiAngle += 72.0;
      const swingEl = document.getElementById("hudSwingAngle");
      if (swingEl) swingEl.textContent = `${aiAngle.toFixed(1)}ยฐ (${Math.min(1, Math.floor(aiAngle / 360))} loop)`;
      playBoing();
      if (aiAngle >= 360.0) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(4);
      }
    }, 550);
  }
  // 05 ํŠธ์œˆ ์•„ํฌ๋กœ๋ฐ”ํ‹ฑ ์Šค์œ™ AI 3์—ฐ์† ํ…€๋ธ”๋ง ํ‚ฅ
  else if (exampleId === 5) {
    let aiCombos = 0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 5) {
        clearInterval(staticBalanceInterval);
        return;
      }
      aiCombos++;
      const acroEl = document.getElementById("hudAcroCombo");
      if (acroEl) acroEl.textContent = `${aiCombos} / 3 ๐Ÿคธ`;
      playBoing();
      if (aiCombos >= 3) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(5);
      }
    }, 800);
  }
  // 06 ์Šฌ๋ผ์ด๋“œ ๋ ˆ์ด์Šค AI ์Šฌ๋ฆฝ์ŠคํŠธ๋ฆผ ์ถ”์›” ์—ญ์ „์Šน
  else if (exampleId === 6) {
    staticLifecycleTimer = setTimeout(() => {
      if (currentGameState !== "playing" || currentExampleId !== 6) return;
      if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[6]) {
        screenImg.src = EMBEDDED_CLEARED[6];
      }
      const leaderEl = document.getElementById("hudRaceLeader");
      if (leaderEl) leaderEl.textContent = "Pink Bean Won! ๐Ÿ†";
      triggerStaticVictory(6);
    }, 2400);
  }
  // 07 ์นดํŠธํด LQR AI ํผํŽ™ํŠธ ๋ฐธ๋Ÿฐ์‹ฑ (3.5์ดˆ ๋ฐ๋ชจ ํ›„ ์Šน๋ฆฌ)
  else if (exampleId === 7) {
    staticSurvivalTime = 0.0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentExampleId !== 7) {
        clearInterval(staticBalanceInterval);
        return;
      }
      staticSurvivalTime += 0.5;
      const scoreEl = document.getElementById("hudScore");
      const angleEl = document.getElementById("hudAngle");
      if (scoreEl) scoreEl.textContent = `${staticSurvivalTime.toFixed(2)}s`;
      if (angleEl) {
        const sway = (Math.sin(staticSurvivalTime * 3.5) * 0.8).toFixed(1);
        angleEl.textContent = `${sway > 0 ? "+" : ""}${sway}ยฐ`;
      }
      if (staticSurvivalTime >= 3.5) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(7);
      }
    }, 250);
  }
  // 08 ๋ฒ”ํผ์นด Pure Pursuit AI ์ฝ”์ธ ์ˆœ์ฐจ 5/5 ์ˆ˜์ง‘
  else if (exampleId === 8) {
    let aiCoins = 0;
    staticBalanceInterval = setInterval(() => {
      if (currentGameState !== "playing" || currentControlMode !== "ai" || currentExampleId !== 8) {
        clearInterval(staticBalanceInterval);
        return;
      }
      aiCoins++;
      const coinEl = document.getElementById("hudCoins");
      if (coinEl) coinEl.textContent = aiCoins;
      playBoing();
      if (aiCoins >= 5) {
        clearInterval(staticBalanceInterval);
        triggerStaticVictory(8);
      }
    }, 650);
  }
  // 09 ์ธํ˜•๋ฝ‘๊ธฐ 3๋‹จ๊ณ„ IK ์ž์„ ํฌ๋ ˆ์ธ ๊ตฌ์ถœ
  else if (exampleId === 9) {
    const clawEl = document.getElementById("hudClawHeight");
    if (clawEl) clawEl.textContent = "0.25m (Targeting ๐ŸŽฏ)";
    staticLifecycleTimer = setTimeout(() => {
      if (currentGameState !== "playing" || currentExampleId !== 9) return;
      if (clawEl) clawEl.textContent = "0.45m (Grip ON ๐Ÿงฒ)";
      playBoing();
      staticLifecycleTimer = setTimeout(() => {
        if (currentGameState !== "playing" || currentExampleId !== 9) return;
        if (clawEl) clawEl.textContent = "Rescued! ๐Ÿงธ";
        triggerStaticVictory(9);
      }, 1200);
    }, 1000);
  }
  // 10 ๋งˆ์นด๋กฑ ๋ฉ”๊ฐ€ํƒ€์›Œ ํƒ„๋„ํ•™ CoM ์ €๊ฒฉ ์™„ํŒŒ
  else if (exampleId === 10) {
    staticLifecycleTimer = setTimeout(() => {
      if (currentGameState !== "playing" || currentExampleId !== 10) return;
      if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[10]) {
        screenImg.src = EMBEDDED_CLEARED[10];
      }
      const demoEl = document.getElementById("hudDemo");
      if (demoEl) demoEl.textContent = "100.0";
      triggerStaticVictory(10);
    }, 2300);
  }
}

// ============================================================================
// ๐Ÿ“ก ์„œ๋ฒ„ ์•ก์…˜ ์ „์†ก & ์ŠคํŽ˜์ด์Šค ์ธํ„ฐ๋ž™ํ‹ฐ๋ธŒ ์ƒํƒœ ๋จธ์‹ 
// ============================================================================
async function sendAction(actionType, value = 0.0) {
  const isStatic = (typeof IS_STATIC_SPACE !== "undefined" && IS_STATIC_SPACE) || (typeof EMBEDDED_ANIMATIONS !== "undefined");
  const screenImg = document.getElementById("mjpegStream");

  // ๐Ÿค– ์œ ์ € ์ธํ„ฐ๋ž™ํ‹ฐ๋ธŒ ์กฐ์ž‘ ์‹œ ์Šค๋งˆํŠธ AI ๋ชจ๋“œ โž” ์ธ๊ฐ„ ์ˆ˜๋™ ๋ชจ๋“œ๋กœ ์ž๋™ ์ „ํ™˜ (Human Takeover)
  if (currentControlMode === "ai" && actionType !== "start" && actionType !== "reset") {
    setControlMode("manual");
  }

  // ๐Ÿš€ Client-Side MuJoCo WebAssembly Engine Handler (Instant Response)
  if (useWasm) {
    if (!wasmPlayer || !wasmPlayer.isReady) {
      await initWasmEngine();
    }
    if (wasmPlayer) {
      if (actionType === "start") {
        playStart();
      } else if (actionType === "reset") {
        playPop();
      } else {
        playBoing();
      }
      try {
        wasmPlayer.applyAction(actionType, value);
      } catch (err) {
        console.warn("wasmPlayer.applyAction suppressed error:", err);
      }
      currentGameState = wasmPlayer.gameState;
      updateGameStateUI();
      return;
    }
  }

  if (actionType === "start" || actionType === "fire_cannon" || actionType === "push_domino" || actionType === "start_race") {
    playStart();
    currentGameState = "playing";
    updateGameStateUI();

    if (isStatic && screenImg) {
      if (staticLifecycleTimer) clearTimeout(staticLifecycleTimer);
      if (staticBalanceInterval) clearInterval(staticBalanceInterval);

      // ๋ชจ๋“œ์— ๋”ฐ๋ผ ์™„์ „ํžˆ ๋ถ„๋ฆฌ๋œ ๊ฒŒ์ž„ ๋ฃจํ”„ ์‹คํ–‰!
      if (currentControlMode === "ai") {
        // [๐Ÿค– ์Šค๋งˆํŠธ AI ๋ชจ๋“œ]: ์ž์œจ ์ฃผํ–‰ ๋ฌผ๋ฆฌ ์• ๋‹ˆ๋ฉ”์ด์…˜ ๊ฐ€๋™ ๋ฐ ์ „ 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ 100% ํด๋ฆฌ์–ด ์‹œ์—ฐ!
        if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[currentExampleId]) {
          screenImg.src = EMBEDDED_ANIMATIONS[currentExampleId] + "?t=" + Date.now();
        }
        startStaticAISimulation(currentExampleId);
      } else {
        // [๐ŸŽฎ ์ธ๊ฐ„ ์ˆ˜๋™ ์กฐ์ž‘ ๋ชจ๋“œ]:
        // ์œ ์ €๊ฐ€ ํ‚ค๋ฅผ ์ง์ ‘ ๋ˆ„๋ฅด๊ธฐ ์ „๊นŒ์ง€๋Š” ์ •์ง€ ์Šคํ‹ธ์ปท(Still)์„ ์œ ์ง€ํ•˜์—ฌ ํ˜ผ์ž ์‹คํ–‰๋˜๋Š” ํ˜„์ƒ ์›์ฒœ ์ฐจ๋‹จ!
        if (actionType === "fire_cannon" || (currentExampleId === 10 && actionType === "start" && value === 1.0)) {
          // 10๋ฒˆ ๋Œ€ํฌ: ์œ ์ €๊ฐ€ ์ŠคํŽ˜์ด์Šค๋ฐ”๋‚˜ ๋ฐœ์‚ฌ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ๋งŒ ๊ฒฉ๋ฐœ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์žฌ์ƒ ๋ฐ ํด๋ฆฌ์–ด!
          if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[10]) {
            screenImg.src = EMBEDDED_ANIMATIONS[10] + "?t=" + Date.now();
          }
          staticLifecycleTimer = setTimeout(() => {
            if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[10]) {
              screenImg.src = EMBEDDED_CLEARED[10];
            }
            const demoEl = document.getElementById("hudDemo");
            if (demoEl) demoEl.textContent = "100.0";
            triggerStaticVictory(10);
          }, 2300);
        } else if (actionType === "push_domino" || (currentExampleId === 3 && actionType === "start" && value === 1.0)) {
          // 03๋ฒˆ ๋„๋ฏธ๋…ธ: ์œ ์ €๊ฐ€ ์ŠคํŽ˜์ด์Šค๋ฐ”๋‚˜ ๋„๋ฏธ๋…ธ ๋ฐ€๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ๋งŒ ์—ฐ์‡„ ์ „๋„ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์žฌ์ƒ ๋ฐ ํด๋ฆฌ์–ด!
          if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[3]) {
            screenImg.src = EMBEDDED_ANIMATIONS[3] + "?t=" + Date.now();
          }
          staticLifecycleTimer = setTimeout(() => {
            if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[3]) {
              screenImg.src = EMBEDDED_CLEARED[3];
            }
            const domEl = document.getElementById("hudDominoStatus");
            if (domEl) domEl.textContent = "Cleared! (0.83s) ๐ŸŒŸ";
            triggerStaticVictory(3);
          }, 2400);
        } else if (actionType === "start_race" || (currentExampleId === 6 && actionType === "start" && value === 1.0)) {
          // 06๋ฒˆ ์Šฌ๋ผ์ด๋“œ: ๋ ˆ์ด์Šค ์ถœ๋ฐœ ์‹ ํ˜ธ ์‹œ ์Šฌ๋ผ์ด๋“œ ๋‹ค์šด ์• ๋‹ˆ๋ฉ”์ด์…˜ ์žฌ์ƒ ๋ฐ ํด๋ฆฌ์–ด!
          if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[6]) {
            screenImg.src = EMBEDDED_ANIMATIONS[6] + "?t=" + Date.now();
          }
          staticLifecycleTimer = setTimeout(() => {
            if (screenImg && typeof EMBEDDED_CLEARED !== "undefined" && EMBEDDED_CLEARED[6]) {
              screenImg.src = EMBEDDED_CLEARED[6];
            }
            const leaderEl = document.getElementById("hudRaceLeader");
            if (leaderEl) leaderEl.textContent = "Pink Bean Won! ๐Ÿ†";
            triggerStaticVictory(6);
          }, 2400);
        } else if (currentExampleId === 7) {
          // 07๋ฒˆ ์นดํŠธํด: 15์ดˆ ์ƒ์กด ๋„์ „ ์นด์šดํŠธ๋‹ค์šด
          staticSurvivalTime = 0.0;
          if (typeof EMBEDDED_ANIMATIONS !== "undefined" && EMBEDDED_ANIMATIONS[7]) {
            screenImg.src = EMBEDDED_ANIMATIONS[7] + "?t=" + Date.now();
          }
          staticBalanceInterval = setInterval(() => {
            if (currentGameState !== "playing" || currentExampleId !== 7) {
              clearInterval(staticBalanceInterval);
              return;
            }
            staticSurvivalTime += 0.1;
            const scoreEl = document.getElementById("hudScore");
            const angleEl = document.getElementById("hudAngle");
            if (scoreEl) scoreEl.textContent = `${staticSurvivalTime.toFixed(2)}s`;
            if (angleEl) {
              const sway = (Math.sin(staticSurvivalTime * 3.5) * 1.2).toFixed(1);
              angleEl.textContent = `${sway > 0 ? "+" : ""}${sway}ยฐ`;
            }
            if (staticSurvivalTime >= 15.0) {
              clearInterval(staticBalanceInterval);
              triggerStaticVictory(7);
            }
          }, 100);
        } else {
          // 01, 02, 04, 05, 08, 09๋ฒˆ: ๊ฒŒ์ž„ ์‹œ์ž‘ ์‹œ ์ •์ง€ ์Šคํ‹ธ์ปท(Still)์„ ์œ ์ง€ํ•˜์—ฌ ํ˜ผ์ž ์‹คํ–‰๋˜๋Š” ํ˜„์ƒ ์ฐจ๋‹จ!
          if (typeof EMBEDDED_STILLS !== "undefined" && EMBEDDED_STILLS[currentExampleId]) {
            screenImg.src = EMBEDDED_STILLS[currentExampleId];
          }
        }
      }
    }
  } else if (actionType === "reset") {
    playPop();
    currentGameState = "ready";

    if (staticLifecycleTimer) {
      clearTimeout(staticLifecycleTimer);
      staticLifecycleTimer = null;
    }
    if (staticBalanceInterval) {
      clearInterval(staticBalanceInterval);
      staticBalanceInterval = null;
    }
    staticBeanCounter = 0;
    staticPinballScore = 0;
    staticSwingLoops = 0;
    staticAcroCombo = 0;
    staticCoinCounter = 0;
    staticClawMagnet = false;
    staticSurvivalTime = 0.0;

    // ๋Œ€๊ธฐ ์ƒํƒœ์˜ ๊นจ๋—ํ•œ ์ •์ง€ ์Šคํ‹ธ์ปท์œผ๋กœ ๋ณต๊ท€
    if (isStatic && screenImg && typeof EMBEDDED_STILLS !== "undefined" && EMBEDDED_STILLS[currentExampleId]) {
      screenImg.src = EMBEDDED_STILLS[currentExampleId];
    }

    updateGameStateUI();

    // 10๋Œ€ ๋ฏธ๋‹ˆ๊ฒŒ์ž„ ์ „์ฒด HUD ์ˆ˜์น˜ ๋ฆฌ์…‹
    const scoreEl = document.getElementById("hudScore");
    if (scoreEl) scoreEl.textContent = "0.00s";
    const angleEl = document.getElementById("hudAngle");
    if (angleEl) angleEl.textContent = "0.0ยฐ";
    const coinEl = document.getElementById("hudCoins");
    if (coinEl) coinEl.textContent = "0";
    const demoEl = document.getElementById("hudDemo");
    if (demoEl) demoEl.textContent = "0.0";
    const beanEl = document.getElementById("hudBeansLanded");
    if (beanEl) beanEl.textContent = "0 / 4 ๐ŸŽˆ";
    const pinEl = document.getElementById("hudPinballScore");
    if (pinEl) pinEl.textContent = "0";
    const domEl = document.getElementById("hudDominoStatus");
    if (domEl) domEl.textContent = "Ready ๐ŸŒŸ";
    const acroEl = document.getElementById("hudAcroCombo");
    if (acroEl) acroEl.textContent = "0 / 3 ๐Ÿคธ";
    const clawEl = document.getElementById("hudClawHeight");
    if (clawEl) clawEl.textContent = "0.12m ๐Ÿงธ";
    const leaderEl = document.getElementById("hudRaceLeader");
    if (leaderEl) leaderEl.textContent = "Ready to Race ๐Ÿ";
    const swingEl = document.getElementById("hudSwingAngle");
    if (swingEl) swingEl.textContent = "0.0ยฐ";
  } else {
    playBoing();
  }

  if (useWasm && wasmPlayer) {
    wasmPlayer.applyAction(actionType, value);
    currentGameState = wasmPlayer.gameState;
    updateGameStateUI();
    return;
  }

  try {
    const res = await fetch("/api/action", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action_type: actionType, value: value })
    });
    if (res.ok) {
      const data = await res.json();
      if (data.game_state) {
        currentGameState = data.game_state;
        updateGameStateUI(data);
      }
    }
  } catch (err) {
    if (!useWasm) {
      useWasm = true;
      await initWasmEngine();
      if (wasmPlayer) {
        wasmPlayer.loadGame(currentExampleId);
        wasmPlayer.applyAction(actionType, value);
      }
    }
  }
}

function handleMainStartClick() {
  if (currentGameState === "playing") {
    sendAction("reset");
  } else {
    sendAction("start");
  }
}

function updateGameStateUI(telemetry = null) {
  const readyOverlay = document.getElementById("readyOverlay");
  const gameoverOverlay = document.getElementById("gameoverOverlay");
  const victoryOverlay = document.getElementById("victoryOverlay");
  const mainStartBtn = document.getElementById("mainStartBtn");
  const dict = I18N[currentLang] || I18N.en;

  if (currentGameState === "ready") {
    if (readyOverlay) readyOverlay.style.display = "flex";
    if (gameoverOverlay) gameoverOverlay.style.display = "none";
    if (victoryOverlay) victoryOverlay.style.display = "none";
    if (mainStartBtn) mainStartBtn.textContent = dict.btn_start_game;
  } else if (currentGameState === "playing") {
    if (readyOverlay) readyOverlay.style.display = "none";
    if (gameoverOverlay) gameoverOverlay.style.display = "none";
    if (victoryOverlay) victoryOverlay.style.display = "none";
    if (mainStartBtn) mainStartBtn.textContent = dict.btn_playing;
  } else if (currentGameState === "gameover") {
    if (readyOverlay) readyOverlay.style.display = "none";
    if (gameoverOverlay) gameoverOverlay.style.display = "flex";
    if (victoryOverlay) victoryOverlay.style.display = "none";
    if (mainStartBtn) mainStartBtn.textContent = dict.btn_retry;

    if (telemetry) {
      const resSurv = document.getElementById("resSurvival");
      if (resSurv) resSurv.textContent = `${(telemetry.survival_time || 0).toFixed(2)}s`;
      const resRnk = document.getElementById("resRank");
      if (resRnk) resRnk.textContent = telemetry.rank || "B";
    }
  } else if (currentGameState === "victory") {
    if (readyOverlay) readyOverlay.style.display = "none";
    if (gameoverOverlay) gameoverOverlay.style.display = "none";
    if (victoryOverlay) victoryOverlay.style.display = "flex";
    if (mainStartBtn) mainStartBtn.textContent = dict.btn_play_again;

    if (telemetry && telemetry.victory_banner) {
      const iconEl = document.getElementById("vicIcon");
      const titleEl = document.getElementById("vicTitle");
      const subEl = document.getElementById("vicSub");
      if (iconEl) iconEl.textContent = telemetry.victory_banner.icon || "๐ŸŒŸ";
      if (titleEl) titleEl.textContent = telemetry.victory_banner.title || "VICTORY!";
      if (subEl) subEl.textContent = telemetry.victory_banner.sub || "Great job!";
    } else {
      const banner = (currentLang === "ko" ? VICTORY_BANNERS_KR[currentExampleId] : VICTORY_BANNERS[currentExampleId]);
      if (banner) {
        const iconEl = document.getElementById("vicIcon");
        const titleEl = document.getElementById("vicTitle");
        const subEl = document.getElementById("vicSub");
        if (iconEl) iconEl.textContent = banner.icon;
        if (titleEl) titleEl.textContent = banner.title;
        if (subEl) subEl.textContent = banner.sub;
      }
    }
  }
}

// ============================================================================
// ๐Ÿค– ์กฐ์ž‘ ๋ชจ๋“œ ๋ฐ ํŒŒ๋ผ๋ฏธํ„ฐ ์กฐ์ ˆ
// ============================================================================
async function setControlMode(mode) {
  playPop();
  currentControlMode = mode;
  document.getElementById("btnModeManual").classList.toggle("active", mode === "manual");
  document.getElementById("btnModeAI").classList.toggle("active", mode === "ai");

  const indicatorIcon = document.getElementById("indicatorIcon");
  const indicatorText = document.getElementById("indicatorText");
  if (indicatorIcon) {
    indicatorIcon.textContent = mode === "ai" ? "๐Ÿค–" : "๐ŸŽฎ";
  }
  if (indicatorText) {
    indicatorText.textContent = mode === "ai"
      ? (currentLang === "ko" ? "AI ์ž์œจ ์ œ์–ด ๋ชจ๋“œ" : "Autonomous AI Mode")
      : (currentLang === "ko" ? "์ธ๊ฐ„ ์ˆ˜๋™ ์กฐ์ž‘ ๋ชจ๋“œ" : "Human Manual Mode");
  }
  updateModeHelpText();

  if (useWasm && wasmPlayer) {
    wasmPlayer.setMode(mode);
    return;
  }

  if (mode === "ai" && currentGameState === "ready") {
    sendAction("start");
  }

  try {
    await fetch("/api/set_mode", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ mode: mode })
    });
  } catch (err) {
    // offline
  }
}

async function updateGravity(val) {
  const g = parseFloat(val);
  document.getElementById("gravityVal").textContent = `${g.toFixed(2)} m/sยฒ`;

  if (useWasm && wasmPlayer && wasmPlayer.model) {
    wasmPlayer.model.opt.gravity[2] = g;
    return;
  }

  try {
    await fetch("/api/set_gravity", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ gravity: g })
    });
  } catch (err) {}
}

function setGravityPreset(g) {
  playPop();
  document.getElementById("gravitySlider").value = g;
  updateGravity(g);
  document.querySelectorAll(".preset-pill").forEach(btn => {
    btn.classList.toggle("active", parseFloat(btn.textContent.match(/-?\d+\.?\d*/)?.[0] || 0) === g);
  });
}

async function updateCannonPower(val) {
  const p = parseFloat(val);
  document.getElementById("cannonPowerVal").textContent = `${p.toFixed(1)}x`;

  if (useWasm && wasmPlayer) {
    wasmPlayer.cannonPower = p;
    return;
  }

  try {
    await fetch("/api/cannon_power", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ power: p })
    });
  } catch (err) {}
}

function setCannonPowerPreset(p) {
  playPop();
  document.getElementById("cannonSlider").value = p;
  updateCannonPower(p);
}

// ============================================================================
// โŒจ๏ธ ํ‚ค๋ณด๋“œ ์ž…๋ ฅ ๋ฐ ์‹œ๊ฐํ™”
// ============================================================================
function setupKeyboardListeners() {
  window.addEventListener("keydown", (e) => {
    if (e.repeat) return;
    const code = e.code;
    activeKeySet.add(code);
    highlightKeyBox(code, true);

    // ๊ณตํ†ต ๋ฆฌ์…‹
    if (code === "KeyR") {
      sendAction("reset");
      return;
    }

    // ์นด๋ฉ”๋ผ ์ „ํ™˜ ๋‹จ์ถ•ํ‚ค [C]
    if (code === "KeyC") {
      cycleCamera();
      return;
    }

    // ์™€์ด๋“œ ์ „์ฒดํ™”๋ฉด ์ „ํ™˜ ๋‹จ์ถ•ํ‚ค [F]
    if (code === "KeyF") {
      const fsBtn = document.getElementById("fullscreenBtn");
      if (fsBtn) fsBtn.click();
      return;
    }

    // ๋ชจ๋“œ ํ† ๊ธ€ [M]
    if (code === "KeyM") {
      setControlMode(currentControlMode === "manual" ? "ai" : "manual");
      return;
    }

    // ์ŠคํŽ˜์ด์Šค ํ‚ค
    if (code === "Space") {
      e.preventDefault();
      if (currentGameState === "ready" || currentGameState === "gameover") {
        if (currentExampleId === 3) {
          sendAction("push_domino");
        } else if (currentExampleId === 6) {
          sendAction("start_race");
        } else if (currentExampleId === 10) {
          sendAction("fire_cannon");
        } else {
          sendAction("start");
        }
      } else if (currentExampleId === 1) {
        sendAction("drop_bean");
      } else if (currentExampleId === 2) {
        sendAction("ball_rain");
      } else if (currentExampleId === 3) {
        sendAction("push_domino");
      } else if (currentExampleId === 4) {
        sendAction("swing_pump");
      } else if (currentExampleId === 5) {
        sendAction("acrobatic_flip");
      } else if (currentExampleId === 6) {
        sendAction("start_race");
      } else if (currentExampleId === 9) {
        sendAction("claw_magnet_toggle");
      } else if (currentExampleId === 10) {
        sendAction("fire_cannon");
      }
      return;
    }

    // ๊ฒŒ์ž„ 01 ์Šค์นด์ด๋‹ค์ด๋น™ (A/D ๋ฐ ์ขŒ์šฐ ๋ฐฉํ–ฅํ‚ค๋กœ ์ฟ ์…˜ ํŠ•๊ธฐ๊ธฐ)
    if (currentExampleId === 1) {
      if (code === "KeyA" || code === "ArrowLeft") sendAction("bounce_cushion", -1);
      if (code === "KeyD" || code === "ArrowRight") sendAction("bounce_cushion", 1);
    }
    // ๊ฒŒ์ž„ 02 ํ•€๋ณผ (A/D ๋ฐ ์ขŒ์šฐ ๋ฐฉํ–ฅํ‚ค ๋™์‹œ ์ง€์›)
    else if (currentExampleId === 2) {
      if (code === "KeyA" || code === "ArrowLeft") sendAction("flip_left");
      if (code === "KeyD" || code === "ArrowRight") sendAction("flip_right");
    }
    // ๊ฒŒ์ž„ 04 ๊ทธ๋„ค ํŽŒํ•‘ (W, Up, Space)
    else if (currentExampleId === 4) {
      if (code === "KeyW" || code === "ArrowUp") sendAction("swing_pump");
    }
    // ๊ฒŒ์ž„ 05 ์•„ํฌ๋กœ๋ฐ”ํ‹ฑ ๊ด€์ ˆ ์ œ์–ด (W/S: ๊ด€์ ˆ1, A/D: ๊ด€์ ˆ2)
    else if (currentExampleId === 5) {
      if (code === "KeyW" || code === "ArrowUp") sendAction("acrobatic_j1_up");
      if (code === "KeyS" || code === "ArrowDown") sendAction("acrobatic_j1_down");
      if (code === "KeyA" || code === "ArrowLeft") sendAction("acrobatic_j2_up");
      if (code === "KeyD" || code === "ArrowRight") sendAction("acrobatic_j2_down");
    }
    // ๊ฒŒ์ž„ 06 ์Šฌ๋ผ์ด๋“œ ๋ถ€์Šคํ„ฐ (A/Left: ํ•‘ํฌ๋นˆ, D/Right: ๋ฏผํŠธ๋นˆ)
    else if (currentExampleId === 6) {
      if (code === "KeyA" || code === "ArrowLeft") sendAction("slide_boost_pink");
      if (code === "KeyD" || code === "ArrowRight") sendAction("slide_boost_mint");
    }
    // ๊ฒŒ์ž„ 07 ์นดํŠธํด ๋ฐธ๋Ÿฐ์„œ (A/D ๋ฐ ๋ฐฉํ–ฅํ‚ค ์ขŒ์šฐ ๋™์‹œ ์ง€์›)
    else if (currentExampleId === 7) {
      if (code === "KeyA" || code === "ArrowLeft") sendAction("cart_left");
      if (code === "KeyD" || code === "ArrowRight") sendAction("cart_right");
    }
    // ๊ฒŒ์ž„ 08 ๋ฒ”ํผ์นด ๋“œ๋ผ์ด๋ธŒ (WASD ๋ฐ ๋ฐฉํ–ฅํ‚ค ์ƒํ•˜์ขŒ์šฐ ๋™์‹œ ์ง€์›)
    else if (currentExampleId === 8) {
      if (code === "KeyW" || code === "ArrowUp") sendAction("car_forward");
      if (code === "KeyS" || code === "ArrowDown") sendAction("car_backward");
      if (code === "KeyA" || code === "ArrowLeft") sendAction("car_left");
      if (code === "KeyD" || code === "ArrowRight") sendAction("car_right");
    }
    // ๊ฒŒ์ž„ 09 ๋กœ๋ด‡ํŒ” ํฌ๋ ˆ์ธ (WASD ๋ฐ ๋ฐฉํ–ฅํ‚ค ๋™์‹œ ์ง€์›)
    else if (currentExampleId === 9) {
      if (code === "ArrowUp" || code === "KeyW") sendAction("arm_shoulder_up");
      if (code === "ArrowDown" || code === "KeyS") sendAction("arm_shoulder_down");
      if (code === "ArrowRight" || code === "KeyD") sendAction("arm_elbow_up");
      if (code === "ArrowLeft" || code === "KeyA") sendAction("arm_elbow_down");
    }
    // ๊ฒŒ์ž„ 10 ๋งˆ์นด๋กฑ ๋Œ€ํฌ ํŒŒ์›Œ ์กฐ์ ˆ (W/โ†‘: ํŒŒ์›Œ ์ฆํญ, S/โ†“: ํŒŒ์›Œ ๊ฐ์‡ )
    else if (currentExampleId === 10) {
      const slider = document.getElementById("cannonSlider");
      if (slider) {
        if (code === "ArrowUp" || code === "KeyW") {
          const newVal = Math.min(2.5, +(parseFloat(slider.value) + 0.1).toFixed(1));
          slider.value = newVal;
          updateCannonPower(newVal);
        } else if (code === "ArrowDown" || code === "KeyS") {
          const newVal = Math.max(0.4, +(parseFloat(slider.value) - 0.1).toFixed(1));
          slider.value = newVal;
          updateCannonPower(newVal);
        }
      }
    }
  });

  window.addEventListener("keyup", (e) => {
    const code = e.code;
    activeKeySet.delete(code);
    highlightKeyBox(code, false);

    // 02 ํ•€๋ณผ
    if (currentExampleId === 2) {
      const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
      const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");
      if (!leftHeld && !rightHeld) sendAction("flip_stop");
      else if (leftHeld) sendAction("flip_left");
      else if (rightHeld) sendAction("flip_right");
    }
    // 05 ์•„ํฌ๋กœ๋ฐ”ํ‹ฑ
    else if (currentExampleId === 5) {
      sendAction("acrobatic_stop");
    }
    // 07 ์นดํŠธํด (A/D ๋ฐ ์ขŒ์šฐ ๋ฐฉํ–ฅํ‚ค ๋™์‹œ ์ง€์›)
    else if (currentExampleId === 7) {
      const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
      const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");
      if (!leftHeld && !rightHeld) sendAction("cart_stop");
      else if (leftHeld) sendAction("cart_left");
      else if (rightHeld) sendAction("cart_right");
    }
    // 08 ๋ฒ”ํผ์นด (๋ณตํ•ฉ ์ž…๋ ฅ ํ™€๋“œ ๋ณด์กด)
    else if (currentExampleId === 8) {
      const upHeld = activeKeySet.has("KeyW") || activeKeySet.has("ArrowUp");
      const downHeld = activeKeySet.has("KeyS") || activeKeySet.has("ArrowDown");
      const leftHeld = activeKeySet.has("KeyA") || activeKeySet.has("ArrowLeft");
      const rightHeld = activeKeySet.has("KeyD") || activeKeySet.has("ArrowRight");

      if (upHeld) sendAction("car_forward");
      else if (downHeld) sendAction("car_backward");
      else if (leftHeld) sendAction("car_left");
      else if (rightHeld) sendAction("car_right");
      else sendAction("car_stop");
    }
  });
}

function highlightKeyBox(code, isActive) {
  const keyMap = {
    KeyW: "keyW", ArrowUp: "keyW",
    KeyA: "keyA", ArrowLeft: "keyLeft",
    KeyS: "keyS", ArrowDown: "keyS",
    KeyD: "keyD", ArrowRight: "keyRight",
    Space: "keySpace", KeyR: "keyR", KeyC: "keyC"
  };
  const elemId = keyMap[code];
  if (elemId) {
    const el = document.getElementById(elemId);
    if (el) el.classList.toggle("active", isActive);
  }
}

// ============================================================================
// ๐Ÿ”„ ์‹ค์‹œ๊ฐ„ ํ…”๋ ˆ๋ฉ”ํŠธ๋ฆฌ ํด๋ง ๋ฃจํ”„
// ============================================================================
function startTelemetryLoop() {
  setInterval(async () => {
    if (useWasm) return;
    if ((typeof IS_STATIC_SPACE !== "undefined" && IS_STATIC_SPACE) || (typeof EMBEDDED_ANIMATIONS !== "undefined")) {
      return;
    }
    try {
      const res = await fetch("/api/telemetry");
      if (!res.ok) return;
      const data = await res.json();

      // ์ƒํƒœ ๋ณ€ํ™” ๊ฐ์ง€
      if (data.game_state !== currentGameState) {
        const prevState = currentGameState;
        currentGameState = data.game_state;
        if (currentGameState === "gameover" && prevState !== "gameover") {
          playGameOver();
        } else if (currentGameState === "victory" && prevState !== "victory") {
          playCheer();
          triggerConfetti();
        } else if (currentGameState === "playing" && prevState === "ready") {
          playStart();
          triggerConfetti();
        }
        updateGameStateUI(data);
      }

      // ์‚ฌ์šด๋“œ FX ์•Œ๋ฆผ (์ฝ”์ธ ํš๋“ ๋“ฑ)
      if (data.new_coin_sound) {
        playCoinSound();
        triggerConfetti();
      }

      // 1. ์Šค์นด์ด๋‹ค์ด๋น™
      if (data.example_id === 1) {
        const beanEl = document.getElementById("hudBeansLanded");
        if (beanEl) beanEl.textContent = `${data.beans_landed} (${data.beans_dropped} drops)`;
      }
      // 2. ์บ”๋”” ํ•€๋ณผ
      else if (data.example_id === 2) {
        const pinEl = document.getElementById("hudPinballScore");
        if (pinEl) pinEl.textContent = data.pinball_score || 0;
      }
      // 3. ๋„๋ฏธ๋…ธ ์ŠคํŠธ๋ผ์ดํฌ
      else if (data.example_id === 3) {
        const domEl = document.getElementById("hudDominoStatus");
        if (domEl) {
          domEl.textContent = data.domino_cleared
            ? "Cleared! (0.83s) ๐ŸŒŸ"
            : (data.survival_time > 0 ? `${data.survival_time.toFixed(2)}s ๐Ÿƒ` : "Ready ๐ŸŒŸ");
        }
      }
      // 4. ์ž์ด์–ธํŠธ ๊ทธ๋„ค
      else if (data.example_id === 4) {
        const swingEl = document.getElementById("hudSwingAngle");
        if (swingEl) swingEl.textContent = `${data.swing_angle_deg}ยฐ (Loops: ${data.swing_loops})`;
      }
      // 5. ์•„ํฌ๋กœ๋ฐ”ํ‹ฑ ํŠธ์œˆ
      else if (data.example_id === 5) {
        const acroEl = document.getElementById("hudAcroCombo");
        if (acroEl) acroEl.textContent = `${data.somersault_count} / 3 ๐Ÿคธ`;
      }
      // 6. ์Šฌ๋ผ์ด๋“œ ๋ ˆ์ด์Šค
      else if (data.example_id === 6) {
        const leaderEl = document.getElementById("hudRaceLeader");
        if (leaderEl) {
          leaderEl.textContent = data.race_winner ? `${data.race_winner} Won! ๐Ÿ†` : (data.race_leader || "Racing downhill...");
        }
      }
      // 7. ์นดํŠธํด ๋ฐธ๋Ÿฐ์„œ
      else if (data.example_id === 7) {
        const scoreEl = document.getElementById("hudScore");
        if (scoreEl) scoreEl.textContent = `${data.survival_time.toFixed(2)}s`;
        const bestEl = document.getElementById("hudBest");
        if (bestEl) bestEl.textContent = `${data.best_score.toFixed(2)}s`;
        const angleEl = document.getElementById("hudAngle");
        if (angleEl) angleEl.textContent = `${data.pole_angle_deg}ยฐ`;
      }
      // 8. ๋ฒ”ํผ์นด ์ฝ”์ธ ๋Œ€์‹œ
      else if (data.example_id === 8) {
        const coinsEl = document.getElementById("hudCoins");
        if (coinsEl) coinsEl.textContent = data.coins_collected;
      }
      // 9. ์ธํ˜•๋ฝ‘๊ธฐ ํฌ๋ ˆ์ธ
      else if (data.example_id === 9) {
        const clawEl = document.getElementById("hudClawHeight");
        if (clawEl) {
          clawEl.textContent = data.plushie_grabbed
            ? "Rescued! ๐Ÿงธ"
            : (data.claw_magnet_on ? `${(data.plushie_z || 0.12).toFixed(2)}m (Grip ON ๐Ÿงฒ)` : `${(data.plushie_z || 0.12).toFixed(2)}m ๐ŸŽฏ`);
        }
      }
      // 10. ๋งˆ์นด๋กฑ ํƒ€์›Œ ๋Œ€ํฌ
      else if (data.example_id === 10) {
        const demoEl = document.getElementById("hudDemo");
        if (demoEl) demoEl.textContent = data.demolition_rate.toFixed(1);
      }

    } catch (e) {
      // ignore
    }
  }, 80);
}

// ============================================================================
// ๐Ÿ“‹ ์ฝ”๋“œ ๋‚ด๋ณด๋‚ด๊ธฐ ๋ชจ๋‹ฌ
// ============================================================================
async function openCodeModal() {
  playPop();
  const modal = document.getElementById("codeModal");
  modal.style.display = "flex";
  document.getElementById("modalBrickTitle").textContent = `Brick #${currentExampleId.toString().padStart(2, "0")} Code Export`;

  if (typeof EMBEDDED_CODES !== "undefined" && EMBEDDED_CODES[String(currentExampleId)]) {
    currentCodeData = EMBEDDED_CODES[String(currentExampleId)];
    renderModalCode();
    return;
  }

  if (typeof window !== "undefined" && window.PREMIUM_GAME_XMLS && window.PREMIUM_GAME_XMLS[String(currentExampleId)]) {
    const rawXml = window.PREMIUM_GAME_XMLS[String(currentExampleId)];
    currentCodeData = {
      xml: rawXml,
      python: `# MuJoCo Standalone Executable Brick #${currentExampleId}\nimport mujoco\nimport mujoco.viewer\n\nxml = """${rawXml}"""\n\nmodel = mujoco.MjModel.from_xml_string(xml)\ndata = mujoco.MjData(model)\nmujoco.viewer.launch(model, data)\n`
    };
    renderModalCode();
    return;
  }
}

function closeCodeModal() {
  playPop();
  document.getElementById("codeModal").style.display = "none";
}

function switchCodeTab(tab) {
  playPop();
  currentCodeTab = tab;
  document.getElementById("tabPy").classList.toggle("active", tab === "py");
  document.getElementById("tabXml").classList.toggle("active", tab === "xml");
  renderModalCode();
}

function renderModalCode() {
  if (!currentCodeData) return;
  const viewer = document.getElementById("codeViewer");
  viewer.textContent = currentCodeTab === "py" ? currentCodeData.python : currentCodeData.xml;
}

function copyCurrentCode() {
  playCheer();
  triggerConfetti();
  const text = document.getElementById("codeViewer").textContent;
  navigator.clipboard.writeText(text).then(() => {
    alert(currentLang === "ko" ? "๐Ÿ“‹ ์ฝ”๋“œ๊ฐ€ ํด๋ฆฝ๋ณด๋“œ์— ๋ณต์‚ฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!" : "๐Ÿ“‹ Code copied to clipboard! Paste it into Antigravity.");
  });
}

// Expose all interactive functions to window for HTML onclick / onchange handlers
if (typeof window !== "undefined") {
  window.setCamera = setCamera;
  window.selectExample = selectExample;
  window.nextExample = nextExample;
  window.sendAction = sendAction;
  window.setControlMode = setControlMode;
  window.setGravityPreset = setGravityPreset;
  window.updateGravity = updateGravity;
  window.setCannonPowerPreset = setCannonPowerPreset;
  window.updateCannonPower = updateCannonPower;
  window.handleMainStartClick = handleMainStartClick;
  window.openCodeModal = openCodeModal;
  window.closeCodeModal = closeCodeModal;
  window.switchCodeTab = switchCodeTab;
  window.copyCurrentCode = copyCurrentCode;
  window.toggleBgm = toggleBgm;
}