File size: 102,606 Bytes
beb5dfd
 
 
 
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
beb5dfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b95853
beb5dfd
0b95853
beb5dfd
 
 
 
 
 
 
 
0b95853
 
beb5dfd
 
 
 
0b95853
beb5dfd
 
 
 
 
 
 
 
 
 
0b95853
 
beb5dfd
 
 
 
0b95853
beb5dfd
0b95853
beb5dfd
0b95853
beb5dfd
 
 
 
0b95853
 
 
 
beb5dfd
 
0b95853
 
beb5dfd
 
0b95853
beb5dfd
0b95853
 
beb5dfd
 
0b95853
beb5dfd
 
0b95853
 
 
 
 
beb5dfd
0b95853
 
 
beb5dfd
 
 
 
 
0b95853
beb5dfd
 
0b95853
 
 
 
beb5dfd
 
 
 
 
0b95853
 
beb5dfd
 
0b95853
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
 
 
 
 
 
 
 
 
 
 
0b95853
beb5dfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b95853
beb5dfd
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
beb5dfd
 
 
 
0b95853
 
 
beb5dfd
 
0b95853
 
beb5dfd
0b95853
 
beb5dfd
 
 
0b95853
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
beb5dfd
 
 
 
 
 
0b95853
 
 
 
 
 
 
 
beb5dfd
 
 
 
0b95853
 
 
beb5dfd
0b95853
beb5dfd
0b95853
 
 
 
 
 
beb5dfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b95853
beb5dfd
 
 
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
beb5dfd
0b95853
 
 
beb5dfd
0b95853
beb5dfd
0b95853
 
 
 
beb5dfd
0b95853
 
 
beb5dfd
 
0b95853
 
beb5dfd
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
0b95853
 
 
 
 
 
 
beb5dfd
0b95853
beb5dfd
0b95853
 
 
beb5dfd
0b95853
 
 
 
beb5dfd
0b95853
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
beb5dfd
 
 
0b95853
beb5dfd
0b95853
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
beb5dfd
 
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
beb5dfd
 
 
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
 
 
 
 
 
 
 
 
 
0b95853
 
 
beb5dfd
 
 
 
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
beb5dfd
 
0b95853
beb5dfd
 
0b95853
 
beb5dfd
 
 
 
0b95853
 
 
 
 
 
 
beb5dfd
 
 
 
0b95853
beb5dfd
 
 
0b95853
 
 
beb5dfd
 
 
 
 
 
 
0b95853
 
 
 
 
beb5dfd
 
 
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
 
 
 
0b95853
 
 
 
beb5dfd
 
0b95853
 
 
beb5dfd
0b95853
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
beb5dfd
 
0b95853
beb5dfd
 
 
 
 
 
 
 
0b95853
beb5dfd
 
 
 
0b95853
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
beb5dfd
0b95853
 
beb5dfd
 
0b95853
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
beb5dfd
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
 
 
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
 
 
 
 
 
0b95853
beb5dfd
 
 
 
 
 
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
0b95853
 
 
 
 
 
beb5dfd
 
0b95853
beb5dfd
 
0b95853
beb5dfd
 
 
0b95853
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
0b95853
 
 
 
beb5dfd
0b95853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beb5dfd
 
 
0b95853
beb5dfd
0b95853
 
 
beb5dfd
0b95853
beb5dfd
 
 
 
 
0b95853
 
