File size: 102,625 Bytes
1d353bd
 
 
 
 
4b76367
7c0cab7
4b76367
 
 
 
 
 
 
 
 
 
 
797c7a3
 
 
 
 
 
 
4b76367
797c7a3
 
 
 
 
 
 
4b76367
797c7a3
4b76367
797c7a3
 
 
 
 
 
 
 
 
4b76367
797c7a3
4b76367
797c7a3
4b76367
797c7a3
 
 
 
 
 
 
 
 
 
 
 
4b76367
 
 
797c7a3
4b76367
797c7a3
 
 
 
4b76367
5cf7eec
797c7a3
 
4b76367
5cf7eec
797c7a3
 
 
 
 
 
 
 
4b76367
797c7a3
4b76367
797c7a3
4b76367
 
 
 
 
797c7a3
4b76367
797c7a3
 
 
4b76367
 
 
797c7a3
4b76367
797c7a3
4b76367
 
 
 
 
 
797c7a3
 
 
 
 
7c0cab7
1d353bd
 
7c0cab7
6c1f7e8
7c0cab7
0a69594
7c0cab7
0a69594
 
 
576e2ca
 
58c0666
0a69594
576e2ca
 
0a69594
 
7c0cab7
1d353bd
7c0cab7
797c7a3
 
 
 
 
7c0cab7
 
 
 
 
 
 
0a69594
 
 
 
 
7c0cab7
797c7a3
 
0a69594
797c7a3
0a69594
797c7a3
 
 
 
 
0a69594
797c7a3
 
1d47995
797c7a3
 
 
 
 
7c0cab7
 
797c7a3
58c0666
 
797c7a3
 
 
 
 
 
 
4b76367
797c7a3
0a69594
797c7a3
 
 
9169e3a
7c0cab7
 
 
 
797c7a3
 
 
 
 
 
 
 
7c0cab7
 
 
0a69594
797c7a3
 
 
 
 
 
4b76367
797c7a3
 
 
 
 
 
 
 
0a69594
 
 
797c7a3
 
 
 
 
 
 
 
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576e2ca
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
9169e3a
797c7a3
9169e3a
 
 
 
 
 
 
 
 
 
 
 
797c7a3
 
 
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
 
9169e3a
 
797c7a3
9169e3a
797c7a3
 
 
 
 
 
 
9169e3a
 
797c7a3
 
 
9169e3a
797c7a3
9169e3a
797c7a3
9169e3a
8a79bb7
9169e3a
 
 
 
 
 
576e2ca
9169e3a
797c7a3
 
 
 
9169e3a
 
 
 
797c7a3
 
9169e3a
797c7a3
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576e2ca
 
 
9169e3a
797c7a3
9169e3a
797c7a3
 
 
 
9169e3a
 
 
 
 
 
 
 
 
576e2ca
 
9169e3a
 
576e2ca
1d47995
6c1f7e8
797c7a3
9169e3a
 
 
 
 
8a79bb7
 
576e2ca
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
9169e3a
 
 
 
 
 
 
797c7a3
 
9169e3a
 
797c7a3
9169e3a
 
 
 
 
 
 
 
 
576e2ca
9169e3a
 
 
576e2ca
9169e3a
 
576e2ca
9169e3a
576e2ca
9169e3a
 
 
 
 
576e2ca
 
 
 
 
9169e3a
576e2ca
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576e2ca
9169e3a
576e2ca
9169e3a
576e2ca
9169e3a
 
 
 
 
576e2ca
 
9169e3a
 
576e2ca
 
 
 
 
9169e3a
576e2ca
 
9169e3a
 
 
8a79bb7
576e2ca
9169e3a
576e2ca
 
 
 
9169e3a
 
1d47995
 
9169e3a
 
 
 
797c7a3
 
9169e3a
 
797c7a3
 
 
9169e3a
 
 
797c7a3
9169e3a
 
 
 
 
 
797c7a3
1d47995
9169e3a
797c7a3
 
 
9169e3a
 
 
 
 
797c7a3
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
 
 
576e2ca
9169e3a
 
 
 
797c7a3
9169e3a
 
 
 
576e2ca
9169e3a
 
 
 
 
 
 
797c7a3
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576e2ca
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
576e2ca
9169e3a
 
 
 
 
5cf7eec
 
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
9169e3a
797c7a3
 
