File size: 63,283 Bytes
20526ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Isekai RPG Adventure</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=MedievalSharp&family=Roboto:wght@300;400;500&display=swap');
        
        :root {
            --primary: #4a5568;
            --secondary: #2d3748;
            --accent: #d69e2e;
            --text: #e2e8f0;
            --dark: #1a202c;
        }
        
        body {
            font-family: 'Roboto', sans-serif;
            background-color: var(--dark);
            color: var(--text);
            overflow: hidden;
        }
        
        .medieval {
            font-family: 'MedievalSharp', cursive;
        }
        
        .scrollbar-custom::-webkit-scrollbar {
            width: 8px;
        }
        
        .scrollbar-custom::-webkit-scrollbar-track {
            background: #2d3748;
        }
        
        .scrollbar-custom::-webkit-scrollbar-thumb {
            background: #4a5568;
            border-radius: 4px;
        }
        
        .scrollbar-custom::-webkit-scrollbar-thumb:hover {
            background: #718096;
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .parchment {
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23f7fafc" opacity="0.1"/><path d="M0,0 L100,0 L100,100 L0,100 Z" fill="none" stroke="%23d69e2e" stroke-width="2"/></svg>');
            background-size: 100% 100%;
            border: 1px solid #d69e2e;
            box-shadow: 0 0 15px rgba(214, 158, 46, 0.3);
        }
        
        .health-bar {
            background: linear-gradient(to right, #e53e3e, #c53030);
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .mana-bar {
            background: linear-gradient(to right, #4299e1, #3182ce);
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .xp-bar {
            background: linear-gradient(to right, #48bb78, #38a169);
            height: 100%;
            transition: width 0.3s ease;
        }
        
        .typewriter {
            overflow: hidden;
            border-right: 2px solid var(--accent);
            white-space: pre-wrap;
            margin: 0 auto;
            letter-spacing: 0.15em;
            animation: typing 3.5s steps(40, end), blink-caret 0.75s step-end infinite;
        }
        
        @keyframes typing {
            from { width: 0 }
            to { width: 100% }
        }
        
        @keyframes blink-caret {
            from, to { border-color: transparent }
            50% { border-color: var(--accent) }
        }
        
        .loading-spinner {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 3px solid #d69e2e;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .notification {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem;
            background-color: #38a169;
            color: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            z-index: 50;
            animation: slideIn 0.5s forwards, fadeOut 0.5s 2.5s forwards;
        }
        
        @keyframes slideIn {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }
        
        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }
        
        .equipped-item {
            border: 2px solid #d69e2e;
            box-shadow: 0 0 10px rgba(214, 158, 46, 0.5);
        }
        
        .skill-progress {
            height: 4px;
            background-color: #4a5568;
            border-radius: 2px;
            margin-top: 2px;
        }
        
        .skill-progress-bar {
            height: 100%;
            background-color: #d69e2e;
            border-radius: 2px;
            transition: width 0.3s ease;
        }
        
        /* Button click animation */
        .btn-click {
            transition: transform 0.1s ease, background-color 0.3s ease;
        }
        
        .btn-click:active {
            transform: scale(0.95);
        }
        
        /* Disabled button styling */
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        /* Chat message styling */
        .chat-message {
            max-width: 80%;
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            border-radius: 0.5rem;
            word-wrap: break-word;
        }
        
        .player-message {
            background-color: #2d3748;
            border-left: 3px solid #d69e2e;
            margin-left: auto;
            margin-right: 0;
        }
        
        .npc-message {
            background-color: #2d3748;
            border-left: 3px solid #4299e1;
            margin-right: auto;
            margin-left: 0;
        }
        
        .system-message {
            background-color: #2d3748;
            border-left: 3px solid #48bb78;
            margin-right: auto;
            margin-left: 0;
            font-style: italic;
        }
        
        /* Dropdown menu */
        .dropdown-menu {
            position: absolute;
            right: 0;
            top: 100%;
            background-color: #2d3748;
            border: 1px solid #4a5568;
            border-radius: 0.25rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            z-index: 100;
            min-width: 150px;
            display: none;
        }
        
        .dropdown-menu.show {
            display: block;
        }
        
        .dropdown-item {
            padding: 0.5rem 1rem;
            color: #e2e8f0;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .dropdown-item:hover {
            background-color: #4a5568;
        }
        
        .dropdown-divider {
            height: 1px;
            background-color: #4a5568;
            margin: 0.25rem 0;
        }
    </style>
</head>
<body class="h-screen flex flex-col">
    <!-- Game Header -->
    <header class="bg-gray-900 text-yellow-500 p-4 flex justify-between items-center border-b border-yellow-700">
        <div class="flex items-center space-x-4">
            <h1 class="text-2xl font-bold medieval">Isekai RPG Adventure</h1>
        </div>
        <div class="flex items-center space-x-4 relative">
            <div class="relative">
                <button id="menuBtn" class="text-yellow-400 hover:text-yellow-300 btn-click">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <div id="menuDropdown" class="dropdown-menu">
                    <div class="dropdown-item" id="newGameOption">
                        <i class="fas fa-plus mr-2"></i> New Game
                    </div>
                    <div class="dropdown-item" id="saveOption">
                        <i class="fas fa-save mr-2"></i> Save Game
                    </div>
                    <div class="dropdown-item" id="loadOption">
                        <i class="fas fa-folder-open mr-2"></i> Load Game
                    </div>
                    <div class="dropdown-divider"></div>
                    <div class="dropdown-item" id="settingsOption">
                        <i class="fas fa-cog mr-2"></i> Settings
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Game Container -->
    <div class="flex flex-1 overflow-hidden">
        <!-- Left Panel - Character Stats -->
        <div class="w-64 bg-gray-800 p-4 flex flex-col border-r border-gray-700">
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Character</h2>
                <div class="flex items-center mb-4">
                    <div class="w-16 h-16 rounded-full bg-gray-700 border-2 border-yellow-500 flex items-center justify-center">
                        <i class="fas fa-user text-3xl text-yellow-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="font-bold" id="charName">Sir Aldric</p>
                        <p class="text-sm text-gray-400" id="charClass">Knight</p>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="flex justify-between text-sm mb-1">
                        <span>Level <span id="charLevel">5</span></span>
                        <span>XP: <span id="charXP">1200</span>/<span id="charNextLevel">2000</span></span>
                    </div>
                    <div class="h-2 bg-gray-700 rounded-full overflow-hidden">
                        <div id="xpBar" class="xp-bar" style="width: 60%"></div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="flex justify-between text-sm mb-1">
                        <span>Health</span>
                        <span><span id="charHealth">75</span>/<span id="charMaxHealth">100</span></span>
                    </div>
                    <div class="h-2 bg-gray-700 rounded-full overflow-hidden">
                        <div id="healthBar" class="health-bar" style="width: 75%"></div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="flex justify-between text-sm mb-1">
                        <span>Mana</span>
                        <span><span id="charMana">40</span>/<span id="charMaxMana">60</span></span>
                    </div>
                    <div class="h-2 bg-gray-700 rounded-full overflow-hidden">
                        <div id="manaBar" class="mana-bar" style="width: 66%"></div>
                    </div>
                </div>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Attributes</h2>
                <div class="grid grid-cols-2 gap-2 text-sm">
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Strength</div>
                        <div id="charStr" class="font-bold">16</div>
                    </div>
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Dexterity</div>
                        <div id="charDex" class="font-bold">12</div>
                    </div>
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Constitution</div>
                        <div id="charCon" class="font-bold">14</div>
                    </div>
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Intelligence</div>
                        <div id="charInt" class="font-bold">10</div>
                    </div>
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Wisdom</div>
                        <div id="charWis" class="font-bold">8</div>
                    </div>
                    <div class="bg-gray-700 p-2 rounded">
                        <div class="text-yellow-400">Charisma</div>
                        <div id="charCha" class="font-bold">13</div>
                    </div>
                </div>
                <div class="mt-2 text-xs text-gray-400" id="statPointsDisplay">Stat Points: 0</div>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Equipped Items</h2>
                <div class="bg-gray-700 rounded p-2 h-24 overflow-y-auto scrollbar-custom">
                    <div class="grid grid-cols-3 gap-2" id="equippedItems">
                        <div class="bg-gray-600 p-1 rounded text-center">
                            <i class="fas fa-question text-gray-400"></i>
                            <div class="text-xs">None</div>
                        </div>
                        <div class="bg-gray-600 p-1 rounded text-center">
                            <i class="fas fa-question text-gray-400"></i>
                            <div class="text-xs">None</div>
                        </div>
                        <div class="bg-gray-600 p-1 rounded text-center">
                            <i class="fas fa-question text-gray-400"></i>
                            <div class="text-xs">None</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Inventory</h2>
                <div class="bg-gray-700 rounded p-2 h-40 overflow-y-auto scrollbar-custom">
                    <div class="grid grid-cols-3 gap-2" id="inventoryItems">
                        <!-- Items will be populated here -->
                    </div>
                </div>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Skills & Abilities</h2>
                <div class="bg-gray-700 rounded p-2 h-40 overflow-y-auto scrollbar-custom" id="skillsList">
                    <!-- Skills will be populated here -->
                </div>
            </div>
            
            <div class="mt-auto">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Current Location</h2>
                <div class="bg-gray-700 rounded p-3">
                    <div class="font-bold" id="currentLocation">Tavern</div>
                    <div class="text-sm text-gray-300" id="locationDesc">The Rusty Tankard</div>
                </div>
            </div>
        </div>
        
        <!-- Center Panel - Game Content -->
        <div class="flex-1 flex flex-col">
            <!-- Scene Image -->
            <div class="h-1/3 relative">
                <div id="sceneImage" class="absolute inset-0 bg-gray-900 flex items-center justify-center">
                    <div class="w-full h-full bg-cover bg-center" style="background-image: url('https://images.unsplash.com/photo-1518709766631-a6a7f45921c3?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');"></div>
                    <div class="absolute inset-0 bg-black bg-opacity-40"></div>
                </div>
            </div>
            
            <!-- Chat Log -->
            <div id="chatLog" class="flex-1 p-4 overflow-y-auto scrollbar-custom">
                <div class="chat-message system-message">
                    Welcome to the world of Eldoria. Your adventure begins now.
                </div>
                <div class="chat-message npc-message">
                    <div class="font-bold text-blue-400 medieval">Old Man:</div>
                    Welcome, traveler, to the Rusty Tankard. What brings you to our humble establishment this fine evening?
                </div>
            </div>
            
            <!-- Chat Input -->
            <div class="p-4 border-t border-gray-700">
                <div class="flex">
                    <input type="text" id="chatInput" placeholder="What will you do or say?" class="flex-1 bg-gray-700 border border-yellow-700 rounded-l px-4 py-2 text-white focus:outline-none focus:ring-1 focus:ring-yellow-500">
                    <button id="chatSubmit" class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-r medieval flex items-center justify-center min-w-[100px] btn-click">
                        <span id="submitText">Send</span>
                        <div id="submitSpinner" class="loading-spinner ml-2 hidden"></div>
                    </button>
                </div>
                <div class="mt-2 text-xs text-gray-400">
                    Examples: "I ask the old man about work", "I draw my sword", "I look around the tavern"
                </div>
            </div>
        </div>
        
        <!-- Right Panel - Game Log and Map -->
        <div class="w-64 bg-gray-800 p-4 flex flex-col border-l border-gray-700">
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Game Log</h2>
                <div id="gameLog" class="bg-gray-700 rounded p-2 h-40 overflow-y-auto text-sm scrollbar-custom">
                    <div class="text-green-400">> Entered the Rusty Tankard</div>
                </div>
            </div>
            
            <div class="mb-6">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Mini Map</h2>
                <div class="bg-gray-700 rounded p-3">
                    <div class="grid grid-cols-5 gap-1" id="miniMapGrid">
                        <!-- Map cells will be populated here -->
                    </div>
                </div>
                <div class="mt-2 text-sm">
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-yellow-600 mr-2"></div>
                        <span>Your position</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-gray-500 mr-2"></div>
                        <span>Unexplored</span>
                    </div>
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-blue-500 mr-2"></div>
                        <span>Points of interest</span>
                    </div>
                </div>
            </div>
            
            <div class="mt-auto">
                <h2 class="text-lg font-bold text-yellow-400 mb-2 medieval">Quest Log</h2>
                <div id="questLog" class="bg-gray-700 rounded p-3 h-40 overflow-y-auto scrollbar-custom">
                    <!-- Quests will be populated here -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- New Game Modal -->
    <div id="newGameModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-gray-800 rounded-lg w-full max-w-md border border-yellow-700">
            <div class="p-4 border-b border-gray-700 flex justify-between items-center">
                <h3 class="text-xl font-bold text-yellow-400 medieval">Create New Character</h3>
                <button id="closeNewGame" class="text-gray-400 hover:text-white btn-click">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <div class="space-y-4">
                    <div>
                        <label class="block text-gray-300 mb-1">Character Name</label>
                        <input type="text" id="newCharName" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="Enter your name">
                    </div>
                    <div>
                        <label class="block text-gray-300 mb-1">Class/Role</label>
                        <input type="text" id="newCharClass" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="e.g. Slime Sage, Cyber Samurai">
                    </div>
                    <div>
                        <label class="block text-gray-300 mb-1">World Setting</label>
        <input type="text" id="newWorldSetting" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="e.g. Medieval Fantasy, Cyberpunk">
      </div>
      <div>
        <label class="block text-gray-300 mb-1">Time Period</label>
        <input type="text" id="newTimePeriod" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="e.g. Year 1200, Future 3000">
      </div>
      <div>
        <label class="block text-gray-300 mb-1">Starting Stats</label>
        <div class="grid grid-cols-3 gap-2 text-sm">
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">STR</div>
            <input type="number" id="newCharStr" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">DEX</div>
            <input type="number" id="newCharDex" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">CON</div>
            <input type="number" id="newCharCon" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">INT</div>
            <input type="number" id="newCharInt" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">WIS</div>
            <input type="number" id="newCharWis" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
          <div class="bg-gray-700 p-2 rounded">
            <div class="text-yellow-400">CHA</div>
            <input type="number" id="newCharCha" class="w-full bg-gray-800 border border-gray-600 rounded px-1 py-1 text-white text-center" value="10" min="1" max="20">
          </div>
        </div>
        <div class="mt-2 text-xs text-gray-400">Total points used: <span id="statPointsUsed">60</span>/60</div>
      </div>
    </div>
    
    <div class="flex justify-end space-x-3 mt-6">
      <button id="startNewGame" class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded medieval btn-click">Begin Adventure</button>
      <button id="cancelNewGame" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded medieval btn-click">Cancel</button>
    </div>
  </div>
</div>
</div>

<!-- Settings Modal -->
<div id="settingsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
  <div class="bg-gray-800 rounded-lg w-full max-w-2xl border border-yellow-700">
    <div class="p-4 border-b border-gray-700 flex justify-between items-center">
      <h3 class="text-xl font-bold text-yellow-400 medieval">Game Settings</h3>
      <button id="closeSettings" class="text-gray-400 hover:text-white btn-click">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="p-6">
      <div class="mb-6">
        <h4 class="text-lg font-bold text-yellow-400 mb-3 medieval">AI Configuration</h4>
        <div class="space-y-4">
          <!-- Story Teller Configuration -->
          <div class="bg-gray-700 p-4 rounded border border-gray-600">
            <h5 class="font-bold text-yellow-300 mb-2">Story Teller Model</h5>
            <div class="space-y-2">
              <div>
                <label class="block text-gray-300 mb-1">API Key</label>
                <input type="text" id="storyTellerApiKey" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="Enter API key">
              </div>
              <div>
                <label class="block text-gray-300 mb-1">URL/IP</label>
                <input type="text" id="storyTellerUrl" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="http://localhost:5000/story">
              </div>
              <button id="testStoryTeller" class="mt-2 bg-gray-600 hover:bg-gray-500 text-white px-3 py-1 rounded text-sm medieval btn-click">
                Test Connection
              </button>
            </div>
          </div>
          
          <!-- Mechanics Configuration -->
          <div class="bg-gray-700 p-4 rounded border border-gray-600">
            <h5 class="font-bold text-yellow-300 mb-2">Mechanics Model</h5>
            <div class="space-y-2">
              <div>
                <label class="block text-gray-300 mb-1">API Key</label>
                <input type="text" id="mechanicsApiKey" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="Enter API key">
              </div>
              <div>
                <label class="block text-gray-300 mb-1">URL/IP</label>
                <input type="text" id="mechanicsUrl" class="w-full bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white" placeholder="http://localhost:5001/mechanics">
              </div>
              <button id="testMechanics" class="mt-2 bg-gray-600 hover:bg-gray-500 text-white px-3 py-1 rounded text-sm medieval btn-click">
                Test Connection
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="mb-6">
        <h4 class="text-lg font-bold text-yellow-400 mb-3 medieval">Gameplay Settings</h4>
        <div class="space-y-3">
          <div class="flex items-center">
            <input type="checkbox" id="autoSave" class="mr-2" checked>
            <label for="autoSave" class="text-gray-300">Enable Auto-Save</label>
          </div>
          <div class="flex items-center">
            <input type="checkbox" id="typewriterEffect" class="mr-2" checked>
            <label for="typewriterEffect" class="text-gray-300">Typewriter Text Effect</label>
          </div>
          <div class="flex items-center">
            <input type="checkbox" id="showImages" class="mr-2" checked>
            <label for="showImages" class="text-gray-300">Show Scene Images</label>
          </div>
        </div>
      </div>
      
      <div class="flex justify-end space-x-3">
        <button id="saveSettings" class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded medieval btn-click">Save Settings</button>
        <button id="cancelSettings" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded medieval btn-click">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Save/Load Modal -->
<div id="saveLoadModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
  <div class="bg-gray-800 rounded-lg w-full max-w-md border border-yellow-700">
    <div class="p-4 border-b border-gray-700 flex justify-between items-center">
      <h3 id="modalTitle" class="text-xl font-bold text-yellow-400 medieval">Save Game</h3>
      <button id="closeSaveLoad" class="text-gray-400 hover:text-white btn-click">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="p-6">
      <div class="space-y-3 mb-6" id="saveSlots">
        <!-- Save slots will be populated here -->
      </div>
      
      <div class="flex justify-end space-x-3">
        <button id="confirmSaveLoad" class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded medieval btn-click">Confirm</button>
        <button id="cancelSaveLoad" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded medieval btn-click">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Skill Notification -->
<div id="skillNotification" class="notification hidden"></div>

<script>
// Game State Management
const gameState = {
  character: {
    name: 'Sir Aldric',
    class: 'Knight',
    level: 5,
    xp: 1200,
    nextLevel: 2000,
    health: 75,
    maxHealth: 100,
    mana: 40,
    maxMana: 60,
    str: 16,
    dex: 12,
    con: 14,
    int: 10,
    wis: 8,
    cha: 13,
    statPoints: 0,
    baseStats: {
      str: 10,
      dex: 10,
      con: 10,
      int: 10,
      wis: 10,
      cha: 10
    }
  },
  equipped: {
    weapon: null,
    armor: null,
    accessory: null
  },
  location: {
    name: 'Tavern',
    description: 'The Rusty Tankard',
    x: 2,
    y: 2
  },
  inventory: [
    { name: "Longsword", type: "weapon", equipped: false, effect: { str: 3 }, icon: "fa-sword" },
    { name: "Shield", type: "armor", equipped: false, effect: { con: 2 }, icon: "fa-shield-alt" },
    { name: "Health Potion", type: "consumable", quantity: 3, effect: { heal: 20 }, icon: "fa-flask" },
    { name: "Ring of Wisdom", type: "accessory", equipped: false, effect: { wis: 2 }, icon: "fa-ring" },
    { name: "Scroll of Fireball", type: "consumable", quantity: 1, effect: { damage: 30 }, icon: "fa-scroll" },
    { name: "50 Gold", type: "currency", quantity: 50, icon: "fa-coins" }
  ],
  skills: [
    { name: "Sword Mastery", level: 2, xp: 45, nextLevel: 100, description: "Increased proficiency with swords", effect: { str: 1 } },
    { name: "Shield Block", level: 1, xp: 20, nextLevel: 100, description: "Improved defense with shields", effect: { con: 1 } }
  ],
  abilities: [
    { name: "Power Strike", description: "Deliver a powerful sword attack", requirements: [{ skill: "Sword Mastery", level: 2 }] }
  ],
  quests: [
    {
      title: 'The Bandit Threat',
      description: 'The tavern keeper mentioned bandits attacking travelers on the north road. Investigate and deal with the threat.',
      status: 'active'
    },
    {
      title: 'The Missing Heirloom',
      description: 'A distressed woman lost her family ring somewhere in the tavern. Help her find it.',
      status: 'active'
    }
  ],
  worldMap: [],
  gameLog: ["> Entered the Rusty Tankard"],
  settings: {
    autoSave: true,
    typewriterEffect: true,
    showImages: true
  }
};

// AI Configuration
let aiConfig = {
  storyTeller: { apiKey: "", url: "http://localhost:5000/story" },
  mechanics: { apiKey: "", url: "http://localhost:5001/mechanics" }
};

// Load saved AI config from localStorage if available
try {
  const savedConfig = localStorage.getItem('aiConfig');
  if (savedConfig) {
    aiConfig = JSON.parse(savedConfig);
    console.log('Loaded AI config from localStorage');
  }
} catch (error) {
  console.error('Error loading AI config:', error);
}

// DOM Elements
const menuBtn = document.getElementById('menuBtn');
const menuDropdown = document.getElementById('menuDropdown');
const newGameOption = document.getElementById('newGameOption');
const saveOption = document.getElementById('saveOption');
const loadOption = document.getElementById('loadOption');
const settingsOption = document.getElementById('settingsOption');
const settingsModal = document.getElementById('settingsModal');
const closeSettings = document.getElementById('closeSettings');
const newGameModal = document.getElementById('newGameModal');
const closeNewGame = document.getElementById('closeNewGame');
const startNewGame = document.getElementById('startNewGame');
const cancelNewGame = document.getElementById('cancelNewGame');
const saveLoadModal = document.getElementById('saveLoadModal');
const closeSaveLoad = document.getElementById('closeSaveLoad');
const modalTitle = document.getElementById('modalTitle');
const confirmSaveLoad = document.getElementById('confirmSaveLoad');
const cancelSaveLoad = document.getElementById('cancelSaveLoad');
const chatInput = document.getElementById('chatInput');
const chatSubmit = document.getElementById('chatSubmit');
const submitText = document.getElementById('submitText');
const submitSpinner = document.getElementById('submitSpinner');
const chatLog = document.getElementById('chatLog');
const sceneImage = document.getElementById('sceneImage');
const gameLog = document.getElementById('gameLog');
const questLog = document.getElementById('questLog');
const inventoryItems = document.getElementById('inventoryItems');
const equippedItems = document.getElementById('equippedItems');
const skillsList = document.getElementById('skillsList');
const miniMapGrid = document.getElementById('miniMapGrid');
const statPointsDisplay = document.getElementById('statPointsDisplay');
const skillNotification = document.getElementById('skillNotification');

// New Game Modal elements
const newCharName = document.getElementById('newCharName');
const newCharClass = document.getElementById('newCharClass');
const newWorldSetting = document.getElementById('newWorldSetting');
const newTimePeriod = document.getElementById('newTimePeriod');
const newCharStr = document.getElementById('newCharStr');
const newCharDex = document.getElementById('newCharDex');
const newCharCon = document.getElementById('newCharCon');
const newCharInt = document.getElementById('newCharInt');
const newCharWis = document.getElementById('newCharWis');
const newCharCha = document.getElementById('newCharCha');
const statPointsUsed = document.getElementById('statPointsUsed');

// Settings modal elements
const storyTellerApiKey = document.getElementById('storyTellerApiKey');
const storyTellerUrl = document.getElementById('storyTellerUrl');
const mechanicsApiKey = document.getElementById('mechanicsApiKey');
const mechanicsUrl = document.getElementById('mechanicsUrl');
const testStoryTeller = document.getElementById('testStoryTeller');
const testMechanics = document.getElementById('testMechanics');
const saveSettings = document.getElementById('saveSettings');
const cancelSettings = document.getElementById('cancelSettings');
const autoSave = document.getElementById('autoSave');
const typewriterEffect = document.getElementById('typewriterEffect');
const showImages = document.getElementById('showImages');

// Save/Load modal elements
const saveSlots = document.getElementById('saveSlots');

// Initialize world map with default values
function initWorldMap() {
  gameState.worldMap = [];
  for (let y = 0; y < 5; y++) {
    gameState.worldMap[y] = [];
    for (let x = 0; x < 5; x++) {
      gameState.worldMap[y][x] = {
        explored: false,
        name: '',
        description: '',
        type: ''
      };
    }
  }
  
  // Set starting location
  gameState.worldMap[2][2] = {
    explored: true,
    name: 'Tavern',
    description: 'The Rusty Tankard',
    type: 'building'
  };
}

// Initialize game state and UI
function initGame() {
  // Initialize world map
  initWorldMap();
  
  // Update all UI displays
  updateCharacterDisplay();
  updateInventory();
  updateEquippedItems();
  updateSkillsList();
  updateGameLog();
  updateQuestLog();
  updateMiniMap();
  updateSaveSlots();
}

// Toggle modal visibility
function toggleModal(modal) {
  if (!modal) {
    console.error('Modal element not found');
    return;
  }
  modal.classList.toggle('hidden');
}

// Open settings modal and load current settings
function openSettingsModal() {
  console.log('Opening settings modal');
  
  // Load current config into settings modal
  if (storyTellerApiKey) storyTellerApiKey.value = aiConfig.storyTeller.apiKey;
  if (storyTellerUrl) storyTellerUrl.value = aiConfig.storyTeller.url;
  if (mechanicsApiKey) mechanicsApiKey.value = aiConfig.mechanics.apiKey;
  if (mechanicsUrl) mechanicsUrl.value = aiConfig.mechanics.url;
  
  // Load game settings
  if (autoSave) autoSave.checked = gameState.settings.autoSave;
  if (typewriterEffect) typewriterEffect.checked = gameState.settings.typewriterEffect;
  if (showImages) showImages.checked = gameState.settings.showImages;
  
  toggleModal(settingsModal);
}

// Open save modal
function openSaveModal() {
  console.log('Opening save modal');
  if (!modalTitle || !saveLoadModal) return;
  modalTitle.textContent = 'Save Game';
  updateSaveSlots();
  toggleModal(saveLoadModal);
}

// Open load modal
function openLoadModal() {
  console.log('Opening load modal');
  if (!modalTitle || !saveLoadModal) return;
  modalTitle.textContent = 'Load Game';
  updateSaveSlots();
  toggleModal(saveLoadModal);
}

// Handle save/load confirmation based on current modal mode
function handleSaveLoadConfirm() {
  if (!modalTitle || !saveLoadModal) return;
  
  if (modalTitle.textContent === 'Save Game') {
    saveGame();
  } else {
    loadGame();
  }
  toggleModal(saveLoadModal);
}

// Update character stats display
function updateCharacterDisplay() {
  const char = gameState.character;
  
  // Update text content
  if (document.getElementById('charName')) document.getElementById('charName').textContent = char.name;
  if (document.getElementById('charClass')) document.getElementById('charClass').textContent = char.class;
  if (document.getElementById('charLevel')) document.getElementById('charLevel').textContent = char.level;
  if (document.getElementById('charXP')) document.getElementById('charXP').textContent = char.xp;
  if (document.getElementById('charNextLevel')) document.getElementById('charNextLevel').textContent = char.nextLevel;
  if (document.getElementById('charHealth')) document.getElementById('charHealth').textContent = char.health;
  if (document.getElementById('charMaxHealth')) document.getElementById('charMaxHealth').textContent = char.maxHealth;
  if (document.getElementById('charMana')) document.getElementById('charMana').textContent = char.mana;
  if (document.getElementById('charMaxMana')) document.getElementById('charMaxMana').textContent = char.maxMana;
  if (document.getElementById('charStr')) document.getElementById('charStr').textContent = char.str;
  if (document.getElementById('charDex')) document.getElementById('charDex').textContent = char.dex;
  if (document.getElementById('charCon')) document.getElementById('charCon').textContent = char.con;
  if (document.getElementById('charInt')) document.getElementById('charInt').textContent = char.int;
  if (document.getElementById('charWis')) document.getElementById('charWis').textContent = char.wis;
  if (document.getElementById('charCha')) document.getElementById('charCha').textContent = char.cha;
  if (statPointsDisplay) statPointsDisplay.textContent = `Stat Points: ${char.statPoints}`;
  
  // Update progress bars
  if (document.getElementById('healthBar')) document.getElementById('healthBar').style.width = `${(char.health / char.maxHealth) * 100}%`;
  if (document.getElementById('manaBar')) document.getElementById('manaBar').style.width = `${(char.mana / char.maxMana) * 100}%`;
  if (document.getElementById('xpBar')) document.getElementById('xpBar').style.width = `${(char.xp / char.nextLevel) * 100}%`;
  
  // Update location
  if (document.getElementById('currentLocation')) document.getElementById('currentLocation').textContent = gameState.location.name;
  if (document.getElementById('locationDesc')) document.getElementById('locationDesc').textContent = gameState.location.description;
}

// Update inventory display
function updateInventory() {
  if (!inventoryItems) return;
  inventoryItems.innerHTML = '';
  
  gameState.inventory.forEach(item => {
    const itemElement = document.createElement('div');
    itemElement.className = 'bg-gray-600 p-1 rounded text-center cursor-pointer hover:bg-gray-500 transition';
    
    // Add equipped class if item is equipped
    if (item.equipped) {
      itemElement.classList.add('equipped-item');
    }
    
    itemElement.innerHTML = `
      <i class="fas ${item.icon} ${item.type === 'currency' ? 'text-yellow-400' : 'text-gray-300'}"></i>
      <div class="text-xs mt-1">${item.name}${item.quantity > 1 ? ` (${item.quantity})` : ''}</div>
    `;
    
    // Add click handler for item actions
    itemElement.addEventListener('click', () => showItemActions(item));
    
    inventoryItems.appendChild(itemElement);
  });
}

// Show item actions menu
function showItemActions(item) {
  // Create a simple popup menu
  const menu = document.createElement('div');
  menu.className = 'absolute bg-gray-800 border border-yellow-700 rounded shadow-lg p-2 z-50';
  menu.style.minWidth = '150px';
  
  // Position near the clicked item
  const rect = event.target.getBoundingClientRect();
  menu.style.left = `${rect.left}px`;
  menu.style.top = `${rect.bottom}px`;
  
  // Add menu items based on item type
  if (['weapon', 'armor', 'accessory'].includes(item.type)) {
    const equipText = item.equipped ? 'Unequip' : 'Equip';
    const equipBtn = document.createElement('button');
    equipBtn.className = 'w-full text-left px-2 py-1 hover:bg-gray-700 rounded';
    equipBtn.textContent = equipText;
    equipBtn.addEventListener('click', () => {
      toggleEquipItem(item);
      document.body.removeChild(menu);
    });
    menu.appendChild(equipBtn);
  }
  
  if (item.type === 'consumable') {
    const useBtn = document.createElement('button');
    useBtn.className = 'w-full text-left px-2 py-1 hover:bg-gray-700 rounded';
    useBtn.textContent = 'Use';
    useBtn.addEventListener('click', () => {
      useItem(item);
      document.body.removeChild(menu);
    });
    menu.appendChild(useBtn);
  }
  
  const cancelBtn = document.createElement('button');
  cancelBtn.className = 'w-full text-left px-2 py-1 hover:bg-gray-700 rounded';
  cancelBtn.textContent = 'Cancel';
  cancelBtn.addEventListener('click', () => {
    document.body.removeChild(menu);
  });
  menu.appendChild(cancelBtn);
  
  // Add menu to body
  document.body.appendChild(menu);
  
  // Close menu when clicking elsewhere
  const closeMenu = (e) => {
    if (!menu.contains(e.target)) {
      document.body.removeChild(menu);
      document.removeEventListener('click', closeMenu);
    }
  };
  
  document.addEventListener('click', closeMenu);
}

// Toggle item equip/unequip
function toggleEquipItem(item) {
  if (!item) return;
  
  if (item.equipped) {
    // Unequip the item
    item.equipped = false;
    gameState.equipped[item.type] = null;
    addToGameLog(`> Unequipped ${item.name}`);
  } else {
    // Equip the item
    // First unequip any currently equipped item of this type
    if (gameState.equipped[item.type]) {
      const currentEquipped = gameState.inventory.find(i => i.name === gameState.equipped[item.type]);
      if (currentEquipped) {
        currentEquipped.equipped = false;
      }
    }
    
    item.equipped = true;
    gameState.equipped[item.type] = item.name;
    addToGameLog(`> Equipped ${item.name}`);
  }
  
  // Update displays
  updateInventory();
  updateEquippedItems();
  updateCharacterDisplay();
}

// Use a consumable item
async function useItem(item) {
  if (!item || item.type !== 'consumable') {
    addToGameLog(`> Cannot use ${item?.name || 'item'} - not a consumable`);
    return;
  }
  
  // Process item effect
  const result = await calculateMechanics('useItem', item);
  
  // Reduce quantity or remove if last one
  if (item.quantity > 1) {
    item.quantity--;
  } else {
    const index = gameState.inventory.indexOf(item);
    if (index > -1) {
      gameState.inventory.splice(index, 1);
    }
  }
  
  // Update displays
  updateInventory();
  updateCharacterDisplay();
  
  addToGameLog(`> Used ${item.name}. ${result}`);
  
  // Auto-save if enabled
  if (gameState.settings.autoSave) {
    saveGame();
  }
}

// Update equipped items display
function updateEquippedItems() {
  if (!equippedItems) return;
  equippedItems.innerHTML = '';
  
  // Create slots for each equipment type
  const equipmentTypes = ['weapon', 'armor', 'accessory'];
  
  equipmentTypes.forEach(type => {
    const slot = document.createElement('div');
    slot.className = 'bg-gray-600 p-1 rounded text-center';
    
    const equippedItem = gameState.inventory.find(item => 
      item.equipped && item.type === type
    );
    
    if (equippedItem) {
      slot.innerHTML = `
        <i class="fas ${equippedItem.icon} text-yellow-400"></i>
        <div class="text-xs mt-1">${equippedItem.name}</div>
      `;
      slot.classList.add('equipped-item');
    } else {
      slot.innerHTML = `
        <i class="fas fa-question text-gray-400"></i>
        <div class="text-xs">None</div>
      `;
    }
    
    equippedItems.appendChild(slot);
  });
}

// Update skills list display
function updateSkillsList() {
  if (!skillsList) return;
  skillsList.innerHTML = '';
  
  gameState.skills.forEach(skill => {
    const skillElement = document.createElement('div');
    skillElement.className = 'mb-2 p-2 bg-gray-800 rounded';
    
    skillElement.innerHTML = `
      <div class="flex justify-between items-center">
        <span class="font-medium">${skill.name} (Lvl ${skill.level})</span>
        <span class="text-xs text-gray-400">${skill.xp}/${skill.nextLevel} XP</span>
      </div>
      <div class="text-xs text-gray-300 mb-1">${skill.description}</div>
      <div class="skill-progress">
        <div class="skill-progress-bar" style="width: ${(skill.xp / skill.nextLevel) * 100}%"></div>
      </div>
    `;
    
    skillsList.appendChild(skillElement);
  });
}

// Update game log display
function updateGameLog() {
  if (!gameLog) return;
  gameLog.innerHTML = '';
  
  gameState.gameLog.forEach(logEntry => {
    const entry = document.createElement('div');
    entry.className = 'text-green-400';
    entry.textContent = logEntry;
    gameLog.appendChild(entry);
  });
  
  // Scroll to bottom
  gameLog.scrollTop = gameLog.scrollHeight;
}

// Add entry to game log
function addToGameLog(text) {
  if (!text) return;
  gameState.gameLog.push(text);
  updateGameLog();
}

// Update quest log display
function updateQuestLog() {
  if (!questLog) return;
  questLog.innerHTML = '';
  
  gameState.quests.forEach(quest => {
    const questElement = document.createElement('div');
    questElement.className = 'mb-3 p-2 bg-gray-800 rounded';
    
    questElement.innerHTML = `
      <div class="font-bold text-yellow-400">${quest.title}</div>
      <div class="text-sm text-gray-300">${quest.description}</div>
      <div class="text-xs text-right mt-1 ${quest.status === 'completed' ? 'text-green-400' : 'text-yellow-400'}">
        ${quest.status}
      </div>
    `;
    
    questLog.appendChild(questElement);
  });
}

// Update mini map display
function updateMiniMap() {
  if (!miniMapGrid) return;
  miniMapGrid.innerHTML = '';
  
  for (let y = 0; y < 5; y++) {
    for (let x = 0; x < 5; x++) {
      const cell = document.createElement('div');
      cell.className = 'aspect-square rounded-sm';
      
      // Set cell color based on exploration and player position
      if (x === gameState.location.x && y === gameState.location.y) {
        cell.classList.add('bg-yellow-600');
      } else if (gameState.worldMap[y][x].explored) {
        cell.classList.add('bg-blue-500');
      } else {
        cell.classList.add('bg-gray-500');
      }
      
      miniMapGrid.appendChild(cell);
    }
  }
}

// Update save slots display
function updateSaveSlots() {
  if (!saveSlots) return;
  saveSlots.innerHTML = '';
  
  // Create 3 save slots
  for (let i = 1; i <= 3; i++) {
    const slot = document.createElement('div');
    slot.className = 'bg-gray-700 p-3 rounded border border-gray-600';
    
    // Check if save exists
    const saveKey = `isekaiRpgSave_${i}`;
    const saveData = localStorage.getItem(saveKey);
    
    if (saveData) {
      try {
        const parsed = JSON.parse(saveData);
        slot.innerHTML = `
          <div class="font-bold">Slot ${i}</div>
          <div class="text-sm text-gray-300">${parsed.character.name} - Lvl ${parsed.character.level}</div>
          <div class="text-xs text-gray-400 mt-1">${new Date(parsed.timestamp).toLocaleString()}</div>
        `;
      } catch (e) {
        slot.innerHTML = `
          <div class="font-bold">Slot ${i}</div>
          <div class="text-sm text-gray-300">Corrupted Save</div>
        `;
      }
    } else {
      slot.innerHTML = `
        <div class="font-bold">Slot ${i}</div>
        <div class="text-sm text-gray-300">Empty Slot</div>
      `;
    }
    
    // Add click handler
    slot.addEventListener('click', () => selectSaveSlot(i));
    saveSlots.appendChild(slot);
  }
}

// Select save slot for save/load
function selectSaveSlot(slotNumber) {
  if (!saveSlots) return;
  
  // Highlight selected slot
  const slots = saveSlots.querySelectorAll('div');
  slots.forEach((slot, index) => {
    if (index + 1 === slotNumber) {
      slot.classList.add('border-yellow-500');
    } else {
      slot.classList.remove('border-yellow-500');
    }
  });
  
  // Store selected slot in modal
  if (saveLoadModal) saveLoadModal.dataset.selectedSlot = slotNumber;
}

// Save game to selected slot
function saveGame() {
  if (!saveLoadModal) return;
  const slotNumber = saveLoadModal.dataset.selectedSlot;
  
  if (!slotNumber) {
    alert('Please select a save slot first!');
    return;
  }
  
  const saveKey = `isekaiRpgSave_${slotNumber}`;
  
  // Add timestamp to save data
  const saveData = {
    ...gameState,
    timestamp: Date.now()
  };
  
  try {
    localStorage.setItem(saveKey, JSON.stringify(saveData));
    addToGameLog(`> Game saved to slot ${slotNumber}`);
    
    // Show notification
    showNotification('Game saved successfully!');
  } catch (e) {
    console.error('Error saving game:', e);
    alert('Failed to save game!');
  }
}

// Load game from selected slot
function loadGame() {
  if (!saveLoadModal) return;
  const slotNumber = saveLoadModal.dataset.selectedSlot;
  
  if (!slotNumber) {
    alert('Please select a save slot first!');
    return;
  }
  
  const saveKey = `isekaiRpgSave_${slotNumber}`;
  const saveData = localStorage.getItem(saveKey);
  
  if (!saveData) {
    alert('No save data found in this slot!');
    return;
  }
  
  try {
    const parsed = JSON.parse(saveData);
    
    // Update game state with loaded data
    Object.assign(gameState, parsed);
    
    addToGameLog(`> Game loaded from slot ${slotNumber}`);
    
    // Update all displays
    updateCharacterDisplay();
    updateInventory();
    updateEquippedItems();
    updateSkillsList();
    updateGameLog();
    updateQuestLog();
    updateMiniMap();
    
    // Show notification
    showNotification('Game loaded successfully!');
  } catch (e) {
    console.error('Error loading game:', e);
    alert('Failed to load game! Save file may be corrupted.');
  }
}

// Handle chat input
async function handleChatInput() {
  if (!chatInput || !chatSubmit || !submitText || !submitSpinner || !chatLog) return;
  
  const input = chatInput.value.trim();
  if (!input) return;
  
  try {
    // Show loading state
    submitText.textContent = "Processing...";
    submitSpinner.classList.remove('hidden');
    chatSubmit.disabled = true;
    
    // Add player message to chat
    addToChatLog(input, 'player');
    addToGameLog(`> ${input}`);
    
    // Clear input
    chatInput.value = '';
    
    // Process input with Story Teller AI
    const response = await getStoryTellerResponse(input);
    
    // Add response to chat
    addToChatLog(response.text, 'npc', response.character);
    
    // Handle mechanics if present
    if (response.mechanics) {
      if (response.mechanics.quest) {
        const questExists = gameState.quests.some(q => q.title === response.mechanics.quest);
        if (!questExists) {
          gameState.quests.push({
            title: response.mechanics.quest,
            description: response.mechanics.description,
            status: 'active'
          });
          updateQuestLog();
        }
      }
      
      if (response.mechanics.location) {
        gameState.location.name = response.mechanics.location.name;
        gameState.location.description = response.mechanics.location.description;
        updateCharacterDisplay();
      }
      
      if (response.mechanics.image) {
        updateSceneImage(response.mechanics.image);
      }
    }
    
    // Auto-save if enabled
    if (gameState.settings.autoSave) {
      saveGame();
    }
  } catch (error) {
    console.error('Error processing input:', error);
    addToChatLog("An error occurred while processing your input.", 'system');
  } finally {
    // Reset button state
    submitText.textContent = "Send";
    submitSpinner.classList.add('hidden');
    chatSubmit.disabled = false;
  }
}

// Add message to chat log
function addToChatLog(message, type, character = '') {
  if (!chatLog) return;
  
  const messageElement = document.createElement('div');
  messageElement.className = `chat-message ${type}-message`;
  
  if (type === 'player') {
    messageElement.innerHTML = `
      <div class="font-bold text-yellow-400 medieval">You:</div>
      <div class="text-gray-300">${message}</div>
    `;
  } else if (type === 'npc') {
    messageElement.innerHTML = `
      <div class="font-bold text-blue-400 medieval">${character}:</div>
      <div class="text-gray-300">${message}</div>
    `;
  } else {
    messageElement.innerHTML = `
      <div class="text-gray-300">${message}</div>
    `;
  }
  
  chatLog.appendChild(messageElement);
  
  // Scroll to bottom
  chatLog.scrollTop = chatLog.scrollHeight;
}

// Update scene image
function updateSceneImage(imageUrl) {
  if (!sceneImage) return;
  
  const imageDiv = sceneImage.querySelector('div');
  if (imageDiv) {
    imageDiv.style.backgroundImage = `url('${imageUrl}')`;
  }
}

// Show notification
function showNotification(message) {
  if (!skillNotification) return;
  
  skillNotification.textContent = message;
  skillNotification.classList.remove('hidden');
  
  setTimeout(() => {
    skillNotification.classList.add('hidden');
  }, 3000);
}

// Get response from Story Teller AI
async function getStoryTellerResponse(input) {
  // In a real implementation, this would call your AI API
  // For demo purposes, we'll simulate a response
  
  const responses = [
    {
      text: "The old man strokes his beard thoughtfully. 'Work, you say? Well, there's been trouble with bandits on the north road. The local merchants would pay handsomely to have that problem dealt with.'",
      character: "Old Man",
      mechanics: {
        quest: "The Bandit Threat",
        description: "The tavern keeper mentioned bandits attacking travelers on the north road. Investigate and deal with the threat."
      }
    },
    {
      text: "'Ah, our house specialty is Dragon's Breath Ale!' the old man says with a chuckle. 'Strong enough to put hair on a dwarf's chest, that one.'",
      character: "Old Man"
    },
    {
      text: "The old man's expression darkens. 'Aye, there's been strange happenings in these parts. Folk disappearing in the night, livestock found drained of blood. Some say it's vampires, others blame the cult that's taken up in the old ruins.'",
      character: "Old Man",
      mechanics: {
        image: "https://images.unsplash.com/photo-1518709766631-a6a7f45921c3?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
      }
    }
  ];
  
  // Return a random response for demo purposes
  return responses[Math.floor(Math.random() * responses.length)];
}

// Calculate game mechanics
async function calculateMechanics(action, item) {
  // In a real implementation, this would call your mechanics API
  // For demo purposes, we'll simulate results
  
  if (action === 'useItem') {
    if (item.name === 'Health Potion') {
      const healAmount = item.effect.heal;
      gameState.character.health = Math.min(
        gameState.character.health + healAmount,
        gameState.character.maxHealth
      );
      return `Restored ${healAmount} health.`;
    } else if (item.name === 'Scroll of Fireball') {
      return "You unleash a fiery explosion! (30 damage)";
    }
  }
  
  return "Action completed.";
}

// Test AI connection
async function testAIConnection(type) {
  const apiKey = document.getElementById(`${type}ApiKey`)?.value;
  const url = document.getElementById(`${type}Url`)?.value;
  
  if (!apiKey || !url) {
    alert('Please enter both API Key and URL');
    return;
  }
  
  try {
    // In a real implementation, this would test the API connection
    // For demo purposes, we'll simulate a successful test
    showNotification(`${type} connection successful!`);
  } catch (error) {
    console.error(`Error testing ${type} connection:`, error);
    alert(`Failed to connect to ${type} API`);
  }
}

// Save settings handler
function saveSettingsHandler() {
  // Save AI config
  aiConfig.storyTeller.apiKey = storyTellerApiKey?.value || '';
  aiConfig.storyTeller.url = storyTellerUrl?.value || '';
  aiConfig.mechanics.apiKey = mechanicsApiKey?.value || '';
  aiConfig.mechanics.url = mechanicsUrl?.value || '';
  
  // Save game settings
  gameState.settings.autoSave = autoSave?.checked || false;
  gameState.settings.typewriterEffect = typewriterEffect?.checked || false;
  gameState.settings.showImages = showImages?.checked || false;
  
  // Save to localStorage
  try {
    localStorage.setItem('aiConfig', JSON.stringify(aiConfig));
    showNotification('Settings saved successfully!');
    toggleModal(settingsModal);
  } catch (error) {
    console.error('Error saving settings:', error);
    alert('Failed to save settings!');
  }
}

// Start new game handler
function startNewGameHandler() {
  if (!newCharName || !newCharClass) return;
  
  const name = newCharName.value.trim();
  const charClass = newCharClass.value.trim();
  
  if (!name || !charClass) {
    alert('Please enter both character name and class');
    return;
  }
  
  // Create new character
  gameState.character = {
    name,
    class: charClass,
    level: 1,
    xp: 0,
    nextLevel: 100,
    health: 100,
    maxHealth: 100,
    mana: 50,
    maxMana: 50,
    str: parseInt(newCharStr?.value) || 10,
    dex: parseInt(newCharDex?.value) || 10,
    con: parseInt(newCharCon?.value) || 10,
    int: parseInt(newCharInt?.value) || 10,
    wis: parseInt(newCharWis?.value) || 10,
    cha: parseInt(newCharCha?.value) || 10,
    statPoints: 0,
    baseStats: {
      str: 10,
      dex: 10,
      con: 10,
      int: 10,
      wis: 10,
      cha: 10
    }
  };
  
  // Reset other game state
  gameState.inventory = [
    { name: "Rusty Sword", type: "weapon", equipped: true, effect: { str: 1 }, icon: "fa-sword" },
    { name: "Health Potion", type: "consumable", quantity: 2, effect: { heal: 20 }, icon: "fa-flask" },
    { name: "10 Gold", type: "currency", quantity: 10, icon: "fa-coins" }
  ];
  
  gameState.equipped = {
    weapon: "Rusty Sword",
    armor: null,
    accessory: null
  };
  
  gameState.skills = [
    { name: "Sword Mastery", level: 1, xp: 0, nextLevel: 100, description: "Basic proficiency with swords", effect: { str: 1 } }
  ];
  
  gameState.quests = [];
  gameState.gameLog = ["> Game started"];
  
  // Initialize world map
  initWorldMap();
  
  // Update all displays
  updateCharacterDisplay();
  updateInventory();
  updateEquippedItems();
  updateSkillsList();
  updateGameLog();
  updateQuestLog();
  updateMiniMap();
  
  // Clear chat and add welcome message
  if (chatLog) chatLog.innerHTML = '';
  addToChatLog("Welcome to your new adventure!", 'system');
  
  // Close modal
  toggleModal(newGameModal);
}

// Update stat points used in new game modal
function updateStatPointsUsed() {
  if (!statPointsUsed) return;
  
  const str = parseInt(newCharStr?.value) || 10;
  const dex = parseInt(newCharDex?.value) || 10;
  const con = parseInt(newCharCon?.value) || 10;
  const int = parseInt(newCharInt?.value) || 10;
  const wis = parseInt(newCharWis?.value) || 10;
  const cha = parseInt(newCharCha?.value) || 10;
  
  const totalPoints = str + dex + con + int + wis + cha - 60;
  statPointsUsed.textContent = totalPoints;
  
  // Highlight if over limit
  if (totalPoints > 0) {
    statPointsUsed.classList.add('text-red-400');
  } else {
    statPointsUsed.classList.remove('text-red-400');
  }
}

// Setup event listeners
function setupEventListeners() {
  // Menu button and dropdown
  if (menuBtn) {
    menuBtn.addEventListener('click', () => {
      menuDropdown.classList.toggle('show');
    });
  }
  
  // Close dropdown when clicking elsewhere
  document.addEventListener('click', (e) => {
    if (!menuBtn.contains(e.target) && !menuDropdown.contains(e.target)) {
      menuDropdown.classList.remove('show');
    }
  });
  
  // Menu options
  if (newGameOption) {
    newGameOption.addEventListener('click', () => {
      menuDropdown.classList.remove('show');
      toggleModal(newGameModal);
    });
  }
  
  if (saveOption) {
    saveOption.addEventListener('click', () => {
      menuDropdown.classList.remove('show');
      openSaveModal();
    });
  }
  
  if (loadOption) {
    loadOption.addEventListener('click', () => {
      menuDropdown.classList.remove('show');
      openLoadModal();
    });
  }
  
  if (settingsOption) {
    settingsOption.addEventListener('click', () => {
      menuDropdown.classList.remove('show');
      openSettingsModal();
    });
  }
  
  // New Game Modal
  if (closeNewGame) {
    closeNewGame.addEventListener('click', () => toggleModal(newGameModal));
  }
  
  if (cancelNewGame) {
    cancelNewGame.addEventListener('click', () => toggleModal(newGameModal));
  }
  
  if (startNewGame) {
    startNewGame.addEventListener('click', startNewGameHandler);
  }
  
  // Stat point allocation in new game modal
  [newCharStr, newCharDex, newCharCon, newCharInt, newCharWis, newCharCha].forEach(input => {
    if (input) {
      input.addEventListener('change', updateStatPointsUsed);
    }
  });
  
  // Settings Modal
  if (closeSettings) {
    closeSettings.addEventListener('click', () => toggleModal(settingsModal));
  }
  
  if (cancelSettings) {
    cancelSettings.addEventListener('click', () => toggleModal(settingsModal));
  }
  
  if (saveSettings) {
    saveSettings.addEventListener('click', saveSettingsHandler);
  }
  
  // Test connection buttons
  if (testStoryTeller) {
    testStoryTeller.addEventListener('click', () => testAIConnection('storyTeller'));
  }
  
  if (testMechanics) {
    testMechanics.addEventListener('click', () => testAIConnection('mechanics'));
  }
  
  // Save/Load Modal
  if (closeSaveLoad) {
    closeSaveLoad.addEventListener('click', () => toggleModal(saveLoadModal));
  }
  
  if (cancelSaveLoad) {
    cancelSaveLoad.addEventListener('click', () => toggleModal(saveLoadModal));
  }
  
  if (confirmSaveLoad) {
    confirmSaveLoad.addEventListener('click', handleSaveLoadConfirm);
  }
  
  // Chat Input
  if (chatSubmit) {
    chatSubmit.addEventListener('click', handleChatInput);
  }
  
  if (chatInput) {
    chatInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        handleChatInput();
      }
    });
  }
}

// Initialize the game when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM fully loaded and parsed');
  setupEventListeners();
  initGame();
});
</script>
</html>