beb5dfd
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
<!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 Enhanced Procedural Adventure</title>
    <style>
        @keyframes subtlePulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }
        @keyframes flicker {
          0%, 100% { opacity: 1; }
          20% { opacity: 0.7; }
          40% { opacity: 1; }
          60% { opacity: 0.5; }
          80% { opacity: 0.9; }
        }

        body {
            font-family: 'Courier New', monospace;
            background-color: #111;
            color: #eee;
            margin: 0;
            padding: 0;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        #game-container {
            display: flex;
            flex-grow: 1;
            overflow: hidden;
        }

        #scene-container {
            flex-grow: 3;
            position: relative;
            border-right: 2px solid #444;
            min-width: 200px;
            background-color: #0a0a0a;
            height: 100%;
            box-sizing: border-box;
        }

        #ui-container {
            flex-grow: 2;
            padding: 20px;
            overflow-y: auto;
            background-color: #282828;
            min-width: 300px;
            height: 100%;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            border-left: 1px solid #444;
        }

        #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.5em;
            text-shadow: 1px 1px 2px #000;
        }

        #story-content {
            margin-bottom: 20px;
            line-height: 1.7;
            flex-grow: 1;
            font-size: 1.05em;
        }
        #story-content p { margin-bottom: 1.2em; }
        #story-content p:last-child { margin-bottom: 0; }

        #stats-inventory-container {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #444;
            border-radius: 5px;
            background-color: #333;
            font-size: 0.9em;
        }
        #stats-display, #inventory-display, #effects-display {
            margin-bottom: 12px;
            line-height: 1.8;
        }
        #stats-display span, #inventory-display span, #effects-display span {
            display: inline-block;
            background-color: #4a4a4a;
            padding: 4px 10px;
            border-radius: 15px;
            margin-right: 8px;
            margin-bottom: 6px;
            border: 1px solid #666;
            white-space: nowrap;
            box-shadow: 1px 1px 2px rgba(0,0,0,0.3);
            transition: transform 0.1s ease-in-out;
        }
        #stats-display span:hover, #inventory-display span:hover, #effects-display span:hover {
             transform: translateY(-1px);
        }

        #stats-display strong, #inventory-display strong, #effects-display strong { color: #bbb; margin-right: 5px; }
        #inventory-display em, #effects-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-consumable { background-color: #664430; border-color: #996648;}
        #inventory-display .item-unknown { background-color: #555; border-color: #777;}

        #effects-display .effect-buff { background-color: #306030; border-color: #489048; color: #afa;}
        #effects-display .effect-debuff { background-color: #603030; border-color: #904848; color: #faa;}
        #effects-display .effect-neutral { 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: #bbb; }
        #choices { display: flex; flex-direction: column; gap: 12px; }

        .choice-button {
            display: block; width: 100%; padding: 12px 15px;
            margin-bottom: 0;
            background-color: #5a5a5a; color: #eee; border: 1px solid #777;
            border-radius: 5px; cursor: pointer; text-align: left;
            font-family: 'Courier New', monospace; font-size: 1.05em;
            transition: background-color 0.2s, border-color 0.2s, transform 0.1s;
            box-sizing: border-box;
            box-shadow: 1px 1px 3px rgba(0,0,0,0.4);
        }
        .choice-button:hover:not(:disabled) {
            background-color: #d4a017; color: #111; border-color: #b8860b;
            transform: scale(1.01);
        }
        .choice-button:disabled {
            background-color: #444; color: #888; cursor: not-allowed; border-color: #666;
            opacity: 0.6;
        }
        .choice-button[title]:disabled::after {
            content: ' (' attr(title) ')';
            font-style: italic;
            color: #aaa;
            font-size: 0.9em;
            margin-left: 5px;
        }

        .roll-success { color: #7f7; border-left: 3px solid #4a4; padding-left: 8px; margin-bottom: 1em; font-size: 0.95em; background-color: rgba(0, 255, 0, 0.05); padding: 5px;}
        .roll-failure { color: #f77; border-left: 3px solid #a44; padding-left: 8px; margin-bottom: 1em; font-size: 0.95em; background-color: rgba(255, 0, 0, 0.05); padding: 5px;}
        .effect-text { color: #aaa; font-style: italic; font-size: 0.9em; margin-bottom: 1em; border-left: 3px solid #666; padding-left: 8px; background-color: rgba(100, 100, 100, 0.1); padding: 5px; }
        .item-text { color: #6af; font-style: italic; font-size: 0.9em; margin-bottom: 1em; border-left: 3px solid #369; padding-left: 8px; background-color: rgba(0, 100, 200, 0.1); padding: 5px;}
        .stat-increase-text { color: #9f9; font-style: italic; font-size: 0.9em; margin-bottom: 1em; border-left: 3px solid #4a4; padding-left: 8px; background-color: rgba(0, 200, 0, 0.1); padding: 5px;}


    </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="effects-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 effectsElement = document.getElementById('effects-display');
        const inventoryElement = document.getElementById('inventory-display');

        let scene, camera, renderer, clock;
        let currentAssemblyGroup = null;
        let currentLights = [];
        let currentFog = null;

        const stoneMaterial = new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85, metalness: 0.1 });
        const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75, metalness: 0 });
        const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x6F4E2D, roughness: 0.7, metalness: 0 });
        const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x3E9B4E, roughness: 0.6, metalness: 0, side: THREE.DoubleSide });
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.95, metalness: 0 });
        const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.85, roughness: 0.35 });
        const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xB9AB88, roughness: 0.7, metalness: 0.15 });
        const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5, emissive: 0x331a00 });
        const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xcc0000, roughness: 0.6, metalness: 0.2, emissive: 0x220000 });
        const dirtMaterial = new THREE.MeshStandardMaterial({ color: 0x8B5E3C, roughness: 0.9 });
        const grassMaterial = new THREE.MeshStandardMaterial({ color: 0x4CB781, roughness: 0.85 });
        const oceanMaterial = new THREE.MeshStandardMaterial({ color: 0x3E90CF, roughness: 0.4, metalness: 0.3, transparent: true, opacity: 0.8 });
        const sandMaterial = new THREE.MeshStandardMaterial({ color: 0xF4A460, roughness: 0.9 });
        const wetStoneMaterial = new THREE.MeshStandardMaterial({ color: 0x3F5F5F, roughness: 0.6, metalness: 0.1 });
        const glowMaterial = new THREE.MeshStandardMaterial({ color: 0x33FFBB, emissive: 0x33FFBB, emissiveIntensity: 0.6 });
        const vineMaterial = new THREE.MeshStandardMaterial({ color: 0x448844, roughness: 0.8 });
        const goblinSkinMaterial = new THREE.MeshStandardMaterial({ color: 0x6B8E23, roughness: 0.7 });
        const mossMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9 });

        function initThreeJS() {
            if (!sceneContainer) { console.error("Scene container not found!"); return; }
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x1a1a1a);
            clock = new THREE.Clock();

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

            renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
            renderer.setSize(width || 400, height || 300);
            renderer.shadowMap.enabled = true;
            renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            renderer.toneMapping = THREE.ACESFilmicToneMapping;
            renderer.outputColorSpace = THREE.SRGBColorSpace;

            sceneContainer.appendChild(renderer.domElement);

            const ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
            scene.add(ambientLight);
            currentLights.push(ambientLight);

            window.addEventListener('resize', onWindowResize, false);
            setTimeout(onWindowResize, 100);
            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 delta = clock.getDelta();
            const time = clock.getElapsedTime();

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

            if (currentFog && currentFog.density !== undefined) {
                 const baseDensity = currentFog.userData.baseDensity || currentFog.density;
                 currentFog.density = baseDensity + Math.sin(time * 0.3) * baseDensity * 0.05;
            }

            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.01;
            ground.receiveShadow = true; ground.castShadow = false;
            return ground;
        }

        function createLSystemInspiredTree(position = { x: 0, y: 0, z: 0 }, baseHeight = 3, baseRadius = 0.2, iterations = 2, branchFactor = 3) {
            const treeGroup = new THREE.Group();
            treeGroup.position.copy(position);

            const trunkGeo = new THREE.CylinderGeometry(baseRadius * 0.7, baseRadius, baseHeight, 8);
            const trunk = createMesh(trunkGeo, woodMaterial, { x: 0, y: baseHeight / 2, z: 0 });
            treeGroup.add(trunk);

            function addBranches(parent, currentHeight, currentRadius, currentIteration) {
                if (currentIteration <= 0) {
                    const leafSize = baseHeight * 0.3 * (Math.random() * 0.5 + 0.7);
                    const leafGeo = new THREE.SphereGeometry(leafSize, 8, 6);
                    const leaves = createMesh(leafGeo, leafMaterial, { x: 0, y: currentHeight + leafSize * 0.5, z: 0 });
                    leaves.scale.y = Math.random() * 0.5 + 0.8;
                    parent.add(leaves);
                    return;
                }

                for (let i = 0; i < branchFactor; i++) {
                    const branchLength = baseHeight * 0.6 * (0.8 / currentIteration) * (Math.random() * 0.4 + 0.8);
                    const branchRadius = currentRadius * 0.6 * (Math.random() * 0.3 + 0.7);
                    const branchGeo = new THREE.CylinderGeometry(branchRadius * 0.7, branchRadius, branchLength, 6);

                    const branch = new THREE.Group();
                    const branchMesh = createMesh(branchGeo, woodMaterial, { x: 0, y: branchLength / 2, z: 0 });
                    branch.add(branchMesh);

                    branch.position.y = currentHeight;

                    const angleX = (Math.random() - 0.3) * Math.PI / 3;
                    const angleZ = (Math.random() - 0.5) * Math.PI / 3;
                    const angleY = Math.random() * Math.PI * 2;
                    branch.rotation.set(angleX, angleY, angleZ);

                    parent.add(branch);
                    addBranches(branchMesh, branchLength, branchRadius, currentIteration - 1);
                }
            }

            addBranches(trunk, baseHeight, baseRadius, iterations);
            return treeGroup;
        }

        function createForestAssembly(treeCount = 15, areaSize = 15) {
            const group = new THREE.Group();
            const forestFloorMat = Math.random() > 0.3 ? groundMaterial : grassMaterial;
            group.add(createGroundPlane(forestFloorMat, areaSize * 1.2));

            for (let i = 0; i < treeCount; i++) {
                 const x = (Math.random() - 0.5) * areaSize;
                 const z = (Math.random() - 0.5) * areaSize;
                 if (Math.sqrt(x * x + z * z) > areaSize * 0.1) {
                      const baseHeight = Math.random() * 2 + 2.5;
                      const baseRadius = Math.random() * 0.15 + 0.15;
                      const iterations = Math.random() > 0.5 ? 2 : 3;
                      const tree = createLSystemInspiredTree({ x, y: 0, z }, baseHeight, baseRadius, iterations);
                      tree.rotation.y = Math.random() * Math.PI * 2;
                      group.add(tree);
                 }
            }
             const bushGeo = new THREE.IcosahedronGeometry(0.4 + Math.random() * 0.3, 0);
             for (let i = 0; i < treeCount * 0.7; i++) {
                 const bush = createMesh(bushGeo, leafMaterial, { x: (Math.random() - 0.5) * areaSize, y: 0.3, z: (Math.random() - 0.5) * areaSize });
                 bush.scale.set(Math.random()*0.5+0.8, Math.random()*0.5+0.8, Math.random()*0.5+0.8);
                 group.add(bush);
             }
             const rockGeo = new THREE.IcosahedronGeometry(0.3 + Math.random() * 0.4, 0);
             for (let i = 0; i < treeCount * 0.3; i++) {
                 const rock = createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * areaSize, y: 0.2, z: (Math.random() - 0.5) * areaSize });
                 rock.rotation.set(Math.random()*0.5, Math.random()*Math.PI*2, Math.random()*0.5);
                 group.add(rock);
             }
            return group;
        }

        function createDefaultAssembly() {
             const group = new THREE.Group();
             const sphereGeo = new THREE.SphereGeometry(0.8, 16, 12);
             group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.8, z: 0 }));
             group.add(createGroundPlane(dirtMaterial, 10));
             return group;
         }

         function createCityGatesAssembly() {
            const group = new THREE.Group();
            const gh=4.5, gw=1.8, gd=1.0, ah=1.2, aw=3.5;
            const pillarMat = stoneMaterial.clone();
            pillarMat.color.lerp(new THREE.Color(0x666677), 0.2);

            const tlGeo = new THREE.BoxGeometry(gw, gh, gd);
            group.add(createMesh(tlGeo, pillarMat, { x:-(aw/2+gw/2), y:gh/2, z:0 }));
            const trGeo = new THREE.BoxGeometry(gw, gh, gd);
            group.add(createMesh(trGeo, pillarMat, { x:(aw/2+gw/2), y:gh/2, z:0 }));

            const archSegments = 10;
            const archPoints = [];
            for (let i = 0; i <= archSegments; i++) {
                const angle = Math.PI * (i / archSegments);
                archPoints.push(new THREE.Vector2(Math.cos(angle) * aw / 2, Math.sin(angle) * ah));
            }
            const archShape = new THREE.Shape(archPoints);
            const extrudeSettings = { depth: gd, bevelEnabled: false };
            const aGeo = new THREE.ExtrudeGeometry(archShape, extrudeSettings);
            const archMesh = createMesh(aGeo, stoneMaterial, { x:0, y:gh-ah, z:-gd/2}, {y: Math.PI});
             archMesh.position.y = gh - ah;
             archMesh.position.x = -aw/2;
             archMesh.rotation.y = 0;
             group.add(archMesh);

            const cs=0.45;
            const cg = new THREE.BoxGeometry(cs, cs, gd*1.1);
            for(let i=-1; i<=1; i+=2){
                group.add(createMesh(cg.clone(), stoneMaterial, { x:-(aw/2+gw/2)+i*cs*0.8, y:gh+cs/2, z:0 }));
                group.add(createMesh(cg.clone(), stoneMaterial, { x:(aw/2+gw/2)+i*cs*0.8, y:gh+cs/2, z:0 }));
            }
            group.add(createMesh(cg.clone(), stoneMaterial, { x:0, y:gh+ah-cs*0.2, z:0 }));
            group.add(createGroundPlane(stoneMaterial, 15));
            return group;
        }

        function createTempleAssembly() {
            const group = new THREE.Group();
            const bs=6, bsh=0.6, ch=3.5, cr=0.3, rh=0.7;
            const baseMat = templeMaterial.clone();
            baseMat.color.lerp(new THREE.Color(0xffffff), 0.1);

            const bGeo = new THREE.CylinderGeometry(bs, bs, bsh, 32);
            group.add(createMesh(bGeo, baseMat, { x:0, y:bsh/2, z:0 }));

            const cGeo = new THREE.CylinderGeometry(cr, cr, ch, 12);
            const numCols = 8;
            for(let i=0; i<numCols; i++){
                 const angle = (i / numCols) * Math.PI * 2;
                 const radius = bs * 0.7;
                 const x = Math.cos(angle) * radius;
                 const z = Math.sin(angle) * radius;
                 group.add(createMesh(cGeo.clone(), templeMaterial, { x:x, y:bsh+ch/2, z:z }));
            }

            const roofGeo = new THREE.ConeGeometry(bs*0.8, rh*2, 32);
            group.add(createMesh(roofGeo, templeMaterial, { x:0, y:bsh+ch+rh, z:0 }));

            const altarGeo = new THREE.BoxGeometry(bs*0.2, bs*0.2, bs*0.2);
            const altar = createMesh(altarGeo, glowMaterial.clone().set({color: 0xFFFF99, emissiveIntensity: 0.3}), {x: 0, y: bsh + bs*0.1, z: 0});
            group.add(altar);

            group.add(createGroundPlane(grassMaterial, 20));
            return group;
        }

        function createDarkCaveAssembly() {
            const group = new THREE.Group();
            const caveRadius = 6;
            const caveHeight = 5;

            const floorGeo = new THREE.PlaneGeometry(caveRadius * 2.5, caveRadius * 2.5, 20, 20);
            const positions = floorGeo.attributes.position;
            for (let i = 0; i < positions.count; i++) {
                 const x = positions.getX(i);
                 const z = positions.getZ(i);
                 const dist = Math.sqrt(x*x + z*z);
                 const noise = (Math.random() - 0.5) * 0.3;
                 const dip = -dist * 0.05;
                 positions.setY(i, noise + dip);
            }
            floorGeo.computeVertexNormals();
            const floor = new THREE.Mesh(floorGeo, wetStoneMaterial);
            floor.rotation.x = -Math.PI / 2;
            floor.receiveShadow = true;
            group.add(floor);

             const wallGeo = new THREE.SphereGeometry(caveRadius * 1.1, 32, 16, 0, Math.PI * 2, 0, Math.PI * 0.8);
             const wallMat = stoneMaterial.clone();
             wallMat.side = THREE.BackSide;
             wallMat.color.lerp(new THREE.Color(0x444455), 0.3);
             const walls = new THREE.Mesh(wallGeo, wallMat);
             walls.position.y = caveHeight * 0.4;
             walls.receiveShadow = true;
             group.add(walls);

            const coneGeo = new THREE.ConeGeometry(0.1 + Math.random() * 0.2, 0.5 + Math.random() * 1.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.4) {
                    const stalactite = createMesh(coneGeo.clone(), wetStoneMaterial, {x, y: caveHeight * 0.8 + Math.random() * 0.5, z});
                    stalactite.rotation.x = Math.PI;
                    group.add(stalactite);
                }
                if (Math.random() > 0.4) {
                    const stalagmite = createMesh(coneGeo.clone(), wetStoneMaterial, {x, y: 0, z});
                     const raycaster = new THREE.Raycaster(new THREE.Vector3(x, 5, z), new THREE.Vector3(0, -1, 0));
                     const intersects = raycaster.intersectObject(floor);
                     if (intersects.length > 0) {
                         stalagmite.position.y = intersects[0].point.y + (0.5 + Math.random() * 1.5)/2;
                     }
                    group.add(stalagmite);
                }
            }

            const dripGeo = new THREE.SphereGeometry(0.03, 6, 6);
            const dripMat = oceanMaterial.clone();
            dripMat.opacity = 0.6;
            for (let i = 0; i < 5; i++) {
                const startX = (Math.random() - 0.5) * caveRadius;
                const startZ = (Math.random() - 0.5) * caveRadius;
                const startY = caveHeight * 0.8 + Math.random() * 0.5;
                const drip = createMesh(dripGeo, dripMat, { x: startX, y: startY, z: startZ });
                drip.castShadow = false;
                drip.userData.startY = startY;
                drip.userData.speed = Math.random() * 2 + 2;
                drip.userData.update = (time, delta) => {
                    drip.position.y -= drip.userData.speed * delta;
                    if (drip.position.y < 0) {
                        drip.position.y = drip.userData.startY;
                        drip.position.x = startX + (Math.random()-0.5)*0.1;
                        drip.position.z = startZ + (Math.random()-0.5)*0.1;
                    }
                };
                group.add(drip);
            }

             const flickerLight = new THREE.PointLight(0xffaa55, 3, 8, 1);
             flickerLight.position.set(0, 1.5, 0);
             flickerLight.castShadow = true;
             flickerLight.shadow.mapSize.width = 512;
             flickerLight.shadow.mapSize.height = 512;
             flickerLight.userData.baseIntensity = 3;
             flickerLight.userData.update = (time) => {
                 flickerLight.intensity = flickerLight.userData.baseIntensity * (0.7 + Math.random() * 0.6);
                 flickerLight.position.x = 0 + (Math.random()-0.5)*0.1;
                 flickerLight.position.z = 0 + (Math.random()-0.5)*0.1;
             };
             group.add(flickerLight);
            return group;
        }

         function createOvergrownPathAssembly() {
            const group = new THREE.Group();
            const areaSize = 15;
            group.add(createGroundPlane(dirtMaterial, areaSize));

             for (let i = 0; i < 25; i++) {
                 const edgeDist = areaSize * 0.45;
                 const angle = Math.random() * Math.PI * 2;
                 const radius = edgeDist + Math.random() * (areaSize*0.2);
                 const x = Math.cos(angle) * radius;
                 const z = Math.sin(angle) * radius;
                  const baseHeight = Math.random() * 2 + 2;
                  const baseRadius = Math.random() * 0.1 + 0.1;
                  const tree = createLSystemInspiredTree({ x, y: 0, z }, baseHeight, baseRadius, 2);
                  tree.rotation.y = Math.random() * Math.PI * 2;
                  group.add(tree);
             }

            const fungiGeo = new THREE.SphereGeometry(0.05 + Math.random()*0.05, 6, 5);
            for (let i = 0; i < 15; i++) {
                 const clusterX = (Math.random() - 0.5) * areaSize * 0.6;
                 const clusterZ = (Math.random() - 0.5) * areaSize * 0.6;
                 const clusterYBase = 0.1;
                 for (let j = 0; j < 5 + Math.random()*5; j++) {
                     const fungi = createMesh(fungiGeo, glowMaterial, {
                         x: clusterX + (Math.random() - 0.5) * 0.3,
                         y: clusterYBase + Math.random() * 0.1,
                         z: clusterZ + (Math.random() - 0.5) * 0.3
                     });
                     fungi.castShadow = false;
                     group.add(fungi);
                 }
            }

            const vineGeo = new THREE.CylinderGeometry(0.03, 0.04, 1.5 + Math.random(), 5);
            for (let i = 0; i < 10; i++) {
                 const x = (Math.random() - 0.5) * areaSize * 0.5;
                 const z = (Math.random() - 0.5) * areaSize * 0.5;
                 const y = 2.5 + Math.random();
                 const vine = createMesh(vineGeo, vineMaterial, { x, y, z },
                     { x: Math.random()*0.4 - 0.2, z: Math.random()*0.4 - 0.2 }
                 );
                 group.add(vine);
            }
            return group;
        }

         function createClearingStatueAssembly() {
             const group = new THREE.Group();
             const clearingSize = 12;
             group.add(createGroundPlane(grassMaterial.clone().set({color: 0x6AAA6A}), clearingSize));

             const baseGeo = new THREE.CylinderGeometry(0.6, 0.8, 0.4, 12);
             const base = createMesh(baseGeo, stoneMaterial, {y: 0.2});
             group.add(base);

             const bodyGeo = new THREE.BoxGeometry(0.7, 1.5, 0.7);
             const body = createMesh(bodyGeo, stoneMaterial, {y: 0.4 + 1.5/2});
             group.add(body);

             const headGeo = new THREE.SphereGeometry(0.4, 12, 8);
             const head = createMesh(headGeo, stoneMaterial, {y: 0.4 + 1.5 + 0.4});
             group.add(head);

             const mossGeo = new THREE.SphereGeometry(0.1, 6, 4);
             for (let i = 0; i < 25; i++) {
                  const targetMesh = Math.random() > 0.5 ? body : (Math.random() > 0.5 ? head : base);
                  const pos = new THREE.Vector3(
                      (Math.random() - 0.5) * (targetMesh.geometry.parameters.width || targetMesh.geometry.parameters.radiusTop || 0.5),
                      (Math.random() - 0.5) * targetMesh.geometry.parameters.height,
                      (Math.random() - 0.5) * (targetMesh.geometry.parameters.depth || targetMesh.geometry.parameters.radiusTop || 0.5)
                  );
                   pos.multiplyScalar(0.9);
                  pos.add(targetMesh.position);

                  const moss = createMesh(mossGeo, mossMaterial, pos);
                  moss.scale.setScalar(Math.random()*0.5 + 0.8);
                  group.add(moss);
             }

             const leafGeo = new THREE.PlaneGeometry(0.15, 0.15);
             for (let i = 0; i < 40; i++) {
                 const leaf = createMesh(leafGeo, leafMaterial,
                     { x: (Math.random() - 0.5) * clearingSize * 0.8, y: 0.01, z: (Math.random() - 0.5) * clearingSize * 0.8 },
                     { x: -Math.PI / 2, z: Math.random() * Math.PI * 2 }
                 );
                 leaf.receiveShadow = true;
                 group.add(leaf);
             }

             return group;
         }

         function createGoblinAmbushAssembly() {
            const group = createOvergrownPathAssembly();

            const createGoblin = (position) => {
                const goblinGroup = new THREE.Group();
                goblinGroup.position.copy(position);

                const bodyHeight = 0.8;
                const bodyRadius = 0.25;
                const bodyGeo = new THREE.CapsuleGeometry(bodyRadius, bodyHeight - bodyRadius*2, 4, 8);
                const body = createMesh(bodyGeo, goblinSkinMaterial, { y: bodyHeight / 2 + 0.1});
                goblinGroup.add(body);

                const headSize = 0.3;
                const headGeo = new THREE.SphereGeometry(headSize, 10, 8);
                const head = createMesh(headGeo, goblinSkinMaterial, { y: bodyHeight + headSize * 0.8 });
                goblinGroup.add(head);

                const limbGeo = new THREE.CylinderGeometry(0.05, 0.04, 0.6, 6);
                const arm1 = createMesh(limbGeo, goblinSkinMaterial, {x:-bodyRadius*0.8, y: bodyHeight*0.7, z:0}, {z: Math.PI/4});
                const arm2 = createMesh(limbGeo, goblinSkinMaterial, {x:bodyRadius*0.8, y: bodyHeight*0.7, z:0}, {z: -Math.PI/4});
                goblinGroup.add(arm1);
                goblinGroup.add(arm2);

                const spearLength = 1.5;
                const spearGeo = new THREE.CylinderGeometry(0.03, 0.03, spearLength, 6);
                const spear = createMesh(spearGeo, darkWoodMaterial, { x: 0.3, y: 0.6, z: 0.1 }, { z: Math.PI / 3, x: -0.2 });
                goblinGroup.add(spear);

                 const tipGeo = new THREE.ConeGeometry(0.05, 0.15, 6);
                 const tip = createMesh(tipGeo, metalMaterial.clone().set({roughness: 0.7, color: 0x666666}), {y: spearLength/2});
                 spear.add(tip);

                return goblinGroup;
            };

            const goblin1 = createGoblin(new THREE.Vector3(-1.5, 0, 2));
            const goblin2 = createGoblin(new THREE.Vector3(1.8, 0, 2.5));
            goblin1.rotation.y = Math.PI / 8;
            goblin2.rotation.y = -Math.PI / 6;
            group.add(goblin1);
            group.add(goblin2);

            return group;
         }

        function createCoastalCliffsAssembly() {
             const group = new THREE.Group();
             const cliffWidth = 15;
             const cliffHeight = 8;
             const cliffDepth = 15;

             const cliffGeo = new THREE.BoxGeometry(cliffWidth, cliffHeight, cliffDepth);
             const cliffMat = stoneMaterial.clone();

             const positions = cliffGeo.attributes.position;
             const normals = cliffGeo.attributes.normal;
             for(let i=0; i<positions.count; i++){
                 const x = positions.getX(i);
                 const y = positions.getY(i);
                 const z = positions.getZ(i);
                 const nx = normals.getX(i);

                 if (Math.abs(nx - 1) < 0.1) {
                     positions.setX(i, positions.getX(i) + (Math.random() - 0.7) * 2);
                     positions.setY(i, positions.getY(i) + (Math.random() - 0.5) * 1);
                 }
             }
             cliffGeo.computeVertexNormals();

             const cliff = createMesh(cliffGeo, cliffMat, { x:-cliffWidth/2, y: cliffHeight / 2 - 3, z: 0 });
             group.add(cliff);

             const pathWidth = 1.5;
             const pathSegmentLength = 3;
             const pathSegments = 5;
             let currentPathPos = new THREE.Vector3(cliffWidth/2 - 3, cliffHeight-1, -cliffDepth/2 + 2);
             for (let i=0; i< pathSegments; i++) {
                 const pathGeo = new THREE.PlaneGeometry(pathWidth, pathSegmentLength);
                 const angleX = -Math.PI / 2 - (Math.random()*0.1 + 0.1);
                 const angleZ = (i%2 === 0 ? 1 : -1) * (Math.random()*0.2 + Math.PI / 8);
                 const path = createMesh(pathGeo, dirtMaterial, currentPathPos, {x: angleX, y: 0, z: angleZ});
                 group.add(path);
                 currentPathPos.x -= Math.sin(angleZ) * pathSegmentLength * 0.8;
                 currentPathPos.y += Math.sin(angleX) * pathSegmentLength * 0.8;
                 currentPathPos.z += Math.cos(angleZ) * pathSegmentLength * 0.8;
             }

             const oceanGeo = new THREE.PlaneGeometry(100, 100, 20, 20);
             const oceanMat = oceanMaterial.clone();
             oceanMat.transparent = true;
             oceanMat.opacity = 0.9;
             const ocean = new THREE.Mesh(oceanGeo, oceanMat);
             ocean.rotation.x = -Math.PI / 2;
             ocean.position.y = -2;
             ocean.receiveShadow = false;
             ocean.userData.baseY = -2;
             ocean.userData.update = (time) => {
                ocean.position.y = ocean.userData.baseY + Math.sin(time * 0.5) * 0.15;
                 const oceanPos = oceanGeo.attributes.position;
                 for(let i=0; i<oceanPos.count; i++){
                     const x = oceanPos.getX(i);
                     const z = oceanPos.getZ(i);
                     oceanPos.setZ(i, Math.sin(x * 0.1 + time * 0.3) * 0.3 + Math.cos(z * 0.05 + time * 0.2) * 0.2);
                 }
                 oceanPos.needsUpdate = true;
                 oceanGeo.computeVertexNormals();
             };
             group.add(ocean);

             const foamGeo = new THREE.PlaneGeometry(cliffWidth*1.2, 2, 10, 1);
             const foamMat = new THREE.MeshBasicMaterial({color: 0xffffff, transparent: true, opacity: 0.6});
             const foam = createMesh(foamGeo, foamMat, {x: -cliffWidth/2+cliffWidth*1.2/2, y: -1.9, z: -cliffDepth/2}, {x: -Math.PI/2});
             group.add(foam);

             return group;
         }

        function createRollingHillsAssembly() {
             const group = new THREE.Group();
             const hillSize = 60;
             const hillSegments = 30;
             const hillGeo = new THREE.PlaneGeometry(hillSize, hillSize, hillSegments, hillSegments);
             const hillMat = grassMaterial.clone();
             const hill = new THREE.Mesh(hillGeo, hillMat);
             hill.rotation.x = -Math.PI / 2;
             hill.receiveShadow = true;

             const positions = hillGeo.attributes.position;
             for (let i = 0; i < positions.count; i++) {
                 const x = positions.getX(i);
                 const z = positions.getZ(i);
                 const y = (Math.sin(x * 0.08 + z * 0.05) * 2.5 + Math.cos(x * 0.04 - z * 0.07) * 2.0) * (1 - Math.sqrt(x*x+z*z)/(hillSize*0.7));
                 positions.setY(i, Math.max(0, y));
             }
             hillGeo.computeVertexNormals();
             group.add(hill);

             const shepherdGeo = new THREE.CapsuleGeometry(0.2, 1.2, 4, 8);
             const shepherd = createMesh(shepherdGeo, darkWoodMaterial, { x: 15, y: 0, z: -20 });
             const raycaster = new THREE.Raycaster(new THREE.Vector3(15, 10, -20), new THREE.Vector3(0, -1, 0));
             const intersects = raycaster.intersectObject(hill);
             if (intersects.length > 0) {
                 shepherd.position.y = intersects[0].point.y + 1.4/2;
             }
             group.add(shepherd);


             const sheepGeo = new THREE.SphereGeometry(0.3, 8, 6);
             const sheepMat = new THREE.MeshStandardMaterial({color: 0xeeeeee, roughness: 0.9});
             for (let i = 0; i < 10; i++) {
                 const sx = 15 + (Math.random() - 0.5) * 8;
                 const sz = -20 + (Math.random() - 0.5) * 8;
                 const sheep = createMesh(sheepGeo, sheepMat, { x: sx, y: 0, z: sz });
                 const sheepRaycaster = new THREE.Raycaster(new THREE.Vector3(sx, 10, sz), new THREE.Vector3(0, -1, 0));
                 const sheepIntersects = sheepRaycaster.intersectObject(hill);
                 if (sheepIntersects.length > 0) {
                     sheep.position.y = sheepIntersects[0].point.y + 0.3;
                 }
                 group.add(sheep);
             }

             const flowerGeo = new THREE.ConeGeometry(0.05, 0.2, 5);
             const flowerMat = new THREE.MeshStandardMaterial({color: 0xffff00});
             for (let i = 0; i < 100; i++) {
                 const fx = (Math.random() - 0.5) * hillSize * 0.8;
                 const fz = (Math.random() - 0.5) * hillSize * 0.8;
                 const flower = createMesh(flowerGeo, flowerMat, { x: fx, y: 0, z: fz });
                 const flowerRaycaster = new THREE.Raycaster(new THREE.Vector3(fx, 10, fz), new THREE.Vector3(0, -1, 0));
                 const flowerIntersects = flowerRaycaster.intersectObject(hill);
                 if (flowerIntersects.length > 0) {
                     flower.position.y = flowerIntersects[0].point.y + 0.1;
                 }
                 group.add(flower);
             }

             return group;
         }

        function createCrossroadsAssembly() {
             const group = new THREE.Group();
             group.add(createGroundPlane(dirtMaterial, 30));

             const poleGeo = new THREE.CylinderGeometry(0.15, 0.12, 3.5, 8);
             group.add(createMesh(poleGeo, darkWoodMaterial, { y: 1.75 }));

             const signGeo = new THREE.BoxGeometry(1.8, 0.4, 0.1);
             const signMat = woodMaterial.clone();
             group.add(createMesh(signGeo, signMat, { y: 2.8, z: 0.3, x: 0.7 }, { y: Math.PI / 5 }));
             group.add(createMesh(signGeo.clone(), signMat, { y: 2.5, x: -0.7 }, { y: -Math.PI / 6 }));
             group.add(createMesh(signGeo.clone(), signMat, { y: 2.2, z: -0.3, x: 0.1 }, { y: Math.PI + Math.PI / 7 }));


             const grassGeo = new THREE.ConeGeometry(0.15, 0.4, 6);
             for (let i = 0; i < 80; i++) {
                 const x = (Math.random() - 0.5) * 28;
                 const z = (Math.random() - 0.5) * 28;
                 if (Math.abs(x) > 3 || Math.abs(z) > 3) {
                     const grass = createMesh(grassGeo, grassMaterial, { x, y: 0.2, z }, { y: Math.random() * Math.PI });
                     grass.scale.setScalar(0.8 + Math.random()*0.4);
                     group.add(grass);
                 }
             }

             const rockGeo = new THREE.IcosahedronGeometry(0.4 + Math.random()*0.3, 0);
             for (let i = 0; i < 15; i++) {
                 const rock = createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * 25, y: 0.2, z: (Math.random() - 0.5) * 25 }, { y: Math.random() * Math.PI });
                  rock.rotation.x = Math.random()*0.3; rock.rotation.z = Math.random()*0.3;
                 group.add(rock);
             }
             return group;
         }

        function createForestEntranceAssembly() {
             const group = createForestAssembly(30, 18);
             const rootGeo = new THREE.TorusGeometry(0.8 + Math.random()*0.4, 0.15 + Math.random()*0.1, 8, 16);
             for (let i = 0; i < 15; i++) {
                 const root = createMesh(rootGeo, darkWoodMaterial, { x: (Math.random() - 0.5) * 12, y: 0.15, z: (Math.random() - 0.5) * 12 }, { x: Math.PI / 2 + (Math.random()-0.5)*0.3, y: Math.random()*Math.PI });
                 root.scale.y = 0.5 + Math.random();
                 group.add(root);
             }
             return group;
         }

        function createHiddenCoveAssembly() {
             const group = new THREE.Group();
             const coveSize = 20;
             group.add(createGroundPlane(sandMaterial, coveSize));

             const caveEntranceWidth = 4;
             const caveEntranceHeight = 3;
             const caveWallGeo = new THREE.BoxGeometry(coveSize*1.5, 8, coveSize*0.3);
             const caveWall = createMesh(caveWallGeo, stoneMaterial, { z: -coveSize/2 - coveSize*0.15, y: 4});
             group.add(caveWall);


             const rockGeo = new THREE.IcosahedronGeometry(0.6 + Math.random()*0.5, 0);
             for (let i = 0; i < 20; i++) {
                 const x = (Math.random() - 0.5) * coveSize * 0.9;
                 const z = Math.random() * coveSize * 0.4;
                 const rock = createMesh(rockGeo, wetStoneMaterial, { x: x, y: 0.3, z: z });
                  rock.rotation.set(Math.random()*0.5, Math.random()*Math.PI*2, Math.random()*0.5);
                 group.add(rock);
             }

             const seaweedGeo = new THREE.ConeGeometry(0.15, 1.2 + Math.random()*0.5, 6);
             for (let i = 0; i < 15; i++) {
                 const x = (Math.random() - 0.5) * coveSize * 0.7;
                 const z = Math.random() * coveSize * 0.3;
                 const seaweed = createMesh(seaweedGeo, leafMaterial, { x: x, y: 0.6, z: z }, {x: (Math.random()-0.5)*0.2});
                 group.add(seaweed);
             }

             const oceanGeo = new THREE.PlaneGeometry(coveSize*1.5, coveSize*0.7, 10, 5);
             const ocean = createMesh(oceanGeo, oceanMaterial, {y: 0.1, z: coveSize*0.35}, {x: -Math.PI/2});
             group.add(ocean);

             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})));
             return group;
         }

        function createErrorAssembly() {
             const group = new THREE.Group();
             const coneGeo = new THREE.ConeGeometry(0.8, 1.5, 8);
             group.add(createMesh(coneGeo, errorMaterial, { x: 0, y: 0.75, z: 0 }));
             group.add(createGroundPlane());
             return group;
         }
         function createPrisonerCellAssembly() { return createDefaultAssembly(); }
         function createResistanceMeetingAssembly() { return createDefaultAssembly(); }
         function createRoadAmbushAssembly() { return createDefaultAssembly(); }
         function createForestEdgeAssembly() { return createDefaultAssembly(); }
         function createWeaponsmithAssembly() { return createDefaultAssembly(); }

        const itemsData = {
            "Flaming Sword":{type:"weapon", description:"A fiery blade"},
            "Whispering Bow":{type:"weapon", description:"A silent bow"},
            "Guardian Shield":{type:"armor", description:"A protective shield"},
            "Healing Light Spell":{type:"spell", description:"Mends minor wounds"},
            "Shield of Faith Spell":{type:"spell", description:"Temporary shield"},
            "Binding Runes Scroll":{type:"spell", description:"Binds an enemy"},
            "Secret Tunnel Map":{type:"quest", description:"Shows a hidden path"},
            "Poison Daggers":{type:"weapon", description:"Daggers with poison"},
            "Master Key":{type:"quest", description:"Unlocks many doors"},
            "Crude Dagger":{type:"weapon", description:"A roughly made dagger."},
            "Scout's Pouch":{type:"quest", description:"Contains odds and ends."},
            "Health Potion": {type:"consumable", description:"A swirling red liquid. Restores some health when drunk.", effect: { hpGain: 15 }},
            "Antidote": {type:"consumable", description:"A chalky blue vial. Cures poison.", effect: { cure: "Poisoned" }},
        };

        const gameData = {
            "1": { title: "The Crossroads", content: `<p>Dust swirls... 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" },
            "2": { title: "Rolling Hills", content: `<p>Verdant hills stretch before you... It feels peaceful...</p>`, options: [ { text: "Follow the narrow path", next: 4 }, { text: "Try to hail the distant shepherd (Charisma Check - DC 10)", check: { stat: 'charisma', dc: 10, onFailure: 201 }, next: 200 } ], illustration: "rolling-green-hills-shepherd-distance" },
            "3": { title: "Coastal Cliffs Edge", content: `<p>You stand atop windswept cliffs... A precarious-looking path descends...</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check - DC 12)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Scan the cliff face for easier routes (Wisdom Check - DC 11)", check: { stat: 'wisdom', dc: 11, onFailure: 32 }, next: 33 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" },
            "4": { title: "Hill Path Overlook", content: `<p>The path crests a hill... you see a small, overgrown shrine...</p>`, options: [ { text: "Investigate the overgrown shrine", next: 40 }, { text: "Continue towards the badlands", next: 41 } ], illustration: "hilltop-view-overgrown-shrine-wildflowers" },
            "5": { title: "Shadowwood Entrance", content: `<p>Sunlight struggles to pierce the dense canopy... How do you proceed?</p>`, options: [ { text: "Follow the main, albeit overgrown, path", next: 6 }, { text: "Try to navigate through the lighter undergrowth", next: 7 }, { text: "Look for animal trails or signs of passage (Wisdom Check - DC 10)", check: { stat: 'wisdom', dc: 10, onFailure: 6 }, next: 8 } ], illustration: "dark-forest-entrance-gnarled-roots-filtered-light" },
            "6": { title: "Overgrown Forest Path", content: `<p>The path is barely visible... You hear a twig snap nearby!</p>`, options: [ { text: "Ready your weapon and investigate", next: 10 }, { text: "Attempt to hide quietly (Dexterity Check - DC 11)", check: { stat: 'dexterity', dc: 11, onFailure: 10 }, next: 11 }, { text: "Call out cautiously", next: 10 } ], illustration: "overgrown-forest-path-glowing-fungi-vines" },
            "7": { title: "Tangled Undergrowth", content: `<p>Pushing through ferns... You stumble upon a small clearing containing a moss-covered, weathered stone statue...</p>`, options: [ { text: "Examine the statue closely (Intelligence Check - DC 13)", check: { stat: 'intelligence', dc: 13, onFailure: 71 }, next: 70 }, { text: "Ignore the statue and press on", next: 72 }, { text: "Leave a small offering (Requires: non-quest item)", requireItemType: "non-quest", consumeItem: true, next: 73 }, { text: "Rest briefly in the clearing", next: 74} ], illustration: "forest-clearing-mossy-statue-weathered-stone" },
            "8": { title: "Hidden Game Trail", content: `<p>Your sharp eyes spot a faint trail... It leads towards a ravine spanned by a rickety rope bridge.</p><p class="effect-text"><em>Gained +20 XP.</em></p>`, options: [ { text: "Risk crossing the rope bridge (Dexterity Check - DC 10)", check: { stat: 'dexterity', dc: 10, onFailure: 81 }, next: 80 }, { text: "Search for another way across the ravine (Wisdom Check - DC 13)", check: { stat: 'wisdom', dc: 13, onFailure: 81 }, next: 82 } ], illustration: "narrow-game-trail-forest-rope-bridge-ravine", reward: { xp: 20 } },
            "10": { title: "Goblin Ambush!", content: `<p>Two scraggly goblins leap out, brandishing crude spears!</p>`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them (Dexterity Check - DC 13)", check: { stat: 'dexterity', dc: 13, onFailure: 101 }, next: 13 }, { text: "Try to intimidate them (Charisma Check - DC 14)", check: { stat: 'charisma', dc: 14, onFailure: 101 }, next: 102 } ], illustration: "two-goblins-ambush-forest-path-spears" },
            "11": { title: "Hidden Evasion", content: `<p>You melt into the shadows as the goblins blunder past.</p><p class="effect-text"><em>+30 XP.</em></p>`, options: [ { text: "Continue cautiously", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } },
            "12": { title: "Ambush Victory!", content: `<p>You defeat the goblins! Found a Crude Dagger and a Health Potion.</p><p class="effect-text"><em>+50 XP, Crude Dagger, Health Potion.</em></p>`, options: [ { text: "Press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: ["Crude Dagger", "Health Potion"] } },
            "13": { title: "Daring Escape", content: `<p>With surprising agility, you tumble past the goblins!</p><p class="effect-text"><em>+25 XP.</em></p>`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } },
            "14": { title: "Forest Stream Crossing", content: `<p>The path leads to a clear, shallow stream...</p>`, options: [ { text: "Wade across the stream", next: 16 }, { text: "Look for a drier crossing point (fallen log?)", next: 15 } ], illustration: "forest-stream-crossing-dappled-sunlight-stones" },
            "15": { title: "Log Bridge", content: `<p>Further upstream, a large, mossy log spans the stream.</p>`, options: [ { text: "Cross carefully on the log (Dexterity Check - DC 9)", check: { stat: 'dexterity', dc: 9, onFailure: 151 }, next: 16 }, { text: "Go back and wade instead", next: 14 } ], illustration: "mossy-log-bridge-over-forest-stream" },
            "151": { title: "Splash!", content: `<p>You slip on the mossy log and tumble into the cold stream! You're soaked but unharmed.</p><p class="effect-text"><em>Gained 'Chilled' effect (-1 Dex temporarily).</em></p>`, options: [ { text: "Shake yourself off and continue", next: 16 } ], illustration: "character-splashing-into-stream-from-log", effects: [{name: "Chilled", duration: 2, mod: {dexterity: -1}}] },
            "16": { title: "Edge of the Woods", content: `<p>You emerge from the Shadowwood... Before you lie rocky foothills...</p>`, options: [ { text: "Begin the ascent into the foothills", next: 17 }, { text: "Scan the fortress from afar (Wisdom Check - DC 14)", check: { stat: 'wisdom', dc: 14, onFailure: 17 }, next: 18 } ], illustration: "forest-edge-view-rocky-foothills-distant-mountain-fortress" },
            "17": { title: "Rocky Foothills Path", content: `<p>The climb is arduous... The fortress looms larger now.</p>`, options: [ { text: "Continue the direct ascent", next: 19 }, { text: "Look for signs of a hidden trail (Wisdom Check - DC 15)", check: { stat: 'wisdom', dc: 15, onFailure: 19 }, next: 20 } ], illustration: "climbing-rocky-foothills-path-fortress-closer" },
            "18": { title: "Distant Observation", content: `<p>You notice what might be a less-guarded approach along the western ridge...</p><p class="effect-text"><em>+30 XP.</em></p>`, options: [ { text: "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 } },
            "19": { title: "Blocked Pass", content: `<p>The main path is blocked by a recent rockslide!</p>`, options: [ { text: "Try to climb over (Strength Check - DC 14)", check: { stat: 'strength', dc: 14, onFailure: 191 }, next: 190 }, { text: "Search for another way around", next: 192 } ], illustration: "rockslide-blocking-mountain-path-boulders" },
            "20": { title: "Goat Trail", content: `<p>You discover a narrow trail barely wide enough for a mountain goat...</p><p class="effect-text"><em>+40 XP.</em></p>`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } },
            "30": { title: "Hidden Cove", content: `<p>Your careful descent brings you to a secluded cove. A dark cave entrance is visible...</p><p class="effect-text"><em>+25 XP.</em></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... landing hard on the sandy cove floor. You lose 5 HP. A dark cave entrance beckons.</p>`, options: [ { text: "Gingerly 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 cliffs intently but find no obviously easier routes.</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check - DC 12)", 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 a series of barely visible handholds and steps carved into the rock...</p><p class="effect-text"><em>+15 XP.</em></p>`, options: [ { text: "Use the hidden steps (Easier Dex Check - DC 8)", 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>The cave smells of salt and decay. Water drips somewhere within.</p>`, options: [{ text: "Press deeper into the darkness", next: 99 } ], illustration: "dark-cave-entrance-dripping-water" },
            "40": { title: "Overgrown Shrine", content: `<p>Wildflowers grow thick around a small stone shrine. It feels ancient and neglected.</p>`, options: [{ text: "Examine the carvings (Intelligence Check - DC 11)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 } ], illustration: "overgrown-stone-shrine-wildflowers-close" },
            "41": { title: "Rocky Badlands", content: `<p>The green hills give way to cracked earth and jagged rock formations under a harsh sun.</p>`, options: [{ text: "Scout ahead", next: 99 } ], illustration: "rocky-badlands-cracked-earth-harsh-sun" },
            "70": { title: "Statue's Secret", content:"<p>Running your fingers over the mossy stone... found a Scout's Pouch!</p><p class='item-text'><em>Found Scout's Pouch! +40 XP.</em></p>", options: [{text:"Take the pouch and press on", next: 72}], illustration:"forest-clearing-mossy-statue-hidden-compartment", reward:{addItem: "Scout's Pouch", xp: 40}},
            "71": { title: "Just an Old Statue", content:"<p>Despite a careful examination, the statue appears to be just that – an old, weathered stone figure.</p>", options: [{text:"Ignore the statue and press on", next: 72}, { text: "Rest briefly in the clearing", next: 74}], illustration:"forest-clearing-mossy-statue-weathered-stone"},
            "72": { title: "Back to the Thicket", content:"<p>Leaving the clearing, you push back into the undergrowth, eventually relocating the main 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 offering (<i>{consumedItem}</i>) at the statue's base. You feel a subtle sense of approval.</p><p class='effect-text'><em>Gained 'Statue's Blessing' effect (+1 Wis temporarily).</em></p>", options: [{text:"Try to find the main path again", next: 72}], illustration:"forest-clearing-mossy-statue-offering", effects: [{name: "Statue's Blessing", duration: 3, mod: {wisdom: 1}}]},
            "74": { title: "Moment of Rest", content:"<p>You spend a quiet moment in reflection. The tranquility settles your nerves.</p><p class='effect-text'><em>Recovered 1 Sanity. Cleared 'Chilled' if present.</em></p>", options: [{text:"Press on", next: 72}], illustration:"forest-clearing-mossy-statue-offering", reward: {sanityGain: 1, clearEffect: "Chilled"} },
            "80": { title: "Across the Ravine", content:"<p>You make your way carefully across the swaying rope bridge.</p><p class="effect-text"><em>+25 XP.</em></p>", options: [{text:"Continue following the game trail", next: 14}], illustration:"character-crossing-rope-bridge-safely", reward:{xp:25}},
            "81": { title: "Bridge Collapse!", content:"<p>A rope snaps! The bridge lurches, sending you plunging into the ravine! You lose 10 HP.</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>You find a place where a fallen log provides a safer way across.</p>", options: [{text:"Cross the log bridge and continue", next: 14}], illustration:"fallen-log-crossing-ravine"},
            "190": { title: "Over the Rocks", content:"<p>With considerable effort, you manage to climb over the rockslide.</p><p class="effect-text"><em>+35 XP.</em></p>", options: [{text:"Continue up the path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} },
            "191": { title: "Climb Fails", content:"<p>The boulders are too unstable or sheer. You cannot climb them safely.</p>", options: [{text:"Search for another way around", next: 192}], illustration:"character-slipping-on-rockslide-boulders"},
            "192": { title: "Detour Found", content:"<p>After some searching, you find a rough path leading around the rockslide, eventually rejoining the main trail.</p>", options: [{text:"Continue up the path", next: 22}], illustration:"rough-detour-path-around-rockslide"},
            "21": { title: "Western Ridge", content:"<p>The ridge path is narrow and exposed, with strong winds threatening to push you off.</p>", options: [{text:"Proceed carefully (Dexterity Check - DC 14)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" },
            "22": { title: "Fortress Approach", content:"<p>You've navigated the treacherous paths and now stand near the outer walls of the dark fortress. Guards patrol the battlements.</p>", options: [{text:"Look for an unguarded entrance", next: 99}], illustration:"approaching-dark-fortress-walls-guards"},
            "211": {title:"Lost Balance", content:"<p>A strong gust of wind catches you off guard, sending you tumbling down a steep slope! You lose 10 HP.</p>", options:[{text:"Climb back up and find another way", next: 17}], illustration:"character-falling-off-windy-ridge", hpLoss: 10},
            "400": { title: "Shrine Insights", content:"<p>The carvings depict cycles of growth. You feel a sense of calm. (+1 HP)</p>", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close", reward: {hpGain: 1}},
            "401": { title: "Mysterious Carvings", content:"<p>The carvings are too worn to decipher.</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. The tranquility settles your nerves.</p>", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close"},
            "200": { title: "Shepherd's Greeting", content: "<p>You call out. The shepherd turns, leaning on their crook, and waves cautiously. 'Lost, traveler?' they call back, their voice surprisingly strong.</p>", options: [{text: "Ask for directions", next: 202}, {text: "Ask about the fortress", next: 203}], illustration: "rolling-green-hills-shepherd-close"},
            "201": { title: "Shepherd Ignores You", content: "<p>You call out, but the wind snatches your words away, or perhaps the shepherd simply chooses to ignore you, focusing on their flock.</p>", options: [{text: "Follow the narrow path further East", next: 4}], illustration: "rolling-green-hills-shepherd-distance"},
            "202": { title: "Directions Given", content: "<p>'The path eastward leads to the badlands,' the shepherd says, pointing. 'West takes you back to the crossroads eventually. North... only trouble lies north in those woods these days.'</p>", options: [{text: "Thank them and head East", next: 4}, {text: "Ask about the fortress", next: 203}], illustration: "rolling-green-hills-shepherd-close"},
            "203": { title: "Whispers of the Fortress", content: "<p>The shepherd lowers their voice. 'The Dark Lord's Keep? Aye, it looms over all. Few go near. Fewer return. They say there's a hidden way, though... something about the western ridge, if you've the stomach for heights.'</p><p class='effect-text'><em>Gained clue about Western Ridge. +10 XP.</em></p>", options: [{text: "Thank them and head East", next: 4}], illustration: "rolling-green-hills-shepherd-close", reward: {xp: 10}},
             "101": { title: "Caught!", content: `<p>You try to slip past or scare them, but stumble / fail to impress. You're forced to fight!</p>`, options: [ { text: "Fight the goblins!", next: 12 } ], illustration: "two-goblins-ambush-forest-path-spears" },
             "102": { title: "Intimidating Success", content: `<p>You let out a fearsome roar! The goblins, clearly not brave, hesitate, glance at each other, and scurry back into the undergrowth.</p><p class="effect-text"><em>Intimidated goblins! +35 XP.</em></p>`, options: [ { text: "Continue onward, heart pounding", next: 14 } ], illustration: "forest-path-scared-goblins-fleeing", reward: { xp: 35 } },
            "99": { title: "Game Over / To Be Continued...", content: "<p>Your adventure ends here (for now).</p>", options: [{ text: "Restart Adventure", next: 1 }], illustration: "game-over-generic", gameOver: true }
        };

        let gameState = {
            currentPageId: 1,
            previousPageId: 1,
            character: {
                name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
                level: 1, xp: 0, xpToNextLevel: 100,
                stats: { strength: 10, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 10, hp: 20, maxHp: 20, sanity: 10, maxSanity: 10 },
                inventory: [],
                effects: []
            }
        };

        function startGame() {
            const defaultChar = {
                name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
                level: 1, xp: 0, xpToNextLevel: 100,
                stats: { strength: 10, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 10, hp: 20, maxHp: 20, sanity: 10, maxSanity: 10 },
                inventory: [],
                effects: []
            };
            gameState = { currentPageId: 1, previousPageId: 1, character: JSON.parse(JSON.stringify(defaultChar)) };
            console.log("Starting new game state:", gameState);
            renderPage(gameState.currentPageId);
        }

        function applyEffect(effectData) {
            if (!gameState.character.effects.some(e => e.name === effectData.name)) {
                 gameState.character.effects.push({...effectData});
                 console.log(`Applied effect: ${effectData.name}`);
                 return `<p class="effect-text"><em>Gained effect: ${effectData.name}</em></p>`;
            } else {
                 console.log(`Effect ${effectData.name} already active.`);
                 return "";
            }
        }

        function clearEffect(effectName) {
             const initialLength = gameState.character.effects.length;
             gameState.character.effects = gameState.character.effects.filter(e => e.name !== effectName);
             if (gameState.character.effects.length < initialLength) {
                 console.log(`Cleared effect: ${effectName}`);
                 return `<p class="effect-text"><em>Effect Cleared: ${effectName}</em></p>`;
             }
             return "";
        }

         function tickEffects() {
             let effectsClearedMessage = "";
             gameState.character.effects = gameState.character.effects.filter(effect => {
                 if (effect.duration !== undefined) {
                     effect.duration -= 1;
                     if (effect.duration <= 0) {
                         console.log(`Effect expired: ${effect.name}`);
                         effectsClearedMessage += `<p class="effect-text"><em>Effect Expired: ${effect.name}</em></p>`;
                         return false;
                     }
                 }
                 return true;
             });
             return effectsClearedMessage;
         }

         function getStatModifier(statName) {
             let modifier = 0;
             gameState.character.effects.forEach(effect => {
                 if (effect.mod && effect.mod[statName]) {
                     modifier += effect.mod[statName];
                 }
             });
             return modifier;
         }

          function getEffectiveStat(statName) {
              return (gameState.character.stats[statName] || 0) + getStatModifier(statName);
          }

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

            message += tickEffects();

             if (choiceData.nextPage === 1 && (gameState.currentPageId === 99 || gameData[gameState.currentPageId]?.gameOver)) {
                console.log("Restarting game...");
                startGame();
                return;
            }

            let consumedItemName = null;
            if (choiceData.consumeItem) {
                let itemToRemove = choiceData.requireItem;
                if (choiceData.requireItemType) {
                    itemToRemove = gameState.character.inventory.find(itemName => {
                         const itemDef = itemsData[itemName];
                         if (choiceData.requireItemType === 'non-quest') {
                            return itemDef && itemDef.type !== 'quest';
                         }
                         if (choiceData.requireItemType === 'consumable') {
                            return itemDef && itemDef.type === 'consumable';
                         }
                         return false;
                    });
                }

                if (itemToRemove && gameState.character.inventory.includes(itemToRemove)) {
                    gameState.character.inventory = gameState.character.inventory.filter(i => i !== itemToRemove);
                    consumedItemName = itemToRemove;
                    console.log(`Consumed item: ${consumedItemName}`);
                     message += `<p class="item-text"><em>Used: ${consumedItemName}</em></p>`;
                } else {
                     console.error("Attempted to consume an item that wasn't required or available:", choiceData);
                     renderPageInternal(gameState.currentPageId, gameData[gameState.currentPageId], "<p style='color:red;'>Error: Tried to use an unavailable item.</p>");
                     return;
                 }
            }

            const optionNextPageId = parseInt(choiceData.nextPage);
            let nextPageId = optionNextPageId;
            const check = choiceData.check;

            if (isNaN(nextPageId) && !check) {
                console.error("Invalid choice data (no nextPage or check):", choiceData);
                renderPageInternal(99, gameData[99], `<p style="color:red;">Error: Invalid choice data!</p>`);
                return;
            }

            if (check) {
                const baseStatValue = gameState.character.stats[check.stat] || 10;
                const modifierFromEffects = getStatModifier(check.stat);
                const effectiveStatValue = baseStatValue + modifierFromEffects;
                const roll = Math.floor(Math.random() * 20) + 1;
                const totalResult = roll + Math.floor((effectiveStatValue - 10) / 2);
                const dc = check.dc;
                console.log(`Check: ${check.stat} (Base: ${baseStatValue}, Effects: ${modifierFromEffects}, Eff: ${effectiveStatValue}, Mod: ${Math.floor((effectiveStatValue - 10) / 2)}) | Roll: ${roll} -> Total: ${totalResult} vs DC ${dc}`);

                if (totalResult >= dc) {
                    nextPageId = optionNextPageId;
                    message += `<p class="roll-success"><em>${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Success! (${totalResult} vs DC ${dc})</em></p>`;

                    const statToIncrease = check.stat;
                    if (gameState.character.stats.hasOwnProperty(statToIncrease)) {
                        const oldValue = gameState.character.stats[statToIncrease];
                        gameState.character.stats[statToIncrease]++;
                        const statCap = 20;
                        gameState.character.stats[statToIncrease] = Math.min(statCap, gameState.character.stats[statToIncrease]);

                        if (gameState.character.stats[statToIncrease] > oldValue) {
                             console.log(`${statToIncrease} increased by 1. New value: ${gameState.character.stats[statToIncrease]}`);
                             message += `<p class="stat-increase-text"><em>Your ${statToIncrease} improved! (+1)</em></p>`;

                            if (statToIncrease === 'constitution') {
                                recalculateMaxHp();
                                 const oldMod = Math.floor(((gameState.character.stats.constitution -1) - 10) / 2);
                                 const newMod = Math.floor((gameState.character.stats.constitution - 10) / 2);
                                 if (newMod > oldMod) {
                                     const hpGain = (newMod - oldMod) * gameState.character.level;
                                     gameState.character.stats.hp += hpGain;
                                     message += `<p class="effect-text"><em>Increased vitality! (+${hpGain} HP)</em></p>`;
                                 }
                            }
                            if (statToIncrease === 'wisdom') {
                                 recalculateMaxSanity();
                            }
                        } else {
                            console.log(`${statToIncrease} already at cap (${statCap}).`);
                        }
                    }

                } else {
                    nextPageId = parseInt(check.onFailure);
                    message += `<p class="roll-failure"><em>${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Failed! (${totalResult} vs DC ${dc})</em></p>`;
                    if (isNaN(nextPageId)) {
                        console.error("Invalid onFailure ID:", check.onFailure);
                        nextPageId = 99;
                        message += `<p style="color:red;">Error: Invalid failure path ID!</p>`;
                    }
                }
            }

            const targetPageData = gameData[nextPageId];

            if (!targetPageData) {
                console.error(`Data for page ${nextPageId} not found!`);
                renderPageInternal(99, gameData[99], message + `<p style="color:red;">Error: Page data for ${nextPageId} missing!</p>`);
                return;
            }

             let hpLostThisTurn = 0;
             let sanityLostThisTurn = 0;

             if (targetPageData.effects) {
                 targetPageData.effects.forEach(effect => message += applyEffect(effect));
             }

             if (targetPageData.hpLoss) {
                hpLostThisTurn = targetPageData.hpLoss;
                gameState.character.stats.hp -= hpLostThisTurn;
                console.log(`Lost ${hpLostThisTurn} HP.`);
             }
             if (targetPageData.sanityLoss) {
                 sanityLostThisTurn = targetPageData.sanityLoss;
                 gameState.character.stats.sanity -= sanityLostThisTurn;
                 console.log(`Lost ${sanityLostThisTurn} Sanity.`);
                 message += `<p class="effect-text"><em>Your resolve wavers... (-${sanityLostThisTurn} Sanity)</em></p>`;
             }

             if (targetPageData.reward) {
                 if (targetPageData.reward.hpGain) {
                     const hpGained = targetPageData.reward.hpGain;
                     gameState.character.stats.hp += hpGained;
                     console.log(`Gained ${hpGained} HP.`);
                 }
                 if (targetPageData.reward.sanityGain) {
                     const sanityGained = targetPageData.reward.sanityGain;
                     gameState.character.stats.sanity += sanityGained;
                     console.log(`Gained ${sanityGained} Sanity.`);
                     message += `<p class="effect-text"><em>You feel more composed. (+${sanityGained} Sanity)</em></p>`;
                 }
                 if (targetPageData.reward.xp) {
                    gameState.character.xp += targetPageData.reward.xp;
                    console.log(`Gained ${targetPageData.reward.xp} XP! Total: ${gameState.character.xp}`);
                     message += `<p class="effect-text"><em>Gained ${targetPageData.reward.xp} XP.</em></p>`;
                 }
                 if (targetPageData.reward.addItem) {
                     const itemsToAdd = Array.isArray(targetPageData.reward.addItem) ? targetPageData.reward.addItem : [targetPageData.reward.addItem];
                     itemsToAdd.forEach(itemName => {
                         if (itemsData[itemName]) {
                              if (!gameState.character.inventory.includes(itemName)) {
                                 gameState.character.inventory.push(itemName);
                                 console.log(`Found item via reward: ${itemName}`);
                                 message += `<p class="item-text"><em>Item acquired: ${itemName}</em></p>`;
                              } else {
                                   console.log(`Already had item: ${itemName}. Not adding duplicate.`);
                              }
                         } else {
                             console.warn(`Attempted to add unknown item from reward: ${itemName}`);
                             message += `<p style="color:orange;">Warning: Tried to add unknown reward item '${itemName}'.</p>`;
                         }
                     });
                 }
                 if (targetPageData.reward.clearEffect) {
                    message += clearEffect(targetPageData.reward.clearEffect);
                 }
            }

             gameState.character.stats.hp = Math.max(0, Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp));
             gameState.character.stats.sanity = Math.max(0, Math.min(gameState.character.stats.sanity, gameState.character.stats.maxSanity));


            if (gameState.character.stats.hp <= 0) {
                console.log("Player died!");
                nextPageId = 99;
                message += `<p style="color:red; font-weight:bold;"><em>You have succumbed to your injuries!${hpLostThisTurn > 0 ? ` (-${hpLostThisTurn} HP)` : ''}</em></p>`;
                renderPageInternal(nextPageId, gameData[nextPageId], message);
                return;
            }
             if (gameState.character.stats.sanity <= 0) {
                 console.log("Player sanity broke!");
                 nextPageId = 99;
                 message += `<p style="color:purple; font-weight:bold;"><em>Your mind shatters under the strain!${sanityLostThisTurn > 0 ? ` (-${sanityLostThisTurn} Sanity)`: ''}</em></p>`;
                 renderPageInternal(nextPageId, gameData[nextPageId], message);
                 return;
             }

            gameState.previousPageId = gameState.currentPageId;
            gameState.currentPageId = nextPageId;

            console.log("Transitioning to page:", nextPageId);
            let pageContent = targetPageData.content || "<p>...</p>";
            if (consumedItemName) {
                 pageContent = pageContent.replace('{consumedItem}', consumedItemName);
            }

            renderPageInternal(nextPageId, gameData[nextPageId], message, pageContent);
        }

        function recalculateMaxHp() {
            const baseHpPerLevel = 8;
            const conModifier = Math.floor((getEffectiveStat('constitution') - 10) / 2);
            gameState.character.stats.maxHp = 12 + (gameState.character.level * (baseHpPerLevel + conModifier));
             gameState.character.stats.maxHp = Math.max(1, gameState.character.stats.maxHp);
            console.log(`Max HP recalculated: ${gameState.character.stats.maxHp}`);
             gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp);
        }
         function recalculateMaxSanity() {
             const wisModifier = Math.floor((getEffectiveStat('wisdom') - 10) / 2);
             gameState.character.stats.maxSanity = 10 + wisModifier;
             gameState.character.stats.maxSanity = Math.max(1, gameState.character.stats.maxSanity);
             console.log(`Max Sanity recalculated: ${gameState.character.stats.maxSanity}`);
             gameState.character.stats.sanity = Math.min(gameState.character.stats.sanity, gameState.character.stats.maxSanity);
         }

         function renderPageInternal(pageId, pageData, message = "", contentOverride = null) {
             if (!pageData) {
                 console.error(`Render Error: No data for page ${pageId}! Falling back to page 99.`);
                 pageData = gameData[99];
                 message += `<p style="color:red;">Render Error: Data for page ${pageId} not found!</p>`;
                 pageId = 99;
             }

             console.log(`Rendering page ${pageId}`);
             storyTitleElement.textContent = pageData.title || "Untitled Page";
             storyContentElement.innerHTML = message + (contentOverride || pageData.content || "<p>...</p>");

             updateStatsDisplay();
             updateEffectsDisplay();
             updateInventoryDisplay();
             choicesElement.innerHTML = '';

             if (pageData.options && pageData.options.length > 0) {
                 pageData.options.forEach(option => {
                     const button = document.createElement('button');
                     button.classList.add('choice-button');
                     button.textContent = option.text;
                     let requirementMet = true;
                     let requirementText = [];

                     if (option.requireItem) {
                         if (!gameState.character.inventory.includes(option.requireItem)) {
                             requirementMet = false;
                             requirementText.push(`Requires: ${option.requireItem}`);
                         }
                     }
                     if (option.requireItemType && requirementMet) {
                         const hasItemOfType = gameState.character.inventory.some(itemName => {
                             const itemDef = itemsData[itemName];
                             if (option.requireItemType === 'non-quest') {
                                return itemDef && itemDef.type !== 'quest';
                             }
                              if (option.requireItemType === 'consumable') {
                                 return itemDef && itemDef.type === 'consumable';
                              }
                             return false;
                         });
                         if (!hasItemOfType) {
                             requirementMet = false;
                             requirementText.push(`Requires: ${option.requireItemType} item`);
                         }
                     }

                     button.disabled = !requirementMet;
                     if (!requirementMet) {
                         button.title = requirementText.join(', ');
                     } else {
                         const choiceData = {
                             nextPage: option.next,
                             check: option.check,
                             addItem: option.addItem,
                             requireItem: option.requireItem,
                             requireItemType: option.requireItemType,
                             consumeItem: option.consumeItem,
                         };
                         button.onclick = () => handleChoiceClick(choiceData);
                     }
                     choicesElement.appendChild(button);
                 });
             } else {
                 const button = document.createElement('button');
                 button.classList.add('choice-button');
                 button.textContent = (pageData.gameOver || pageId === 99) ? "Restart Adventure" : "The End (Restart?)";
                 button.onclick = () => handleChoiceClick({ nextPage: 1 });
                 choicesElement.appendChild(button);
                 if (!pageData.gameOver && pageId !== 99) {
                     choicesElement.insertAdjacentHTML('afterbegin', '<p><i>The path ends here...</i></p>');
                 }
             }
             updateScene(pageData.illustration || 'default');
         }

        function renderPage(pageId) {
            renderPageInternal(pageId, gameData[pageId]);
        }

        function updateStatsDisplay() {
            const char = gameState.character;
             const hpColor = char.stats.hp / char.stats.maxHp < 0.3 ? 'style="color:#f99;"' : (char.stats.hp / char.stats.maxHp < 0.6 ? 'style="color:#fd5;"' : '');
             const sanityColor = char.stats.sanity / char.stats.maxSanity < 0.3 ? 'style="color:#c9f;"' : (char.stats.sanity / char.stats.maxSanity < 0.6 ? 'style="color:#daf;"' : '');

            let statsHtml = `<strong>Stats:</strong> <span>Lvl: ${char.level}</span> <span>XP: ${char.xp}/${char.xpToNextLevel}</span> <span ${hpColor}>HP: ${char.stats.hp}/${char.stats.maxHp}</span> <span ${sanityColor}>San: ${char.stats.sanity}/${char.stats.maxSanity}</span> `;
             ['strength', 'intelligence', 'wisdom', 'dexterity', 'constitution', 'charisma'].forEach(stat => {
                 const base = char.stats[stat];
                 const mod = getStatModifier(stat);
                 const effective = base + mod;
                 let display = `${effective}`;
                 if (mod !== 0) {
                     display += ` (${base}${mod > 0 ? '+' : ''}${mod})`;
                 }
                 statsHtml += `<span>${stat.substring(0,3).toUpperCase()}: ${display}</span> `;
             });
            statsElement.innerHTML = statsHtml;
        }

         function updateEffectsDisplay() {
             let h = '<strong>Effects:</strong> ';
             if (gameState.character.effects.length === 0) {
                 h += '<em>None</em>';
             } else {
                 gameState.character.effects.forEach(effect => {
                     const durationText = effect.duration !== undefined ? ` (${effect.duration} turns)` : '';
                     let effectClass = 'effect-neutral';
                     if (effect.mod) {
                         const isBuff = Object.values(effect.mod).some(val => val > 0);
                         const isDebuff = Object.values(effect.mod).some(val => val < 0);
                         if (isBuff && !isDebuff) effectClass = 'effect-buff';
                         else if (isDebuff && !isBuff) effectClass = 'effect-debuff';
                     }
                     const modDesc = effect.mod ? Object.entries(effect.mod).map(([key, val]) => `${key} ${val > 0 ? '+' : ''}${val}`).join(', ') : 'No stat change';
                     h += `<span class="${effectClass}" title="${modDesc}">${effect.name}${durationText}</span>`;
                 });
             }
             effectsElement.innerHTML = h;
         }

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

        function updateScene(illustrationKey) {
            if (!scene) return;

            if (currentAssemblyGroup) {
                currentAssemblyGroup.traverse(child => {
                    if (child.isMesh) {
                        child.geometry.dispose();
                    }
                });
                scene.remove(currentAssemblyGroup);
                currentAssemblyGroup = null;
            }
             currentLights.forEach(light => {
                 if (light !== scene.children.find(c => c.isAmbientLight)) {
                     scene.remove(light);
                     if (light.dispose) light.dispose();
                 }
             });
             currentLights = [scene.children.find(c => c.isAmbientLight)];

             scene.fog = null;
             currentFog = null;

            camera.position.set(0, 3, 8);
            camera.lookAt(0, 1, 0);

            let assemblyFunction;
            let fogSettings = { type: 'none' };
            let background = new THREE.Color(0x1a1a1a);

            switch (illustrationKey) {
                case 'crossroads-signpost-sunny':
                    assemblyFunction = createCrossroadsAssembly;
                    fogSettings = { type: 'linear', color: 0xB0E0E6, near: 10, far: 35 };
                     background = new THREE.Color(0xADD8E6);
                     camera.position.set(0, 3, 10);
                     camera.lookAt(0, 1, 0);
                    break;
                 case 'rolling-green-hills-shepherd-distance':
                 case 'rolling-green-hills-shepherd-close':
                     assemblyFunction = createRollingHillsAssembly;
                     fogSettings = { type: 'exp2', color: 0xD0F0C0, density: 0.02 };
                     background = new THREE.Color(0xACE1AF);
                     camera.position.set(0, 5, 18);
                     camera.lookAt(0, 1, -5);
                     break;
                 case 'windy-sea-cliffs-crashing-waves-path-down':
                 case 'scanning-sea-cliffs-no-other-paths-visible':
                 case 'close-up-handholds-carved-in-cliff-face':
                     assemblyFunction = createCoastalCliffsAssembly;
                     fogSettings = { type: 'linear', color: 0x778899, near: 5, far: 50 };
                     background = new THREE.Color(0x87CEFA);
                     camera.position.set(6, 6, 12);
                     camera.lookAt(-2, 1, -5);
                     break;
                 case 'dark-forest-entrance-gnarled-roots-filtered-light':
                     assemblyFunction = createForestEntranceAssembly;
                     fogSettings = { type: 'exp2', color: 0x1A2A1A, density: 0.08 };
                     background = new THREE.Color(0x112211);
                     camera.position.set(0, 2, 7);
                     camera.lookAt(0, 1, 0);
                     break;
                case 'overgrown-forest-path-glowing-fungi-vines':
                case 'two-goblins-ambush-forest-path-spears':
                case 'forest-shadows-hiding-goblins-walking-past':
                case 'defeated-goblins-forest-path-loot':
                case 'blurred-motion-running-past-goblins-forest':
                case 'forest-path-scared-goblins-fleeing':
                    assemblyFunction = createOvergrownPathAssembly;
                    if (illustrationKey.includes('goblin')) {
                        assemblyFunction = createGoblinAmbushAssembly;
                    }
                    fogSettings = { type: 'exp2', color: 0x182820, density: 0.1 };
                    background = new THREE.Color(0x0a1810);
                    camera.position.set(0, 1.8, 6);
                    camera.lookAt(0, 0.8, 0);
                    break;
                 case 'forest-clearing-mossy-statue-weathered-stone':
                 case 'forest-clearing-mossy-statue-hidden-compartment':
                 case 'forest-clearing-mossy-statue-offering':
                     assemblyFunction = createClearingStatueAssembly;
                     fogSettings = { type: 'linear', color: 0x3A5F3A, near: 5, far: 30 };
                     background = new THREE.Color(0x2A4F2A);
                     camera.position.set(0, 2.5, 7);
                     camera.lookAt(0, 1, 0);
                     break;
                 case 'hidden-cove-beach-dark-cave-entrance':
                 case 'character-fallen-at-bottom-of-cliff-path-cove':
                     assemblyFunction = createHiddenCoveAssembly;
                     fogSettings = { type: 'linear', color: 0x6688AA, near: 8, far: 40 };
                     background = new THREE.Color(0x7799BB);
                     camera.position.set(0, 3, 10);
                     camera.lookAt(0, 1, -2);
                     break;
                 case 'dark-cave-entrance-dripping-water':
                     assemblyFunction = createDarkCaveAssembly;
                     fogSettings = { type: 'exp2', color: 0x050508, density: 0.15 };
                     background = new THREE.Color(0x000000);
                     camera.position.set(0, 1.5, 5);
                     camera.lookAt(0, 1, 0);
                     break;
                 case 'game-over': case 'game-over-generic':
                     assemblyFunction = createGameOverAssembly;
                     fogSettings = { type: 'exp2', color: 0x330000, density: 0.05 };
                     background = new THREE.Color(0x220000);
                     break;
                 case 'error':
                     assemblyFunction = createErrorAssembly;
                     fogSettings = { type: 'linear', color: 0x886600, near: 2, far: 15 };
                     background = new THREE.Color(0x553300);
                     break;
                case 'hilltop-view-overgrown-shrine-wildflowers': assemblyFunction = createRollingHillsAssembly; fogSettings = { type: 'exp2', color: 0xD0F0C0, density: 0.02 }; background = new THREE.Color(0xACE1AF); camera.position.set(0, 5, 15); camera.lookAt(0, 1, -5); break;
                case 'character-splashing-into-stream-from-log':
                case 'forest-stream-crossing-dappled-sunlight-stones':
                case 'mossy-log-bridge-over-forest-stream': assemblyFunction = createForestAssembly; fogSettings = { type: 'exp2', color: 0x668866, density: 0.06 }; background = new THREE.Color(0x557755); camera.position.set(0, 2, 6); camera.lookAt(0, 0.5, 0); break;
                case 'forest-edge-view-rocky-foothills-distant-mountain-fortress': assemblyFunction = createForestEdgeAssembly; fogSettings = { type: 'linear', color: 0xAAAAAA, near: 10, far: 40 }; background = new THREE.Color(0xB0B0B0); camera.position.set(0, 3, 10); camera.lookAt(0, 1, -5); break;
                case 'climbing-rocky-foothills-path-fortress-closer':
                case 'zoomed-view-mountain-fortress-western-ridge':
                case 'rockslide-blocking-mountain-path-boulders':
                case 'narrow-goat-trail-mountainside-fortress-view':
                case 'character-climbing-over-boulders':
                case 'character-slipping-on-rockslide-boulders':
                case 'rough-detour-path-around-rockslide':
                case 'narrow-windy-mountain-ridge-path':
                case 'approaching-dark-fortress-walls-guards':
                case 'character-falling-off-windy-ridge':
                case 'rocky-badlands-cracked-earth-harsh-sun':
                case 'pushing-through-forest-undergrowth':
                case 'narrow-game-trail-forest-rope-bridge-ravine':
                case 'character-crossing-rope-bridge-safely':
                case 'rope-bridge-snapping-character-falling':
                case 'fallen-log-crossing-ravine':
                     assemblyFunction = createDefaultAssembly;
                     console.warn(`Using default assembly for illustration key: ${illustrationKey}`);
                     fogSettings = { type: 'linear', color: 0xAAAAAA, near: 5, far: 25 };
                     background = new THREE.Color(0x999999);
                     break;
                default:
                    console.warn(`Unknown illustration key: "${illustrationKey}". Using default assembly.`);
                    assemblyFunction = createDefaultAssembly;
                     fogSettings = { type: 'linear', color: 0xAAAAAA, near: 5, far: 25 };
                     background = new THREE.Color(0x999999);
                    break;
            }

             if (fogSettings.type === 'linear') {
                 scene.fog = new THREE.Fog(fogSettings.color, fogSettings.near, fogSettings.far);
             } else if (fogSettings.type === 'exp2') {
                 scene.fog = new THREE.FogExp2(fogSettings.color, fogSettings.density);
                  scene.fog.userData = { baseDensity: fogSettings.density };
             }
             currentFog = scene.fog;
             scene.background = background;


            try {
                currentAssemblyGroup = assemblyFunction();
                if (currentAssemblyGroup && currentAssemblyGroup.isGroup) {
                    scene.add(currentAssemblyGroup);
                    adjustLighting(illustrationKey);
                } else {
                    throw new Error("Assembly function failed to return a valid THREE.Group");
                }
            } catch (error) {
                console.error(`Error creating assembly for ${illustrationKey}:`, error);
                if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); }
                currentAssemblyGroup = createErrorAssembly();
                scene.add(currentAssemblyGroup);
                adjustLighting('error');
            }
        }

        function adjustLighting(illustrationKey) {
            if (!scene) return;
             const ambient = currentLights[0];
             if (!ambient || !ambient.isAmbientLight) {
                 console.error("Ambient light not found or invalid!");
                  if (!ambient) {
                     const newAmbient = new THREE.AmbientLight(0xffffff, 0.2);
                     scene.add(newAmbient);
                     currentLights[0] = newAmbient;
                      console.warn("Recreated missing ambient light.");
                 }
                  return;
             }

            let dirLight = null;
            let hemiLight = null;

             ambient.intensity = 0.2;
             let dirIntensity = 0.8;
             let dirColor = 0xffffff;
             let dirPosition = new THREE.Vector3(10, 15, 8);
             let hemiSkyColor = 0xB1E1FF;
             let hemiGroundColor = 0xB97A20;
             let hemiIntensity = 0.3;


            switch (illustrationKey) {
                case 'crossroads-signpost-sunny':
                    ambient.intensity = 0.4;
                    dirIntensity = 1.2;
                    dirColor = 0xFFF8DC;
                    dirPosition = new THREE.Vector3(15, 20, 10);
                     hemiSkyColor = 0xFFE4B5;
                     hemiGroundColor = 0xCD853F;
                     hemiIntensity = 0.5;
                    break;

                 case 'dark-forest-entrance-gnarled-roots-filtered-light':
                 case 'overgrown-forest-path-glowing-fungi-vines':
                 case 'forest-clearing-mossy-statue-weathered-stone':
                    ambient.intensity = 0.15;
                    dirIntensity = 0.5;
                    dirColor = 0x98FB98;
                    dirPosition = new THREE.Vector3(5, 10, 5);
                     dirLight = new THREE.DirectionalLight(dirColor, dirIntensity);
                     dirLight.shadow.bias = -0.001;
                     dirLight.position.copy(dirPosition);
                     hemiSkyColor = 0xADD8E6;
                     hemiGroundColor = 0x4F4F2F;
                     hemiIntensity = 0.4;
                    break;
                 case 'two-goblins-ambush-forest-path-spears':
                     ambient.intensity = 0.1;
                     dirIntensity = 0.4;
                     dirColor = 0x9ACD32;
                     dirPosition = new THREE.Vector3(3, 8, 6);
                     hemiSkyColor = 0xA0B0A0;
                     hemiGroundColor = 0x404020;
                     hemiIntensity = 0.3;
                     break;

                 case 'dark-cave-entrance-dripping-water':
                     ambient.intensity = 0.05;
                     dirIntensity = 0;
                     hemiSkyColor = 0x445577;
                     hemiGroundColor = 0x333344;
                     hemiIntensity = 0.2;
                     break;

                 case 'game-over': case 'game-over-generic':
                     ambient.intensity = 0.1;
                     dirIntensity = 0.5;
                     dirColor = 0xFF6347;
                     dirPosition = new THREE.Vector3(0, 10, -5);
                     hemiSkyColor = 0x8B0000;
                     hemiGroundColor = 0x400000;
                     hemiIntensity = 0.4;
                     break;
                case 'error':
                     ambient.intensity = 0.2;
                     dirIntensity = 0.7;
                     dirColor = 0xFFA500;
                     hemiSkyColor = 0xFFD700;
                     hemiGroundColor = 0x8B4513;
                     hemiIntensity = 0.5;
                    break;

                default:
                    ambient.intensity = 0.3;
                    dirIntensity = 1.0;
                    dirColor = 0xffffff;
                    dirPosition = new THREE.Vector3(8, 15, 10);
                    hemiSkyColor = 0xB1E1FF;
                    hemiGroundColor = 0xB97A20;
                    hemiIntensity = 0.4;
            }

             if (dirIntensity > 0 && !dirLight) {
                 dirLight = new THREE.DirectionalLight(dirColor, dirIntensity);
                 dirLight.position.copy(dirPosition);
             }
             if(dirLight){
                dirLight.castShadow = true;
                dirLight.shadow.mapSize.width = 1024;
                dirLight.shadow.mapSize.height = 1024;
                dirLight.shadow.camera.near = 0.5;
                dirLight.shadow.camera.far = 50;
                const shadowBounds = 20;
                dirLight.shadow.camera.left = -shadowBounds;
                dirLight.shadow.camera.right = shadowBounds;
                dirLight.shadow.camera.top = shadowBounds;
                dirLight.shadow.camera.bottom = -shadowBounds;
                dirLight.shadow.bias = -0.0005;

                scene.add(dirLight);
                currentLights.push(dirLight);

            }

             if (hemiIntensity > 0) {
                 hemiLight = new THREE.HemisphereLight(hemiSkyColor, hemiGroundColor, hemiIntensity);
                 scene.add(hemiLight);
                 currentLights.push(hemiLight);
             }

             currentAssemblyGroup?.traverse(child => {
                if (child.isPointLight) {
                    currentLights.push(child);
                     child.castShadow = true;
                     child.shadow.mapSize.width = 512;
                     child.shadow.mapSize.height = 512;
                     child.shadow.bias = -0.005;
                 }
             });

        }

        document.addEventListener('DOMContentLoaded', () => {
            console.log("DOM Ready - Initializing Enhanced Adventure.");
            try {
                initThreeJS();
                 if (!scene || !camera || !renderer) {
                    throw new Error("Three.js core component initialization failed.");
                 }
                startGame();
                console.log("Game started.");
            } catch (error) {
                console.error("Initialization failed:", error);
                storyTitleElement.textContent = "Error During Initialization";
                storyContentElement.innerHTML = `<p>Could not start the adventure. Please check the developer console (F12) for more details.</p><pre>${error.stack || error}</pre>`;
                 choicesElement.innerHTML = '';
                 if(sceneContainer) sceneContainer.innerHTML = '<p style="color:red; padding: 20px;">3D Scene Failed to Load</p>';
            }
        });
    </script>
</body>
</html>