File size: 54,571 Bytes
17b162a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced CYOA - 3D Interaction & Skills</title>
    <style>
        body { font-family: 'Courier New', monospace; background-color: #111; color: #eee; 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: 2px solid #444; min-width: 250px; background-color: #000; height: 100%; box-sizing: border-box; overflow: hidden; cursor: default; }
        #ui-container { flex-grow: 2; padding: 20px; overflow-y: auto; background-color: #2b2b2b; min-width: 350px; height: 100%; box-sizing: border-box; display: flex; flex-direction: column; }
        #scene-container canvas { display: block; }
        #story-title { color: #f0c060; margin: 0 0 15px 0; padding-bottom: 10px; border-bottom: 1px solid #555; font-size: 1.6em; text-shadow: 1px 1px 1px #000; }
        #story-content { margin-bottom: 20px; line-height: 1.7; flex-grow: 1; font-size: 1.1em; min-height: 100px; /* Ensure space */}
        #stats-inventory-container { margin-bottom: 15px; padding: 15px; border: 1px solid #444; border-radius: 4px; background-color: #333; font-size: 0.95em; }
        #stats-display, #inventory-display, #history-log { margin-bottom: 10px; line-height: 1.8; }
        #history-log { max-height: 150px; overflow-y: auto; border-top: 1px dashed #555; padding-top: 10px; font-size: 0.9em; color: #aaa; }
        #history-log strong { color: #ccc; }
        #history-log div { margin-bottom: 4px; }
        #stats-display span, #inventory-display .item-tag { display: inline-block; background-color: #484848; padding: 3px 9px; border-radius: 15px; margin: 0 8px 5px 0; border: 1px solid #6a6a6a; white-space: nowrap; box-shadow: inset 0 1px 2px rgba(0,0,0,0.3); }
        #stats-display strong, #inventory-display strong { color: #bbb; margin-right: 6px; }
        #inventory-display em { color: #888; font-style: normal; }
        .item-quest { background-color: #666030; border-color: #999048;}
        .item-weapon { background-color: #663030; border-color: #994848;}
        .item-armor { background-color: #306630; border-color: #489948;}
        .item-consumable { background-color: #664430; border-color: #996648;}
        .item-unknown { background-color: #555; border-color: #777;}
        #choices-container { margin-top: auto; padding-top: 15px; border-top: 1px solid #555; }
        #choices-container h3 { margin-top: 0; margin-bottom: 12px; color: #ccc; font-size: 1.1em; }
        #choices { display: flex; flex-direction: column; gap: 10px; }
        .choice-button { display: block; width: 100%; padding: 10px 15px; margin-bottom: 0; background-color: #555; color: #eee; border: 1px solid #777; border-radius: 4px; cursor: pointer; text-align: left; font-family: 'Courier New', monospace; font-size: 1.0em; transition: background-color 0.2s, border-color 0.2s, box-shadow 0.1s; box-sizing: border-box; }
        .choice-button:hover:not(:disabled) { background-color: #e0b050; color: #111; border-color: #c89040; box-shadow: 0 0 5px rgba(255, 200, 100, 0.5); }
        .choice-button:disabled { background-color: #404040; color: #777; cursor: not-allowed; border-color: #555; opacity: 0.7; }
        .message { padding: 8px 12px; margin-bottom: 1em; border-left-width: 3px; border-left-style: solid; font-size: 0.95em; background-color: rgba(255, 255, 255, 0.05); border-color: #666; color: #aaa;}
        .message-success { color: #8f8; border-left-color: #4a4; }
        .message-failure { color: #f88; border-left-color: #a44; }
        .message-info { color: #8af; border-left-color: #46a; }
        #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;}
        /* Placement Preview Style */
        .placement-preview { opacity: 0.6; /* Make it semi-transparent */ }
    </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 assets...</p></div>
            <div id="stats-inventory-container">
                <div id="stats-display">HP: ?/? | XP: ? | STR: ? | DEX: ? | INT: ?</div>
                <div id="inventory-display">Inventory: Empty</div>
                <div id="history-log"><strong>History:</strong><div>Game Started.</div></div>
            </div>
            <div id="choices-container">
                <h3>What will you do?</h3>
                <div id="choices">Loading...</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 { OrbitControls } from 'three/addons/controls/OrbitControls.js';

        // --- 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');
        const statsElement = document.getElementById('stats-display');
        const inventoryElement = document.getElementById('inventory-display');
        const historyElement = document.getElementById('history-log');
        const actionInfoElement = document.getElementById('action-info');

        // --- Three.js Variables ---
        let scene, camera, renderer, clock, controls, raycaster, mouse;
        let worldGroup = null;
        let zoneGroups = {}; // Stores { group, lighting, title, entryText, options, zoneId, items: [], interactables: [] }
        let currentLights = [];
        let playerAvatar = null;

        // --- Game State Variables ---
        let gameState = {};
        let currentMessage = "";
        let placementMode = false;
        let itemToPlace = null; // The name (key) of the item being placed
        let previewMesh = null;

        // --- Constants ---
        const MAP_ROWS = 5; // Increased for more zones
        const MAP_COLS = 4;
        const PLAYER_HEIGHT = 1.0; // For avatar y-position

        // --- Materials ---
        const MAT = {
            stone: new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85 }),
            wood: new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75 }),
            leaf: new THREE.MeshStandardMaterial({ color: 0x3E9B4E, roughness: 0.6, side: THREE.DoubleSide }),
            ground: new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.95 }),
            dirt: new THREE.MeshStandardMaterial({ color: 0x8B5E3C, roughness: 0.9 }),
            grass: new THREE.MeshStandardMaterial({ color: 0x4CB781, roughness: 0.85 }),
            water: new THREE.MeshStandardMaterial({ color: 0x4682B4, roughness: 0.3, transparent: true, opacity: 0.85 }),
            sand: new THREE.MeshStandardMaterial({ color: 0xC2B280, roughness: 0.9 }),
            ice: new THREE.MeshStandardMaterial({ color: 0xadd8e6, roughness: 0.2, transparent: true, opacity: 0.9 }),
            portal: new THREE.MeshStandardMaterial({ color: 0x9933ff, emissive: 0x6600cc, roughness: 0.4, side: THREE.DoubleSide }),
            itemGeneric: new THREE.MeshStandardMaterial({ color: 0xffcc00, roughness: 0.5 }), // For pickup items
            preview: new THREE.MeshStandardMaterial({ color: 0x00ff00, transparent: true, opacity: 0.5, wireframe: true }), // For placement
            simple: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8 }),
        };

        // --- Item Data ---
        const itemsData = {
            "Rusty Sword": {type:"weapon", description:"Old but sharp.", baseDamage: 3, meshGeo: new THREE.BoxGeometry(0.1, 0.8, 0.05), meshMat: MAT.simple.clone().set({color:0x999999})},
            "Health Potion": {type:"consumable", description:"Restores 10 HP.", effect: { hpGain: 10 }, meshGeo: new THREE.SphereGeometry(0.15, 8, 6), meshMat: MAT.simple.clone().set({color:0xff4444})},
            "Goblin Ear": {type:"quest", description:"A gruesome trophy.", meshGeo: new THREE.PlaneGeometry(0.2, 0.3), meshMat: MAT.simple.clone().set({color:0x55aa55})},
            "Cave Crystal": {type:"unknown", description:"A faintly glowing crystal shard.", meshGeo: new THREE.IcosahedronGeometry(0.2, 0), meshMat: MAT.simple.clone().set({color:0xaaaaff, emissive: 0x5555cc})},
            "Ancient Key": {type:"quest", description:"A large, ornate key.", meshGeo: new THREE.BoxGeometry(0.05, 0.3, 0.05), meshMat: MAT.simple.clone().set({color:0xccaa00})},
        };

        // --- Zone Creation ---
        const zoneCreators = {}; // Populated later

        function initThreeJS() {
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x1a1a1a);
            clock = new THREE.Clock();
            raycaster = new THREE.Raycaster();
            mouse = new THREE.Vector2();
            worldGroup = new THREE.Group();
            scene.add(worldGroup);

            // Add Player Avatar
            const avatarGeo = new THREE.CapsuleGeometry(0.3, PLAYER_HEIGHT - 0.6, 4, 10);
            playerAvatar = new THREE.Mesh(avatarGeo, new THREE.MeshStandardMaterial({ color: 0xeeeeff, roughness: 0.7 }));
            playerAvatar.position.y = PLAYER_HEIGHT / 2; // Center it vertically
            playerAvatar.castShadow = true;
            // Don't add to worldGroup directly, add to current zone's group later if needed or keep separate
            scene.add(playerAvatar); // Keep it at scene root for now

            const width = sceneContainer.clientWidth || 1;
            const height = sceneContainer.clientHeight || 1;
            camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
            camera.position.set(0, 6, 8); // Slightly different starting view

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

            controls = new OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.1;
            controls.target.set(0, PLAYER_HEIGHT / 2, 0); // Target the avatar's center
            controls.maxPolarAngle = Math.PI / 2 - 0.05;
            controls.minDistance = 2;
            controls.maxDistance = 25;

            window.addEventListener('resize', onWindowResize, false);
            sceneContainer.addEventListener('click', handleRaycast, false); // Use scene container for clicks
            document.addEventListener('keydown', handleKeyPress); // Listen for key presses globally
            setTimeout(onWindowResize, 50);
            animate();
        }

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

        function animate() {
            requestAnimationFrame(animate);
            const delta = clock.getDelta();
            controls.update();

            // Update placement preview position if active
            if (placementMode && previewMesh) {
                updatePreviewMesh();
            }

            // Simple animation example (e.g., make portals pulse)
             worldGroup.traverse(child => {
                 if (child.userData?.isPortal) {
                     child.material.emissiveIntensity = Math.sin(clock.elapsedTime * 3) * 0.5 + 0.7;
                 }
                 if (child.userData?.isItem && child.userData.itemName === "Cave Crystal") {
                     child.rotation.y += delta * 0.5;
                 }
             });


            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 createGround(material = MAT.ground, size = 20) {
             const geo = new THREE.PlaneGeometry(size, size);
             const ground = new THREE.Mesh(geo, material);
             ground.rotation.x = -Math.PI / 2; ground.position.y = 0;
             ground.receiveShadow = true; ground.castShadow = false; // Ground doesn't cast shadows
             ground.userData.isGround = true; // Mark for raycasting
             return ground;
        }

        function setupLighting(type = 'default') {
            currentLights.forEach(light => {
                 if (light && light.parent) light.parent.remove(light);
                 if (light && !light.parent) scene.remove(light); // Remove from scene if not parented
             });
             currentLights = [];

             let ambientIntensity = 0.6;
             let dirIntensity = 1.0;
             let dirColor = 0xffffff;
             let dirPosition = new THREE.Vector3(10, 15, 8);
             let needsPointLight = false;
             let pointLightInfo = { color: 0xffaa55, intensity: 1.5, distance: 12, decay: 1, pos: {x:0, y:3, z:0} };

             if (type === 'forest') { ambientIntensity = 0.4; dirIntensity = 0.8; dirColor = 0xccffcc; dirPosition = new THREE.Vector3(5, 10, 5); }
             if (type === 'cave') {
                 ambientIntensity = 0.15; dirIntensity = 0; // No sun in cave
                 needsPointLight = true;
             }
             if (type === 'ruins') { ambientIntensity = 0.5; dirIntensity = 0.7; dirColor = 0xaaaaff; dirPosition = new THREE.Vector3(-8, 12, -5); }
             if (type === 'desert') { ambientIntensity = 0.7; dirIntensity = 1.5; dirColor = 0xffffcc; dirPosition = new THREE.Vector3(15, 20, 10); }
             if (type === 'mountain') { ambientIntensity = 0.6; dirIntensity = 1.2; dirColor = 0xddddff; dirPosition = new THREE.Vector3(0, 25, 15); }

             const ambientLight = new THREE.AmbientLight(0xffffff, ambientIntensity);
             scene.add(ambientLight); // Ambient always added to scene
             currentLights.push(ambientLight);

             if (dirIntensity > 0) {
                 const directionalLight = new THREE.DirectionalLight(dirColor, dirIntensity);
                 directionalLight.position.copy(dirPosition);
                 directionalLight.castShadow = true;
                 directionalLight.shadow.mapSize.set(1024*2, 1024*2); // Higher res shadow map
                 directionalLight.shadow.camera.near = 0.5; directionalLight.shadow.camera.far = 60; // Increased range
                 const sb = 25; // Increased shadow box size
                 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); // Directional always added to scene
                 // const helper = new THREE.CameraHelper( directionalLight.shadow.camera ); scene.add( helper ); // Debug Shadow Camera
                 currentLights.push(directionalLight);
             }

             if (needsPointLight) {
                 const ptLight = new THREE.PointLight(pointLightInfo.color, pointLightInfo.intensity, pointLightInfo.distance, pointLightInfo.decay);
                 ptLight.position.set(pointLightInfo.pos.x, pointLightInfo.pos.y, pointLightInfo.pos.z);
                 ptLight.castShadow = true;
                 ptLight.shadow.mapSize.set(512, 512);
                 ptLight.shadow.bias = -0.005; // Point lights might need more bias adjustment
                 // Will be added to the zone group later
                 currentLights.push(ptLight); // Track it
             }
        }

        // --- Zone Creation Functions (Add more for your 20 environments) ---

        function createFieldZone(zoneId) {
            const group = new THREE.Group();
            group.add(createGround(MAT.grass, 30));
            const rockGeo = new THREE.IcosahedronGeometry(0.5 + Math.random()*0.5, 0);
            for(let i=0; i<5; i++) {
                 group.add(createMesh(rockGeo, MAT.stone, {x: (Math.random()-0.5)*25, y:0.3, z: (Math.random()-0.5)*25}));
            }
             // Add an item
            const potion = createMesh(itemsData["Health Potion"].meshGeo, itemsData["Health Potion"].meshMat, {x: 3, y: 0.2, z: 2});
            potion.userData = { isItem: true, itemName: "Health Potion" };
            group.add(potion);

            group.visible = false;
            return { group, lighting: 'default', title: "Open Field", entryText: "You stand in an open, grassy field. A small red potion lies nearby.", options: [
                { text: "Look for interesting plants (INT)", action: 'skillCheck', skill: 'int', difficulty: 10, successText: "You spot some edible herbs!", failureText:"Just grass.", reward: { item: "Health Potion" } } // Example skill check
            ], zoneId: zoneId, items: [potion], interactables: [] }; // Track items in zone
        }

        function createForestZone(zoneId) {
            const group = new THREE.Group();
            group.add(createGround(MAT.ground, 30));
            const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 4, 8);
            const leafGeo = new THREE.SphereGeometry(1.5, 8, 6);
            for(let i=0; i<25; i++) {
                 const x = (Math.random() - 0.5) * 28;
                 const z = (Math.random() - 0.5) * 28;
                 if(Math.sqrt(x*x+z*z) < 1) continue;
                 const tree = new THREE.Group();
                 const trunk = createMesh(trunkGeo, MAT.wood, {y: 2});
                 const leaves = createMesh(leafGeo, MAT.leaf, {y: 4.5});
                 tree.add(trunk); tree.add(leaves);
                 tree.position.set(x, 0, z);
                 tree.rotation.y = Math.random() * Math.PI * 2;
                 group.add(tree);
            }
             // Add an item
             const sword = createMesh(itemsData["Rusty Sword"].meshGeo, itemsData["Rusty Sword"].meshMat, {x: -4, y: 0.5, z: -1}, {z: Math.PI/2});
             sword.userData = { isItem: true, itemName: "Rusty Sword" };
             group.add(sword);

            group.visible = false;
            return { group, lighting: 'forest', title: "Dark Forest", entryText: "Sunlight is sparse beneath the thick canopy. An old sword rests against a tree.", options: [
                { text: "Search for tracks (INT)", action: 'skillCheck', skill: 'int', difficulty: 12, successText: "You find signs of goblin passage.", failureText:"The forest floor reveals little." }
            ], zoneId: zoneId, items: [sword], interactables: [] };
        }

        function createCaveZone(zoneId) {
            const group = new THREE.Group();
            group.add(createGround(MAT.stone.clone().set({color: 0x555560}), 18));
             const wallGeo = new THREE.SphereGeometry(12, 32, 16, 0, Math.PI*2, 0, Math.PI*0.7);
             const walls = createMesh(wallGeo, MAT.stone, {y: 4});
             walls.material.side = THREE.BackSide;
             walls.material.receiveShadow = true; // Cave walls should receive shadow
             walls.castShadow = false;
             group.add(walls);
             const coneGeo = new THREE.ConeGeometry(0.2, 1.0, 8);
             for(let i=0; i<15; i++){
                 const st = createMesh(coneGeo, MAT.stone, {x: (Math.random()-0.5)*16, y: 6 + Math.random()*2, z: (Math.random()-0.5)*16}, {x:Math.PI});
                 group.add(st);
                 const sb = createMesh(coneGeo, MAT.stone, {x: (Math.random()-0.5)*16, y: 0.5, z: (Math.random()-0.5)*16});
                 group.add(sb);
             }
             // Add an item
             const crystal = createMesh(itemsData["Cave Crystal"].meshGeo, itemsData["Cave Crystal"].meshMat, {x: 1, y: 0.8, z: -3});
             crystal.userData = { isItem: true, itemName: "Cave Crystal" };
             crystal.material.emissiveIntensity = 0.8; // Make it glow slightly
             group.add(crystal);

             group.visible = false;
             return { group, lighting: 'cave', title: "Dim Cave", entryText: "It's dark and damp. Water drips. A crystal glimmers faintly.", options: [
                { text: "Squeeze through a narrow gap (DEX)", action: 'skillCheck', skill: 'dex', difficulty: 14, successText: "You manage to wiggle through!", failureText:"You're too clumsy and get stuck briefly.", targetZoneId: 'zone_SPECIAL_SECRET' } // Example transition on success
             ], zoneId: zoneId, items: [crystal], interactables: [] };
        }

         function createRuinsZone(zoneId) {
             const group = new THREE.Group();
             group.add(createGround(MAT.dirt, 25));
             const wallGeo = new THREE.BoxGeometry(0.5, 2, 3);
             for(let i=0; i<8; i++) {
                 const wall = createMesh(wallGeo, MAT.stone,
                       {x: (Math.random()-0.5)*20, y:1, z: (Math.random()-0.5)*20},
                       {y: Math.random() * Math.PI}
                 );
                 wall.scale.y = 0.5 + Math.random() * 0.8;
                 wall.rotation.x = (Math.random()-0.5)*0.1;
                 wall.rotation.z = (Math.random()-0.5)*0.1;
                 group.add(wall);
             }
             // Add an interactable portal (Example of interactive movement point)
             const portalGeo = new THREE.RingGeometry(0.8, 1.2, 16);
             const portal = createMesh(portalGeo, MAT.portal, {x: 5, y: 1.5, z: -5}, {y: Math.PI/4});
             portal.userData = { isPortal: true, targetZoneId: getZoneId(0,0) }; // Example: links back to forest
             group.add(portal);

             group.visible = false;
             return { group, lighting: 'ruins', title: "Crumbling Ruins", entryText: "The wind whistles through broken walls. A strange shimmering portal hangs in the air.", options: [
                { text: "Try to decipher markings (INT)", action: 'skillCheck', skill: 'int', difficulty: 13, successText: "You recognize ancient symbols hinting at a hidden path.", failureText:"The markings are meaningless scratches." }
             ], zoneId: zoneId, items: [], interactables: [portal] };
         }

         function createDesertZone(zoneId) {
            const group = new THREE.Group();
            group.add(createGround(MAT.sand, 40));
            // Add some dunes (simple sine wave bumps)
            const duneGeo = new THREE.PlaneGeometry(40, 40, 20, 20);
            const posAttr = duneGeo.attributes.position;
            for (let i = 0; i < posAttr.count; i++) {
                const x = posAttr.getX(i);
                const z = posAttr.getZ(i);
                posAttr.setY(i, Math.sin(x * 0.2) * Math.cos(z * 0.3) * 0.8); // Simple dune formula
            }
            duneGeo.computeVertexNormals();
            const dunes = new THREE.Mesh(duneGeo, MAT.sand);
            dunes.rotation.x = -Math.PI / 2;
            dunes.receiveShadow = true;
            dunes.castShadow = false;
            dunes.userData.isGround = true; // Mark for raycasting
            group.add(dunes); // Replace flat ground with dunes

            // Add a key item
            const key = createMesh(itemsData["Ancient Key"].meshGeo, itemsData["Ancient Key"].meshMat, {x: -2, y: 0.2 + Math.sin(-2*0.2)*Math.cos(1*0.3)*0.8, z: 1}); // Place on dune surface
            key.userData = { isItem: true, itemName: "Ancient Key" };
            group.add(key);

            group.visible = false;
            return { group, lighting: 'desert', title: "Scorching Desert", entryText: "Endless dunes stretch under a blazing sun. Something glints in the sand.", options: [
                 { text: "Endure the heat (STR - passive check?)", action: 'message', messageText:"The heat is oppressive but bearable for now." }, // Example passive/flavor option
            ], zoneId: zoneId, items: [key], interactables: [] };
         }

         function createMountainZone(zoneId) {
            const group = new THREE.Group();
            group.add(createGround(MAT.stone.clone().set({color: 0x9999aa}), 35)); // Rocky ground

            // Add jagged peaks
            const peakGeo = new THREE.ConeGeometry(3, 8, 8);
            for (let i=0; i<5; i++) {
                const peak = createMesh(peakGeo, MAT.stone.clone().set({color: 0xbbbbcc}),
                    {x: (Math.random()-0.5)*30, y: 4, z: (Math.random()-0.5)*30},
                    {x: (Math.random()-0.5)*0.2, z: (Math.random()-0.5)*0.2} // Slightly tilted
                );
                peak.scale.set(1 + Math.random(), 1 + Math.random()*1.5, 1 + Math.random());
                group.add(peak);
            }
             // Add icy patches
            const iceGeo = new THREE.PlaneGeometry(5,5);
            const icePatch = new THREE.Mesh(iceGeo, MAT.ice);
            icePatch.rotation.x = -Math.PI/2;
            icePatch.position.set(4, 0.1, -6); // Slightly above ground
            icePatch.receiveShadow = true;
            group.add(icePatch);

            group.visible = false;
            return { group, lighting: 'mountain', title: "Jagged Peaks", entryText: "Sharp rocks and biting wind dominate this high altitude pass. Patches of ice make footing treacherous.", options: [
                { text: "Climb a rocky outcrop (STR)", action: 'skillCheck', skill: 'str', difficulty: 14, successText: "You scale the rock, getting a better view!", failureText:"You slip and nearly fall. Best stay on the path." }
            ], zoneId: zoneId, items: [], interactables: [] };
         }

         // --- Utility Functions ---

         function getZoneId(row, col) { return `zone_${row}_${col}`; }

         function populateZoneCreators() {
            const creators = [
                createForestZone, createFieldZone, createCaveZone, createRuinsZone, createDesertZone, createMountainZone
                // Add ALL your 20 creator functions here
            ];
            let creatorIndex = 0;
            for (let r = 0; r < MAP_ROWS; r++) {
                for (let c = 0; c < MAP_COLS; c++) {
                    const zoneId = getZoneId(r, c);
                    // Cycle through the available creators - Customize this logic!
                    const creatorFunc = creators[creatorIndex % creators.length];
                    zoneCreators[zoneId] = () => creatorFunc(zoneId);
                    creatorIndex++;
                }
            }
            console.log(`Zone creators populated for ${MAP_ROWS}x${MAP_COLS} grid.`);
         }

         function getZoneNeighbors(zoneId) {
            const parts = zoneId.split('_');
            if (parts.length !== 3 || parts[0] !== 'zone') return {};
            const r = parseInt(parts[1]);
            const c = parseInt(parts[2]);
            const neighbors = {};
            // Check bounds and if the zone exists in the creators map
            if (r > 0 && zoneCreators[getZoneId(r - 1, c)]) neighbors.north = getZoneId(r - 1, c);
            if (r < MAP_ROWS - 1 && zoneCreators[getZoneId(r + 1, c)]) neighbors.south = getZoneId(r + 1, c);
            if (c > 0 && zoneCreators[getZoneId(r, c - 1)]) neighbors.west = getZoneId(r, c - 1);
            if (c < MAP_COLS - 1 && zoneCreators[getZoneId(r, c + 1)]) neighbors.east = getZoneId(r, c + 1);
            return neighbors;
         }

        function logEvent(message) {
            if (!gameState.character || !gameState.character.history) return;
            gameState.character.history.push(message);
            // Optional: Limit history size
            // if (gameState.character.history.length > 20) {
            //     gameState.character.history.shift();
            // }
            updateHistoryDisplay(); // Update UI immediately
        }

        // --- Game Logic ---

        function startGame() {
            const defaultChar = {
                 name: "Adventurer",
                 stats: { hp: 25, maxHp: 25, xp: 0, str: 10, dex: 10, int: 10 }, // Added stats
                 inventory: [],
                 history: ["Game Started."] // Initialize history
            };
            gameState = {
                 currentZoneId: null,
                 character: JSON.parse(JSON.stringify(defaultChar))
            };
            populateZoneCreators();
            zoneGroups = {}; // Clear existing zones if restarting
             while(worldGroup.children.length > 0){
                 worldGroup.remove(worldGroup.children[0]);
             }
             // Reset placement mode if game restarts
             placementMode = false;
             itemToPlace = null;
             if (previewMesh) {
                 scene.remove(previewMesh);
                 previewMesh = null;
             }

            console.log("Starting new game:", gameState);
            transitionToZone(getZoneId(MAP_ROWS-1, Math.floor(MAP_COLS/2))); // Start near bottom-center
        }

        function transitionToZone(newZoneId) {
            console.log(`Transitioning to ${newZoneId}`);
            currentMessage = ""; // Clear messages on zone change

            if (gameState.currentZoneId && zoneGroups[gameState.currentZoneId]) {
                 zoneGroups[gameState.currentZoneId].group.visible = false;
                 // Remove zone-specific lights from the old group before hiding
                 currentLights.forEach(light => {
                     if (light && light.isPointLight && light.parent === zoneGroups[gameState.currentZoneId].group) {
                         zoneGroups[gameState.currentZoneId].group.remove(light);
                     }
                 });
            }

            let zoneInfo;
            if (zoneGroups[newZoneId]) {
                 zoneInfo = zoneGroups[newZoneId];
                 zoneInfo.group.visible = true;
                 console.log(`Re-entering zone ${newZoneId}`);
                 logEvent(`Entered ${zoneInfo.title || newZoneId}.`);
            } else {
                 const creator = zoneCreators[newZoneId];
                 if (creator) {
                     zoneInfo = creator();
                     zoneGroups[newZoneId] = zoneInfo;
                     worldGroup.add(zoneInfo.group);
                     zoneInfo.group.visible = true;
                     console.log(`Created and entered zone ${newZoneId}`);
                     logEvent(`Discovered and entered ${zoneInfo.title || newZoneId}.`);
                 } else {
                     console.error(`No creator found for zone ID: ${newZoneId}, going to fallback`);
                      const fallbackId = getZoneId(MAP_ROWS-1, Math.floor(MAP_COLS/2)); // Fallback start
                      if (!zoneGroups[fallbackId]) { // Ensure fallback exists
                          zoneGroups[fallbackId] = zoneCreators[fallbackId]();
                          worldGroup.add(zoneGroups[fallbackId].group);
                      }
                      zoneInfo = zoneGroups[fallbackId];
                      zoneInfo.group.visible = true;
                      newZoneId = fallbackId;
                      currentMessage = `<p class="message message-failure">Error: Invalid zone transition. Returned to safety.</p>`;
                      logEvent(`Error: Tried to enter invalid zone. Returned to ${zoneInfo.title || fallbackId}.`);
                 }
            }

            gameState.currentZoneId = newZoneId;
            setupLighting(zoneInfo.lighting || 'default'); // Setup general lighting FIRST

            // Add zone-specific lights (like point lights for caves) to the *current* zone's group
            currentLights.forEach(light => {
                 if (light && light.isPointLight && !light.parent) { // If it's a point light tracked but not in scene/group
                     zoneInfo.group.add(light); // Add it to the now visible group
                     console.log("Added point light to zone group:", newZoneId)
                 }
            });

            // Move player avatar to center of the new zone (optional visual)
            playerAvatar.position.set(0, PLAYER_HEIGHT / 2, 0);

            // Reset camera target and position relative to avatar/center
            camera.position.set(0, 6, 8); // Reset relative position
            controls.target.set(0, PLAYER_HEIGHT / 2, 0); // Target avatar center
            controls.update();

            // End placement mode on zone transition
            if (placementMode) {
                togglePlacementMode();
            }

            renderCurrentPageUI();
         }

        // --- Interaction Handling ---

        function handleKeyPress(event) {
            if (event.key.toUpperCase() === 'P') {
                togglePlacementMode();
            }
        }

        function handleRaycast(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;

            // Update the picking ray with the camera and mouse position
            raycaster.setFromCamera(mouse, camera);

            // Calculate objects intersecting the picking ray
            // Important: Check against the *current visible zone group's children* and potentially other global interactables
            const currentZoneGroup = zoneGroups[gameState.currentZoneId]?.group;
            if (!currentZoneGroup) return;

            const intersects = raycaster.intersectObjects(currentZoneGroup.children, true); // Check children recursively

            if (intersects.length > 0) {
                const firstIntersect = intersects[0];
                const obj = firstIntersect.object;
                const point = firstIntersect.point; // World coordinates of the intersection

                if (placementMode) {
                    // If placing, click on ground places item
                    if (obj.userData.isGround || obj.parent?.userData?.isGround) { // Check obj or its immediate parent if ground is complex
                        placeItem(point);
                    } else {
                        console.log("Cannot place item here.");
                        currentMessage = `<p class="message message-failure">You can only place items on the ground.</p>`;
                        renderCurrentPageUI(); // Show message
                    }
                } else {
                    // Normal mode: Check for items or interactables
                    if (obj.userData?.isItem) {
                        pickupItem(obj, currentZoneGroup);
                    } else if (obj.userData?.isPortal) {
                        console.log(`Clicked Portal to: ${obj.userData.targetZoneId}`);
                        logEvent(`Stepped through the portal.`);
                        transitionToZone(obj.userData.targetZoneId);
                    } else if (obj.userData?.isGround) {
                         console.log("Clicked ground at:", point);
                         // Future: Could implement click-to-move here
                    } else {
                         console.log("Clicked non-interactive object:", obj.name, obj.userData);
                    }
                }
            }
        }

        function pickupItem(itemMesh, zoneGroup) {
            const itemName = itemMesh.userData.itemName;
            if (!itemName || !itemsData[itemName]) {
                console.error("Clicked item mesh has invalid data:", itemMesh);
                return;
            }

            // Add to inventory
            gameState.character.inventory.push(itemName);

            // Remove from scene / zone group
            zoneGroup.remove(itemMesh);

            // Remove from zoneInfo's item list (if tracked)
            const zoneInfo = zoneGroups[gameState.currentZoneId];
            if (zoneInfo && zoneInfo.items) {
                zoneInfo.items = zoneInfo.items.filter(item => item !== itemMesh);
            }

             // Set the item for potential placement later
             itemToPlace = itemName; // Track the last picked item's name

            console.log(`Picked up: ${itemName}`);
            currentMessage = `<p class="message message-success">You picked up: ${itemName}. Press 'P' to place it.</p>`;
            logEvent(`Picked up ${itemName}.`);

            renderCurrentPageUI(); // Update inventory display and message
        }

        function togglePlacementMode() {
            if (!itemToPlace) {
                 currentMessage = `<p class="message message-info">You have no item selected to place. Pick up an item first.</p>`;
                 renderCurrentPageUI();
                 return; // Don't enter placement mode without an item
            }

            placementMode = !placementMode;
            console.log("Placement Mode:", placementMode);

            if (placementMode) {
                 actionInfoElement.textContent = `Placement Mode ON (Placing: ${itemToPlace}). Click ground to place. Press P to cancel.`;
                 // Create preview mesh if it doesn't exist
                 if (!previewMesh) {
                     const itemData = itemsData[itemToPlace];
                     if (itemData && itemData.meshGeo) {
                         // Use a generic preview material but original geometry
                         previewMesh = new THREE.Mesh(itemData.meshGeo, MAT.preview);
                         previewMesh.renderOrder = 1; // Try to render on top
                         previewMesh.userData.isPreview = true;
                         scene.add(previewMesh); // Add preview directly to the main scene
                     } else {
                         console.error("Cannot create preview for item:", itemToPlace);
                         placementMode = false; // Exit placement mode if preview fails
                         actionInfoElement.textContent = `Zone: ${gameState.currentZoneId || 'None'}`;
                         return;
                     }
                 }
                 previewMesh.visible = true;
                 updatePreviewMesh(); // Position it initially
            } else {
                 actionInfoElement.textContent = `Zone: ${gameState.currentZoneId || 'None'}`;
                 if (previewMesh) {
                     previewMesh.visible = false; // Hide preview instead of removing
                 }
                 // Optionally clear itemToPlace here if cancelling should forget the item
                 // itemToPlace = null;
                 currentMessage = `<p class="message message-info">Placement mode cancelled.</p>`;
                 renderCurrentPageUI();
            }
        }

        function updatePreviewMesh() {
             if (!placementMode || !previewMesh) return;

             // Raycast from camera to mouse position, ONLY against ground objects
             raycaster.setFromCamera(mouse, camera);
             const currentZoneGroup = zoneGroups[gameState.currentZoneId]?.group;
             if (!currentZoneGroup) return;

             // Filter for ground objects in the current zone
             const groundObjects = [];
             currentZoneGroup.traverse(child => {
                if (child.userData?.isGround) {
                    groundObjects.push(child);
                }
             })

             const intersects = raycaster.intersectObjects(groundObjects, false); // Don't check recursively if ground is simple plane

             if (intersects.length > 0) {
                 const point = intersects[0].point;
                 previewMesh.position.copy(point);
                 // Add small offset based on item geometry bounds if available
                 const itemData = itemsData[itemToPlace];
                 if (itemData && itemData.meshGeo) {
                     itemData.meshGeo.computeBoundingBox();
                     const height = itemData.meshGeo.boundingBox.max.y - itemData.meshGeo.boundingBox.min.y;
                     previewMesh.position.y += height / 2 + 0.01; // Place bottom slightly above ground
                 } else {
                     previewMesh.position.y += 0.1; // Default offset
                 }
                 previewMesh.visible = true;
             } else {
                 previewMesh.visible = false; // Hide if not pointing at ground
             }
         }


        function placeItem(position) {
            if (!placementMode || !itemToPlace) return;

            const itemData = itemsData[itemToPlace];
            const currentZoneGroup = zoneGroups[gameState.currentZoneId]?.group;
            const zoneInfo = zoneGroups[gameState.currentZoneId];

            if (!itemData || !currentZoneGroup || !zoneInfo) {
                console.error("Cannot place item, missing data.");
                togglePlacementMode(); // Exit placement mode on error
                return;
            }

            // Create the actual item mesh
            const newItemMesh = createMesh(itemData.meshGeo, itemData.meshMat);
            newItemMesh.userData = { isItem: true, itemName: itemToPlace };

             // Adjust position based on geometry height, like the preview
             itemData.meshGeo.computeBoundingBox();
             const height = itemData.meshGeo.boundingBox.max.y - itemData.meshGeo.boundingBox.min.y;
             position.y += height / 2 + 0.01;
             newItemMesh.position.copy(position);


            // Add to the scene (current zone's group)
            currentZoneGroup.add(newItemMesh);

            // Add to the zone's item list for tracking
            if (!zoneInfo.items) zoneInfo.items = [];
            zoneInfo.items.push(newItemMesh);

            // Remove from inventory
            const invIndex = gameState.character.inventory.indexOf(itemToPlace);
            if (invIndex > -1) {
                gameState.character.inventory.splice(invIndex, 1);
            }

            console.log(`Placed ${itemToPlace} at ${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}`);
            currentMessage = `<p class="message message-success">You placed the ${itemToPlace}.</p>`;
            logEvent(`Placed ${itemToPlace} in ${zoneInfo.title || gameState.currentZoneId}.`);

            itemToPlace = null; // Clear the item being placed
            togglePlacementMode(); // Exit placement mode
            renderCurrentPageUI(); // Update UI
        }

        function performSkillCheck(skill, difficulty) {
            if (!gameState.character || !gameState.character.stats[skill]) {
                console.error("Invalid skill check:", skill);
                return { success: false, roll: 0, resultValue: 0, message: "Error: Invalid skill." };
            }

            const roll = Math.floor(Math.random() * 20) + 1;
            const skillValue = gameState.character.stats[skill] || 0; // Use 0 if stat doesn't exist
            const resultValue = roll + skillValue;
            const success = resultValue >= difficulty;

            console.log(`Skill Check: ${skill.toUpperCase()} (DC ${difficulty}) | Roll: ${roll} + Stat: ${skillValue} = ${resultValue} | ${success ? 'Success' : 'Failure'}`);

            return { success, roll, skillValue, resultValue };
        }


        // --- UI Rendering ---

        function renderCurrentPageUI() {
            const zoneInfo = zoneGroups[gameState.currentZoneId];
            const zoneId = gameState.currentZoneId;

            if (!zoneInfo) {
                 console.error(`No zone info loaded for ${zoneId}`);
                 storyTitleElement.textContent = "Error";
                 storyContentElement.innerHTML = currentMessage + "<p>Cannot render current zone. World broken.</p>";
                 choicesElement.innerHTML = `<button class="choice-button" onclick="startGame()">Restart Game</button>`; // Offer restart
                 updateStatsDisplay();
                 updateInventoryDisplay();
                 updateHistoryDisplay();
                 updateActionInfo();
                 return;
            }

             storyTitleElement.textContent = zoneInfo.title || "Unknown Zone";
             // Combine current message (from actions) with the zone's entry text
             storyContentElement.innerHTML = currentMessage + (zoneInfo.entryText ? `<p>${zoneInfo.entryText}</p>` : '');
             choicesElement.innerHTML = ''; // Clear previous choices

             // 1. Add Zone-Specific Options (including skill checks)
             if (zoneInfo.options && zoneInfo.options.length > 0) {
                 zoneInfo.options.forEach((option, index) => {
                     const button = document.createElement('button');
                     button.classList.add('choice-button');
                     button.textContent = option.text;

                     button.onclick = () => {
                         currentMessage = ""; // Clear previous action message before processing new one
                         if (option.action === 'skillCheck') {
                             const checkResult = performSkillCheck(option.skill, option.difficulty);
                             const messageClass = checkResult.success ? 'message-success' : 'message-failure';
                             const outcomeText = checkResult.success ? option.successText : option.failureText;
                             currentMessage = `<p class="message ${messageClass}">(${option.skill.toUpperCase()} DC ${option.difficulty}: ${checkResult.roll}+${checkResult.skillValue}=${checkResult.resultValue}) ${outcomeText}</p>`;
                             logEvent(`Skill Check ${option.skill.toUpperCase()}: ${checkResult.success ? 'Success' : 'Failure'} (${checkResult.resultValue} vs ${option.difficulty}).`);

                             if (checkResult.success) {
                                 // Grant reward if defined
                                 if (option.reward?.item && itemsData[option.reward.item]) {
                                    gameState.character.inventory.push(option.reward.item);
                                    currentMessage += `<p class="message message-success">You gained: ${option.reward.item}!</p>`;
                                    logEvent(`Gained ${option.reward.item}.`);
                                 }
                                 // Transition if defined
                                 if(option.targetZoneId) {
                                     transitionToZone(option.targetZoneId);
                                     return; // Stop further processing for this click if transitioning
                                 }
                                 // TODO: Could also modify zoneInfo.options or zoneInfo.entryText here for persistent changes
                             } else {
                                 // Handle failure consequences if any (e.g., take damage, trigger event)
                             }

                         } else if (option.action === 'message') {
                             currentMessage = `<p class="message message-info">${option.messageText}</p>`;
                             logEvent(`Observed: ${option.messageText}`);
                         } else if (option.action === 'goToZone') {
                             logEvent(`Chose to go to ${option.targetZoneId}.`);
                             transitionToZone(option.targetZoneId);
                             return; // Stop processing
                         }
                         // Add more action types here (combat, useItem, etc.)

                         renderCurrentPageUI(); // Re-render UI to show the result message
                     };
                     choicesElement.appendChild(button);
                 });
             }

            // 2. Add Movement Options (Buttons)
            const neighbors = getZoneNeighbors(zoneId);
            const directions = {'north': 'North', 'south': 'South', 'east': 'East', 'west': 'West'};
            for(const dir in neighbors) {
                 const neighborId = neighbors[dir];
                 const button = document.createElement('button');
                 button.classList.add('choice-button');
                 // Maybe get the title of the neighbor zone for a hint?
                 const neighborInfo = zoneGroups[neighborId] ?? zoneCreators[neighborId]?.(); // Preview or get existing
                 const neighborTitle = neighborInfo?.title ? ` (${neighborInfo.title})` : '';

                 button.textContent = `Go ${directions[dir]}${neighborTitle}`;
                 button.onclick = () => transitionToZone(neighborId);
                 choicesElement.appendChild(button);

                 // Cleanup preview if generated just for title
                 if(neighborInfo && !zoneGroups[neighborId]) {
                    // If we generated it just for the title and it wasn't already loaded, dispose of it? Or just let it be created on transition.
                 }
            }

             // 3. Update other UI elements
             updateStatsDisplay();
             updateInventoryDisplay();
             updateHistoryDisplay(); // Make sure history is up-to-date
             updateActionInfo();
        }

        // Make transitionToZone globally accessible for initial call and error recovery button if needed
        window.transitionToZone = transitionToZone;
        window.startGame = startGame; // Allow restarting from console or error button

        function updateStatsDisplay() {
            const { hp, maxHp, xp, str, dex, int } = gameState.character.stats;
            const hpColor = hp / maxHp < 0.3 ? '#f88' : (hp / maxHp < 0.6 ? '#fd5' : '#8f8');
            statsElement.innerHTML = `<strong>Stats:</strong> <span style="color:${hpColor}">HP: ${hp}/${maxHp}</span> <span>XP: ${xp}</span> <span>STR: ${str}</span> <span>DEX: ${dex}</span> <span>INT: ${int}</span>`;
        }

        function updateInventoryDisplay() {
             let invHtml = '<strong>Inventory:</strong> ';
             if (gameState.character.inventory.length === 0) {
                 invHtml += '<em>Empty</em>';
             } else {
                 // Group items
                 const itemCounts = gameState.character.inventory.reduce((acc, item) => {
                    acc[item] = (acc[item] || 0) + 1;
                    return acc;
                 }, {});

                 Object.entries(itemCounts).forEach(([itemName, count]) => {
                    const itemDef = itemsData[itemName] || { type: 'unknown', description: '???' };
                    const itemClass = `item-${itemDef.type || 'unknown'}`;
                    const countDisplay = count > 1 ? ` (x${count})` : '';
                    invHtml += `<span class="item-tag ${itemClass}" title="${itemDef.description}">${itemName}${countDisplay}</span>`;
                 });
             }
             inventoryElement.innerHTML = invHtml;
        }

         function updateHistoryDisplay() {
            if (!historyElement || !gameState.character || !gameState.character.history) return;
            let historyHtml = '<strong>History:</strong>';
            // Display latest events first
            for (let i = gameState.character.history.length - 1; i >= 0; i--) {
                historyHtml += `<div>${gameState.character.history[i]}</div>`;
            }
            historyElement.innerHTML = historyHtml;
            historyElement.scrollTop = 0; // Scroll to top to show latest
        }

        function updateActionInfo() {
            if (!actionInfoElement) return;
            if (placementMode) {
                 actionInfoElement.textContent = `Placement Mode ON (Placing: ${itemToPlace}). Click ground to place. Press P to cancel.`;
            } else {
                 actionInfoElement.textContent = `Zone: ${gameState.currentZoneId || 'None'}`;
            }
        }

        // --- Initialization ---
        document.addEventListener('DOMContentLoaded', () => {
             console.log("DOM Ready - Initializing Enhanced CYOA.");
             try {
                 initThreeJS();
                 if (!scene || !camera || !renderer) throw new Error("Three.js failed to initialize.");
                 startGame(); // Start game directly
                 console.log("Game world initialized and 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>`;
                 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').innerHTML = '<button class="choice-button" onclick="location.reload()">Reload Page</button>'; // Offer reload on critical fail
             }
         });

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