576e2ca
9169e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797c7a3
5cf7eec
 
 
9169e3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Choose Your Own Procedural Adventure</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            background-color: #222;
            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 #555;
            min-width: 200px;
            background-color: #1a1a1a;
            height: 100%;
            box-sizing: border-box;
        }

        #ui-container {
            flex-grow: 2;
            padding: 20px;
            overflow-y: auto;
            background-color: #333;
            min-width: 280px;
            height: 100%;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
        }

        #scene-container canvas { display: block; }

        #story-title {
            color: #ffcc66;
            margin-top: 0;
            margin-bottom: 15px;
            border-bottom: 1px solid #555;
            padding-bottom: 10px;
            font-size: 1.4em;
        }

        #story-content {
            margin-bottom: 20px;
            line-height: 1.6;
            flex-grow: 1;
        }
        #story-content p { margin-bottom: 1em; }
        #story-content p:last-child { margin-bottom: 0; }

        #stats-inventory-container {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #555;
            font-size: 0.9em;
        }
        #stats-display, #inventory-display {
            margin-bottom: 10px;
            line-height: 1.8;
        }
        #stats-display span, #inventory-display span {
            display: inline-block;
            background-color: #444;
            padding: 3px 8px;
            border-radius: 15px;
            margin-right: 8px;
            margin-bottom: 5px;
            border: 1px solid #666;
            white-space: nowrap;
        }
        #stats-display strong, #inventory-display strong { color: #aaa; margin-right: 5px; }
        #inventory-display em { color: #888; font-style: normal; }

        #inventory-display .item-quest { background-color: #666030; border-color: #999048;}
        #inventory-display .item-weapon { background-color: #663030; border-color: #994848;}
        #inventory-display .item-armor { background-color: #306630; border-color: #489948;}
        #inventory-display .item-spell { background-color: #303066; border-color: #484899;}
        #inventory-display .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: 10px; color: #aaa; }
        #choices { display: flex; flex-direction: column; gap: 10px; }

        .choice-button {
            display: block; width: 100%; padding: 10px 12px; margin-bottom: 0;
            background-color: #555; color: #eee; border: 1px solid #777;
            border-radius: 5px; cursor: pointer; text-align: left;
            font-family: 'Courier New', monospace; font-size: 1em;
            transition: background-color 0.2s, border-color 0.2s;
            box-sizing: border-box;
        }
        .choice-button:hover:not(:disabled) { background-color: #d4a017; color: #222; border-color: #b8860b; }
        .choice-button:disabled { background-color: #444; color: #888; cursor: not-allowed; border-color: #666; opacity: 0.7; }

        .roll-success { color: #7f7; border-left: 3px solid #4a4; padding-left: 8px; margin-bottom: 1em; font-size: 0.9em; }
        .roll-failure { color: #f77; border-left: 3px solid #a44; padding-left: 8px; margin-bottom: 1em; font-size: 0.9em; }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="scene-container"></div>
        <div id="ui-container">
            <h2 id="story-title">Loading Adventure...</h2>
            <div id="story-content">
                <p>Please wait while the adventure loads.</p>
            </div>
            <div id="stats-inventory-container">
                <div id="stats-display"></div>
                <div id="inventory-display"></div>
            </div>
            <div id="choices-container">
                <h3>What will you do?</h3>
                <div id="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';

        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');

        let scene, camera, renderer;
        let currentAssemblyGroup = null;

        // Materials
        const stoneMaterial = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.8, metalness: 0.1 });
        const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.7, metalness: 0 });
        const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x5C3D20, roughness: 0.7, metalness: 0 });
        const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57, roughness: 0.6, metalness: 0 });
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9, metalness: 0 });
        const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.3 });
        const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xA99B78, roughness: 0.7, metalness: 0.1 });
        const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5 });
        const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5 });
        const dirtMaterial = new THREE.MeshStandardMaterial({ color: 0x8B5E3C, roughness: 0.9 });
        const grassMaterial = new THREE.MeshStandardMaterial({ color: 0x3CB371, roughness: 0.8 });
        const oceanMaterial = new THREE.MeshStandardMaterial({ color: 0x1E90FF, roughness: 0.5, metalness: 0.2 });
        const sandMaterial = new THREE.MeshStandardMaterial({ color: 0xF4A460, roughness: 0.9 });
        const wetStoneMaterial = new THREE.MeshStandardMaterial({ color: 0x2F4F4F, roughness: 0.7 });
        const glowMaterial = new THREE.MeshStandardMaterial({ color: 0x00FFAA, emissive: 0x00FFAA, emissiveIntensity: 0.5 });

        function initThreeJS() {
            if (!sceneContainer) { console.error("Scene container not found!"); return; }
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x222222);
            const width = sceneContainer.clientWidth;
            const height = sceneContainer.clientHeight;
            camera = new THREE.PerspectiveCamera(75, (width / height) || 1, 0.1, 1000);
            camera.position.set(0, 2.5, 7);
            camera.lookAt(0, 0.5, 0);
            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(width || 400, height || 300);
            renderer.shadowMap.enabled = true;
            renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            sceneContainer.appendChild(renderer.domElement);
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);
            window.addEventListener('resize', onWindowResize, false);
            setTimeout(onWindowResize, 100); // Adjust size shortly after init
            animate();
        }

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

        function animate() {
            requestAnimationFrame(animate);
            const time = performance.now() * 0.001;
            scene.traverse(obj => {
                if (obj.userData.update) obj.userData.update(time);
            });
            if (renderer && scene && camera) {
                renderer.render(scene, camera);
            }
        }

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

        function createGroundPlane(material = groundMaterial, size = 20) {
            const groundGeo = new THREE.PlaneGeometry(size, size);
            const ground = new THREE.Mesh(groundGeo, material);
            ground.rotation.x = -Math.PI / 2; ground.position.y = -0.05;
            ground.receiveShadow = true; ground.castShadow = false;
            return ground;
        }

        // ========================================
        // Procedural Generation Functions
        // ========================================
        function createDefaultAssembly() {
            const group = new THREE.Group();
            const sphereGeo = new THREE.SphereGeometry(0.5, 16, 16);
            group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.5, z: 0 }));
            group.add(createGroundPlane());
            return group;
        }

        function createCityGatesAssembly() {
            const group = new THREE.Group();
            const gh=4, gw=1.5, gd=0.8, ah=1, aw=3; // Gate Height, Gate Width, Gate Depth, Arch Height, Arch Width
            // Towers
            const tlGeo = new THREE.BoxGeometry(gw, gh, gd);
            group.add(createMesh(tlGeo, stoneMaterial, { x:-(aw/2+gw/2), y:gh/2, z:0 }));
            const trGeo = new THREE.BoxGeometry(gw, gh, gd);
            group.add(createMesh(trGeo, stoneMaterial, { x:(aw/2+gw/2), y:gh/2, z:0 }));
            // Arch
            const aGeo = new THREE.BoxGeometry(aw, ah, gd);
            group.add(createMesh(aGeo, stoneMaterial, { x:0, y:gh-ah/2, z:0 }));
            // Crenellations
            const cs=0.4; // Crenellation size
            const cg = new THREE.BoxGeometry(cs, cs, gd*1.1);
            for(let i=-1; i<=1; i+=2){ // Left/Right on towers
                group.add(createMesh(cg.clone(), stoneMaterial, { x:-(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 }));
                group.add(createMesh(cg.clone(), stoneMaterial, { x:(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 }));
            }
            // Center crenellation on arch
            group.add(createMesh(cg.clone(), stoneMaterial, { x:0, y:gh+ah-cs/2, z:0 })); // Adjusted Y pos
            group.add(createGroundPlane(stoneMaterial)); // Stone ground
            return group;
        }

        function createWeaponsmithAssembly() {
            const group = new THREE.Group();
            // Building
            const bw=3, bh=2.5, bd=3.5; // Building Width, Height, Depth
            const bGeo = new THREE.BoxGeometry(bw, bh, bd);
            group.add(createMesh(bGeo, darkWoodMaterial, { x:0, y:bh/2, z:0 }));
            // Chimney
            const ch=3.5; // Chimney Height
            const cGeo = new THREE.CylinderGeometry(0.3, 0.4, ch, 8); // Slightly tapered
            group.add(createMesh(cGeo, stoneMaterial, { x:bw*0.3, y:ch/2, z:-bd*0.3 }));
            // TODO: Add anvil, forge visual?
            group.add(createGroundPlane(dirtMaterial)); // Dirt ground
            return group;
        }

        function createTempleAssembly() {
            const group = new THREE.Group();
            const bs=5, bsh=0.5, ch=3, cr=0.25, rh=0.5; // Base Size, Base Height, Column Height, Column Radius, Roof Height
            // Base platform
            const bGeo = new THREE.BoxGeometry(bs, bsh, bs);
            group.add(createMesh(bGeo, templeMaterial, { x:0, y:bsh/2, z:0 }));
            // Columns
            const cGeo = new THREE.CylinderGeometry(cr, cr, ch, 12);
            const cPos = [{x:-bs/3, z:-bs/3}, {x:bs/3, z:-bs/3}, {x:-bs/3, z:bs/3}, {x:bs/3, z:bs/3}]; // Column positions
            cPos.forEach(p=>group.add(createMesh(cGeo.clone(), templeMaterial, { x:p.x, y:bsh+ch/2, z:p.z })));
            // Roof
            const rGeo = new THREE.BoxGeometry(bs*0.9, rh, bs*0.9); // Slightly smaller than base
            group.add(createMesh(rGeo, templeMaterial, { x:0, y:bsh+ch+rh/2, z:0 }));
            // TODO: Add altar? Steps?
            group.add(createGroundPlane(stoneMaterial)); // Stone ground
            return group;
        }

        function createResistanceMeetingAssembly() {
            const group = new THREE.Group();
            // Table
            const tw=2, th=0.8, td=1, tt=0.1; // Table Width, Height, Depth, Thickness
            const ttg = new THREE.BoxGeometry(tw, tt, td); // Table Top Geometry
            group.add(createMesh(ttg, woodMaterial, { x:0, y:th-tt/2, z:0 }));
            // Table Legs
            const lh=th-tt, ls=0.1; // Leg Height, Size
            const lg=new THREE.BoxGeometry(ls, lh, ls); // Leg Geometry
            const lofW=tw/2-ls*1.5; // Leg Offset Width
            const lofD=td/2-ls*1.5; // Leg Offset Depth
            group.add(createMesh(lg, woodMaterial, { x:-lofW, y:lh/2, z:-lofD }));
            group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:-lofD }));
            group.add(createMesh(lg.clone(), woodMaterial, { x:-lofW, y:lh/2, z:lofD }));
            group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:lofD }));
            // Stools/Crates
            const ss=0.4; // Stool Size
            const sg=new THREE.BoxGeometry(ss, ss*0.8, ss); // Stool Geometry
            group.add(createMesh(sg, darkWoodMaterial, { x:-tw*0.6, y:ss*0.4, z:0 }));
            group.add(createMesh(sg.clone(), darkWoodMaterial, { x:tw*0.6, y:ss*0.4, z:0 }));
            // TODO: Add map/papers on table? Dim lighting?
            group.add(createGroundPlane(stoneMaterial)); // Stone floor
            return group;
        }

        function createForestAssembly(tc=10, a=10) { // Tree Count, Area Size
            const group = new THREE.Group();
            // Tree creation helper function
            const createTree=(x,z)=>{
                const treeGroup=new THREE.Group();
                const trunkHeight=Math.random()*1.5+2; // Random height
                const trunkRadius=Math.random()*0.1+0.1; // Random radius
                const trunkGeo = new THREE.CylinderGeometry(trunkRadius*0.7, trunkRadius, trunkHeight, 8); // Tapered trunk
                treeGroup.add(createMesh(trunkGeo, woodMaterial, {x:0, y:trunkHeight/2, z:0}));
                // Foliage (simple sphere)
                const foliageRadius=trunkHeight*0.4+0.2; // Foliage size based on height
                const foliageGeo=new THREE.SphereGeometry(foliageRadius, 8, 6); // Low poly
                treeGroup.add(createMesh(foliageGeo, leafMaterial, {x:0, y:trunkHeight*0.9, z:0})); // Position foliage near top
                treeGroup.position.set(x,0,z);
                return treeGroup;
            };
            // Place trees randomly
            for(let i=0; i<tc; i++){
                const x=(Math.random()-0.5)*a;
                const z=(Math.random()-0.5)*a;
                // Avoid placing trees too close to the center (0,0)
                if(Math.sqrt(x*x+z*z)>1.0) group.add(createTree(x,z));
            }
            group.add(createGroundPlane(groundMaterial, a*1.1)); // Ground slightly larger than tree area
            return group;
        }

        function createRoadAmbushAssembly() {
            const group = new THREE.Group();
            const areaSize=12;
            // Add forest base
            const forestGroup = createForestAssembly(8, areaSize); // Fewer trees for ambush visibility
            group.add(forestGroup);
            // Add Road
            const roadWidth=3, roadLength=areaSize*1.2;
            const roadGeo=new THREE.PlaneGeometry(roadWidth, roadLength);
            const roadMat=new THREE.MeshStandardMaterial({color:0x966F33, roughness:0.9}); // Dirt road color
            const road=createMesh(roadGeo, roadMat, {x:0, y:0.01, z:0}, {x:-Math.PI/2}); // Lay flat on ground
            road.receiveShadow=true; // Road receives shadows
            group.add(road);
            // Add some rocks/bushes near road for cover
            const rockGeo=new THREE.SphereGeometry(0.5, 5, 4); // Low poly rock
            const rockMat=new THREE.MeshStandardMaterial({color:0x666666, roughness:0.8});
            group.add(createMesh(rockGeo, rockMat, {x:roadWidth*0.7, y:0.25, z:1}, {y:Math.random()*Math.PI}));
            group.add(createMesh(rockGeo.clone().scale(0.8,0.8,0.8), rockMat, {x:-roadWidth*0.8, y:0.2, z:-2}, {y:Math.random()*Math.PI}));
            // Note: Goblins/enemies added separately if needed by game logic/specific scene key
            return group;
        }

        function createForestEdgeAssembly() {
            const group = new THREE.Group();
            const areaSize=15;
            const forestGroup = createForestAssembly(15, areaSize); // Denser forest
            // Remove trees from one side to create the "edge"
            const treesToRemove=[];
            forestGroup.children.forEach(child => {
                // Assuming trees are added as Groups directly to forestGroup
                if(child.type === 'Group' && child.position.x > 0) { // Remove trees on the positive X side
                    treesToRemove.push(child);
                }
            });
            treesToRemove.forEach(tree => forestGroup.remove(tree));
            group.add(forestGroup);
            // TODO: Could add foothills/different terrain visual beyond the edge
            return group;
        }

        function createPrisonerCellAssembly() {
            const group = new THREE.Group();
            const cellSize=3, wallHeight=2.5, wallThickness=0.2, barRadius=0.05, barSpacing=0.25;
            // Floor
            const cellFloorMat=stoneMaterial.clone();
            cellFloorMat.color.setHex(0x555555); // Darker floor
            group.add(createGroundPlane(cellFloorMat, cellSize));
            // Walls (Back and Sides)
            const wallBackGeo=new THREE.BoxGeometry(cellSize, wallHeight, wallThickness);
            group.add(createMesh(wallBackGeo, stoneMaterial, {x:0, y:wallHeight/2, z:-cellSize/2})); // Back wall
            const wallSideGeo=new THREE.BoxGeometry(wallThickness, wallHeight, cellSize);
            group.add(createMesh(wallSideGeo, stoneMaterial, {x:-cellSize/2, y:wallHeight/2, z:0})); // Left wall
            group.add(createMesh(wallSideGeo.clone(), stoneMaterial, {x:cellSize/2, y:wallHeight/2, z:0})); // Right wall
            // Bars (Front)
            const barGeo=new THREE.CylinderGeometry(barRadius, barRadius, wallHeight, 8);
            const numBars=Math.floor(cellSize/barSpacing);
            for(let i=0; i<numBars; i++){
                const xPos=-cellSize/2+(i+0.5)*barSpacing;
                group.add(createMesh(barGeo.clone(), metalMaterial, {x:xPos, y:wallHeight/2, z:cellSize/2}));
            }
            // TODO: Add bench, straw?
            return group;
        }

        function createGameOverAssembly() {
            const group = new THREE.Group();
            const boxGeo = new THREE.BoxGeometry(2, 2, 2);
            group.add(createMesh(boxGeo, gameOverMaterial, { x: 0, y: 1, z: 0 }));
            group.add(createGroundPlane(stoneMaterial.clone().set({color: 0x333333}))); // Dark ground
            return group;
        }

        function createErrorAssembly() {
            const group = new THREE.Group();
            const coneGeo = new THREE.ConeGeometry(0.8, 1.5, 8); // Like a warning cone
            group.add(createMesh(coneGeo, errorMaterial, { x: 0, y: 0.75, z: 0 }));
            group.add(createGroundPlane());
            return group;
        }

        function createCrossroadsAssembly() {
            const group = new THREE.Group();
            group.add(createGroundPlane(dirtMaterial, 30)); // Large dirt area
            // Signpost Pole
            const poleGeo = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
            group.add(createMesh(poleGeo, woodMaterial, { y: 1.5 }));
            // Signpost Arms
            const signGeo = new THREE.BoxGeometry(1.5, 0.3, 0.05);
            group.add(createMesh(signGeo, woodMaterial, { y: 2.5, z: 0.2 }, { y: Math.PI / 4 })); // Angled sign
            group.add(createMesh(signGeo, woodMaterial, { y: 2.2, x: -0.2 }, { y: -Math.PI / 4 })); // Another angled sign, lower
            // Sparse Grass/Rocks
            const grassGeo = new THREE.ConeGeometry(0.2, 0.5, 6); // Simple grass tuft
            for (let i = 0; i < 20; i++) {
                const x = (Math.random() - 0.5) * 25; // Spread out
                const z = (Math.random() - 0.5) * 25;
                if (Math.abs(x) > 2 || Math.abs(z) > 2) { // Avoid center
                    group.add(createMesh(grassGeo, grassMaterial, { x, y: 0.25, z }, { y: Math.random() * Math.PI }));
                }
            }
            const rockGeo = new THREE.SphereGeometry(0.3, 6, 6); // Simple rock
            for (let i = 0; i < 10; i++) {
                group.add(createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * 20, y: 0.15, z: (Math.random() - 0.5) * 20 }, { y: Math.random() * Math.PI }));
            }
            return group;
        }

        function createRollingHillsAssembly() {
            const group = new THREE.Group();
            // Use a PlaneGeometry and modify vertex heights
            const hillGeo = new THREE.PlaneGeometry(50, 50, 20, 20); // More segments for smoother hills
            const hillMat = grassMaterial.clone();
            const hill = new THREE.Mesh(hillGeo, hillMat);
            hill.rotation.x = -Math.PI / 2; // Lay flat initially
            hill.receiveShadow = true;

            const positions = hillGeo.attributes.position;
            for (let i = 0; i < positions.count; i++) {
                const x = positions.getX(i);
                const z = positions.getY(i); // Note: Before rotation, Y is depth (becomes Z)
                // Use sine waves to create rolling hills effect
                const y = (Math.sin(x * 0.1 + z * 0.05) + Math.sin(x * 0.05 + z * 0.2)) * 1.5; // Adjust frequency/amplitude
                positions.setZ(i, y); // Set the height (Z becomes Y after rotation)
            }
            hillGeo.computeVertexNormals(); // Important for correct lighting
            group.add(hill);

            // Add distant shepherd figure (simple cylinder)
            const shepherdGeo = new THREE.CylinderGeometry(0.15, 0.1, 1.2, 8); // Simple figure
            group.add(createMesh(shepherdGeo, darkWoodMaterial, { x: 15, y: 1.5 + Math.sin(15 * 0.1 - 15 * 0.05) * 1.5, z: -15 })); // Place on hill

            // Add some grass tufts
            const grassGeo = new THREE.ConeGeometry(0.3, 0.7, 6);
            for (let i = 0; i < 50; i++) {
                 const x = (Math.random() - 0.5) * 40;
                 const z = (Math.random() - 0.5) * 40;
                 // Calculate height at this point
                 const y = (Math.sin(x * 0.1 + z * 0.05) + Math.sin(x * 0.05 + z * 0.2)) * 1.5 + 0.35;
                 group.add(createMesh(grassGeo, grassMaterial, { x: x, y: y, z: z }, { y: Math.random() * Math.PI }));
            }
            return group;
        }

        function createCoastalCliffsAssembly() {
            const group = new THREE.Group();
            // Main cliff block (simple for now)
            const cliffGeo = new THREE.BoxGeometry(15, 8, 15); // Taller, wider cliffs
             // Displace vertices for more natural look
             const positions = cliffGeo.attributes.position;
             const normals = cliffGeo.attributes.normal;
             for (let i = 0; i < positions.count; i++) {
                 // Push vertices outwards slightly based on normals, more randomness for cliffs
                 const displaceFactor = 1 + (Math.random() - 0.5) * 0.3;
                 if (Math.abs(normals.getX(i)) > 0.5 || Math.abs(normals.getZ(i)) > 0.5) { // Affect sides more
                      positions.setX(i, positions.getX(i) * displaceFactor);
                      positions.setZ(i, positions.getZ(i) * displaceFactor);
                 }
                 positions.setY(i, positions.getY(i) * (1 + (Math.random()-0.5)*0.1)); // Vary height slightly
             }
             cliffGeo.computeVertexNormals();
            group.add(createMesh(cliffGeo, stoneMaterial, { y: 4 })); // Center cliff higher

            // Path down cliff (using a plane deformed along a curve would be better)
            const pathGeo = new THREE.PlaneGeometry(1, 10, 1, 10); // More segments
            const path = createMesh(pathGeo, dirtMaterial, { x: -4, y: 4, z: 0 }, { x: -Math.PI / 2, z: -Math.PI / 6 });
            // TODO: Deform path vertices to follow cliffside better
            group.add(path);

            // Ocean plane
            const oceanGeo = new THREE.PlaneGeometry(100, 100, 20, 20); // More segments for waves
            const ocean = createMesh(oceanGeo, oceanMaterial, { y: -1 }, { x: -Math.PI / 2 }); // Lower ocean level
            ocean.receiveShadow = false; // Ocean doesn't receive shadows
            // Simple wave animation
            const clock = new THREE.Clock();
            ocean.userData.update = (time) => {
                 const delta = clock.getDelta(); // Use clock delta if available
                 const oceanPositions = ocean.geometry.attributes.position;
                 for (let i = 0; i < oceanPositions.count; i++) {
                     const x = oceanPositions.getX(i);
                     const z = oceanPositions.getY(i); // Y before rotation
                     const y = Math.sin(x * 0.1 + time * 0.5) * 0.2 + Math.sin(z * 0.1 + time * 0.3) * 0.1;
                     oceanPositions.setZ(i, y); // Set height (Z becomes Y after rotation)
                 }
                 ocean.geometry.attributes.position.needsUpdate = true;
                 ocean.geometry.computeVertexNormals();
            };
            group.add(ocean);
            return group;
        }

        function createForestEntranceAssembly() {
            const group = createForestAssembly(25, 15); // Denser forest at entrance
            // Add gnarled roots near the center
            const rootGeo = new THREE.TorusGeometry(0.8, 0.15, 8, 16); // Thicker roots
            for (let i = 0; i < 10; i++) {
                group.add(createMesh(rootGeo, woodMaterial,
                    { x: (Math.random() - 0.5) * 5, y: 0.1, z: (Math.random() - 0.5) * 5 + 2 }, // Near front
                    { x: Math.PI / 2 + (Math.random()-0.5)*0.5, y: Math.random()*Math.PI, z:(Math.random()-0.5)*0.5 } // More random rotation
                ));
            }
            return group;
        }

        function createOvergrownPathAssembly() {
            const group = new THREE.Group();
            group.add(createGroundPlane(dirtMaterial, 15));
            const forest = createForestAssembly(20, 12); // Dense forest
            group.add(forest);
            // Glowing Fungi
            const fungiGeo = new THREE.SphereGeometry(0.1, 8, 8);
            for (let i = 0; i < 30; i++) {
                group.add(createMesh(fungiGeo, glowMaterial, { x: (Math.random() - 0.5) * 10, y: 0.1, z: (Math.random() - 0.5) * 10 }));
            }
            // Vines (simple cylinders for now)
            const vineGeo = new THREE.CylinderGeometry(0.05, 0.05, 3, 8); // Longer vines
            for (let i = 0; i < 15; i++) {
                 // Find a tree to attach to (simplistic search)
                 let targetTree = null;
                 for(const child of forest.children) {
                     if(child.type === 'Group' && Math.random() > 0.5) {
                         targetTree = child;
                         break;
                     }
                 }
                 let vinePos = { x: (Math.random() - 0.5) * 8, y: 1.5, z: (Math.random() - 0.5) * 8 };
                 if(targetTree) {
                     vinePos = {x: targetTree.position.x, y: 1.5, z: targetTree.position.z};
                 }

                group.add(createMesh(vineGeo, leafMaterial, vinePos,
                     { x:(Math.random()-0.5)*Math.PI*0.5, y:Math.random()*Math.PI, z: (Math.random()-0.5)*Math.PI*0.5 + Math.PI/2 } // More hanging rotation
                 ));
            }
            return group;
        }

        function createClearingStatueAssembly() {
            const group = new THREE.Group();
            group.add(createGroundPlane(grassMaterial, 10)); // Grassy clearing
            // Statue Base
             const baseGeo = new THREE.CylinderGeometry(0.6, 0.8, 0.3, 12);
             group.add(createMesh(baseGeo, stoneMaterial, { y: 0.15 }));
            // Statue Figure (abstract)
            const statueGeo = new THREE.BoxGeometry(0.8, 2, 0.8);
             // Slightly deform statue geometry
             const sPos = statueGeo.attributes.position;
             for (let i = 0; i < sPos.count; i++) {
                 sPos.setX(i, sPos.getX(i) * (1 + (Math.random()-0.5)*0.05));
                 sPos.setY(i, sPos.getY(i) * (1 + (Math.random()-0.5)*0.05));
                 sPos.setZ(i, sPos.getZ(i) * (1 + (Math.random()-0.5)*0.05));
             }
             statueGeo.computeVertexNormals();
             const statue = createMesh(statueGeo, stoneMaterial, { y: 0.3 + 1 }); // On base
            group.add(statue);
            // Moss patches (using small spheres)
            const mossGeo = new THREE.SphereGeometry(0.1, 6, 6); // Smaller moss
            for (let i = 0; i < 20; i++) {
                 // Place moss on statue surface (approximate)
                 const faceIndex = Math.floor(Math.random() * statueGeo.index.count / 3);
                 const pA = new THREE.Vector3().fromBufferAttribute(sPos, statueGeo.index.getX(faceIndex*3));
                 const pB = new THREE.Vector3().fromBufferAttribute(sPos, statueGeo.index.getY(faceIndex*3));
                 const pC = new THREE.Vector3().fromBufferAttribute(sPos, statueGeo.index.getZ(faceIndex*3));
                 const point = new THREE.Triangle(pA, pB, pC).getMidpoint(new THREE.Vector3());
                 point.add(statue.position); // Add statue's position
                 group.add(createMesh(mossGeo, grassMaterial, point));
            }
            // Fallen Leaves
            const leafGeo = new THREE.PlaneGeometry(0.15, 0.1); // Slightly larger leaves
            for (let i = 0; i < 30; i++) {
                group.add(createMesh(leafGeo, leafMaterial,
                     { x: (Math.random() - 0.5) * 8, y: 0.01, z: (Math.random() - 0.5) * 8 }, // On ground
                     { x: -Math.PI/2, y: 0, z: Math.random() * Math.PI } // Random rotation flat on ground
                ));
            }
            return group;
        }

        function createGoblinAmbushAssembly() {
            // Base scene: overgrown path
            const group = createOvergrownPathAssembly();
            // Goblin Figure creation helper
            const createGoblin = () => {
                 const goblinGroup = new THREE.Group();
                 const bodyGeo = new THREE.CylinderGeometry(0.2, 0.3, 1, 8); // Smaller body
                 const headGeo = new THREE.SphereGeometry(0.25, 8, 8); // Slightly larger head
                 const goblinMat = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.8 }); // Dark olive green
                 goblinGroup.add(createMesh(bodyGeo, goblinMat, { y: 0.5 }));
                 goblinGroup.add(createMesh(headGeo, goblinMat, { y: 1.2 }));
                 // Spear
                 const spearGeo = new THREE.CylinderGeometry(0.03, 0.03, 1.5, 6); // Thinner spear
                 const spearTipGeo = new THREE.ConeGeometry(0.05, 0.15, 6);
                 const spear = new THREE.Group();
                 spear.add(createMesh(spearGeo, woodMaterial, {y:0.75}));
                 spear.add(createMesh(spearTipGeo, metalMaterial.clone().set({color:0x777777}), {y:1.5+0.075}));
                 spear.rotation.z = Math.PI / 5; // Angled spear
                 spear.position.x = 0.3;
                 goblinGroup.add(spear);
                 return goblinGroup;
            }
            // Add two goblins near the path
            const goblin1 = createGoblin();
            goblin1.position.set(-1.5, 0, 2); // Hiding near path edge
            goblin1.rotation.y = Math.PI / 4; // Facing towards path
            group.add(goblin1);

            const goblin2 = createGoblin();
            goblin2.position.set(1.5, 0, 2.5); // Further back, other side
            goblin2.rotation.y = -Math.PI / 6; // Facing towards path
            group.add(goblin2);
            return group;
        }

        function createHiddenCoveAssembly() {
            const group = new THREE.Group();
            group.add(createGroundPlane(sandMaterial, 15)); // Sandy ground
            // Cave Entrance (simple dark box as placeholder)
            const caveGeo = new THREE.BoxGeometry(3, 2.5, 3);
             const caveMat = new THREE.MeshStandardMaterial({color: 0x111111}); // Very dark material
            group.add(createMesh(caveGeo, caveMat, { z: -6, y: 1.25 })); // Positioned at back
            // Rocks scattered around
            const rockGeo = new THREE.SphereGeometry(0.5, 6, 6);
             const rockMat = wetStoneMaterial.clone(); // Use wet stone for cove rocks
            for (let i = 0; i < 15; i++) {
                group.add(createMesh(rockGeo, rockMat,
                     { x: (Math.random() - 0.5) * 12, y: 0.25, z: (Math.random() - 0.5) * 12 },
                     { y: Math.random()*Math.PI}
                ));
            }
            // Seaweed (simple cones)
            const seaweedGeo = new THREE.ConeGeometry(0.2, 1.2, 6);
            const seaweedMat = leafMaterial.clone().set({color: 0x1E4D2B}); // Darker green
            for (let i = 0; i < 10; i++) {
                group.add(createMesh(seaweedGeo, seaweedMat,
                    { x: (Math.random() - 0.5) * 10, y: 0.6, z: (Math.random() - 0.5) * 10 + 2 }, // Closer to front/water edge
                    {x: (Math.random()-0.5)*0.2, z: (Math.random()-0.5)*0.2} // Slight tilt
                ));
            }
             // TODO: Add driftwood? Shells? Simple boat wreck?
            return group;
        }

        function createDarkCaveAssembly() {
            const group = new THREE.Group();
             const caveRadius = 5;
             const caveHeight = 4;
            // Cave floor
            group.add(createGroundPlane(wetStoneMaterial, caveRadius * 2));
            // Cave Walls (Inverted cylinder or sphere)
            // Using Sphere for more natural shape
             const wallGeo = new THREE.SphereGeometry(caveRadius, 32, 16, 0, Math.PI*2, 0, Math.PI/1.5); // Partial sphere for walls/ceiling
             const wallMat = wetStoneMaterial.clone();
             wallMat.side = THREE.BackSide; // Render interior
             const wall = new THREE.Mesh(wallGeo, wallMat);
             wall.position.y = caveHeight * 0.6; // Adjust vertical position
             group.add(wall);

            // Stalactites/Stalagmites (cones)
            const stalactiteGeo = new THREE.ConeGeometry(0.1, 0.8, 8);
             const stalagmiteGeo = new THREE.ConeGeometry(0.15, 0.5, 8);
             for(let i=0; i<15; i++){
                 const x = (Math.random()-0.5)*caveRadius*1.5;
                 const z = (Math.random()-0.5)*caveRadius*1.5;
                 if(Math.random() > 0.5) { // Stalactite
                     group.add(createMesh(stalactiteGeo, wetStoneMaterial, {x:x, y: caveHeight - 0.4, z:z}))
                 } else { // Stalagmite
                      group.add(createMesh(stalagmiteGeo, wetStoneMaterial, {x:x, y: 0.25, z:z}))
                 }
             }

            // Dripping water animation (simple sphere falling)
            const dripGeo = new THREE.SphereGeometry(0.05, 8, 8);
            for (let i = 0; i < 5; i++) {
                const drip = createMesh(dripGeo, oceanMaterial, { x: (Math.random() - 0.5) * caveRadius, y: caveHeight - 0.2, z: (Math.random() - 0.5) * caveRadius });
                 drip.userData.startY = caveHeight - 0.2;
                 drip.userData.update = (time) => {
                     drip.position.y -= 0.1; // Simple constant fall speed
                     if (drip.position.y < 0) {
                          drip.position.y = drip.userData.startY; // Reset drip
                          drip.position.x = (Math.random() - 0.5) * caveRadius; // Reset horizontal position too
                          drip.position.z = (Math.random() - 0.5) * caveRadius;
                     }
                 };
                group.add(drip);
            }
             // TODO: Add crystals? Water pool? Specific entrance visual?
            return group;
        }

        // ========================================
        // Game Data
        // ========================================
        const itemsData = {
            "Flaming Sword":{type:"weapon", description:"A legendary blade, wreathed in magical fire."},
            "Whispering Bow":{type:"weapon", description:"Crafted by elves, its arrows fly almost silently."},
            "Guardian Shield":{type:"armor", description:"A sturdy shield imbued with protective enchantments."},
            "Healing Light Spell":{type:"spell", description:"A scroll containing the incantation to mend minor wounds."},
            "Shield of Faith Spell":{type:"spell", description:"A scroll containing a prayer that grants temporary magical protection."},
            "Binding Runes Scroll":{type:"spell", description:"Complex runes scribbled on parchment, said to temporarily immobilize a foe."},
            "Secret Tunnel Map":{type:"quest", description:"A crudely drawn map showing a hidden path, perhaps into the fortress?"},
            "Poison Daggers":{type:"weapon", description:"A pair of wicked-looking daggers coated in a fast-acting toxin."},
            "Master Key":{type:"quest", description:"An ornate key rumored to unlock many doors, though perhaps not all."},
            "Crude Dagger":{type:"weapon", description:"A roughly made dagger, chipped and stained."},
            "Scout's Pouch":{type:"quest", description:"A small leather pouch containing flint & steel, jerky, and some odd coins."}
            // TODO: Add more items (potions, armor pieces, quest items)
        };

        const gameData = {
            // --- Start and Crossroads ---
            "1": { title: "The Crossroads", content: `<p>Dust swirls around a weathered signpost under a bright, midday sun. Paths lead north into the gloomy Shadowwood, east towards rolling green hills, and west towards coastal cliffs battered by sea spray. Which path calls to you?</p>`, options: [ { text: "Enter the Shadowwood Forest (North)", next: 5 }, { text: "Head towards the Rolling Hills (East)", next: 2 }, { text: "Investigate the Coastal Cliffs (West)", next: 3 } ], illustration: "crossroads-signpost-sunny" },

            // --- Eastern Path: Hills -> Badlands ---
            "2": { title: "Rolling Hills", content: `<p>Verdant hills stretch before you, dotted with wildflowers. A gentle breeze whispers through the tall grass. In the distance, you see a lone figure tending to a flock of sheep. It feels peaceful, almost unnervingly so after the crossroads.</p>`, options: [ { text: "Follow the narrow path winding through the hills", next: 4 }, { text: "Try to hail the distant shepherd (Charisma Check?)", next: 99 } ], illustration: "rolling-green-hills-shepherd-distance" }, // TODO: Add Shepherd interaction branch
            "4": { title: "Hill Path Overlook", content: `<p>The path crests a hill, offering a panoramic view. To the east, the hills gradually give way to rugged, barren badlands. Nearby, nestled amongst wildflowers, you spot a small, ancient-looking shrine, heavily overgrown with vines.</p>`, options: [ { text: "Investigate the overgrown shrine", next: 40 }, { text: "Continue east towards the badlands", next: 41 } ], illustration: "hilltop-view-overgrown-shrine-wildflowers" },
            "40": { title: "Overgrown Shrine", content: `<p>Pushing aside thick vines reveals a small stone shrine dedicated to a forgotten nature deity. Intricate carvings, though worn, are still visible beneath the moss and grime. A sense of ancient peace emanates from the stones. Wildflowers grow in profusion around its base.</p>`, options: [{ text: "Examine the carvings for meaning (Intelligence Check)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 }, {text: "Leave the shrine undisturbed", next: 4}, {text: "Say a quiet prayer for guidance", next: 402}], illustration: "overgrown-stone-shrine-wildflowers-close" },
            "400": { title: "Shrine Insights", content:"<p>The carvings depict cycles of growth and renewal. You feel a sense of calm wash over you, slightly restoring your vitality. (+1 HP)</p>", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close", reward: {hpGain: 1}}, // TODO: Implement hpGain
            "401": { title: "Mysterious Carvings", content:"<p>The carvings are too worn and abstract to decipher their specific meaning, though you sense they are very old.</p>", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close"},
            "402": { title: "Moment of Peace", content:"<p>You spend a quiet moment in reflection. While no divine voice answers, the tranquility of the place settles your nerves.</p>", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close"},
            "41": { title: "Rocky Badlands", content: `<p>The gentle green hills give way abruptly to cracked, sun-baked earth and jagged rock formations. The air is hot and still under a harsh, unforgiving sun. This land looks hostile and sparsely populated.</p>`, options: [{ text: "Scout ahead cautiously", next: 99 } ], illustration: "rocky-badlands-cracked-earth-harsh-sun" }, // TODO: Expand Badlands

            // --- Western Path: Cliffs -> Cove -> Cave ---
            "3": { title: "Coastal Cliffs Edge", content: `<p>You stand atop windswept cliffs, the roar of crashing waves filling the air below. Seabirds circle overhead. A precarious-looking path, seemingly carved by desperate hands, descends the cliff face towards a hidden cove.</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Scan the cliff face for easier routes (Wisdom Check)", check: { stat: 'wisdom', dc: 11, onFailure: 32 }, next: 33 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" },
            "30": { title: "Hidden Cove", content: `<p>Your careful descent, whether via the main path or hidden steps, brings you safely to a secluded, sandy cove sheltered by the towering cliffs. The air smells strongly of salt and seaweed. Half-hidden in the shadows at the back of the cove is the dark, foreboding entrance to a sea cave.</p><p>(+25 XP)</p>`, options: [ { text: "Explore the dark cave", next: 35 } ], illustration: "hidden-cove-beach-dark-cave-entrance", reward: { xp: 25 } },
            "31": { title: "Tumbled Down", content: `<p>You lose your footing on the steep, treacherous path! You tumble and slide the last few feet, landing hard on the sandy cove floor. You take 5 points of damage from the fall. Shaking your head to clear it, you see the dark entrance to a sea cave nearby.</p>`, options: [ { text: "Gingerly get up and explore the dark cave", next: 35 } ], illustration: "character-fallen-at-bottom-of-cliff-path-cove", hpLoss: 5 },
            "32": { title: "No Easier Path", content: `<p>You scan the towering cliffs intently, searching for any alternative routes down. Despite your efforts, you find no obviously easier or safer paths than the precarious one directly before you.</p>`, options: [ { text: "Attempt the precarious descent again (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 } ], illustration: "scanning-sea-cliffs-no-other-paths-visible" },
            "33": { title: "Smuggler's Steps?", content: `<p>Your keen eyes spot what others might miss: a series of barely visible handholds and footholds carved into the rock face, slightly hidden by an overhang. They look old but might offer a slightly less treacherous descent.</p><p>(+15 XP)</p>`, options: [ { text: "Use the hidden steps (Easier Dex Check)", check: { stat: 'dexterity', dc: 8, onFailure: 31 }, next: 30 } ], illustration: "close-up-handholds-carved-in-cliff-face", reward: { xp: 15 } },
            "35": { title: "Dark Cave", content: `<p>You cautiously enter the sea cave. The air inside is heavy with the smell of salt, damp rock, and something else... decay. Water drips rhythmically from unseen stalactites somewhere deeper within the oppressive darkness.</p>`, options: [{ text: "Press deeper into the darkness (Requires Light Source?)", next: 99 } ], illustration: "dark-cave-entrance-dripping-water" }, // TODO: Add light source requirement/check, expand cave

            // --- Northern Path: Forest -> Foothills -> Fortress ---
            "5": { title: "Shadowwood Entrance", content: `<p>The air grows cool and damp as you step beneath the dense canopy of the Shadowwood. Sunlight struggles to pierce the gloom, illuminating gnarled roots that writhe across the forest floor. A narrow, overgrown path leads deeper into the woods.</p>`, options: [ { text: "Follow the main, albeit overgrown, path", next: 6 }, { text: "Try to navigate through the lighter undergrowth beside the path", next: 7 }, { text: "Look for animal trails or signs of passage (Wisdom Check)", check: { stat: 'wisdom', dc: 10, onFailure: 6 }, next: 8 } ], illustration: "dark-forest-entrance-gnarled-roots-filtered-light" },
            // Forest Path Branches
            "6": { title: "Overgrown Forest Path", content: `<p>The path is barely visible beneath a thick layer of fallen leaves and creeping vines. Strange, faintly glowing fungi cling to rotting logs. You push deeper into the oppressive silence when suddenly, you hear a twig snap nearby!</p>`, options: [ { text: "Ready your weapon and investigate the sound", next: 10 }, { text: "Attempt to hide quietly amongst the ferns (Dexterity Check)", check: { stat: 'dexterity', dc: 11, onFailure: 10 }, next: 11 }, { text: "Call out cautiously, 'Who's there?'", next: 10 } ], illustration: "overgrown-forest-path-glowing-fungi-vines" },
            "7": { title: "Tangled Undergrowth", content: `<p>Pushing through thick ferns and thorny bushes proves difficult. You stumble into a small, unexpected clearing. In the center stands a weathered stone statue, its features eroded by time and covered in thick moss. It depicts a forgotten deity or hero.</p>`, options: [ { text: "Examine the statue closely for clues or markings (Intelligence Check)", check: { stat: 'intelligence', dc: 13, onFailure: 71 }, next: 70 }, { text: "Ignore the statue and try to find the main path again", next: 72 }, { text: "Leave a small offering (if you have something suitable)", next: 73 } ], illustration: "forest-clearing-mossy-statue-weathered-stone" },
            "8": { title: "Hidden Game Trail", content: `<p>Your sharp eyes spot a faint trail, almost invisible to the untrained observer, diverging from the main path. It looks like a route used by deer or other forest creatures. Following it, you soon arrive at the edge of a deep ravine spanned by a single, rickety rope bridge.</p><p>(+20 XP)</p>`, options: [ { text: "Risk crossing the rope bridge (Dexterity Check)", check: { stat: 'dexterity', dc: 10, onFailure: 81 }, next: 80 }, { text: "Search along the ravine edge for another way across", next: 82 } ], illustration: "narrow-game-trail-forest-rope-bridge-ravine", reward: { xp: 20 } },
            // Forest Encounters/Events
            "10": { title: "Goblin Ambush!", content: `<p>Suddenly, two scraggly goblins, clad in mismatched leather scraps and wielding crude, sharp spears, leap out from behind large toadstools! Their beady eyes fix on you with malicious intent.</p>`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them and flee down the path (Dexterity Check)", check: { stat: 'dexterity', dc: 13, onFailure: 10 }, next: 13 } ], illustration: "two-goblins-ambush-forest-path-spears" }, // TODO: Implement combat
            "11": { title: "Hidden Evasion", content: `<p>Quickly and silently, you melt into the deep shadows beneath a large, ancient tree. The two goblins blunder past, bickering in their guttural tongue, completely oblivious to your presence.</p><p>(+30 XP)</p>`, options: [ { text: "Continue cautiously down the path once they are gone", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } },
            "12": { title: "Ambush Victory!", content: `<p>Though caught by surprise, you react swiftly. After a brief, vicious skirmish, the goblins lie defeated at your feet. Searching their meagre belongings, you find a single, Crude Dagger.</p><p>(+50 XP)</p>`, options: [ { text: "Wipe your blade clean and press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: "Crude Dagger" } },
            "13": { title: "Daring Escape", content: `<p>With surprising agility, you feint left, then dive right, tumbling past the goblins' clumsy spear thrusts! You scramble to your feet and sprint down the path, leaving the surprised goblins behind.</p><p>(+25 XP)</p>`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } },
            "70": { title: "Statue's Secret", content:"<p>Running your fingers over the mossy stone, you find a small, almost invisible seam near the base. Applying pressure, a hidden compartment clicks open! Inside is a Scout's Pouch.</p><p>(+40 XP)</p>", options: [{text:"Take the pouch and press on", next: 72}], illustration: "forest-clearing-mossy-statue-hidden-compartment", reward:{xp: 40, addItem: "Scout's Pouch"}},
            "71": { title: "Just an Old Statue", content:"<p>Despite a careful examination, the statue appears to be just that – an old, weathered stone figure of no special significance that you can discern.</p>", options: [{text:"Ignore the statue and press on", next: 72}], illustration: "forest-clearing-mossy-statue-weathered-stone"},
            "72": { title: "Back to the Thicket", content:"<p>Leaving the clearing and the statue behind, you push back into the dense undergrowth, eventually relocating the main forest path.</p>", options: [{text:"Continue along the main path", next: 6}], illustration:"pushing-through-forest-undergrowth"},
            "73": { title: "A Small Offering", content:"<p>You place a small, simple offering at the statue's base (a ration, a coin, or perhaps just a moment of respect). You feel a subtle sense of approval or peace before turning to leave.</p>", options: [{text:"Try to find the main path again", next: 72}], illustration:"forest-clearing-mossy-statue-offering"}, // TODO: Check inventory for offering? Grant minor boon?
            "80": { title: "Across the Ravine", content:"<p>Taking a deep breath, you step onto the swaying rope bridge. With careful, deliberate steps, testing each plank before putting your weight on it, you make your way across the chasm to the other side.</p><p>(+25 XP)</p>", options: [{text:"Continue following the game trail", next: 14}], illustration:"character-crossing-rope-bridge-safely", reward:{xp:25}}, // Rejoins main path for now
            "81": { title: "Bridge Collapse!", content:"<p>Halfway across, a frayed rope snaps! The bridge lurches violently, sending you plunging into the ravine below! You lose 10 HP. Luckily, the bottom is covered in soft moss and mud, cushioning your fall.</p>", options: [{text:"Climb out and find another way", next: 82}], illustration:"rope-bridge-snapping-character-falling", hpLoss: 10},
            "82": { title: "Ravine Detour", content:"<p>Searching along the ravine's edge, you eventually find a place where the chasm narrows, and a fallen log provides a much safer, if longer, way across.</p>", options: [{text:"Cross the log bridge and continue", next: 14}], illustration:"fallen-log-crossing-ravine"}, // Rejoins main path for now
             // Forest Path Continues
            "14": { title: "Forest Stream Crossing", content: `<p>The overgrown path eventually leads to the bank of a clear, shallow stream. Smooth, mossy stones line the streambed, and dappled sunlight filters through the leaves overhead, sparkling on the water's surface.</p>`, options: [ { text: "Wade across the stream", next: 16 }, { text: "Look for a drier crossing point (fallen log?) upstream", next: 15 } ], illustration: "forest-stream-crossing-dappled-sunlight-stones" },
            "15": { title: "Log Bridge", content: `<p>A short walk upstream reveals a large, fallen tree spanning the stream. It's covered in slick, green moss, making it look like a potentially treacherous crossing.</p>`, options: [ { text: "Cross carefully on the mossy log (Dexterity Check)", check: { stat: 'dexterity', dc: 9, onFailure: 151 }, next: 16 }, { text: "Decide it's too risky and go back to wade across", next: 14 } ], illustration: "mossy-log-bridge-over-forest-stream" },
            "151": { title: "Splash!", content: `<p>You place a foot carefully on the log, but the moss is slicker than it looks! Your feet shoot out from under you, and you tumble into the cold stream with a loud splash! You're soaked and slightly embarrassed, but otherwise unharmed.</p>`, options: [ { text: "Shake yourself off and continue on the other side", next: 16 } ], illustration: "character-splashing-into-stream-from-log" },
            // Leaving the Forest
            "16": { title: "Edge of the Woods", content: `<p>Finally, the trees begin to thin, and you emerge from the oppressive gloom of the Shadowwood. Before you lie steep, rocky foothills leading up towards a formidable-looking mountain fortress perched high above.</p>`, options: [ { text: "Begin the ascent into the foothills towards the fortress", next: 17 }, { text: "Scan the fortress and surrounding terrain from afar (Wisdom Check)", check: { stat: 'wisdom', dc: 14, onFailure: 17 }, next: 18 } ], illustration: "forest-edge-view-rocky-foothills-distant-mountain-fortress" },
            // Foothills Path Branches
            "17": { title: "Rocky Foothills Path", content: `<p>The climb is arduous, the path winding steeply upwards over loose scree and jagged rocks. The air thins slightly. The dark stone walls of the mountain fortress loom much larger now, seeming to watch your approach.</p>`, options: [ { text: "Continue the direct ascent", next: 19 }, { text: "Look for signs of a hidden trail or less obvious route (Wisdom Check)", check: { stat: 'wisdom', dc: 15, onFailure: 19 }, next: 20 } ], illustration: "climbing-rocky-foothills-path-fortress-closer" },
            "18": { title: "Distant Observation", content: `<p>Taking a moment to study the fortress from this distance, your keen eyes notice something interesting. The main approach looks heavily guarded, but along the western ridge, the terrain seems slightly less sheer, potentially offering a less-guarded, albeit more treacherous, approach.</p><p>(+30 XP)</p>`, options: [ { text: "Decide against the risk and take the main path into the foothills", next: 17 }, { text: "Attempt the western ridge approach", next: 21 } ], illustration: "zoomed-view-mountain-fortress-western-ridge", reward: { xp: 30 } },
            // Foothills Encounters/Events
            "19": { title: "Blocked Pass", content: `<p>As you round a sharp bend, your way is completely blocked by a recent rockslide! Huge boulders and debris choke the path, making further progress impossible along this route.</p>`, options: [ { text: "Try to climb over the unstable rockslide (Strength Check)", check: { stat: 'strength', dc: 14, onFailure: 191 }, next: 190 }, { text: "Search the surrounding cliffs for another way around", next: 192 } ], illustration: "rockslide-blocking-mountain-path-boulders" },
            "190": { title: "Over the Rocks", content:"<p>Summoning your strength, you find handholds and footholds, scrambling and pulling yourself up and over the precarious rockslide. It's exhausting work, but you make it past the blockage.</p><p>(+35 XP)</p>", options: [{text:"Continue up the now clear path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} },
            "191": { title: "Climb Fails", content:"<p>The boulders are too large, too smooth, or too unstable. You try several approaches, but cannot safely climb over the rockslide. This way is blocked.</p>", options: [{text:"Search the surrounding cliffs for another way around", next: 192}], illustration:"character-slipping-on-rockslide-boulders"},
            "192": { title: "Detour Found", content:"<p>After considerable searching along the cliff face, you find a rough, overgrown path leading steeply up and around the rockslide area. It eventually rejoins the main trail further up the mountain.</p>", options: [{text:"Follow the detour path", next: 22}], illustration:"rough-detour-path-around-rockslide"},
            "20": { title: "Goat Trail", content: `<p>Your thorough search pays off! Partially hidden behind a cluster of hardy mountain shrubs, you discover a narrow trail, barely wide enough for a single person (or perhaps a mountain goat). It seems to bypass the main path, heading upwards towards the fortress.</p><p>(+40 XP)</p>`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } },
            "21": { title: "Western Ridge", content:"<p>The path along the western ridge is dangerously narrow and exposed. Loose gravel shifts underfoot, and strong gusts of wind whip around you, threatening to push you off the edge into the dizzying drop below.</p>", options: [{text:"Proceed carefully along the ridge (Dexterity Check)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" },
            "211": {title:"Lost Balance", content:"<p>A particularly strong gust of wind catches you at a bad moment! You lose your balance and stumble, tumbling down a steep, rocky slope before managing to arrest your fall. You lose 10 HP.</p>", options:[{text:"Climb back up and reconsider the main path", next: 17}], illustration:"character-falling-off-windy-ridge", hpLoss: 10},
            // Approaching/At the Fortress
            "22": { title: "Fortress Approach", content:"<p>You've navigated the treacherous paths and finally stand near the imposing outer walls of the dark mountain fortress. Stern-faced guards patrol the battlements, their eyes scanning the approaches. The main gate looks heavily fortified.</p>", options: [
                {text:"Search for a less obvious entrance (Wisdom Check)", check:{stat:'wisdom', dc: 16, onFailure: 221}, next: 220}, // TODO: Success leads to secret entrance page
                {text:"Attempt to bluff your way past the gate guards (Charisma Check)", check:{stat:'charisma', dc: 15, onFailure: 222}, next: 223}, // TODO: Success/Failure pages for bluff
                {text:"Try to sneak past the gate guards (Dexterity Check)", check:{stat:'dexterity', dc: 17, onFailure: 222}, next: 224}, // TODO: Success/Failure pages for sneak
                {text:"Retreat for now", next: 16} // Option to go back
                ], illustration:"approaching-dark-fortress-walls-guards"},
            "220": { title: "Secret Passage?", content:"<p>Your careful search reveals loose stones near the base of the wall, potentially hiding a passage!</p>", options: [{text:"Investigate the loose stones", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, // TODO: Expand secret passage
            "221": { title: "No Obvious Weakness", content:"<p>The fortress walls look solid and well-maintained. You find no obvious weak points or hidden entrances from this vantage point.</p>", options: [{text:"Reconsider your approach", next: 22}], illustration:"approaching-dark-fortress-walls-guards"},
            "222": { title: "Caught!", content:"<p>Your attempt fails miserably! The guards spot you immediately and raise the alarm! You are captured.</p>", options: [{text:"To the dungeons...", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, // TODO: Lead to prisoner cell?
            "223": { title: "Bluff Success?", content:"<p>Amazingly, your story seems plausible enough for the guards to let you pass through the gate!</p>", options: [{text:"Enter the fortress courtyard", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, // TODO: Expand fortress interior
            "224": { title: "Sneak Success?", content:"<p>Moving like a shadow, you manage to slip past the gate guards unnoticed!</p>", options: [{text:"Enter the fortress courtyard", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, // TODO: Expand fortress interior

            // --- Game Over / Error State ---
            "99": { title: "Game Over / To Be Continued...", content: "<p>Your adventure ends here (for now). Thanks for playing!</p>", options: [{ text: "Restart Adventure", next: 1 }], illustration: "game-over-generic", gameOver: true }
        };


        // ========================================
        // Game State
        // ========================================
        let gameState = {
            currentPageId: 1,
            character: {
                name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
                level: 1, xp: 0, xpToNextLevel: 100,
                stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 },
                inventory: []
                // TODO: Add equipment slots (weapon, armor, etc.)
                // TODO: Add status effects array
            }
        };

        // ========================================
        // Game Logic Functions
        // ========================================
        function startGame() {
            // Reset state if restarting
            const defaultChar = {
                 name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
                 level: 1, xp: 0, xpToNextLevel: 100,
                 stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 },
                 inventory: []
             };
            // Deep copy necessary for nested objects like stats
            gameState = { currentPageId: 1, character: JSON.parse(JSON.stringify(defaultChar)) };
             console.log("Starting new game with state:", JSON.stringify(gameState));
            renderPage(gameState.currentPageId);
        }

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

            const optionNextPageId = parseInt(choiceData.next);
            const itemToAdd = choiceData.addItem; // Item from direct choice property (less common now)
            let nextPageId = optionNextPageId;
            let rollResultMessage = "";
            const check = choiceData.check; // Skill check object { stat, dc, onFailure }

            // --- Input Validation ---
             // Handle explicit restart command (typically from page 99)
             if (choiceData.next === 1 && (pageData = gameData[gameState.currentPageId]) && pageData.gameOver) {
                 console.log("Restarting game...");
                 startGame();
                 return;
             }
             // Basic validation for normal choices
            if (isNaN(optionNextPageId) && !check) {
                 console.error("Invalid choice data: Missing 'next' page ID and no check defined.", choiceData);
                 // Attempt to render current page again with an error, or go to game over
                 const currentPageData = gameData[gameState.currentPageId] || gameData[99];
                 renderPageInternal(gameState.currentPageId, currentPageData , "<p><em>Error: Invalid choice data encountered! Cannot proceed.</em></p>");
                 // Make choices inactive?
                 choicesElement.querySelectorAll('button').forEach(b => b.disabled = true);
                 return;
            }

            // --- Skill Check Logic ---
            if (check) {
                const statValue = gameState.character.stats[check.stat] || 10; // Default to 10 if stat missing
                const modifier = Math.floor((statValue - 10) / 2);
                const roll = Math.floor(Math.random() * 20) + 1;
                const totalResult = roll + modifier;
                const dc = check.dc;
                const statName = check.stat.charAt(0).toUpperCase() + check.stat.slice(1); // Capitalize stat name
                console.log(`Check: ${statName} (DC ${dc}) | Roll: ${roll} + Mod: ${modifier} = ${totalResult}`);

                if (totalResult >= dc) { // Success
                    nextPageId = optionNextPageId; // Proceed to the 'next' page defined in the option
                    rollResultMessage = `<p class="roll-success"><em>${statName} Check Success! (Rolled ${roll} + ${modifier} = ${totalResult} vs DC ${dc})</em></p>`;
                } else { // Failure
                    nextPageId = parseInt(check.onFailure); // Go to the 'onFailure' page ID
                    rollResultMessage = `<p class="roll-failure"><em>${statName} Check Failed! (Rolled ${roll} + ${modifier} = ${totalResult} vs DC ${dc})</em></p>`;
                    if (isNaN(nextPageId)) {
                        console.error("Invalid onFailure ID:", check.onFailure);
                        nextPageId = 99; // Default to game over on invalid failure ID
                        rollResultMessage += "<p><em>Error: Invalid failure path defined!</em></p>";
                    }
                }
            }

            // --- Page Transition & Consequences ---
            const targetPageData = gameData[nextPageId]; // Get data for the *next* page
            if (!targetPageData) {
                console.error(`Data for target page ${nextPageId} not found!`);
                renderPageInternal(99, gameData[99] || { title: "Error", content: "<p>Page Data Missing!</p>", illustration: "error", gameOver: true }, "<p><em>Error: Next page data missing! Cannot continue.</em></p>");
                return;
            }

             // Apply consequences/rewards defined on the *target* page
             let hpLostThisTurn = 0;
             if (targetPageData.hpLoss) {
                 hpLostThisTurn = targetPageData.hpLoss;
                 gameState.character.stats.hp -= hpLostThisTurn;
                 console.log(`Lost ${hpLostThisTurn} HP.`);
             }
             // TODO: Implement hpGain (similar to hpLoss but adding HP)
             if (targetPageData.reward && targetPageData.reward.hpGain) {
                  const hpGained = targetPageData.reward.hpGain;
                  gameState.character.stats.hp += hpGained;
                  console.log(`Gained ${hpGained} HP.`);
                  // Clamp HP to maxHP later
             }

             // Check for death *after* applying HP changes for this turn
             if (gameState.character.stats.hp <= 0) {
                 gameState.character.stats.hp = 0; // Don't go below 0
                 console.log("Player died!");
                 nextPageId = 99; // Override navigation to game over page
                 rollResultMessage += `<p><em>You have succumbed to your injuries! (-${hpLostThisTurn} HP)</em></p>`;
                 // Ensure we use game over page data for rendering
                  const gameOverPageData = gameData[nextPageId];
                  renderPageInternal(nextPageId, gameOverPageData, rollResultMessage);
                 return; // Stop further processing for this choice
             }

             // Apply other rewards if the player is still alive
             if (targetPageData.reward) {
                 if (targetPageData.reward.xp) {
                     gameState.character.xp += targetPageData.reward.xp;
                     console.log(`Gained ${targetPageData.reward.xp} XP! Total: ${gameState.character.xp}`);
                     // TODO: Check for Level Up
                     // checkLevelUp();
                 }
                 if (targetPageData.reward.statIncrease) {
                     const stat = targetPageData.reward.statIncrease.stat;
                     const amount = targetPageData.reward.statIncrease.amount;
                     if (gameState.character.stats.hasOwnProperty(stat)) {
                         gameState.character.stats[stat] += amount;
                         console.log(`Stat ${stat} increased by ${amount}. New value: ${gameState.character.stats[stat]}`);
                         // Recalculate Max HP immediately if Constitution changes
                          if (stat === 'constitution') {
                             recalculateMaxHp();
                          }
                     }
                 }
                 // Add item from reward property
                 if (targetPageData.reward.addItem && !gameState.character.inventory.includes(targetPageData.reward.addItem)) {
                     gameState.character.inventory.push(targetPageData.reward.addItem);
                     console.log(`Found item: ${targetPageData.reward.addItem}`);
                      rollResultMessage += `<p><em>Item acquired: ${targetPageData.reward.addItem}</em></p>`; // Add feedback
                 }
             }
             // Add item from direct choice property (less common, but handle for compatibility)
             if (itemToAdd && !gameState.character.inventory.includes(itemToAdd)) {
                 gameState.character.inventory.push(itemToAdd);
                 console.log("Added item:", itemToAdd);
                 rollResultMessage += `<p><em>Item acquired: ${itemToAdd}</em></p>`;
             }

             // --- Update Game State ---
             gameState.currentPageId = nextPageId; // Update current page *after* processing consequences

             // Recalculate derived stats (like Max HP) and clamp current values
             recalculateMaxHp();
             gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp); // Clamp current HP

             console.log("Transitioning to page:", nextPageId, " New state:", JSON.stringify(gameState));
             // Render the determined next page
             renderPageInternal(nextPageId, gameData[nextPageId], rollResultMessage); // Use potentially overridden nextPageId
        }

        function recalculateMaxHp() {
             const baseHp = 10; // Base HP for level 1 adventurer
             const conModifier = Math.floor((gameState.character.stats.constitution - 10) / 2);
             // TODO: Incorporate level into HP calculation, e.g., baseHp + (level * conModifier) + other bonuses
             gameState.character.stats.maxHp = baseHp + conModifier * gameState.character.level;
             // Ensure HP is at least 1?
             gameState.character.stats.maxHp = Math.max(1, gameState.character.stats.maxHp);
        }

        // TODO: function checkLevelUp() { ... }

        function renderPageInternal(pageId, pageData, message = "") {
            // --- Page Data Validation ---
             if (!pageData) {
                 console.error(`Render Error: No data for page ${pageId}`);
                 pageData = gameData[99] || { title: "Error", content: "<p>Render Error! Critical page data missing.</p>", illustration: "error", gameOver: true }; // Fallback to error/game over
                 message += "<p><em>Render Error: Page data was missing! Cannot proceed.</em></p>";
                 pageId = 99; // Ensure we treat this as the game over page
             }

             console.log(`Rendering page ${pageId}: "${pageData.title}"`);

             // --- Update UI Elements ---
             storyTitleElement.textContent = pageData.title || "Untitled Page";
             storyContentElement.innerHTML = message + (pageData.content || "<p>...</p>"); // Prepend messages (like roll results)

             updateStatsDisplay();
             updateInventoryDisplay();

             choicesElement.innerHTML = ''; // Clear previous choices

             // --- Generate Choices ---
             const options = pageData.options || [];
             const isGameOverOrEnd = pageData.gameOver || (options.length === 0 && pageId !== 99); // Check if it's an end state

             if (!isGameOverOrEnd && pageId !== 99) { // Normal page with choices
                 options.forEach(option => {
                     const button = document.createElement('button');
                     button.classList.add('choice-button');
                     button.textContent = option.text;
                     let requirementMet = true;
                     let requirementText = []; // Store unmet requirements text

                     // --- Requirement Checks ---
                     // Example: Check for required item
                     if (option.requireItem) {
                          if (!gameState.character.inventory.includes(option.requireItem)) {
                              requirementMet = false;
                              requirementText.push(`Requires: ${option.requireItem}`);
                          }
                     }
                     // Example: Check for required stat value
                     if (option.requireStat) {
                          const currentStat = gameState.character.stats[option.requireStat.stat] || 0;
                          if (currentStat < option.requireStat.value) {
                              requirementMet = false;
                              requirementText.push(`Requires: ${option.requireStat.stat.charAt(0).toUpperCase() + option.requireStat.stat.slice(1)} ${option.requireStat.value}`);
                          }
                     }
                     // TODO: Add checks for light source, specific quest flags etc.

                     // --- Button State and Click Handler ---
                     button.disabled = !requirementMet;
                     if (!requirementMet) {
                         button.title = requirementText.join(', '); // Show all unmet requirements on hover
                         button.classList.add('disabled');
                     } else {
                         // Attach click handler only if requirements met
                         const choiceData = {
                             next: option.next,
                             addItem: option.addItem, // If defined directly on option
                             check: option.check       // Skill check associated with option
                         };
                         button.onclick = () => handleChoiceClick(choiceData);
                     }
                     choicesElement.appendChild(button);
                 });
             } else { // Game Over or defined end of branch
                 const button = document.createElement('button');
                 button.classList.add('choice-button');
                 // Use specific text for game over page, different for other end pages
                 button.textContent = (pageId === 99 && pageData.gameOver) ? "Restart Adventure" : "The Path Ends Here (Restart)";
                 // The 'next: 1' ensures it triggers the restart logic in handleChoiceClick
                 button.onclick = () => handleChoiceClick({ next: 1 });
                 choicesElement.appendChild(button);
                 if (pageId !== 99) { // Add message only if it's not the explicit game over page
                     choicesElement.insertAdjacentHTML('afterbegin', '<p><i>There are no further paths from here.</i></p>');
                 }
             }

             // --- Update 3D Scene ---
             updateScene(pageData.illustration || 'default');
        }

        function renderPage(pageId) {
             // Simple wrapper, could add pre/post render logic here if needed
             renderPageInternal(pageId, gameData[pageId]);
         }

        function updateStatsDisplay() {
            const char=gameState.character;
            statsElement.innerHTML = `<strong>Stats:</strong> <span>Lvl: ${char.level}</span> <span>XP: ${char.xp}/${char.xpToNextLevel}</span> <span>HP: ${char.stats.hp}/${char.stats.maxHp}</span> <span>Str: ${char.stats.strength}</span> <span>Int: ${char.stats.intelligence}</span> <span>Wis: ${char.stats.wisdom}</span> <span>Dex: ${char.stats.dexterity}</span> <span>Con: ${char.stats.constitution}</span> <span>Cha: ${char.stats.charisma}</span>`;
        }

        function updateInventoryDisplay() {
            let h='<strong>Inventory:</strong> ';
            if(gameState.character.inventory.length === 0){
                h+='<em>Empty</em>';
            } else {
                gameState.character.inventory.forEach(itemName=>{
                    const item = itemsData[itemName] || {type:'unknown',description:'An unknown item.'};
                    const itemClass = `item-${item.type || 'unknown'}`;
                    // Ensure description is a string
                    const descriptionText = typeof item.description === 'string' ? item.description : 'No description available.';
                    h += `<span class="${itemClass}" title="${descriptionText.replace(/"/g, '&quot;')}">${itemName}</span>`; // Escape quotes in title
                });
            }
            inventoryElement.innerHTML = h;
        }

        function updateScene(illustrationKey) {
            if (!scene) {
                 console.warn("Scene not initialized, cannot update visual.");
                 return;
             }
             console.log("Updating scene for illustration key:", illustrationKey);

             // --- Cleanup ---
             if (currentAssemblyGroup) {
                 scene.remove(currentAssemblyGroup);
                 // Basic disposal - more complex scenes might need deeper disposal
                 currentAssemblyGroup.traverse(child => {
                     if (child.isMesh) {
                         child.geometry.dispose();
                         // Dispose materials if they are unique to this assembly and not reused
                         // if (Array.isArray(child.material)) {
                         //     child.material.forEach(m => m.dispose());
                         // } else {
                         //     child.material.dispose();
                         // }
                     }
                 });
                 currentAssemblyGroup = null;
             }
             scene.fog = null; // Reset fog
             scene.background = new THREE.Color(0x222222); // Reset background
             // Reset camera to default unless overridden by case
             camera.position.set(0, 2.5, 7);
             camera.lookAt(0, 0.5, 0);

             // --- Select Assembly ---
             let assemblyFunction;
             switch (illustrationKey) {
                 // Basic Structures
                 case 'city-gates': assemblyFunction = createCityGatesAssembly; break;
                 case 'weaponsmith': assemblyFunction = createWeaponsmithAssembly; break;
                 case 'temple': assemblyFunction = createTempleAssembly; break;
                 case 'resistance-meeting': assemblyFunction = createResistanceMeetingAssembly; break;
                 case 'prisoner-cell': assemblyFunction = createPrisonerCellAssembly; break;
                 case 'game-over': case 'game-over-generic': assemblyFunction = createGameOverAssembly; break;
                 case 'error': assemblyFunction = createErrorAssembly; break;

                 // Landscape / Outdoor Scenes
                 case 'crossroads-signpost-sunny':
                     scene.fog = new THREE.Fog(0x87CEEB, 10, 35); camera.position.set(0, 3, 10); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x87CEEB);
                     assemblyFunction = createCrossroadsAssembly; break;
                 case 'rolling-green-hills-shepherd-distance':
                 case 'hilltop-view-overgrown-shrine-wildflowers': // Base visual is hills
                 case 'overgrown-stone-shrine-wildflowers-close': // Base visual is hills
                     scene.fog = new THREE.Fog(0xA8E4A0, 15, 50); camera.position.set(0, 5, 15); camera.lookAt(0, 2, -5); scene.background = new THREE.Color(0x90EE90);
                     // Adjust camera for close-up shrine views specifically
                     if (illustrationKey === 'overgrown-stone-shrine-wildflowers-close') camera.position.set(1, 2, 4);
                     if (illustrationKey === 'hilltop-view-overgrown-shrine-wildflowers') camera.position.set(3, 4, 8);
                     assemblyFunction = createRollingHillsAssembly; break;
                 case 'windy-sea-cliffs-crashing-waves-path-down':
                 case 'scanning-sea-cliffs-no-other-paths-visible': // Reuse visual
                 case 'close-up-handholds-carved-in-cliff-face': // Reuse visual
                     scene.fog = new THREE.Fog(0x6699CC, 10, 40); camera.position.set(5, 5, 10); camera.lookAt(-2, 0, -5); scene.background = new THREE.Color(0x6699CC);
                     assemblyFunction = createCoastalCliffsAssembly; break;
                 case 'hidden-cove-beach-dark-cave-entrance':
                 case 'character-fallen-at-bottom-of-cliff-path-cove': // Reuse visual
                     scene.fog = new THREE.Fog(0x336699, 5, 30); camera.position.set(0, 2, 8); camera.lookAt(0, 1, -2); scene.background = new THREE.Color(0x336699);
                     assemblyFunction = createHiddenCoveAssembly; break;
                 case 'rocky-badlands-cracked-earth-harsh-sun':
                     scene.fog = new THREE.Fog(0xD2B48C, 15, 40); camera.position.set(0, 3, 12); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0xCD853F);
                     assemblyFunction = createDefaultAssembly; break; // Placeholder - Needs badlands assembly

                 // Forest Scenes
                 case 'shadowwood-forest': // Generic forest, use if needed
                     scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(0, 2, 8); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x1A1A1A);
                     assemblyFunction = createForestAssembly; break;
                 case 'dark-forest-entrance-gnarled-roots-filtered-light':
                     scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(0, 2, 8); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x1A1A1A);
                     assemblyFunction = createForestEntranceAssembly; break;
                 case 'overgrown-forest-path-glowing-fungi-vines':
                 case 'pushing-through-forest-undergrowth': // Reuse visual
                     scene.fog = new THREE.Fog(0x1A2F2A, 3, 15); camera.position.set(0, 1.5, 6); camera.lookAt(0, 0.5, 0); scene.background = new THREE.Color(0x112211);
                     assemblyFunction = createOvergrownPathAssembly; break;
                 case 'forest-clearing-mossy-statue-weathered-stone':
                 case 'forest-clearing-mossy-statue-hidden-compartment': // Reuse visual
                 case 'forest-clearing-mossy-statue-offering': // Reuse visual
                     scene.fog = new THREE.Fog(0x2E4F3A, 5, 25); camera.position.set(0, 2, 5); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x223322);
                     assemblyFunction = createClearingStatueAssembly; break;
                 case 'narrow-game-trail-forest-rope-bridge-ravine':
                 case 'character-crossing-rope-bridge-safely': // Reuse visual
                 case 'rope-bridge-snapping-character-falling': // Reuse visual
                 case 'fallen-log-crossing-ravine': // Reuse visual (needs log added?)
                     scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(2, 3, 6); camera.lookAt(0, -1, -2); scene.background = new THREE.Color(0x1A1A1A);
                     assemblyFunction = createForestAssembly; break; // TODO: Needs bridge/ravine elements
                 case 'two-goblins-ambush-forest-path-spears':
                 case 'forest-shadows-hiding-goblins-walking-past': // Reuse visual, maybe different camera?
                 case 'defeated-goblins-forest-path-loot': // Reuse visual, remove goblins?
                 case 'blurred-motion-running-past-goblins-forest': // Reuse visual
                     scene.fog = new THREE.Fog(0x1A2F2A, 3, 15); camera.position.set(0, 2, 7); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x112211);
                     assemblyFunction = createGoblinAmbushAssembly; break; // TODO: Modify based on state
                 case 'forest-stream-crossing-dappled-sunlight-stones':
                 case 'mossy-log-bridge-over-forest-stream': // Needs log added?
                 case 'character-splashing-into-stream-from-log': // Reuse visual
                     scene.fog = new THREE.Fog(0x668866, 8, 25); camera.position.set(0, 2, 6); camera.lookAt(0, 0.5, 0); scene.background = new THREE.Color(0x446644);
                     if (illustrationKey === 'mossy-log-bridge-over-forest-stream') camera.position.set(1, 2, 5);
                     assemblyFunction = createForestAssembly; break; // TODO: Needs stream/log elements
                 case 'forest-edge-view-rocky-foothills-distant-mountain-fortress':
                 case 'forest-edge': // Explicit key for this scene
                     scene.fog = new THREE.Fog(0xAAAAAA, 10, 40); camera.position.set(0, 3, 10); camera.lookAt(0, 1, -5); scene.background = new THREE.Color(0x888888);
                     assemblyFunction = createForestEdgeAssembly; break;

                // Mountain / Fortress Scenes
                 case 'climbing-rocky-foothills-path-fortress-closer':
                 case 'rockslide-blocking-mountain-path-boulders':
                 case 'character-climbing-over-boulders':
                 case 'character-slipping-on-rockslide-boulders':
                 case 'rough-detour-path-around-rockslide':
                     scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); scene.background = new THREE.Color(0x708090);
                     assemblyFunction = createDefaultAssembly; break; // Placeholder - Needs rocky foothills assembly
                 case 'zoomed-view-mountain-fortress-western-ridge':
                      scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(5, 6, 12); camera.lookAt(-2, 3, -5); scene.background = new THREE.Color(0x708090);
                      assemblyFunction = createDefaultAssembly; break; // Placeholder
                 case 'narrow-goat-trail-mountainside-fortress-view':
                      scene.fog = new THREE.Fog(0x778899, 5, 30); camera.position.set(1, 3, 6); camera.lookAt(0, 2, -2); scene.background = new THREE.Color(0x708090);
                      assemblyFunction = createDefaultAssembly; break; // Placeholder
                 case 'narrow-windy-mountain-ridge-path':
                 case 'character-falling-off-windy-ridge':
                     scene.fog = new THREE.Fog(0x8899AA, 6, 25); camera.position.set(2, 5, 7); camera.lookAt(0, 3, -3); scene.background = new THREE.Color(0x778899);
                     assemblyFunction = createDefaultAssembly; break; // Placeholder
                 case 'approaching-dark-fortress-walls-guards':
                     scene.fog = new THREE.Fog(0x444455, 5, 20); camera.position.set(0, 3, 8); camera.lookAt(0, 2, 0); scene.background = new THREE.Color(0x333344);
                     assemblyFunction = createDefaultAssembly; break; // Placeholder - Needs fortress walls assembly

                 // Indoor Scenes
                 case 'dark-cave-entrance-dripping-water':
                     scene.fog = new THREE.Fog(0x1A1A1A, 2, 10); camera.position.set(0, 1.5, 4); camera.lookAt(0, 1, 0); scene.background = new THREE.Color(0x111111);
                     assemblyFunction = createDarkCaveAssembly; break;

                 // Default / Fallback
                 default:
                     console.warn(`Unknown illustration key: "${illustrationKey}". Using default scene.`);
                     assemblyFunction = createDefaultAssembly; break;
             }

             // --- Create and Add Assembly ---
             try {
                 currentAssemblyGroup = assemblyFunction();
                 if (currentAssemblyGroup && currentAssemblyGroup.isGroup) { // Check if it's a valid group
                      scene.add(currentAssemblyGroup);
                      adjustLighting(illustrationKey); // Adjust lighting based on the final scene key
                 } else {
                      throw new Error("Assembly function did not return a valid THREE.Group.");
                 }
             } catch (error) {
                 console.error(`Error creating assembly for ${illustrationKey}:`, error);
                 if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); } // Clean up potential partial assembly
                 currentAssemblyGroup = createErrorAssembly(); // Display error cone
                 scene.add(currentAssemblyGroup);
                 adjustLighting('error'); // Use default/error lighting
             }
             onWindowResize(); // Ensure camera aspect is correct after potential changes
        }

        function adjustLighting(illustrationKey) {
            if (!scene) return;
            // Remove existing non-ambient lights first
            const lightsToRemove = scene.children.filter(child => child.isLight && !child.isAmbientLight);
            lightsToRemove.forEach(light => scene.remove(light));

            const ambient = scene.children.find(c => c.isAmbientLight);
            if (!ambient) {
                 console.warn("No ambient light found in scene, adding default.");
                 scene.add(new THREE.AmbientLight(0xffffff, 0.5)); // Add default if missing
            }

            let directionalLight;
            let lightIntensity = 1.2;
            let ambientIntensity = 0.5;
            let lightColor = 0xffffff;
            let lightPosition = {x: 8, y: 15, z: 10};

            // Adjust lighting based on scene type (match cases in updateScene)
            switch (illustrationKey) {
                // Sunny / Open Areas
                 case 'crossroads-signpost-sunny':
                 case 'rolling-green-hills-shepherd-distance':
                 case 'hilltop-view-overgrown-shrine-wildflowers':
                 case 'overgrown-stone-shrine-wildflowers-close':
                     ambientIntensity = 0.7; lightIntensity = 1.5; lightColor = 0xFFF8E1; lightPosition = {x: 10, y: 15, z: 10}; break; // Bright, warm light
                 // Forest / Dim Light
                 case 'shadowwood-forest':
                 case 'dark-forest-entrance-gnarled-roots-filtered-light':
                 case 'overgrown-forest-path-glowing-fungi-vines':
                 case 'forest-clearing-mossy-statue-weathered-stone':
                 case 'narrow-game-trail-forest-rope-bridge-ravine':
                 case 'two-goblins-ambush-forest-path-spears':
                 case 'forest-stream-crossing-dappled-sunlight-stones':
                 case 'forest-edge-view-rocky-foothills-distant-mountain-fortress': // Edge might be brighter
                     ambientIntensity = 0.4; lightIntensity = 0.8; lightColor = 0xB0C4DE; lightPosition = {x: 5, y: 12, z: 5}; break; // Dimmer, slightly blue/green filtered light
                 // Caves / Dark Indoors
                 case 'dark-cave-entrance-dripping-water':
                     ambientIntensity = 0.1; lightIntensity = 0.3; lightColor = 0x667799; lightPosition = {x: 0, y: 5, z: 3}; break; // Very dim, cool light from entrance
                 case 'prisoner-cell':
                     ambientIntensity = 0.2; lightIntensity = 0.5; lightColor = 0x7777AA; lightPosition = {x: 0, y: 10, z: 5}; break; // Gloomy, cold light, maybe top-down
                 // Coastal / Overcast
                 case 'windy-sea-cliffs-crashing-waves-path-down':
                 case 'hidden-cove-beach-dark-cave-entrance':
                     ambientIntensity = 0.6; lightIntensity = 1.0; lightColor = 0xCCDDFF; lightPosition = {x: -10, y: 12, z: 8}; break; // Bright but cool/diffused coastal light
                 // Badlands / Harsh Light
                 case 'rocky-badlands-cracked-earth-harsh-sun':
                     ambientIntensity = 0.7; lightIntensity = 1.8; lightColor = 0xFFFFDD; lightPosition = {x: 5, y: 20, z: 5}; break; // Very bright, slightly yellow harsh sunlight
                 // Mountains / Fortress Approach
                 case 'climbing-rocky-foothills-path-fortress-closer':
                 case 'zoomed-view-mountain-fortress-western-ridge':
                 case 'narrow-goat-trail-mountainside-fortress-view':
                 case 'narrow-windy-mountain-ridge-path':
                 case 'approaching-dark-fortress-walls-guards':
                     ambientIntensity = 0.5; lightIntensity = 1.3; lightColor = 0xDDEEFF; lightPosition = {x: 10, y: 18, z: 15}; break; // Clear mountain air light, slightly cool
                 // Special States
                 case 'game-over': case 'game-over-generic':
                      ambientIntensity = 0.2; lightIntensity = 0.8; lightColor = 0xFF6666; lightPosition = {x: 0, y: 5, z: 5}; break; // Reddish tint for game over
                 case 'error':
                      ambientIntensity = 0.4; lightIntensity = 1.0; lightColor = 0xFFCC00; lightPosition = {x: 0, y: 5, z: 5}; break; // Orange/Yellow tint for error
                 default: // Default lighting fallback
                     ambientIntensity = 0.5; lightIntensity = 1.2; lightColor = 0xffffff; lightPosition = {x: 8, y: 15, z: 10}; break;
             }

             // Update ambient light
             const currentAmbient = scene.children.find(c => c.isAmbientLight);
             if (currentAmbient) {
                  currentAmbient.intensity = ambientIntensity;
             }

             // Add new directional light
             directionalLight = new THREE.DirectionalLight(lightColor, lightIntensity);
             directionalLight.position.set(lightPosition.x, lightPosition.y, lightPosition.z);
             directionalLight.castShadow = true;
             // Configure shadow properties (adjust map size and camera frustum as needed)
             directionalLight.shadow.mapSize.set(1024, 1024); // Or 2048 for better quality
             directionalLight.shadow.camera.near = 0.5;
             directionalLight.shadow.camera.far = 50; // Adjust based on typical scene scale
             directionalLight.shadow.camera.left = -20; // Adjust frustum size based on scene scale
             directionalLight.shadow.camera.right = 20;
             directionalLight.shadow.camera.top = 20;
             directionalLight.shadow.camera.bottom = -20;
             directionalLight.shadow.bias = -0.001; // Adjust shadow bias to prevent artifacts
             scene.add(directionalLight);

             // Optional: Add a light helper for debugging
             // const helper = new THREE.DirectionalLightHelper( directionalLight, 5 );
             // scene.add( helper );
             // const shadowHelper = new THREE.CameraHelper( directionalLight.shadow.camera );
             // scene.add( shadowHelper );
        }

        // ========================================
        // Potential Future Improvements (Comment Block)
        // ========================================
        /*
        Potential Areas for Expansion/Improvement:

        * More Scene Variety: Add more create...Assembly functions and corresponding illustration keys for greater visual diversity (e.g., villages, ruins, different cave types, interiors).
        * More Complex Scenes: The current scenes are quite abstract. More detail could be added, potentially involving more complex geometry generation (e.g., procedural buildings, terrain algorithms) or even simple pre-made models loaded for key elements (like the statue, specific monsters).
        * Interaction: Add interaction with the 3D scene (e.g., clicking on objects using raycasting to examine them, pick up items visually, or activate levers).
        * Combat System: Implement a more detailed combat mechanic instead of abstract resolution (e.g., turn-based, display enemy models, track enemy HP, use stats for attack/damage rolls, visual feedback for hits/misses).
        * Character Progression: Implement a level-up system based on XP (increase stats, HP, unlock abilities/spells). Check for level up after gaining XP.
        * Save/Load: Add functionality to save and load game progress (perhaps using `localStorage` to store the `gameState` object as a JSON string). Add save/load buttons to the UI.
        * Data Management: For a larger game, storing `gameData` and `itemsData` in external JSON files and fetching them (`Workspace` API) would be more manageable than keeping them inline.
        * Error Handling: Add more robust checks for missing data (items, pages) or potential errors during scene generation and game logic. Improve feedback on errors (e.g., specific messages instead of just going to page 99).
        * Code Organization: Split the JavaScript into modules (e.g., `three-setup.js`, `game-logic.js`, `ui-manager.js`, `scene-generator.js`, `data.js`) for better maintainability using ES6 modules and imports.
        * Refine Scene Logic: Improve how scene elements correspond to game state (e.g., actually remove defeated goblin models from the scene, visually represent items found on the ground before pickup, change scene lighting based on time of day if implemented).
        * Add More Mechanics: Implement status effects (poison, bless), equipment slots (weapon, armor, shield) with stat modifiers, spells with costs (mana/charges), currency/shops, more complex skill checks (e.g., opposed checks, checks with advantage/disadvantage based on items/status), quest tracking system.
        * Accessibility: Review and improve accessibility (ARIA attributes for dynamic content updates, keyboard navigation for choices).
        * Performance: For very complex scenes or many objects, consider optimizing geometry (instancing similar objects like trees/rocks), using lower-poly models, texture atlases, and optimizing the render loop. Dispose of unused Three.js objects properly.
        * Sound/Music: Add background music loops and sound effects for actions, ambiance, and feedback.
        */

        // ========================================
        // Initialization
        // ========================================
        document.addEventListener('DOMContentLoaded', () => {
            console.log("DOM Ready. Initializing game...");
            try {
                initThreeJS();
                if (scene && camera && renderer) {
                     startGame(); // Start the game logic only after successful Three.js init
                     console.log("Game Started Successfully.");
                 } else {
                     // If initThreeJS failed but didn't throw, or refs are null
                     throw new Error("Three.js initialization failed or did not complete.");
                 }
            } catch (error) {
                console.error("Initialization failed:", error);
                // Display user-friendly error message in the UI
                 storyTitleElement.textContent = "Initialization Error";
                 storyContentElement.innerHTML = `<p>A critical error occurred during setup. The adventure cannot begin. Please check the console (F12) for technical details.</p><pre>${error.stack || error}</pre>`;
                 choicesElement.innerHTML = '<p style="color: #f77;">Cannot proceed due to initialization error.</p>';
                 // Attempt to clear or show error in the 3D view area
                 if (sceneContainer) {
                     sceneContainer.innerHTML = '<p style="color: #f77; padding: 20px; font-size: 1.2em; text-align: center;">3D Scene Failed to Load</p>';
                 }
                 // Prevent further Three.js operations if it failed
                 scene = null; camera = null; renderer = null;
            }
        });
    </script>
</body>
</html>