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
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
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>FunctionGemma Physics Playground</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/decomp.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
  <link
    href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&family=Fira+Code:wght@500;700&display=swap"
    rel="stylesheet" />
  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ["Space Grotesk", "sans-serif"],
            mono: ["Fira Code", "monospace"],
          },
          colors: {
            "neo-bg": "#f0f0f0",
            "neo-black": "#1a1a1a",
            "neo-white": "#ffffff",
            "neo-purple": "#a78bfa",
            "neo-yellow": "#facc15",
            "neo-green": "#4ade80",
            "neo-red": "#f87171",
            "neo-blue": "#60a5fa",
            "neo-gray": "#94a3b8",
          },
          boxShadow: {
            neo: "4px 4px 0px 0px #000000",
            "neo-sm": "2px 2px 0px 0px #000000",
            "neo-lg": "8px 8px 0px 0px #000000",
          },
        },
      },
    };
  </script>

  <style>
    body {
      overflow: hidden;
      background-color: #e0e7ff;
      background-image: radial-gradient(#a5b4fc 1px, transparent 1px);
      background-size: 20px 20px;
    }

    /* Custom Scrollbar */
    ::-webkit-scrollbar {
      width: 12px;
      height: 12px;
    }

    ::-webkit-scrollbar-track {
      background: #fff;
      border-left: 2px solid black;
    }

    ::-webkit-scrollbar-thumb {
      background: #000;
      border: 2px solid #fff;
    }

    ::-webkit-scrollbar-thumb:hover {
      background: #333;
    }

    .neo-border {
      border: 3px solid black;
    }

    .neo-btn {
      transition: all 0.1s ease-in-out;
    }

    .neo-btn:active {
      transform: translate(2px, 2px);
      box-shadow: 2px 2px 0px 0px #000000;
    }

    .level-card {
      transition: all 0.2s;
    }

    .level-card:hover:not(.locked) {
      transform: translate(-2px, -2px);
      box-shadow: 6px 6px 0px 0px #000000;
    }

    .locked {
      background-color: #e2e8f0;
      cursor: not-allowed;
      opacity: 0.7;
      background-image: repeating-linear-gradient(45deg, #cbd5e1 0, #cbd5e1 1px, transparent 0, transparent 50%);
      background-size: 10px 10px;
    }

    .code-editor {
      font-family: "Fira Code", monospace;
      background-color: #ffffff;
      color: #000000;
      line-height: 1.6;
    }

    .toggle-checkbox:checked {
      right: 0;
      border-color: #4ade80;
    }

    .toggle-checkbox:checked+.toggle-label {
      background-color: #4ade80;
    }

    /* Action Item Delete Button Transition */
    .action-item .btn-delete {
      opacity: 0;
      transition: opacity 0.2s;
    }

    .action-item:hover .btn-delete {
      opacity: 1;
    }
  </style>
</head>

<body class="h-screen w-screen flex flex-col md:flex-row p-4 gap-4">
  <!-- Loading Overlay -->
  <div id="loading-overlay" class="fixed inset-0 bg-black/90 z-50 flex flex-col items-center justify-center">
    <div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-neo-green mb-4"></div>
    <div class="text-white font-mono font-bold text-xl">LOADING MODEL...</div>
    <div class="text-gray-400 font-mono text-sm mt-2">This may take a moment</div>
  </div>

  <!-- Sidebar / Controls -->
  <div class="w-full md:w-1/3 lg:w-1/4 flex flex-col neo-border shadow-neo bg-white h-full z-10 relative">
    <!-- Decorative Header Strip -->
    <div class="h-4 w-full bg-neo-black"></div>

    <div class="p-6 border-b-2 border-black bg-neo-yellow flex justify-between items-center shrink-0">
      <div>
        <h1 class="text-3xl font-bold text-black uppercase tracking-tighter">Function <span
            class="text-white bg-black px-1">Gemma</span></h1>
        <div class="text-xs font-mono font-bold text-black mt-1">PHYSICS PLAYGROUND</div>
      </div>
    </div>

    <!-- MENU: Level Select -->
    <div id="view-menu" class="flex-1 overflow-y-auto p-6 bg-white hidden">
      <h2 class="font-bold text-xl mb-4 border-b-2 border-black pb-2">SELECT LEVEL</h2>
      <div id="level-grid" class="grid grid-cols-2 gap-4">
        <!-- Injected via JS -->
      </div>
    </div>

    <!-- MENU: Game View -->
    <div id="view-game" class="flex-1 flex flex-col overflow-hidden relative">
      <div class="overflow-y-auto flex-1 p-6 flex flex-col gap-6">
        <!-- Level Header -->
        <div>
          <div class="flex items-center gap-2 mb-2">
            <button id="btn-back"
              class="neo-btn p-2 border-2 border-black shadow-neo-sm bg-white hover:bg-gray-100 text-xs font-bold"><i
                class="fas fa-arrow-left"></i> LEVELS</button>
            <div class="font-bold text-sm bg-black text-white px-2 py-1 ml-auto" id="level-indicator">LEVEL 1</div>
          </div>

          <!-- Level Info Card -->
          <div class="neo-border p-4 bg-neo-blue shadow-neo-sm relative overflow-hidden group">
            <div
              class="absolute -right-4 -top-4 w-16 h-16 bg-white/20 rounded-full group-hover:scale-150 transition-transform">
            </div>
            <div class="flex justify-between items-center mb-3 relative z-10">
              <h2 class="font-bold text-black text-lg border-b-2 border-black inline-block bg-white px-2"
                id="level-title">...</h2>
              <span id="timer-display"
                class="font-mono text-xl font-bold bg-black text-neo-green px-2 py-0.5 border-2 border-black shadow-[2px_2px_0px_0px_#fff]">0.00s</span>
            </div>
            <p class="text-sm text-black font-medium opacity-90 mb-2" id="level-desc">...</p>

            <!-- Collapsible Hint -->
            <div class="mt-2">
              <button id="btn-hint"
                class="text-xs font-bold border-2 border-black px-2 py-1 bg-white hover:bg-yellow-100 shadow-neo-sm flex items-center gap-2"><i
                  class="fas fa-lightbulb text-yellow-500"></i> SHOW HINT</button>
              <div id="hint-content" class="mt-2 bg-white/50 p-2 border-2 border-black text-xs font-mono hidden"><i
                  class="fas fa-code mr-1"></i> <span id="level-hint-text">...</span></div>
            </div>
          </div>
        </div>

        <!-- Editor / Command Input -->
        <div class="flex flex-col gap-2 shrink-0">
          <div class="flex justify-between items-end">
            <div class="flex gap-2 items-center">
              <label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm">COMMAND</label>
              <button id="btn-solution"
                class="text-xs font-bold border-2 border-black px-2 py-0.5 hover:bg-black hover:text-white transition-colors bg-white shadow-neo-sm"
                title="Load Example Solution"><i class="fas fa-magic"></i> VIEW SOLUTION</button>
            </div>
            <div class="text-xs font-bold text-gray-500" id="star-reqs">3★ < 2 items</div>
            </div>
            <div class="relative flex flex-col gap-2">
              <textarea id="code-input"
                class="code-editor w-full h-24 p-4 border-2 border-black focus:outline-none focus:ring-4 focus:ring-neo-purple/50 resize-none text-sm shadow-neo-sm"
                spellcheck="false" placeholder="e.g., Add a circle in the middle. You can execute multiple commands by separating them with new lines."></textarea>
              <button id="btn-execute"
                class="neo-btn bg-neo-purple border-2 border-black shadow-neo-sm text-black font-bold py-2 hover:bg-purple-400 disabled:opacity-50 disabled:cursor-not-allowed"><i
                  class="fas fa-terminal"></i> EXECUTE</button>
            </div>
            <div id="error-log"
              class="text-white bg-neo-red border-2 border-black text-xs font-bold px-2 py-1 shadow-neo-sm hidden">
            </div>
          </div>

          <!-- Active Elements List -->
          <div class="flex-1 min-h-0 flex flex-col">
            <label class="text-sm font-bold bg-black text-white px-2 py-0.5 shadow-neo-sm w-max mb-1">SCENE
              OBJECTS</label>
            <div id="action-list"
              class="flex-1 overflow-y-auto border-2 border-black bg-gray-50 p-2 space-y-2 shadow-neo-sm min-h-[100px]">
              <div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>
            </div>
          </div>
        </div>

        <!-- Action Bar -->
        <div class="p-4 bg-gray-100 border-t-2 border-black flex gap-3 shrink-0">
          <button id="btn-play"
            class="neo-btn flex-1 bg-neo-green border-2 border-black shadow-neo text-black font-bold py-3 px-4 flex items-center justify-center gap-2 hover:bg-green-400"><i
              class="fas fa-play"></i> RUN</button>
          <button id="btn-reset"
            class="neo-btn px-4 py-3 bg-white border-2 border-black shadow-neo text-black font-bold hover:bg-gray-100"
            title="Reset Simulation">
            <i class="fas fa-undo"></i>
          </button>
          <button id="btn-clear-all"
            class="neo-btn px-4 py-3 bg-white border-2 border-black shadow-neo text-black font-bold hover:bg-neo-red hover:text-white transition-colors"
            title="Clear All Objects">
            <i class="fas fa-trash-alt"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- Main Canvas Area -->
    <div class="flex-1 relative flex items-center justify-center p-2">
      <!-- Canvas Container -->
      <div id="canvas-container"
        class="w-full h-full bg-white neo-border shadow-neo flex justify-center items-center relative overflow-hidden">
        <!-- Win Overlay -->
        <div id="win-message"
          class="absolute z-50 hidden w-full h-full flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div
            class="bg-neo-yellow border-4 border-black p-8 shadow-neo-lg text-center transform rotate-2 max-w-md w-full m-4">
            <h2 class="text-4xl font-black mb-2 text-black">LEVEL CLEAR!</h2>

            <div class="flex justify-center gap-2 mb-4 text-4xl text-white drop-shadow-md" id="result-stars">
              <!-- Stars injected here -->
            </div>

            <div class="text-sm font-bold mb-6 font-mono">ITEMS USED: <span id="result-items">0</span></div>

            <div class="flex flex-col gap-2">
              <button id="btn-next-level"
                class="bg-black text-white font-bold py-3 px-6 border-2 border-transparent hover:bg-neo-green hover:text-black hover:border-black transition-colors shadow-neo-sm">NEXT
                LEVEL <i class="fas fa-arrow-right ml-2"></i></button>
              <button onclick="document.getElementById('btn-reset').click()"
                class="bg-white text-black font-bold py-2 px-6 border-2 border-black hover:bg-gray-100 transition-colors shadow-neo-sm">REPLAY</button>
            </div>
          </div>
        </div>

        <!-- Canvas Injected Here -->
      </div>

      <!-- Status Badge -->
      <div class="absolute top-6 right-8 pointer-events-none z-20">
        <div id="status-badge"
          class="bg-white border-2 border-black shadow-neo-sm px-4 py-2 font-black text-sm uppercase tracking-widest flex items-center gap-2">
          <div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div>
          READY
        </div>
      </div>
    </div>
    <script type="module">
      import { AutoModelForCausalLM, AutoTokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]";

      // --- Game Constants ---
      const CONFIG = {
        width: 1000,
        height: 750,
        gridWidth: 20,
        gridHeight: 15,
        colors: {
          background: "#ffffff",
          wall: "#1a1a1a",
          ball: "#60a5fa",
          goal: "#4ade80",
          userShape: "#facc15",
        },
      };

      const STORAGE_KEY = "functiongemma_save_v1";

      // --- Helper Functions ---
      const pX = (units) => (units * CONFIG.width) / CONFIG.gridWidth;
      const pY = (units) => (units * CONFIG.height) / CONFIG.gridHeight;
      const strokeStyle = { strokeStyle: "#000000", lineWidth: 3 };

      // --- LEVEL DEFINITIONS ---
      const LEVELS = [
        {
          id: 0,
          title: "Tutorial",
          difficulty: 1,
          desc: "Welcome! Press RUN to start the simulation. The ball will move on its own.",
          hint: "Just press the green RUN button!",
          stars: [0, 1],
          solution: `// No code needed!`,
          setup: (World, Bodies, Composite) => {
            const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });

            const ball = Bodies.circle(pX(2), CONFIG.height - 50 - 20, 20, {
              restitution: 0.6,
              friction: 0,
              frictionAir: 0,
              frictionStatic: 0,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            Matter.Body.setVelocity(ball, { x: 10, y: 0 });

            const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
            });

            World.add(Composite, [floor, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 1,
          title: "The Bridge",
          difficulty: 1,
          desc: "There is a gap in the path. Build a bridge so the ball can roll across.",
          hint: "Add a wide line in the center to connect the platforms.",
          stars: [1, 2],
          solution: `add a long line in the middle`,
          setup: (World, Bodies, Composite) => {
            const p1 = Bodies.rectangle(pX(4), pY(4), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });
            const p2 = Bodies.rectangle(pX(16), pY(12), pX(6), 20, { isStatic: true, angle: Math.PI / 8, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });

            const ball = Bodies.circle(pX(3), pY(2), 20, {
              restitution: 0.2,
              friction: 0,
              frictionAir: 0,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            const goal = Bodies.rectangle(pX(18), pY(11), 80, 80, {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            World.add(Composite, [p1, p2, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 2,
          title: "A Little Push",
          difficulty: 2,
          desc: "Oh no, we're stuck! Give the ball a nudge to get it moving towards the goal.",
          hint: "Drop a heavy object in the top left to push it towards the goal.",
          stars: [1, 3],
          solution: `Add a circle at 2,2`,
          setup: (World, Bodies, Composite) => {
            const floor = Bodies.rectangle(CONFIG.width / 2, CONFIG.height + 25, CONFIG.width, 100, { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });

            const ball = Bodies.circle(pX(2.2), CONFIG.height - 50 - 20, 20, {
              restitution: 0.6,
              friction: 0,
              frictionAir: 0,
              frictionStatic: 0,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            const goal = Bodies.rectangle(pX(18), CONFIG.height - 50 - 60, 100, 120, {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle, lineWidth: 2, strokeStyle: "#000" },
            });

            World.add(Composite, [floor, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 3,
          title: "The Bounce",
          difficulty: 2,
          desc: "High velocity incoming! How can you redirect the ball into the goal?",
          hint: "Add a centered platform at the bottom to reflect the ball towards the goal.",
          stars: [1, 2],
          solution: `add a wide line at the bottom`,
          setup: (World, Bodies, Composite) => {
            // Wall in middle top
            const wall = Bodies.rectangle(pX(10), pY(3), 20, pY(6), { isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } });

            const ball = Bodies.circle(pX(2), pY(1.2), 20, {
              restitution: 1.0,
              friction: 0,
              frictionAir: 0.001,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            // Initial Velocity: Down and Right
            Matter.Body.setVelocity(ball, { x: 12, y: 12 });

            const goal = Bodies.rectangle(pX(18), pY(2), pX(2), pY(2), {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            World.add(Composite, [wall, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 4,
          title: "Protect",
          difficulty: 3,
          desc: "Ambush! Ninja stars are incoming. Protect the ball's path so it can land safely.",
          hint: "Add a few heavy blocks at certain locations to shield the ball from the stars.",
          stars: [3,  5],
          solution: `add a heavy block at 5, 3\nadd a heavy block at 15, 5\nadd a heavy block at 5, 7`,
          setup: (World, Bodies, Composite, addEvent) => {
            const ball = Bodies.circle(pX(10), pY(1), 20, {
              restitution: 0.5,
              friction: 0.001,
              frictionAir: 0.001,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            const goal = Bodies.rectangle(pX(10), pY(14), pX(2), pY(2), {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            const createNinjaStar = (x, y, vx, vy, angVel, delay) => {
              const starVerts = Matter.Vertices.fromPath('50 0 63 38 100 38 69 59 82 100 50 75 18 100 31 59 0 38 37 38');
              const star = Matter.Bodies.fromVertices(x, y, starVerts, {
                render: { fillStyle: "#ef4444", strokeStyle: "#ef4444", lineWidth: 1 },
                restitution: 0.8,
                isStatic: true
              }, true);
              Matter.Body.scale(star, 0.5, 0.5);
              Matter.Body.setVelocity(star, { x: vx, y: vy });
              Matter.Body.setAngularVelocity(star, angVel);

              World.add(Composite, star);

              if (addEvent) {
                addEvent(delay, () => {
                  Matter.Body.setStatic(star, false);
                });
              }
              return star;
            };

            // Ninja Stars
            createNinjaStar(pX(2), pY(5), 15, -5, 0.3, 0.1);
            createNinjaStar(pX(18), pY(8), -15, -5, -0.3, 0.3);
            createNinjaStar(pX(2), pY(11), 15, -5, 0.3, 0.50);

            World.add(Composite, [ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 5,
          title: "Timing is Key",
          difficulty: 3,
          desc: "The goal is moving! Push the ball off the ledge so it lands in the moving target.",
          hint: "Add a heavy ball on the top left after a short delay to drop the ball onto the platform.",
          stars: [1, 2],
          solution: `add a heavy ball in the top left after 1 second`,
          setup: (World, Bodies, Composite) => {
            // Rotating Cross
            const cross = Matter.Body.create({
              parts: [
                Bodies.rectangle(pX(8), pY(4), pX(7), 10, { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } }),
                Bodies.rectangle(pX(8), pY(4), 10, pX(7), { render: { fillStyle: CONFIG.colors.wall, ...strokeStyle } })
              ],
              isStatic: true,
            });

            Matter.Events.on(STATE.engine, 'beforeUpdate', () => {
              if (STATE.isPlaying) {
                Matter.Body.rotate(cross, -0.01);
              }
            });

            World.add(Composite, cross);

            // Platform
            const platform = Bodies.rectangle(pX(8), pY(8)-10, pX(14), 20, {
              isStatic: true,
              render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            // Ball
            const ball = Bodies.circle(pX(2.1), pY(7), 20, {
              restitution: 0.5,
              friction: 0.1,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            // Moving Goal
            const goal = Bodies.rectangle(pX(10), pY(13), 120, 120, {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            // Goal Movement Logic
            const updateGoal = () => {
              if (!STATE.isPlaying) return;
              const time = STATE.time;
              const speed = 0.002;
              const range = pX(8);
              const center = pX(10);
              const x = center + Math.sin(time * speed) * range;
              Matter.Body.setPosition(goal, { x: x, y: pY(13) });
            };

            Matter.Events.on(STATE.engine, 'beforeUpdate', updateGoal);

            World.add(Composite, [platform, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 6,
          title: "Catapult",
          difficulty: 3,
          desc: "Launch the ball into the goal! Can you time it right?",
          hint: "Drop a heavy object in the right place at the right time to send the ball flying.",
          stars: [1, 2],
          solution: `add a heavy square at 14, 1, delayed by 2 seconds`,
          setup: (World, Bodies, Composite) => {
            const group = Matter.Body.nextGroup(true);

            // Ramp for ball
            const ramp = Bodies.rectangle(pX(2), pY(11.5), pX(4), 5, {
              isStatic: true,
              angle: Math.PI / 16,
              render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            // Catapult
            const pivotX = pX(10);
            const pivotY = pY(13);
            const catapult = Bodies.rectangle(pivotX, pivotY - 10, pX(12), 10, {
              collisionFilter: { group: group },
              density: 0.0001,
              render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            const pivot = Bodies.rectangle(pivotX, pivotY + 20, 20, 60, {
              isStatic: true,
              collisionFilter: { group: group },
              render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            const constraint = Matter.Constraint.create({
              bodyA: catapult,
              pointB: { x: pivotX, y: pivotY - 10 },
              stiffness: 1.0,
              length: 0,
              render: { visible: true }
            });

            // Ball
            const ball = Bodies.circle(pX(1), pY(8), 20, {
              restitution: 0.0,
              friction: 0.0,
              density: 0.00001,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });

            // Goal
            const goal = Bodies.rectangle(pX(18), pY(2), pX(4), pY(4), {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            World.add(Composite, [ramp, catapult, pivot, constraint, ball, goal]);
            return { ball, goal };
          },
        },
        {
          id: 7,
          title: "Newton's Cradle",
          difficulty: 4,
          desc: "A chain reaction! The ball is part of a Newton's cradle. How can we get things moving?",
          hint: "Add heavy circles on the left and right to start the motion. You may need to time them carefully.",
          stars: [2, 4],
          solution: `Add a heavy circle in the top left.\nAdd a heavy circle in the top right, delayed by 10 seconds.`,
          setup: (World, Bodies, Composite) => {
            const xx = pX(8), yy = pY(2), number = 5, size = 25, length = pY(4);

            const separation = 2.1;
            for (let i = 0; i < number; i++) {
              const x = xx + i * (size * separation);
              const circle = Bodies.circle(x, yy + length, size, {
                inertia: Infinity, restitution: 0.1, friction: 0, frictionAir: 0, slop: size * 0.02,
                render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
              });
              const constraint = Matter.Constraint.create({
                pointA: { x: x, y: yy },
                bodyB: circle,
                stiffness: 1,
                length: length,
                render: { strokeStyle: '#000', lineWidth: 1 }
              });
              World.add(Composite, [circle, constraint]);
            }

            const ramp = Bodies.rectangle(pX(4), pY(5.5), pX(7), 10, {
              friction: 0.01,
              frictionStatic: 0.01,
              restitution: 0.1,
              isStatic: true, angle: Math.PI / 12, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            // Tunnel walls
            const p1 = Bodies.rectangle(pX(14.5), yy + length + 30, pX(3), 10, {
              isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });
            const p2 = Bodies.rectangle(pX(15.25), yy + length + 30 - pY(1) - 10, pX(4.5), 10, {
              isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });
            const p3 = Bodies.rectangle(pX(17.85), pY(8), pX(4), 10, {
              isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });
            const p4 = Bodies.rectangle(pX(19.75), pY(6.1), pX(4), 10, {
              // make vertical
              angle: Math.PI / 2,
              restitution: 0.1,
              isStatic: true, render: { fillStyle: CONFIG.colors.wall, ...strokeStyle }
            });

            const ball = Bodies.circle(xx + number * (size * separation), yy + length, 20, {
              restitution: 0.1, friction: 0.0, frictionAir: 0.0,
              render: { fillStyle: CONFIG.colors.ball, ...strokeStyle },
            });
            const goal = Bodies.rectangle(pX(6.5), pY(12.5), pX(8), pY(4), {
              isStatic: true,
              isSensor: true,
              label: "GoalZone",
              render: { fillStyle: CONFIG.colors.goal, opacity: 0.3, ...strokeStyle },
            });

            World.add(Composite, [ramp, p1, p2, p3, p4, ball, goal]);

            return { ball, goal };
          },
        }
      ];

      // --- State Management ---
      const STATE = {
        engine: null,
        render: null,
        runner: null,
        time: 0,
        startTime: 0,
        isPlaying: false,
        isFinished: false,
        eventQueue: [],
        plannedActions: [],
        currentLevelIndex: 0,
        currentBall: null,
        progress: { unlockedIndex: 0, stars: {} },
        winCondition: null,
      };

      function loadProgress() {
        const saved = localStorage.getItem(STORAGE_KEY);
        if (saved) {
          try {
            STATE.progress = JSON.parse(saved);
          } catch (e) {
            console.error("Save Corrupt");
          }
        }
      }
      function saveProgress() {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(STATE.progress));
      }

      // --- Engine Initialization ---
      function initPhysics() {
        const container = document.getElementById("canvas-container");

        STATE.engine = Matter.Engine.create();
        STATE.engine.world.gravity.y = 1;
        STATE.engine.timing.timeScale = 0.5;

        STATE.render = Matter.Render.create({
          element: container,
          engine: STATE.engine,
          options: {
            width: CONFIG.width,
            height: CONFIG.height,
            wireframes: false,
            background: CONFIG.colors.background,
            pixelRatio: window.devicePixelRatio,
            showAngleIndicator: false,
          },
        });

        Matter.Events.on(STATE.render, "afterRender", function () {
          const context = STATE.render.context;
          const width = STATE.render.options.width;
          const height = STATE.render.options.height;

          // Grid
          context.beginPath();
          context.strokeStyle = "rgba(0, 0, 0, 0.1)";
          context.lineWidth = 1;
          context.font = "bold 10px 'Fira Code'";
          context.fillStyle = "rgba(0, 0, 0, 0.3)";
          context.textAlign = "center";

          for (let i = 0; i <= CONFIG.gridWidth; i++) {
            const x = (width * i) / CONFIG.gridWidth;
            context.moveTo(x, 0);
            context.lineTo(x, height);
            if (i > 0 && i < CONFIG.gridWidth) context.fillText(i, x, 15);
          }
          for (let i = 0; i <= CONFIG.gridHeight; i++) {
            const y = (height * i) / CONFIG.gridHeight;
            context.moveTo(0, y);
            context.lineTo(width, y);
            if (i > 0 && i < CONFIG.gridHeight) context.fillText(i, 15, y + 4);
          }
          context.stroke();

          // Custom Objects
          if (!STATE.isPlaying && !STATE.isFinished) {
            context.font = "bold 14px 'Fira Code', monospace";
            context.textAlign = "center";
            context.textBaseline = "middle";

            STATE.plannedActions.forEach((action) => {
              if (action.previewBody) {
                const body = action.previewBody;
                const x = body.position.x;
                const y = body.position.y;

                if (action.delay > 0) {
                  context.fillStyle = "rgba(0, 0, 0, 0.7)";
                  context.fillText(`in ${action.delay}s`, x, body.bounds.max.y + 20);
                }
                if (action.params.velocity) {
                  const vx = action.params.velocity[0],
                    vy = action.params.velocity[1];
                  drawVelocityArrow(context, x, y, vx, vy, "#ef4444");
                }
              }
            });

            // Draw velocity arrows for any dynamic body in the world (Level setup items)
            Matter.Composite.allBodies(STATE.engine.world).forEach((body) => {
              // Skip planned action previews
              if (STATE.plannedActions.some((a) => a.previewBody === body)) return;

              const vx = body.velocity.x || 0;
              const vy = body.velocity.y || 0;
              if (Math.hypot(vx, vy) > 0.1) {
                let color = body.render.fillStyle;
                // Use red for dark objects (enemies), otherwise use body color
                if (color === "#333" || color === CONFIG.colors.wall) color = "#ef4444";
                drawVelocityArrow(context, body.position.x, body.position.y, vx, vy, color);
              }
            });
          }

          // Goal Zone
          const bodies = Matter.Composite.allBodies(STATE.engine.world);
          bodies.forEach((body) => {
            if (body.label === "GoalZone") {
              const bounds = body.bounds;
              const w = bounds.max.x - bounds.min.x;
              const h = bounds.max.y - bounds.min.y;
              const cx = (bounds.min.x + bounds.max.x) / 2;
              const cy = (bounds.min.y + bounds.max.y) / 2;

              context.save();
              context.translate(cx, cy);
              context.beginPath();
              context.rect(-w / 2, -h / 2, w, h);
              context.strokeStyle = "#4ade80";
              context.lineWidth = 3;
              context.setLineDash([15, 10]);
              context.stroke();

              context.fillStyle = "#1a1a1a";
              context.fillRect(-2, -20, 4, 40);
              context.beginPath();
              context.moveTo(2, -20);
              context.lineTo(25, -10);
              context.lineTo(2, 0);
              context.fill();
              context.font = "bold 14px 'Space Grotesk'";
              context.textAlign = "center";
              context.fillText("GOAL", 0, 35);
              context.restore();
            }
          });
        });

        const canvas = STATE.render.canvas;
        canvas.style.border = "3px solid black";

        const resizeCanvas = () => {
          const cw = container.clientWidth - 40;
          const ch = container.clientHeight - 40;
          const tr = CONFIG.width / CONFIG.height;
          const cr = cw / ch;

          if (cr > tr) {
            canvas.style.height = `${ch}px`;
            canvas.style.width = `${ch * tr}px`;
          } else {
            canvas.style.width = `${cw}px`;
            canvas.style.height = `${cw / tr}px`;
          }
        };

        const resizeObserver = new ResizeObserver(() => {
          window.requestAnimationFrame(() => resizeCanvas());
        });
        resizeObserver.observe(container);
        window.requestAnimationFrame(() => resizeCanvas());

        STATE.runner = Matter.Runner.create({ isFixed: true, delta: 1000 / 60 });
        Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
        Matter.Render.run(STATE.render);
      }

      function drawVelocityArrow(context, x, y, vx, vy, color) {
        if (vx === 0 && vy === 0) return;
        const speed = Math.hypot(vx, vy);
        const arrowScale = 20;
        const maxLength = 150;
        const rawLen = speed * arrowScale;
        const scaleFactor = Math.min(rawLen, maxLength) / speed;
        const endX = x + vx * scaleFactor;
        const endY = y + vy * scaleFactor;

        context.beginPath();
        context.moveTo(x, y);
        context.lineTo(endX, endY);
        context.strokeStyle = color;
        context.lineWidth = 3;
        context.stroke();

        const angle = Math.atan2(endY - y, endX - x);
        const headLen = 12;
        context.beginPath();
        context.moveTo(endX, endY);
        context.lineTo(endX - headLen * Math.cos(angle - Math.PI / 6), endY - headLen * Math.sin(angle - Math.PI / 6));
        context.lineTo(endX - headLen * Math.cos(angle + Math.PI / 6), endY - headLen * Math.sin(angle + Math.PI / 6));
        context.lineTo(endX, endY);
        context.fillStyle = color;
        context.fill();

        context.fillStyle = color;
        context.font = "bold 12px 'Fira Code', monospace";
        context.textAlign = "center";
        context.fillText(`${speed.toFixed(1)}`, endX + (vx / speed) * 15, endY + (vy / speed) * 15);
      }

      function handleUpdate() {
        if (!STATE.isPlaying || STATE.isFinished) return;
        STATE.time = performance.now() - STATE.startTime;
        document.getElementById("timer-display").innerText = (STATE.time / 1000).toFixed(2) + "s";
        STATE.eventQueue
          .filter((e) => e.delay <= STATE.time && !e.executed)
          .forEach((e) => {
            e.action();
            e.executed = true;
          });
        if (STATE.winCondition && STATE.winCondition()) endGame(true);
      }

      function loadLevel(index) {
        if (STATE.runner) Matter.Runner.stop(STATE.runner);

        document.getElementById("view-menu").classList.add("hidden");
        document.getElementById("view-game").classList.remove("hidden");
        document.getElementById("view-game").classList.add("flex");

        STATE.currentLevelIndex = index;
        const level = LEVELS[index];

        const diffs = ["", "EASY", "MEDIUM", "HARD", "EXTREME"];
        const diffColors = ["", "bg-neo-green", "bg-neo-yellow", "bg-neo-red", "bg-neo-purple"];
        const d = level.difficulty || 1;
        document.getElementById("level-indicator").innerHTML = `LEVEL ${index + 1} <span class="ml-2 px-1 ${diffColors[d]} text-black text-[10px] border border-black">${diffs[d]}</span>`;
        document.getElementById("level-title").innerText = level.title;
        document.getElementById("level-desc").innerText = level.desc;
        document.getElementById("level-hint-text").innerText = level.hint;
        document.getElementById("star-reqs").innerText = `3★ < ${level.stars[0] + 1} items`;
        document.getElementById("hint-content").classList.add("hidden");

        resetSimulationState();
        document.getElementById("code-input").value = "";

        const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});

        STATE.currentBall = ball;
        STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;
        Matter.Render.world(STATE.render);
      }

      function resetSimulationState() {
        Matter.Composite.clear(STATE.engine.world);
        STATE.engine.events = {};
        Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);

        STATE.plannedActions = [];
        STATE.eventQueue = [];
        STATE.time = 0;
        STATE.isFinished = false;
        STATE.isPlaying = false;
        STATE.currentBall = null;

        document.getElementById("timer-display").innerText = "0.00s";
        document.getElementById("win-message").style.display = "none";
        document.getElementById("error-log").classList.add("hidden");
        document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;

        updateActionList();
      }

      function endGame(success) {
        STATE.isFinished = true;
        STATE.isPlaying = false;
        Matter.Runner.stop(STATE.runner);

        if (success) {
          document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black"></div> COMPLETE`;
          const used = STATE.plannedActions.length;
          const level = LEVELS[STATE.currentLevelIndex];
          let stars = 1;
          if (used <= level.stars[0]) stars = 3;
          else if (used <= level.stars[1]) stars = 2;

          if (stars > (STATE.progress.stars[level.id] || 0)) STATE.progress.stars[level.id] = stars;
          if (STATE.currentLevelIndex >= STATE.progress.unlockedIndex && STATE.currentLevelIndex < LEVELS.length - 1) {
            STATE.progress.unlockedIndex = STATE.currentLevelIndex + 1;
          }
          saveProgress();

          const starContainer = document.getElementById("result-stars");
          starContainer.innerHTML = "";
          for (let i = 0; i < 3; i++) {
            const filled = i < stars;
            starContainer.innerHTML += `<i class="fas fa-star ${filled ? "text-yellow-400" : "text-gray-600"}"></i>`;
          }
          document.getElementById("result-items").innerText = used;

          const btnNext = document.getElementById("btn-next-level");
          if (STATE.currentLevelIndex >= LEVELS.length - 1) {
            // Update Max
            btnNext.style.display = "none";
          } else {
            btnNext.style.display = "inline-block";
            btnNext.onclick = () => loadLevel(STATE.currentLevelIndex + 1);
          }
          document.getElementById("win-message").style.display = "flex";
        }
      }

      function updateActionList() {
        const list = document.getElementById("action-list");
        list.innerHTML = "";
        if (STATE.plannedActions.length === 0) {
          list.innerHTML = `<div class="text-xs text-gray-400 text-center mt-4 italic">No elements added yet.</div>`;
          return;
        }
        STATE.plannedActions.forEach((action, index) => {
          const div = document.createElement("div");
          div.className = "action-item flex justify-between items-center bg-white border border-black p-2 shadow-[2px_2px_0px_0px_rgba(0,0,0,0.1)] hover:shadow-[2px_2px_0px_0px_#000] transition-shadow group";
          
          const p = action.params;
          const details = [];
          if (p.size !== 1) details.push(`size:${p.size}`);
          if (p.weight !== 1) details.push(`mass:${p.weight}`);
          if (p.restitution !== 0) details.push(`bounce:${p.restitution}`);
          if (p.angle !== 0) details.push(`angle:${p.angle}°`);
          if (p.velocity && (p.velocity[0] !== 0 || p.velocity[1] !== 0)) details.push(`v:[${p.velocity}]`);
          if (p.isStatic !== (p.shape === 'line')) details.push(p.isStatic ? 'static' : 'dynamic');
          if (p.delay > 0) details.push(`delay:${p.delay}s`);

          const typeName = p.shape;
          const color = p.color || "#000";
          div.innerHTML = `
                    <div class="flex items-center gap-2">
                        <div class="w-3 h-3 border border-black" style="background-color: ${color}"></div>
                        <div class="flex flex-col">
                            <div class="flex items-center gap-2">
                                <span class="text-xs font-bold uppercase">${typeName}</span>
                                <span class="text-[10px] text-gray-500 font-mono">@ [${p.location[0]}, ${p.location[1]}]</span>
                            </div>
                            ${details.length > 0 ? `<div class="text-[9px] text-gray-400 font-mono leading-tight uppercase">${details.join(' | ')}</div>` : ''}
                        </div>
                    </div>
                `;
          const btnDelete = document.createElement("button");
          btnDelete.className = "btn-delete w-6 h-6 flex items-center justify-center bg-red-100 hover:bg-red-500 hover:text-white text-red-500 border border-black rounded transition-colors";
          btnDelete.innerHTML = `<i class="fas fa-times text-xs"></i>`;
          btnDelete.onclick = () => removeAction(index);
          div.appendChild(btnDelete);
          list.appendChild(div);
        });
      }

      function removeAction(index) {
        const action = STATE.plannedActions[index];
        if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
        STATE.plannedActions.splice(index, 1);
        updateActionList();
      }

      function createBody(shape, x, y, pixelSize, options) {
        switch (shape) {
          case "circle":
          case "ball":
            return Matter.Bodies.circle(x, y, pixelSize / 2, options);
          case "triangle":
            return Matter.Bodies.polygon(x, y, 3, pixelSize / 1.5, options);
          case "line":
            const thickness = 5;
            return Matter.Bodies.rectangle(x, y, pixelSize, thickness, options);
          default: // square, rectangle, etc.
            return Matter.Bodies.rectangle(x, y, pixelSize, pixelSize, options);
        }
      }

      // --- UNIFIED TOOL IMPLEMENTATION ---
      const Tools = {
        add: (params) => {
          let {
            shape = "square",
            location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2],
            size = 1,
            color = CONFIG.colors.userShape,
            mass = 1,
            weight = params.weight || mass,
            delay = 0,
            restitution = 0,
            friction = 0.1,
            rotation = 0,
            angle = params.angle || rotation,
            velocity = [0, 0],
            static: isStaticParam,
            isStatic = params.isStatic !== undefined ? params.isStatic : (isStaticParam !== undefined ? isStaticParam : ["platform", "line"].includes(shape)),
          } = params;

          // Handle location as string (comma-separated or descriptive)
          if (typeof location === 'string') {
            const parts = location.match(/\d+/g);
            if (parts && parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
              location = [parseFloat(parts[0]), parseFloat(parts[1])];
            } else {
              const loc = location.toLowerCase();
              const midX = CONFIG.gridWidth / 2;
              const midY = CONFIG.gridHeight / 2;
              const margin = 2;

              const locations = {
                "center": [midX, midY],
                "top-left": [margin, margin],
                "top-center": [midX, margin],
                "top-right": [CONFIG.gridWidth - margin, margin],
                "center-left": [margin, midY],
                "center": [midX, midY],
                "center-right": [CONFIG.gridWidth - margin, midY],
                "bottom-left": [margin, CONFIG.gridHeight - margin],
                "bottom-center": [midX, CONFIG.gridHeight - margin],
                "bottom-right": [CONFIG.gridWidth - margin, CONFIG.gridHeight - margin],
              };
              location = locations[loc] || [midX, midY];
            }
          }

          // Ensure location is an array
          if (!Array.isArray(location) || location.length !== 2) {
            console.warn("Invalid location format. Defaulting to center.");
            location = [CONFIG.gridWidth / 2, CONFIG.gridHeight / 2];
          }

          const finalParams = {
            shape,
            location,
            size,
            color,
            weight,
            delay,
            restitution,
            friction,
            angle,
            velocity,
            isStatic,
          };

          const x = pX(location[0]);
          const y = pY(location[1]);
          const pixelSize = pX(size); // Use grid-relative sizing

          const commonProps = {
            angle: (angle * Math.PI) / 180,
            restitution: restitution,
            friction: friction,
            render: { fillStyle: color, ...strokeStyle },
            density: weight * 0.005,
          };

          // For preview (ghosts)
          const previewProps = {
            ...commonProps,
            isStatic: true,
            isSensor: true,
            render: {
              fillStyle: color,
              opacity: 0.4,
              strokeStyle: "#000000",
              lineWidth: 2,
            },
          };

          const body = createBody(shape, x, y, pixelSize, previewProps);

          Matter.World.add(STATE.engine.world, body);

          STATE.plannedActions.push({
            type: "add",
            params: finalParams, // Use the complete object
            delay: delay || 0,
            previewBody: body,
          });
        },
      };

      // --- AI Model Setup ---
      const MODEL_ID = "Xenova/functiongemma-270m-game";
      let tokenizer, model;

      const TOOL_SCHEMA = [{"type": "function", "function": {"name": "add", "description": "Add a shape into the game scene.", "parameters": {"type": "object", "properties": {"shape": {"type": "string", "enum": ["circle", "square", "triangle", "star", "rectangle", "line", "ellipse"], "description": "The kind shape to add. Required."}, "location": {"type": "string", "description": "The [x, y] coordinates where the shape will be placed or a descriptive string. Required."}, "size": {"type": "number", "description": "The size of the object (between 0.1 and 10.0). Default is 1.0."}, "rotation": {"type": "integer", "description": "The initial clockwise rotation of the object in degrees (0-360). Default is 0."}, "friction": {"type": "number", "description": "The friction of the object (between 0.0 and 1.0). Default is 0.0."}, "restitution": {"type": "number", "description": "The bounciness of the object (between 0.0 and 1.0). Default is 0.0."}, "mass": {"type": "number", "description": "The mass of the object (between 1.0 and 10.0). Default is 1.0."}, "delay": {"type": "number", "description": "The time in seconds to wait before the object appears in the scene. Default is 0.0."}, "static": {"type": "boolean", "description": "Whether the object is static (immovable) or dynamic. Default is False."}, "velocity": {"type": "array", "items": {"type": "number"}, "description": "The initial [vx, vy] velocity vector of the object (values between -10.0 and 10.0). Default is [0.0, 0.0]."}, "color": {"type": "string", "description": "The color of the object as a string or hex code (e.g., \"red\", \"blue\", \"#FF00FF\"). Default is \"red\"."}}, "required": ["shape", "location"]}, "return": {"type": "string", "description": "A unique identifier for the added shape."}}}];

      async function initModel() {
        try {
          tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID);
          model = await AutoModelForCausalLM.from_pretrained(MODEL_ID, {
            device: "webgpu",
            dtype: "q4",
          });
          document.getElementById("loading-overlay").classList.add("hidden");
        } catch (e) {
          console.error(e);
          document.getElementById("loading-overlay").innerHTML = `<div class="text-red-500 font-bold p-4 bg-white border-2 border-black">Error: ${e.message}</div>`;
        }
      }

      // --- Command Execution ---
      async function executeCommand() {
        const input = document.getElementById("code-input").value.trim();
        if (!input) return;

        const btn = document.getElementById("btn-execute");
        const errorLog = document.getElementById("error-log");

        // UI Loading State
        btn.disabled = true;
        btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> THINKING...`;
        errorLog.classList.add("hidden");

        const systemPrompt = `You are a model that can do function calling with the following functions`;

        try {
          const lines = input.split('\n').map(l => l.trim()).filter(l => l.length > 0 && !l.startsWith("//"));

          for (const line of lines) {
            // 2. Prepare Messages
            const messages = [
              { role: "developer", content: systemPrompt },
              { role: "user", content: line },
            ];

            // 3. Apply Template
            const inputs = tokenizer.apply_chat_template(messages, {
              tools: TOOL_SCHEMA,
              tokenize: true,
              add_generation_prompt: true,
              return_dict: true,
            });

            // 4. Generate
            const output = await model.generate({ ...inputs, max_new_tokens: 128, do_sample: false });
            const decoded = tokenizer.decode(output.slice(0, [inputs.input_ids.dims[1], null]), { skip_special_tokens: false });

            // 5. Parse Output
            // Format: <start_function_call>call:add{...}<end_function_call>
            const startTag = "<start_function_call>";
            const endTag = "<end_function_call>";
            const startIndex = decoded.indexOf(startTag);
            const endIndex = decoded.indexOf(endTag);

            if (startIndex !== -1 && endIndex !== -1) {
              let callStr = decoded.substring(startIndex + startTag.length, endIndex);
              if (callStr.startsWith("call:add")) {
                // Extract JSON-like string: {location:[...],shape:<escape>...<escape>}
                let argsStr = callStr.substring(callStr.indexOf("{"));

                // Sanitize to valid JSON
                argsStr = argsStr
                  .replace(/<escape>(.*?)<escape>/g, '"$1"') // Handle string escapes
                  .replace(/(\w+):/g, '"$1":'); // Quote keys

                const args = JSON.parse(argsStr);
                Tools.add(args);
              } else {
                throw new Error("Model did not generate a valid add command.");
              }
            } else {
                throw new Error(`Could not understand command: "${line}"`);
            }
          }
          document.getElementById("code-input").value = "";
        } catch (err) {
          errorLog.innerText = err.message;
          errorLog.classList.remove("hidden");
          console.error(err);
        } finally {
          btn.disabled = false;
          btn.innerHTML = `<i class="fas fa-terminal"></i> EXECUTE`;
          updateActionList();
        }
      }

      // --- Real Simulation Run ---
      function runSimulation() {
        if (STATE.runner) Matter.Runner.stop(STATE.runner);

        const storedActions = [...STATE.plannedActions];
        const level = LEVELS[STATE.currentLevelIndex];

        Matter.Composite.clear(STATE.engine.world);
        STATE.engine.events = {};
        Matter.Events.on(STATE.engine, "beforeUpdate", handleUpdate);
        STATE.eventQueue = [];
        STATE.isFinished = false;

        const addEvent = (delay, action) => {
          STATE.eventQueue.push({
            delay: delay * 1000,
            action: action,
            executed: false,
          });
        };

        const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, addEvent);

        STATE.currentBall = ball;
        STATE.winCondition = () => Matter.Collision.collides(ball, goal) !== null;

        // Real Action Executioner
        const executeReal = (params) => {
          const { shape, location, size, weight, restitution, friction, angle, velocity, isStatic } = params;
          const x = pX(location[0]),
            y = pY(location[1]);
          const pixelSize = pX(size);

          const props = {
            angle: (angle * Math.PI) / 180,
            restitution,
            friction,
            isStatic,
            render: strokeStyle,
            density: weight * 0.005,
          };

          const body = createBody(shape, x, y, pixelSize, props);

          if (!isStatic && (velocity[0] !== 0 || velocity[1] !== 0)) {
            Matter.Body.setVelocity(body, { x: velocity[0], y: velocity[1] });
          }

          Matter.World.add(STATE.engine.world, body);
        };

        storedActions.forEach((action) => {
          STATE.eventQueue.push({
            delay: action.delay * 1000,
            action: () => executeReal(action.params),
            executed: false,
          });
        });

        STATE.plannedActions = storedActions;

        STATE.isPlaying = true;
        STATE.startTime = performance.now();
        document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-green-500 rounded-full border border-black animate-ping"></div> RUNNING`;
        Matter.Runner.run(STATE.runner, STATE.engine);
      }

      function renderMenu() {
        if (STATE.runner) Matter.Runner.stop(STATE.runner);

        document.getElementById("view-game").classList.add("hidden");
        document.getElementById("view-game").classList.remove("flex");
        document.getElementById("view-menu").classList.remove("hidden");

        const grid = document.getElementById("level-grid");
        grid.innerHTML = "";

        LEVELS.forEach((level, index) => {
          const unlocked = index <= STATE.progress.unlockedIndex;
          const stars = STATE.progress.stars[index] || 0;

          const card = document.createElement("div");
          card.className = `level-card neo-border p-4 flex flex-col items-center justify-center gap-2 aspect-square ${unlocked ? "bg-white cursor-pointer" : "locked"}`;

          if (unlocked) {
            card.onclick = () => loadLevel(index);
            card.innerHTML = `
                        <div class="text-3xl font-black">${index + 1}</div>
                        <div class="flex gap-1 text-xs">
                            ${Array(3)
                .fill(0)
                .map((_, i) => `<i class="fas fa-star ${i < stars ? "text-neo-yellow" : "text-gray-300"}"></i>`)
                .join("")}
                        </div>
                    `;
          } else {
            card.innerHTML = `<i class="fas fa-lock text-gray-400 text-2xl"></i>`;
          }
          grid.appendChild(card);
        });
      }

      // --- Bindings ---
      document.getElementById("btn-execute").onclick = executeCommand;
      document.getElementById("btn-play").onclick = runSimulation;

      document.getElementById("btn-reset").onclick = () => {
        Matter.Runner.stop(STATE.runner);
        const level = LEVELS[STATE.currentLevelIndex];
        Matter.Composite.clear(STATE.engine.world);
        const { ball, goal } = level.setup(Matter.World, Matter.Bodies, STATE.engine.world, () => {});

        STATE.currentBall = ball;

        STATE.plannedActions.forEach((action) => {
          Matter.World.add(STATE.engine.world, action.previewBody);
        });

        STATE.isPlaying = false;
        document.getElementById("status-badge").innerHTML = `<div class="w-3 h-3 bg-red-500 rounded-full border border-black animate-pulse"></div> READY`;
        document.getElementById("timer-display").innerText = "0.00s";
        document.getElementById("win-message").style.display = "none";
      };

      document.getElementById("btn-clear-all").onclick = () => {
        document.getElementById("code-input").value = "";
        STATE.plannedActions.forEach((action) => {
          if (action.previewBody) Matter.World.remove(STATE.engine.world, action.previewBody);
        });
        STATE.plannedActions = [];
        updateActionList();
        document.getElementById("btn-reset").click();
      };

      document.getElementById("btn-back").onclick = renderMenu;
      document.getElementById("btn-hint").onclick = () => {
        const content = document.getElementById("hint-content");
        content.classList.toggle("hidden");
      };

      document.getElementById("btn-solution").addEventListener("click", () => {
        const level = LEVELS[STATE.currentLevelIndex];
        if (level.solution) {
          document.getElementById("code-input").value = level.solution;
        }
      });

      window.onload = () => {
        loadProgress();
        initPhysics();
        renderMenu();
        initModel();
      };
    </script>
</body>

</html>