File size: 59,328 Bytes
1aff277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wacky D&D Shapes Adventure!</title>
    <style>
        /* --- Base Styles --- */
        body { font-family: 'Verdana', sans-serif; background-color: #2a3a4a; color: #f0f0f0; margin: 0; padding: 0; overflow: hidden; display: flex; flex-direction: column; height: 100vh; }
        #game-container { display: flex; flex-grow: 1; overflow: hidden; }
        #scene-container { flex-grow: 3; position: relative; border-right: 3px solid #506070; min-width: 250px; background-color: #101820; height: 100%; box-sizing: border-box; overflow: hidden; cursor: default; }
        #ui-container { flex-grow: 2; padding: 25px; overflow-y: auto; background-color: #3a4a5a; min-width: 320px; height: 100%; box-sizing: border-box; display: flex; flex-direction: column; }
        #scene-container canvas { display: block; }

        /* --- UI Elements --- */
        #story-title { color: #ffd700; margin: 0 0 15px 0; padding-bottom: 10px; border-bottom: 2px solid #506070; font-size: 1.8em; font-weight: bold; text-shadow: 1px 1px 2px #111; }
        #story-content { margin-bottom: 25px; line-height: 1.7; flex-grow: 1; font-size: 1.1em; color: #e8e8e8;}
        #stats-inventory-container { margin-bottom: 25px; padding: 15px; border: 1px solid #506070; border-radius: 5px; background-color: #4a5a6a; font-size: 0.95em; }
        #stats-display, #inventory-display { margin-bottom: 10px; line-height: 1.8; }
        #stats-display span { display: inline-block; background-color: #5a6a7a; padding: 4px 10px; border-radius: 15px; margin: 0 8px 5px 0; border: 1px solid #7a8a9a; white-space: nowrap; box-shadow: inset 0 1px 2px rgba(0,0,0,0.2); }
        #inventory-display .item-tag { display: inline-block; background-color: #5a6a7a; padding: 4px 10px; border-radius: 15px; margin: 0 8px 5px 0; border: 1px solid #7a8a9a; white-space: nowrap; box-shadow: inset 0 1px 2px rgba(0,0,0,0.2); cursor: default; }
        #stats-display strong, #inventory-display strong { color: #e0e0e0; margin-right: 6px; font-weight:bold; }
        #inventory-display em { color: #aabbcc; font-style: normal; }
        .item-tool { background-color: #a0522d; border-color: #cd853f; color: #fff;}
        .item-key { background-color: #ffd700; border-color: #f0e68c; color: #333;}
        .item-treasure { background-color: #20b2aa; border-color: #48d1cc; color: #fff;}
        .item-food { background-color: #ff6347; border-color: #fa8072; color: #fff;}
        .item-quest { background-color: #da70d6; border-color: #ee82ee; color: #fff;} /* Orchid/Violet */
        .item-unknown { background-color: #778899; border-color: #b0c4de;}

        /* --- Choices & Messages --- */
        #choices-container { margin-top: auto; padding-top: 20px; border-top: 2px solid #506070; }
        #choices-container h3 { margin-top: 0; margin-bottom: 12px; color: #e0e0e0; font-size: 1.2em; font-weight: bold;}
        #choices { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;} /* Grid for nav */
        #action-choices { display: flex; flex-direction: column; gap: 12px; margin-top: 15px; border-top: 1px dashed #607080; padding-top: 15px;} /* Separate area for actions */
        .choice-button { display: block; width: 100%; padding: 13px 16px; margin-bottom: 0; background-color: #607080; color: #fff; border: 1px solid #8090a0; border-radius: 5px; cursor: pointer; text-align: center; font-family: 'Verdana', sans-serif; font-size: 1.0em; font-weight: bold; transition: background-color 0.2s, transform 0.1s; box-sizing: border-box; letter-spacing: 0.5px; }
        .choice-button.action { text-align: left; grid-column: span 2;} /* Action buttons span full width */
        .choice-button:hover:not(:disabled) { background-color: #ffc107; color: #222; border-color: #ffca2c; transform: translateY(-1px); }
        .choice-button:disabled { background-color: #4e5a66; color: #8a9aab; cursor: not-allowed; border-color: #607080; opacity: 0.6; transform: none; box-shadow: none;}
        .choice-button[title]:disabled::after { content: ' (' attr(title) ')'; font-style: italic; font-size: 0.9em; margin-left: 5px; }
        .message { padding: 8px 12px; margin: 10px 0; border-left-width: 4px; border-left-style: solid; font-size: 1em; background-color: rgba(0, 0, 0, 0.1); border-radius: 3px; }
        .message-info { color: #ccc; border-left-color: #666; }
        .message-item { color: #9cf; border-left-color: #48a; }
        .message-xp { color: #af8; border-left-color: #6a4; }
        .message-warning { color: #f99; border-left-color: #c66; }
        .message-success { color: #8f8; border-left-color: #4a4; }
        .message-failure { color: #f88; border-left-color: #a44; }
        .message-combat { color: #f98; border-left-color: #c64; font-weight: bold;}
        .combat-button { background-color: #a33; border-color: #c66; color: #fff; font-weight: bold; text-align: center;}
        .combat-button:hover:not(:disabled) { background-color: #d44; border-color: #f88;}

        /* --- Action Info --- */
        #action-info { position: absolute; bottom: 10px; left: 10px; background-color: rgba(0,0,0,0.7); color: #ffcc66; padding: 5px 10px; border-radius: 3px; font-size: 0.9em; display: block; z-index: 10;}
    </style>
</head>
<body>
    <div id="game-container">
        <div id="scene-container">
             <div id="action-info">Initializing...</div>
        </div>
        <div id="ui-container">
            <h2 id="story-title">Initializing...</h2>
            <div id="story-content"><p>Loading world...</p></div>
            <div id="stats-inventory-container">
                <div id="stats-display">Loading Stats...</div>
                <div id="inventory-display">Inventory: ...</div>
            </div>
            <div id="choices-container">
                <h3>Navigation</h3>
                <div id="choices">Loading...</div>
                <div id="action-choices"></div>
            </div>
        </div>
    </div>

    <script type="importmap">
        { "imports": {
                "three": "https://unpkg.com/[email protected]/build/three.module.js",
                "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
        }}
    </script>

    <script type="module">
        import * as THREE from 'three';
        import { FontLoader } from 'three/addons/loaders/FontLoader.js';
        import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
        // Orbit Controls removed again for simplicity focus

        console.log("Script module execution started.");

        // --- DOM Elements ---
        const sceneContainer = document.getElementById('scene-container');
        const storyTitleElement = document.getElementById('story-title');
        const storyContentElement = document.getElementById('story-content');
        const choicesElement = document.getElementById('choices'); // Nav buttons grid
        const actionChoicesElement = document.getElementById('action-choices'); // Action buttons list
        const statsElement = document.getElementById('stats-display');
        const inventoryElement = document.getElementById('inventory-display');
        const actionInfoElement = document.getElementById('action-info');

        console.log("DOM elements obtained.");

        // --- Core Three.js Variables ---
        let scene, camera, renderer, clock;
        let currentSceneGroup = null;
        let currentLights = [];
        let threeFont = null;
        let currentMessage = "";

        // --- Materials ---
        const MAT = {
            stone_grey: new THREE.MeshStandardMaterial({ color: 0x8a8a8a, roughness: 0.8 }),
            stone_brown: new THREE.MeshStandardMaterial({ color: 0x9d8468, roughness: 0.85 }),
            wood_light: new THREE.MeshStandardMaterial({ color: 0xcdaa7d, roughness: 0.7 }),
            wood_dark: new THREE.MeshStandardMaterial({ color: 0x6f4e2d, roughness: 0.75 }),
            leaf_green: new THREE.MeshStandardMaterial({ color: 0x4caf50, roughness: 0.6, side: THREE.DoubleSide }),
            leaf_autumn: new THREE.MeshStandardMaterial({ color: 0xffa040, roughness: 0.65, side: THREE.DoubleSide }),
            ground_dirt: new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.9 }),
            ground_grass: new THREE.MeshStandardMaterial({ color: 0x558b2f, roughness: 0.85 }),
            metal_shiny: new THREE.MeshStandardMaterial({ color: 0xc0c0c0, roughness: 0.2, metalness: 0.8 }),
            metal_rusty: new THREE.MeshStandardMaterial({ color: 0xb7410e, roughness: 0.9, metalness: 0.2 }),
            crystal_blue: new THREE.MeshStandardMaterial({ color: 0x87cefa, roughness: 0.1, metalness: 0.1, transparent: true, opacity: 0.8, emissive:0x205080, emissiveIntensity: 0.4 }),
            crystal_red: new THREE.MeshStandardMaterial({ color: 0xff7f7f, roughness: 0.1, metalness: 0.1, transparent: true, opacity: 0.8, emissive:0x802020, emissiveIntensity: 0.4 }),
            bright_yellow: new THREE.MeshStandardMaterial({ color: 0xffeb3b, roughness: 0.6 }),
            deep_purple: new THREE.MeshStandardMaterial({ color: 0x9c27b0, roughness: 0.7 }),
            sky_blue: new THREE.MeshStandardMaterial({ color: 0x03a9f4, roughness: 0.5 }),
            town_wood: new THREE.MeshStandardMaterial({ color: 0xae8a63, roughness: 0.7 }),
            town_roof: new THREE.MeshStandardMaterial({ color: 0x8b4513, roughness: 0.8 }),
            goblin_skin: new THREE.MeshStandardMaterial({ color: 0x8FBC8F, roughness: 0.8 }), // DarkSeaGreen
            text_material: new THREE.MeshBasicMaterial({ color: 0xffddaa }),
        };

        // --- Game State ---
        let gameState = {};

        // --- Item Data ---
        const itemsData = {
            "Sturdy Stick": {type:"tool", description:"Surprisingly pointy."},
            "Wobbly Key": {type:"key", description:"Might fit a wobbly lock?"},
            "Goblin's Favorite Sock": {type:"quest", description:"Smells... unique."},
            "Shiny Rock": {type:"treasure", description:"Distractingly shiny."},
            "Suspicious Mushroom": {type:"food", description:"Maybe... just maybe..."},
        };

        // --- Enemy Data ---
         const enemyData = {
            'goblin': { name: "Grumpy Goblin", hp: 12, defense: 12, attackBonus: 1, damageDice: 4, xp: 25, drops: ["Goblin's Favorite Sock", "Shiny Rock"] },
            // Add more enemies later
        };

        // --- Procedural Assembly Shapes ---
         const SHAPE_GENERATORS = {
            'pointy_cone': (size) => new THREE.ConeGeometry(size * 0.5, size * 1.2, 6 + Math.floor(Math.random() * 5)),
            'round_blob': (size) => new THREE.SphereGeometry(size * 0.6, 12, 8),
            'spinny_torus': (size) => new THREE.TorusGeometry(size * 0.5, size * 0.15, 8, 16),
            'boxy_chunk': (size) => new THREE.BoxGeometry(size, size * (0.8 + Math.random() * 0.4), size * (0.8 + Math.random() * 0.4)),
            'spiky_ball': (size) => new THREE.IcosahedronGeometry(size * 0.7, 0),
            'flat_plate': (size) => new THREE.BoxGeometry(size * 1.5, size * 0.1, size * 1.5),
            'tall_cylinder': (size) => new THREE.CylinderGeometry(size * 0.3, size * 0.3, size * 2.0, 8),
            'knotty_thing': (size) => new THREE.TorusKnotGeometry(size * 0.4, size * 0.1, 50, 8),
            'gem_shape': (size) => new THREE.OctahedronGeometry(size * 0.6, 0),
            'basic_tetra': (size) => new THREE.TetrahedronGeometry(size * 0.7, 0),
            'squashed_ball': (size) => new THREE.SphereGeometry(size * 0.6, 12, 8).scale(1, 0.6, 1),
            'holed_box': (size) => {
                 const shape = new THREE.Shape();
                 shape.moveTo(-size/2, -size/2); shape.lineTo(-size/2, size/2); shape.lineTo(size/2, size/2); shape.lineTo(size/2, -size/2); shape.closePath();
                 const hole = new THREE.Path();
                 hole.absellipse(0, 0, size*0.2, size*0.2, 0, Math.PI*2, false);
                 shape.holes.push(hole);
                 return new THREE.ExtrudeGeometry(shape, {depth: size*0.3, bevelEnabled: false});
            }
        };
        const shapeKeys = Object.keys(SHAPE_GENERATORS);

        // --- Game Data (Page-Based, Expanded Story) ---
        const gameData = {
            1: {
                title: "Snoring Meadows",
                content: "<p>You wake up in a field of gently snoring grass. Yup, snoring. To the North are some Wiggly Woods. East leads to the Clanky Caves entrance.</p>",
                options: [
                    { text: "Enter Wiggly Woods (North)", next: 2 },
                    { text: "Approach Clanky Caves (East)", next: 5 },
                    { text: "Poke the snoring grass (Wisdom Check DC 10)", check: { stat: 'wisdom', dc: 10, next: 10, onFailure: 11 } }
                ],
                assemblyParams: { baseShape: 'ground_grass', baseSize: 30, mainShapes: ['squashed_ball', 'pointy_cone'], accents: [], count: 30, scaleRange: [0.5, 1.2], colorTheme: [MAT.grass, MAT.leaf_green, MAT.sky_blue], arrangement: 'scatter' }
            },
            2: {
                title: "Wiggly Woods",
                content: "<p>These trees really do wiggle! It's making you a bit dizzy. A grumpy-looking goblin blocks the path deeper into the woods (South?).</p>",
                options: [
                    { text: "Talk to the Goblin", next: 3 },
                    { text: "Try to sneak past (Dexterity Check DC 12)", check: { stat: 'dexterity', dc: 12, next: 4, onFailure: 3 } },
                    { text: "Go Back (South)", next: 1 }
                ],
                assemblyParams: { baseShape: 'ground_dirt', baseSize: 25, mainShapes: ['tall_cylinder', 'knotty_thing'], accents: ['leaf_autumn'], count: 20, scaleRange: [1.0, 3.0], colorTheme: [MAT.wood_dark, MAT.leaf_autumn, MAT.deep_purple], arrangement: 'cluster', clusterRadius: 10 }
            },
             3: {
                title: "Grumpy Goblin",
                content: "<p>'Oi! You wanna pass?' grunts the goblin, pointing a wobbly spear. 'Dis my wood! Whatcha gonna do?'</p>",
                options: [
                    { text: "Fight the Grumpy Goblin!", action: 'triggerCombat', enemy: 'goblin', nextOnWin: 4, nextOnLoss: 98 },
                    { text: "Offer him a Shiny Rock (Requires Shiny Rock)", requires: "Shiny Rock", consume: true, next: 4, reward: {xp: 10} },
                    { text: "Try to reason with him (Charisma Check DC 14)", check: { stat: 'charisma', dc: 14, next: 4, onFailure: 12 } },
                    { text: "Run Away!", next: 2 }
                ],
                assemblyParams: { // Similar to woods, maybe add goblin representation
                     baseShape: 'ground_dirt', baseSize: 25,
                     mainShapes: ['tall_cylinder', 'knotty_thing'], accents: ['leaf_autumn', 'basic_tetra'],
                     count: 20, scaleRange: [1.0, 3.0],
                     colorTheme: [MAT.wood_dark, MAT.leaf_autumn, MAT.deep_purple, MAT.goblin_skin],
                     arrangement: 'cluster', clusterRadius: 10
                 }
            },
             4: {
                title: "Past the Goblin!",
                content: "<p>You somehow got past the goblin! The path continues North to a weirdly Square Clearing. Or you can go back South.</p>",
                options: [
                    { text: "Go to Square Clearing (North)", next: 7 },
                    { text: "Go Back (South)", next: 2 }
                ],
                 assemblyParams: { baseShape: 'ground_dirt', baseSize: 25, mainShapes: ['tall_cylinder'], accents: ['leaf_green'], count: 15, scaleRange: [1.0, 2.5], colorTheme: [MAT.wood_light, MAT.leaf_green], arrangement: 'scatter' }
            },
            5: {
                 title: "Clanky Caves Entrance",
                 content: "<p>The entrance to the cave clanks and whirs softly. It smells like old metal and damp socks. A sign reads 'Beware of... Clanks?'</p>",
                 options: [ { text: "Enter the Caves", next: 8 }, { text: "Go Back West", next: 1 } ],
                 assemblyParams: { baseShape: 'stone_grey', baseSize: 20, mainShapes: ['spiky_ball', 'spinny_torus'], accents: ['metal_rusty', 'basic_tetra'], count: 25, scaleRange: [0.5, 1.8], colorTheme: [MAT.stone_grey, MAT.metal_rusty], arrangement: 'cluster', clusterRadius: 8 }
             },
             7: { // Added North from page 4
                 title: "The Square Clearing",
                 content: "<p>This clearing is unnervingly square. Even the rocks look cubic! In the center is a perfectly square chest with a wobbly-looking lock.</p>",
                 options: [
                     { text: "Try the Wobbly Key (Requires Wobbly Key)", requires: "Wobbly Key", consume: true, next: 13 },
                     { text: "Whack it with a Stick (Requires Sturdy Stick)", requires: "Sturdy Stick", next: 14 },
                     { text: "Go Back South", next: 4 }
                 ],
                 assemblyParams: { baseShape: 'ground_grass', baseSize: 20, mainShapes: ['boxy_chunk', 'holed_box'], accents: [], count: 15, scaleRange: [0.8, 1.5], colorTheme: [MAT.stone_brown, MAT.grass], arrangement: 'patch', patchRadius: 8 }
             },
             8: { // Inside Clanky Caves
                  title: "Clanky Caves - Junction",
                  content: "<p>Clank! Whirr! Sproing! The cave is full of noisy, spinning metal things. Passages lead West and East.</p>",
                  options: [ { text: "Go West (Deeper?)", next: 9 }, { text: "Go East (Exit?)", next: 5 } ],
                  assemblyParams: { baseShape: 'stone_grey', baseSize: 25, mainShapes: ['spinny_torus', 'holed_box'], accents: ['metal_shiny', 'basic_tetra'], count: 30, scaleRange: [0.6, 2.0], colorTheme: [MAT.stone_grey, MAT.metal_shiny, MAT.metal_rusty, MAT.bright_yellow], arrangement: 'cluster', clusterRadius: 10 }
             },
             9: { // Deeper Cave
                  title: "Sprocket Stash",
                  content: "<p>You found a pile of shiny sprockets! And maybe some suspicious mushrooms growing nearby.</p>",
                  options: [ { text: "Take a Sprocket!", reward: { addItem: "Shiny Sprocket", xp: 10 }, next: 8 }, { text: "Eat a Mushroom?", next: 15 }, { text: "Go Back East", next: 8 } ],
                  assemblyParams: { baseShape: 'stone_grey', baseSize: 15, mainShapes: ['gem_shape'], accents: ['spinny_torus', 'metal_shiny'], count: 20, scaleRange: [0.4, 1.0], colorTheme: [MAT.metal_shiny, MAT.bright_yellow, MAT.deep_purple], arrangement: 'patch', patchRadius: 4 }
             },
             10: { // Success poking grass
                 title: "Grass Tickled!",
                 content: "<p>You gently poke the snoring grass. It giggles and coughs up a Wobbly Key! Weird.</p>",
                 options: [ { text: "Grab the Key!", reward: { addItem: "Wobbly Key", xp: 5 }, next: 1 } ],
                 assemblyParams: { baseShape: 'ground_grass', baseSize: 30, mainShapes: ['squashed_ball', 'pointy_cone'], accents: [], count: 30, scaleRange: [0.5, 1.2], colorTheme: [MAT.grass, MAT.leaf_green, MAT.sky_blue], arrangement: 'scatter' }
             },
             11: { // Fail poking grass
                 title: "Grass Bites Back!",
                 content: "<p>Ouch! You poked too hard. The grass blade snapped back like a tiny whip! (-1 HP)</p>",
                 options: [ { text: "Okay, fine, leave it alone.", next: 1 } ],
                 hpLoss: 1,
                 assemblyParams: { baseShape: 'ground_grass', baseSize: 30, mainShapes: ['squashed_ball', 'pointy_cone'], accents: [], count: 30, scaleRange: [0.5, 1.2], colorTheme: [MAT.grass, MAT.leaf_green, MAT.sky_blue], arrangement: 'scatter' }
             },
              12: { // Fail charisma check on goblin
                 title: "Goblin Unimpressed",
                 content: "<p>'Nice try, smooth-talker!' the goblin sneers, waving his spear more menacingly. 'Now what?'</p>",
                 options: [
                     { text: "Fight him!", action: 'triggerCombat', enemy: 'goblin', nextOnWin: 4, nextOnLoss: 98 },
                     { text: "Offer a Shiny Rock (If you have one)", requires: "Shiny Rock", consume: true, next: 4, reward: {xp: 10} },
                     { text: "Run Away!", next: 2 }
                 ],
                  assemblyParams: { baseShape: 'ground_dirt', baseSize: 25, mainShapes: ['tall_cylinder', 'knotty_thing'], accents: ['leaf_autumn', 'basic_tetra'], count: 20, scaleRange: [1.0, 3.0], colorTheme: [MAT.wood_dark, MAT.leaf_autumn, MAT.deep_purple, MAT.goblin_skin], arrangement: 'cluster', clusterRadius: 10 }
            },
             13: { // Open chest with key
                 title: "Chest Opens!",
                 content: "<p>Click! The wobbly key fits the wobbly lock! Inside you find... another Shiny Rock?</p>",
                 options: [ { text: "Take the rock!", reward: { addItem: "Shiny Rock", xp: 15 }, next: 7 } ],
                 assemblyParams: { baseShape: 'ground_grass', baseSize: 20, mainShapes: ['boxy_chunk', 'holed_box'], accents: [], count: 15, scaleRange: [0.8, 1.5], colorTheme: [MAT.stone_brown, MAT.grass], arrangement: 'patch', patchRadius: 8 }
            },
             14: { // Whack chest
                 title: "Thwack!",
                 content: "<p>You whack the square chest with your Sturdy Stick. It makes a dull *thud*. Nothing happens, but the stick feels slightly less sturdy.</p>",
                 options: [ { text: "Try the Wobbly Key (Requires Wobbly Key)", requires: "Wobbly Key", consume: true, next: 13 }, { text: "Give up and go back", next: 7 } ],
                 // Maybe add consequence: Sturdy Stick breaks? Requires more state tracking.
                 assemblyParams: { baseShape: 'ground_grass', baseSize: 20, mainShapes: ['boxy_chunk', 'holed_box'], accents: [], count: 15, scaleRange: [0.8, 1.5], colorTheme: [MAT.stone_brown, MAT.grass], arrangement: 'patch', patchRadius: 8 }
            },
             15: { // Eat Mushroom
                 title: "Gulp!",
                 content: "<p>You bravely (or foolishly?) eat the Suspicious Mushroom. Your vision goes purple for a second, then... you feel... bouncy! (+5 Max HP! HP Restored!)</p>",
                 options: [ { text: "Weird! Go back.", next: 8 } ],
                 reward: { statGain: { maxHp: 5 }, hpGain: 5, xp: 5 }, // Example stat gain
                 assemblyParams: { baseShape: 'stone_grey', baseSize: 15, mainShapes: ['gem_shape'], accents: ['spinny_torus', 'metal_shiny'], count: 20, scaleRange: [0.4, 1.0], colorTheme: [MAT.metal_shiny, MAT.bright_yellow, MAT.deep_purple], arrangement: 'patch', patchRadius: 4 }
            },
            98: { // Lose combat
                title: "Oof!",
                content: "<p>You were defeated! You wake up back where you started, feeling dizzy.</p>",
                options: [ { text: "Okay...", next: 1 } ],
                assemblyParams: { baseShape: 'ground_grass', count: 5, mainShapes:['round_blob'], colorTheme:[MAT.grass]} // Simple scene
            },
            99: { // Generic End/TBC
                title: "Adventure Paused!",
                content: "<p>That's as far as this path goes for now. What an adventure!</p>",
                options: [ { text: "Start Over?", next: 1 } ],
                assemblyParams: { baseShape: 'flat_plate', baseSize: 10, mainShapes: ['basic_tetra'], count: 5, scaleRange: [1, 2], colorTheme: [MAT.sky_blue, MAT.bright_yellow], arrangement: 'center_stack', stackHeight: 3 }
            }
        };

        // --- Core Functions ---

        function initThreeJS() {
            console.log("initThreeJS started.");
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x2a3a4a);
            clock = new THREE.Clock();
            raycaster = new THREE.Raycaster();
            mouse = new THREE.Vector2();

            const width = sceneContainer.clientWidth || 1;
            const height = sceneContainer.clientHeight || 1;
            camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
            camera.position.set(0, 8, 15);
            camera.lookAt(0, 1, 0);

            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(width, height);
            renderer.shadowMap.enabled = true;
            renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            sceneContainer.appendChild(renderer.domElement);

            // OrbitControls removed for focus on page-based nav
            // controls = new OrbitControls(camera, renderer.domElement);

            window.addEventListener('resize', onWindowResize, false);
            renderer.domElement.addEventListener('click', onMouseClick, false); // For pickup
            setTimeout(onWindowResize, 100);
            animate();
            console.log("initThreeJS finished.");
        }

        function loadFontAndStart() {
             console.log("Loading font...");
             const loader = new FontLoader();
             loader.load('https://unpkg.com/[email protected]/examples/fonts/helvetiker_regular.typeface.json', function (font) {
                 threeFont = font;
                 console.log("Font loaded.");
                 startGame();
             }, undefined, function (error) {
                 console.error('Font loading failed:', error);
                 threeFont = null; // Ensure font is null if failed
                 startGame(); // Start anyway
             });
        }


        function onWindowResize() {
             if (!renderer || !camera || !sceneContainer) return;
             const width = sceneContainer.clientWidth || 1;
             const height = sceneContainer.clientHeight || 1;
             if (width > 0 && height > 0) {
                camera.aspect = width / height;
                camera.updateProjectionMatrix();
                renderer.setSize(width, height);
             }
        }

         function onMouseClick( event ) {
             // Calculate mouse position in normalized device coordinates (-1 to +1)
             const rect = renderer.domElement.getBoundingClientRect();
             mouse.x = ( (event.clientX - rect.left) / rect.width ) * 2 - 1;
             mouse.y = - ( (event.clientY - rect.top) / rect.height ) * 2 + 1;
             pickupItem(); // Only pickup is enabled via click now
         }


        function animate() {
            requestAnimationFrame(animate);
            const delta = clock.getDelta();
            const time = clock.getElapsedTime();

            // controls?.update(); // OrbitControls removed

            if (currentSceneGroup) {
                currentSceneGroup.traverse(obj => {
                     if (obj.userData.update) obj.userData.update(time, delta);
                 });
            }

            if (renderer && scene && camera) renderer.render(scene, camera);
        }

        function createMesh(geometry, material, pos = {x:0,y:0,z:0}, rot = {x:0,y:0,z:0}, scale = {x:1,y:1,z:1}) {
             const mesh = new THREE.Mesh(geometry, material);
             mesh.position.set(pos.x, pos.y, pos.z);
             mesh.rotation.set(rot.x, rot.y, rot.z);
             mesh.scale.set(scale.x, scale.y, scale.z);
             mesh.castShadow = true; mesh.receiveShadow = true;
             return mesh;
         }

        function setupLighting(type = 'default') {
            currentLights.forEach(light => { if (light.parent) light.parent.remove(light); if(scene.children.includes(light)) scene.remove(light); });
            currentLights = [];

            const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); // Brighter ambient for kid-friendly
            scene.add(ambientLight);
            currentLights.push(ambientLight);

            const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2); // Brighter directional
            directionalLight.position.set(8, 12, 10);
            directionalLight.castShadow = true;
            directionalLight.shadow.mapSize.set(1024, 1024);
            directionalLight.shadow.camera.near = 0.5; directionalLight.shadow.camera.far = 50;
            const sb = 25;
            directionalLight.shadow.camera.left = -sb; directionalLight.shadow.camera.right = sb;
            directionalLight.shadow.camera.top = sb; directionalLight.shadow.camera.bottom = -sb;
            directionalLight.shadow.bias = -0.0005;
            scene.add(directionalLight);
            currentLights.push(directionalLight);
        }

        function createProceduralAssembly(params) {
            console.log("Creating procedural assembly with params:", params);
            const group = new THREE.Group();
            const {
                baseShape = 'ground_grass', baseSize = 20,
                mainShapes = ['boxy_chunk'], accents = ['pointy_cone'],
                count = 10, scaleRange = [0.5, 1.5],
                colorTheme = [MAT.stone_grey, MAT.wood_light, MAT.leaf_green],
                arrangement = 'scatter',
                stackHeight = 5,
                clusterRadius = 5,
                patchPos = {x:0, y:0, z:0}, patchRadius = 3
            } = params;

            let baseMesh;
            if (baseShape.startsWith('ground_')) {
                const groundMat = MAT[baseShape] || MAT.ground_grass;
                const groundGeo = new THREE.PlaneGeometry(baseSize, baseSize);
                baseMesh = new THREE.Mesh(groundGeo, groundMat);
                baseMesh.rotation.x = -Math.PI / 2; baseMesh.position.y = 0;
                baseMesh.receiveShadow = true; baseMesh.castShadow = false;
                baseMesh.userData.isGround = true; // Mark for placement/raycasting
                group.add(baseMesh);
            } else {
                const baseGeoFunc = SHAPE_GENERATORS[baseShape] || SHAPE_GENERATORS['flat_plate'];
                const baseGeo = baseGeoFunc(baseSize);
                baseMesh = createMesh(baseGeo, colorTheme[0] || MAT.stone_grey, {y:0.1});
                baseMesh.receiveShadow = true; baseMesh.castShadow = false;
                 baseMesh.userData.isGround = true; // Allow placing on non-plane bases
                group.add(baseMesh);
            }

            const allShapes = [...mainShapes, ...accents];
            let lastY = 0.1; // Start stacking slightly above base
            let stackCount = 0;

            for (let i = 0; i < count; i++) {
                if(allShapes.length === 0) break;
                const shapeKey = allShapes[Math.floor(Math.random() * allShapes.length)];
                const geoFunc = SHAPE_GENERATORS[shapeKey];
                if (!geoFunc) { console.warn(`Shape generator missing: ${shapeKey}`); continue; }

                const scaleFactor = scaleRange[0] + Math.random() * (scaleRange[1] - scaleRange[0]);
                const geometry = geoFunc(scaleFactor);
                const material = colorTheme[Math.floor(Math.random() * colorTheme.length)];
                const mesh = createMesh(geometry, material);

                geometry.computeBoundingBox(); // Needed for height calculation
                 let height = 0;
                 if (geometry.boundingBox) {
                    height = (geometry.boundingBox.max.y - geometry.boundingBox.min.y) * mesh.scale.y;
                 } else {
                    console.warn("Geometry missing boundingBox", geometry);
                    height = scaleFactor; // Estimate height if bbox failed
                 }
                 height = Math.max(0.1, height); // Ensure minimum height


                let position = { x:0, y:0, z:0 };
                let isValidPosition = false; // Flag to check if position calculation succeeded

                switch(arrangement) {
                    case 'stack':
                        if (stackCount < stackHeight) {
                            position.y = lastY + height / 2;
                            position.x = (Math.random() - 0.5) * 0.5 * scaleFactor;
                            position.z = (Math.random() - 0.5) * 0.5 * scaleFactor;
                            lastY += height * 0.9;
                            stackCount++;
                            isValidPosition = true;
                        }
                        break;
                    case 'center_stack':
                         if (stackCount < stackHeight) {
                            position.y = lastY + height / 2;
                            lastY += height * 0.95;
                            stackCount++;
                            isValidPosition = true;
                         }
                         break;
                    case 'cluster':
                        const angle = Math.random() * Math.PI * 2;
                        const radius = Math.random() * clusterRadius;
                        position.x = Math.cos(angle) * radius;
                        position.z = Math.sin(angle) * radius;
                        position.y = height / 2;
                        isValidPosition = true;
                        break;
                     case 'patch':
                         const pAngle = Math.random() * Math.PI * 2;
                         const pRadius = Math.random() * patchRadius;
                         position.x = patchPos.x + Math.cos(pAngle) * pRadius;
                         position.z = patchPos.z + Math.sin(pAngle) * pRadius;
                         position.y = (patchPos.y || 0) + height / 2;
                         isValidPosition = true;
                         break;
                    case 'scatter':
                    default:
                        position.x = (Math.random() - 0.5) * baseSize * 0.8;
                        position.z = (Math.random() - 0.5) * baseSize * 0.8;
                        position.y = height / 2;
                        isValidPosition = true;
                        break;
                }

                if (!isValidPosition) continue; // Skip if arrangement logic failed (e.g., stack full)

                 mesh.position.set(position.x, position.y, position.z);
                 mesh.rotation.set(
                    Math.random() * (arrangement.includes('stack') ? 0.2 : Math.PI),
                    Math.random() * Math.PI * 2,
                    Math.random() * (arrangement.includes('stack') ? 0.2 : Math.PI)
                );

                if (Math.random() < 0.3) {
                     mesh.userData.rotSpeed = (Math.random() - 0.5) * 0.4;
                     mesh.userData.bobSpeed = 1 + Math.random();
                     mesh.userData.bobAmount = 0.05 + Math.random() * 0.05;
                     mesh.userData.startY = mesh.position.y;
                     mesh.userData.update = (time, delta) => {
                         mesh.rotation.y += mesh.userData.rotSpeed * delta;
                         mesh.position.y = mesh.userData.startY + Math.sin(time * mesh.userData.bobSpeed) * mesh.userData.bobAmount;
                     };
                }
                group.add(mesh);
            }
            console.log(`Assembly created with ${group.children.length -1} procedural objects.`); // -1 for base
            return group;
        }

        function updateScene(assemblyParams) {
             console.log("updateScene called");
             if (currentSceneGroup) {
                currentSceneGroup.traverse(child => {
                    if (child.isMesh) {
                        if(child.geometry) child.geometry.dispose();
                    }
                });
                scene.remove(currentSceneGroup);
                currentSceneGroup = null;
             }
             setupLighting('default'); // Use default lighting for simplicity now

             if (!assemblyParams) {
                 console.warn("No assemblyParams provided, creating default scene.");
                 assemblyParams = { baseShape: 'ground_dirt', count: 5, mainShapes: ['boxy_chunk'] };
             }

             try {
                 currentSceneGroup = createProceduralAssembly(assemblyParams);
                 scene.add(currentSceneGroup);
                 console.log("New scene group added.");
             } catch (error) {
                 console.error("Error creating procedural assembly:", error);
                 // Add error indicator?
             }
         }

        function startGame() {
            console.log("startGame called.");
            const defaultChar = {
                name: "Player",
                stats: { hp: 25, maxHp: 25, xp: 0, strength: 12, dexterity: 11, constitution: 13, intelligence: 9, wisdom: 10, charisma: 8 },
                inventory: ["Sturdy Stick"]
            };
            gameState = {
                currentPageId: 1,
                character: JSON.parse(JSON.stringify(defaultChar)),
                combat: null // Ensure combat is null at start
            };
            renderPage(gameState.currentPageId);
            console.log("startGame finished.");
        }

        function handleChoiceClick(choiceData) {
             console.log("Choice clicked:", choiceData);
             currentMessage = "";

             let nextPageId = parseInt(choiceData.next);
             const currentPageData = gameData[gameState.currentPageId];
             const option = currentPageData?.options?.find(opt => opt.next === nextPageId || (opt.action === choiceData.action && opt.enemy === choiceData.enemy)); // Find the specific option

             // 1. Check Requirements
             if (option && option.requires) {
                 if (!gameState.character.inventory.includes(option.requires)) {
                     currentMessage = `<p class="message message-warning">You need a ${option.requires} for that!</p>`;
                     renderPage(gameState.currentPageId); // Re-render current page with message
                     return;
                 }
                 if (option.consume) {
                     gameState.character.inventory = gameState.character.inventory.filter(i => i !== option.requires);
                     currentMessage += `<p class="message message-item">Used your ${option.requires}.</p>`;
                 }
             }

             // 2. Handle Actions (Combat, Checks) before transitioning
             if (option && option.action === 'triggerCombat' && option.enemy) {
                 startCombat(option.enemy, option.nextOnWin, option.nextOnLoss);
                 return; // Combat handles the next transition
             }
             if (option && option.check) {
                 performSkillCheck(option.check, option.next, option.onFailure);
                 return; // Skill check handles the next transition
             }

             // 3. Apply Rewards (if navigating directly)
             if (option && option.reward) {
                 applyReward(option.reward);
             }

             // 4. Transition to Next Page (if not handled by action/check)
             const targetPageData = gameData[nextPageId];
             if (!targetPageData) {
                 console.error(`Invalid next page ID: ${nextPageId}`);
                 currentMessage += `<p class="message message-warning">That path is mysteriously blocked!</p>`;
                 nextPageId = gameState.currentPageId;
             }

             gameState.currentPageId = nextPageId;
             renderPage(nextPageId);
        }

        function performSkillCheck(checkData, successPageId, failurePageId) {
             const {stat, dc} = checkData;
             const baseStat = gameState.character.stats[stat] || 10;
             const modifier = Math.floor((baseStat - 10) / 2);
             const roll = Math.floor(Math.random() * 20) + 1;
             const total = roll + modifier;
             const success = total >= dc;

             console.log(`Skill Check ${stat}: Roll ${roll} + Mod ${modifier} = ${total} vs DC ${dc}`);
             currentMessage += `<p class="message message-info"><em>Rolling ${stat}... (Rolled ${total} vs DC ${dc})</em></p>`;
             displayDiceRoll(roll, success); // Show the roll

             if (success) {
                 currentMessage += `<p class="message message-success"><em>Success!</em></p>`;
                 gameState.currentPageId = successPageId;
             } else {
                 currentMessage += `<p class="message message-failure"><em>Failed!</em></p>`;
                 gameState.currentPageId = failurePageId;
             }
             // Add short delay before rendering next page to see dice roll
             setTimeout(() => renderPage(gameState.currentPageId), 1500);
        }

        function applyReward(rewardData) {
             if(rewardData.addItem && itemsData[rewardData.addItem]) {
                 if (!gameState.character.inventory.includes(rewardData.addItem)) {
                     gameState.character.inventory.push(rewardData.addItem);
                     currentMessage += `<p class="message message-item">You found a ${rewardData.addItem}!</p>`;
                 } else {
                      currentMessage += `<p class="message message-info">You found another ${rewardData.addItem}, but can't carry more.</p>`;
                 }
             }
             if(rewardData.xp) {
                 gameState.character.stats.xp += rewardData.xp;
                 currentMessage += `<p class="message message-xp">You gained ${rewardData.xp} XP!</p>`;
             }
              if(rewardData.hpGain) {
                 gameState.character.stats.hp = Math.min(gameState.character.stats.maxHp, gameState.character.stats.hp + rewardData.hpGain);
                 currentMessage += `<p class="message message-success">You feel better! (+${rewardData.hpGain} HP)</p>`;
             }
             if(rewardData.statGain) { // Example: { statGain: { maxHp: 5 } }
                 for (const stat in rewardData.statGain) {
                     if (gameState.character.stats.hasOwnProperty(stat)) {
                         gameState.character.stats[stat] += rewardData.statGain[stat];
                         currentMessage += `<p class="message message-success">Your ${stat} increased by ${rewardData.statGain[stat]}!</p>`;
                         // If maxHp increases, maybe heal too?
                          if (stat === 'maxHp' && rewardData.statGain[stat] > 0) {
                               gameState.character.stats.hp += rewardData.statGain[stat];
                          }
                     }
                 }
             }
        }


        function renderPage(pageId) {
             console.log(`Rendering page ${pageId}`);
             const pageData = gameData[pageId];

             if (!pageData) { /* Error handling as before */ return; }

             storyTitleElement.textContent = pageData.title || "An Unnamed Place";
             storyContentElement.innerHTML = currentMessage + (pageData.content || "<p>...</p>");
             choicesElement.innerHTML = '';
             actionChoicesElement.innerHTML = ''; // Clear action choices too

             // Setup Navigation Buttons (Always show, disable if unavailable)
             const neighbors = getZoneNeighbors(gameState.currentZoneId || getZoneId(1,1)); // Use placeholder if needed
             const directions = {'north': 'North', 'south': 'South', 'east': 'East', 'west': 'West'};
             for(const dir in directions) {
                  const neighborId = neighbors[dir]; // Note: This uses grid logic, pageData uses .next
                  const button = document.createElement('button');
                  button.classList.add('choice-button');
                  button.textContent = `Go ${directions[dir]}`;
                  // For now, navigation uses pageData.options, not grid neighbors
                  button.disabled = true; // Disable all grid nav by default
                  choicesElement.appendChild(button);
             }


             // Add options from pageData to Action Choices area
             if (pageData.options && pageData.options.length > 0) {
                 pageData.options.forEach(option => {
                     const button = document.createElement('button');
                     button.classList.add('choice-button', 'action'); // Mark as action
                     button.textContent = option.text;

                     // Disable if required item is missing
                     let requirementMet = true;
                     if (option.requires && !gameState.character.inventory.includes(option.requires)) {
                         requirementMet = false;
                         button.title = `Requires: ${option.requires}`;
                     }
                     button.disabled = !requirementMet;

                     button.onclick = () => handleChoiceClick(option); // Pass full option data
                     actionChoicesElement.appendChild(button);
                 });
             } else {
                 actionChoicesElement.innerHTML = '<p><i>Nothing else to do here right now.</i></p>';
             }

             updateStatsDisplay();
             updateInventoryDisplay();
             updateActionInfo();
             updateScene(pageData.assemblyParams);
        }
        window.handleChoiceClick = handleChoiceClick; // Make global


        function updateStatsDisplay() {
             if (!gameState.character || !statsElement) return;
             const stats = gameState.character.stats;
             const hpColor = stats.hp / stats.maxHp < 0.3 ? '#f88' : (stats.hp / stats.maxHp < 0.6 ? '#fd5' : '#8f8');
             const statBonus = (statVal) => {
                const mod = Math.floor((statVal - 10) / 2);
                return `${statVal} (${mod >= 0 ? '+' : ''}${mod})`;
             };

             statsElement.innerHTML = `<strong>Stats:</strong>
                 <span style="color:${hpColor}">HP: ${stats.hp}/${stats.maxHp}</span> <span>XP: ${stats.xp}</span><br>
                 <span>Str: ${statBonus(stats.strength)}</span> <span>Dex: ${statBonus(stats.dexterity)}</span> <span>Con: ${statBonus(stats.constitution)}</span>
                 <span>Int: ${statBonus(stats.intelligence)}</span> <span>Wis: ${statBonus(stats.wisdom)}</span> <span>Cha: ${statBonus(stats.charisma)}</span>`;
         }

        function updateInventoryDisplay() {
             if (!gameState.character || !inventoryElement) return;
             let invHtml = '<strong>Inventory:</strong> ';
             if (gameState.character.inventory.length === 0) {
                 invHtml += '<em>Empty</em>';
             } else {
                 gameState.character.inventory.forEach(item => {
                     const itemDef = itemsData[item] || { type: 'unknown', description: '???' };
                     const itemClass = `item-${itemDef.type || 'unknown'}`;
                     invHtml += `<span class="item-tag ${itemClass}" title="${itemDef.description}">${item}</span>`;
                 });
             }
             inventoryElement.innerHTML = invHtml;
        }

        function updateActionInfo() {
            if (!actionInfoElement || !gameState ) return;
            const mode = gameState.combat?.active ? "Combat!" : "Exploring";
            actionInfoElement.textContent = `Location: ${gameData[gameState.currentPageId]?.title || 'Unknown'} | ${mode}`;
        }

        // --- Combat ---
        function startCombat(enemyTypeId, nextOnWin, nextOnLoss) {
            const enemyBase = enemyData[enemyTypeId];
            if (!enemyBase) { console.error("Unknown enemy type:", enemyTypeId); return; }
            gameState.combat = {
                active: true, enemyId: enemyTypeId, enemyName: enemyBase.name,
                enemyHp: enemyBase.hp, enemyMaxHp: enemyBase.hp,
                enemyDefense: enemyBase.defense, enemyAttackBonus: 2, // Simplified bonus
                enemyDamageDice: enemyBase.damageDice || 4, enemyXp: enemyBase.xp,
                enemyDrops: enemyBase.drops || [],
                nextOnWin: nextOnWin, nextOnLoss: nextOnLoss
            };
            currentMessage = `<p class="message message-combat">A ${enemyBase.name} blocks your path!</p>`;
            renderCurrentPageUI(); // Update UI to show combat mode
        }

        function handleCombatAction(action) {
            if (!gameState.combat?.active) return;
            currentMessage = ""; // Clear previous messages

            if (action === 'attack') {
                // Player Attack
                const playerRoll = Math.floor(Math.random() * 20) + 1;
                const playerAtkBonus = Math.floor((gameState.character.stats.strength - 10) / 2);
                const playerTotalAttack = playerRoll + playerAtkBonus;
                const playerHit = playerRoll === 20 || (playerRoll !== 1 && playerTotalAttack >= gameState.combat.enemyDefense);

                displayDiceRoll(playerRoll, playerHit); // Show roll

                if (playerHit) {
                    const weapon = gameState.character.inventory.find(i => itemsData[i]?.type === 'weapon');
                    const baseDamage = itemsData[weapon]?.baseDamage || 2; // Unarmed = 1d2 ?
                    const damageRoll = Math.max(1, Math.floor(Math.random() * baseDamage) + 1 + playerAtkBonus);
                    gameState.combat.enemyHp -= damageRoll;
                    currentMessage += `<p class="message message-success">You hit the ${gameState.combat.enemyName} for ${damageRoll} damage! (Rolled ${playerTotalAttack} vs AC ${gameState.combat.enemyDefense})</p>`;
                } else {
                    currentMessage += `<p class="message message-failure">You missed the ${gameState.combat.enemyName}. (Rolled ${playerTotalAttack} vs AC ${gameState.combat.enemyDefense})</p>`;
                }

                // Check Enemy Defeat
                if (gameState.combat.enemyHp <= 0) {
                    currentMessage += `<p class="message message-success"><b>You defeated the ${gameState.combat.enemyName}!</b></p>`;
                    applyReward({ xp: gameState.combat.enemyXp });
                    // Handle Drops (Simplified: drop one random item from list)
                    if (gameState.combat.enemyDrops.length > 0) {
                        const droppedItemName = gameState.combat.enemyDrops[Math.floor(Math.random() * gameState.combat.enemyDrops.length)];
                        dropItemInScene(droppedItemName, new THREE.Vector3(Math.random()*2-1, 0.2, Math.random()*2-1));
                        currentMessage += `<p class="message message-item"><em>The ${gameState.combat.enemyName} dropped a ${droppedItemName}! Click it to pick up.</em></p>`;
                    }
                    const winPage = gameState.combat.nextOnWin;
                    gameState.combat = null; // End combat
                    gameState.currentPageId = winPage; // Go to win page
                    renderPage(gameState.currentPageId);
                    return;
                }

                // Enemy Attack (if enemy still alive)
                const enemyRoll = Math.floor(Math.random() * 20) + 1;
                const enemyTotalAttack = enemyRoll + gameState.combat.enemyAttackBonus;
                const playerAC = 10 + Math.floor((gameState.character.stats.dexterity - 10) / 2);
                const enemyHit = enemyRoll === 20 || (enemyRoll !== 1 && enemyTotalAttack >= playerAC);

                 // Add slight delay for enemy roll display maybe?
                setTimeout(() => displayDiceRoll(enemyRoll, enemyHit), 500); // Display enemy roll slightly later

                if (enemyHit) {
                    const damageRoll = Math.max(1, Math.floor(Math.random() * gameState.combat.enemyDamageDice) + 1);
                    gameState.character.stats.hp -= damageRoll;
                    currentMessage += `<p class="message message-failure">The ${gameState.combat.enemyName} hits you for ${damageRoll} damage! (Rolled ${enemyTotalAttack} vs AC ${playerAC})</p>`;
                    if (gameState.character.stats.hp <= 0) {
                        currentMessage += `<p class="message message-failure"><b>You have been defeated!</b></p>`;
                        const lossPage = gameState.combat.nextOnLoss;
                        gameState.combat = null; // End combat
                        gameState.currentPageId = lossPage; // Go to loss page
                         setTimeout(() => renderPage(gameState.currentPageId), 1500); // Delay transition after showing roll
                        return;
                    }
                } else {
                    currentMessage += `<p class="message message-info">The ${gameState.combat.enemyName} misses you. (Rolled ${enemyTotalAttack} vs AC ${playerAC})</p>`;
                }
                 setTimeout(() => renderPage(gameState.currentPageId), 1500); // Re-render UI after delay
            }
        }
        window.handleCombatAction = handleCombatAction; // Make global

        function displayDiceRoll(result, success) {
             if (!threeFont) { console.warn("Font not loaded for dice roll."); return; }
             activeTimeouts.forEach(timeoutId => clearTimeout(timeoutId)); activeTimeouts = [];
             scene.children.filter(c => c.userData?.isDiceRoll).forEach(c => scene.remove(c)); // Remove old rolls from main scene

             const textGeo = new TextGeometry(result.toString(), { font: threeFont, size: 1.0, height: 0.1, curveSegments: 4 });
             textGeo.computeBoundingBox();
             const textWidth = textGeo.boundingBox.max.x - textGeo.boundingBox.min.x;
             const textMat = MAT.text_material.clone();
             textMat.color.setHex(success ? 0x88ff88 : 0xff8888);
             textMat.transparent = true; // Needed for opacity fade

             const textMesh = new THREE.Mesh(textGeo, textMat);
             textMesh.userData.isDiceRoll = true;

             const distance = 6;
             const textPos = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(distance));
             textMesh.position.copy(textPos);
             textMesh.position.y += 1.0; // Adjust vertical position
             textMesh.position.x -= textWidth / 2 * textMesh.scale.x; // Center horizontally
             textMesh.quaternion.copy(camera.quaternion);

             scene.add(textMesh);

             const duration = 2.5; // seconds
             const startTime = clock.getElapsedTime();
             textMesh.userData.startTime = startTime;
             textMesh.userData.update = (time) => {
                 const elapsed = time - textMesh.userData.startTime;
                 if (elapsed >= duration) {
                     if (textMesh.parent) textMesh.parent.remove(textMesh);
                     delete textMesh.userData.update;
                 } else {
                     textMesh.position.y += 0.01;
                     textMesh.material.opacity = 1.0 - (elapsed / duration);
                 }
             };
        }

         function dropItemInScene(itemName, positionOffset = new THREE.Vector3(0, 0, 0)) {
            const currentGroup = currentSceneGroup; // Items are dropped relative to the current scene group origin
            if (!currentGroup || !itemsData[itemName]) return;

            const itemDef = itemsData[itemName];
            const itemGeo = new THREE.BoxGeometry(0.4, 0.4, 0.4); // Simple representation
            const itemMat = MAT.simple.clone();
             if(itemDef.type === 'weapon') itemMat.color.setHex(0xcc6666);
             else if(itemDef.type === 'consumable') itemMat.color.setHex(0xcc9966);
             else if(itemDef.type === 'quest') itemMat.color.setHex(0xcccc66);
             else itemMat.color.setHex(0xaaaaee);

            const dropPos = new THREE.Vector3(positionOffset.x, 0.2, positionOffset.z);
            const droppedMesh = createMesh(itemGeo, itemMat, dropPos);
            droppedMesh.userData = { isPickupable: true, itemName: itemName, description: `Dropped ${itemName}` };
            currentGroup.add(droppedMesh); // Add item to the current scene group
            console.log(`Dropped ${itemName} in scene`);
        }

        function pickupItem() { // Re-enabled pickup
            if (gameState.combat?.active) return; // No pickup during combat

            raycaster.setFromCamera(mouse, camera);
            const currentGroup = currentSceneGroup;
            if (!currentGroup) return;

            const pickupables = [];
            currentGroup.traverseVisible(child => { // Check only visible objects in current group
                if (child.userData.isPickupable) pickupables.push(child);
            });

            const intersects = raycaster.intersectObjects(pickupables, false);

            if (intersects.length > 0) {
                 const clickedObject = intersects[0].object;
                 const itemName = clickedObject.userData.itemName;

                 if (itemName && itemsData[itemName]) {
                      console.log(`Picked up: ${itemName}`);
                      currentMessage = `<p class="message message-item"><em>Picked up: ${itemName}</em></p>`;

                      if (!gameState.character.inventory.includes(itemName)) {
                           gameState.character.inventory.push(itemName);
                       } else {
                           currentMessage += `<p class="message message-info"><em>(Cannot carry more ${itemName})</em></p>`;
                       }

                       // Remove object fully after pickup
                       if(clickedObject.parent) clickedObject.parent.remove(clickedObject);
                       if(clickedObject.geometry) clickedObject.geometry.dispose();
                       // We assume material is shared from MAT, so don't dispose

                       renderCurrentPageUI(); // Update inventory and messages
                  }
             }
        }


        document.addEventListener('DOMContentLoaded', () => {
             console.log("DOM Ready - Initializing Wacky D&D Shapes Adventure!");
             try {
                 initThreeJS();
                 if (!scene || !camera || !renderer) throw new Error("Three.js failed to initialize.");
                 loadFontAndStart(); // Load font, then start game
                 console.log("Initialization sequence started.");
             } catch (error) {
                 console.error("Initialization failed:", error);
                 storyTitleElement.textContent = "Initialization Error";
                 storyContentElement.innerHTML = `<p style="color:red;">Failed to start game:</p><pre style="color:red; white-space: pre-wrap;">${error.stack || error}</pre><p style="color:yellow;">Check console (F12) for details.</p>`;
                 if(sceneContainer) sceneContainer.innerHTML = '<p style="color:red; padding: 20px;">3D Scene Failed</p>';
                  document.getElementById('stats-inventory-container').style.display = 'none';
                  document.getElementById('choices-container').style.display = 'none';
             }
         });

    </script>
</body>
</html>