File size: 83,780 Bytes
1129bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ============================================
// EUPHORICDOOM - GAME ENGINE v0.8.3
// ============================================

// ===== ITEM & WORLD DATA =====
const ITEMS_DB = {
  'synth-coke': { name: 'Synth-Coke', icon: 'fa-pills', color: 'text-purple-400', category: 'drug', basePrice: 80, volatile: true, description: 'Highly addictive synthetic stimulant. Banned in all districts.' },
  'hack-chip': { name: 'Hacker Chip', icon: 'fa-microchip', color: 'text-cyan-400', category: 'tech', basePrice: 350, volatile: false, description: 'Military-grade hacking implant. Enables digital infiltration.' },
  'warehouse-key': { name: 'Warehouse Key', icon: 'fa-key', color: 'text-pink-400', category: 'key', basePrice: 0, volatile: false, description: 'Key to the Warehouse District smuggling hub.', tradeable: false },
  'stim-pack': { name: 'Stim Pack', icon: 'fa-syringe', color: 'text-green-400', category: 'medical', basePrice: 120, volatile: false, description: 'Combat stimulant. Restores 30 HP instantly.' },
  'echo-revolver': { name: 'Echo Revolver', icon: 'fa-crosshairs', color: 'text-purple-400', category: 'weapon', basePrice: 1800, volatile: false, description: 'Sonic handgun with confuse effect and carnival bell critical sounds.' },
  'ringmaster-crown': { name: "Ringmaster's Crown", icon: 'fa-crown', color: 'text-yellow-400', category: 'relic', basePrice: 1200, volatile: false, description: 'Passive bonus to reputation interactions.' },
  'circuit-heart': { name: 'Heart of the Circuit Priest', icon: 'fa-heart', color: 'text-cyan-400', category: 'relic', basePrice: 2500, volatile: false, description: 'Poison immunity at the cost of extreme DOT vulnerability.' },
  'broker-terminal': { name: "Broker's Terminal", icon: 'fa-laptop-code', color: 'text-green-400', category: 'tech', basePrice: 900, volatile: false, description: 'Portable insider stock trading device.' },
  'glass-veins-serum': { name: 'Glass Veins Serum', icon: 'fa-vial', color: 'text-blue-400', category: 'mutation-serum', basePrice: 600, volatile: true, description: 'Massive movement speed bonus, extreme bleeding weakness.' },
  'neural-dampener': { name: 'Neural Dampener', icon: 'fa-brain', color: 'text-indigo-400', category: 'tech', basePrice: 450, volatile: false, description: 'Blocks dreamworld intrusion for 24 hours.' },
  'shadow-cloak': { name: 'Shadow Cloak', icon: 'fa-user-secret', color: 'text-gray-400', category: 'armor', basePrice: 700, volatile: false, description: '+15% evasion in all encounters.' },
  'plasma-knife': { name: 'Plasma Knife', icon: 'fa-cut', color: 'text-red-400', category: 'weapon', basePrice: 280, volatile: false, description: 'Silent melee weapon. +8 critical hit chance.' },
  'adrenal-shot': { name: 'Adrenal Shot', icon: 'fa-syringe', color: 'text-orange-400', category: 'medical', basePrice: 200, volatile: false, description: 'Boosts all stats by 3 for one encounter.' },
  'data-frag': { name: 'Data Fragment', icon: 'fa-file-code', color: 'text-cyan-400', category: 'tech', basePrice: 50, volatile: false, description: 'Encrypted data worth credits to the right buyer.' },
  'chem-vial': { name: 'Raw Chemical Vial', icon: 'fa-flask', color: 'text-green-400', category: 'component', basePrice: 30, volatile: false, description: 'Base component for crafting drugs and stims.' },
  'circuit-board': { name: 'Salvaged Circuit Board', icon: 'fa-microchip', color: 'text-yellow-600', category: 'component', basePrice: 40, volatile: false, description: 'Base component for crafting tech items.' },
  'relic-shard': { name: 'Relic Shard', icon: 'fa-gem', color: 'text-purple-400', category: 'component', basePrice: 150, volatile: false, description: 'Mysterious fragment pulsing with unknown energy.' }
};

const DISTRICTS_DB = {
  'ash-market': { name: 'Ash Market District', color: '#ff2a6d', icon: 'fa-store-alt', description: 'The beating heart of black market commerce. Auctions, deals, and betrayal.', threatLevel: 'Moderate', available: true, priceModifier: 1.0, marketBias: 'balanced' },
  'warehouse': { name: 'Warehouse District', color: '#ff2a6d', icon: 'fa-warehouse', description: 'Industrial smuggling hub. Cheap goods, dangerous allies.', threatLevel: 'High', available: true, priceModifier: 0.85, marketBias: 'cheap' },
  'carnival': { name: 'Carnival Grounds', color: '#05d9e8', icon: 'fa-theater-masks', description: 'Where nightmare and spectacle collide. Strange relics and darker secrets.', threatLevel: 'Variable', available: true, priceModifier: 1.2, marketBias: 'expensive' },
  'bankers-row': { name: "Banker's Row", color: '#d300c5', icon: 'fa-university', description: 'The legitimate facade of corruption. Stock exchange and loan sharks.', threatLevel: 'Low', available: true, priceModifier: 1.1, marketBias: 'expensive' },
  'digital-sewers': { name: 'Digital Sewers', color: '#05d9e8', icon: 'fa-network-wired', description: 'Hacker underground. Tech items and data trades.', threatLevel: 'High', available: false, unlockCost: 2000, priceModifier: 0.9, marketBias: 'cheap' },
  'bleaks-domain': { name: "Bleak's Domain", color: '#ffd700', icon: 'fa-skull-crossbones', description: 'The loan shark empire. Enter only if you owe or dare.', threatLevel: 'Extreme', available: false, unlockCost: 5000, priceModifier: 0.75, marketBias: 'cheap' }
};

const FACTIONS_DB = {
  'red-sash': { name: 'Red Sash Cartel', color: 'bg-red-700', abbr: 'RS', description: 'Dominant drug empire. Control synth-coke trade and street-level enforcement.', bonus: '+15% drug prices when friendly' },
  'dust-collective': { name: 'Dust Collective', color: 'bg-blue-700', abbr: 'DC', description: 'Militant tech runners. Control hardware and data smuggling.', bonus: '+15% tech prices when friendly' },
  'digital-saints': { name: 'Digital Saints', color: 'bg-green-700', abbr: 'DS', description: 'Hacker collective. Control digital infrastructure and information.', bonus: '-10% hacking tool costs when friendly' },
  'independent-mercs': { name: 'Independent Mercs', color: 'bg-orange-700', abbr: 'IM', description: 'Freelance muscle and fixers. No loyalty but no vendettas either.', bonus: '+10% quest rewards when friendly' }
};

const MUTATIONS_DB = {
  'night-vision': { name: 'Night Vision', icon: 'fa-eye', color: 'text-pink-400', description: 'Enhanced low-light perception. +3 Perception.', statBonus: { perception: 3 }, risk: 'none' },
  'adaptive-reflexes': { name: 'Adaptive Reflexes', icon: 'fa-running', color: 'text-cyan-400', description: 'Reaction time accelerates in combat. +4 Agility.', statBonus: { agility: 4 }, risk: 'none' },
  'glass-veins': { name: 'Glass Veins', icon: 'fa-tint', color: 'text-blue-400', description: 'Massive movement speed bonus, extreme bleeding weakness.', statBonus: { agility: 8 }, statPenalty: { endurance: -5 }, risk: 'high' },
  'circuit-touched': { name: 'Circuit Touched', icon: 'fa-bolt', color: 'text-yellow-400', description: 'Electronic interference aura. +3 Intelligence, tech items cheaper.', statBonus: { intelligence: 3 }, risk: 'medium' },
  'iron-gut': { name: 'Iron Gut', icon: 'fa-shield-alt', color: 'text-green-400', description: 'Poison resistance and +4 Endurance.', statBonus: { endurance: 4 }, risk: 'low' },
  'phantom-limb': { name: 'Phantom Limb', icon: 'fa-hand-sparkles', color: 'text-purple-400', description: 'Ghostly appendage. Can interact with digital objects. +2 Intelligence.', statBonus: { intelligence: 2 }, risk: 'medium' },
  'berserker-adrenal': { name: 'Berserker Adrenal', icon: 'fa-fire', color: 'text-red-400', description: '+6 Strength in combat, -3 Intelligence.', statBonus: { strength: 6 }, statPenalty: { intelligence: -3 }, risk: 'high' }
};

const QUESTS_DB = {
  'painted-veil': {
    name: 'The Painted Veil', description: 'Smuggle rare compounds for the Red Sash Cartel or sabotage them for rivals.',
    type: 'trade', faction: 'red-sash', steps: 5,
    rewards: { credits: 250, xp: 150, faction: { 'red-sash': 10 } },
    alternativeRewards: { credits: 180, xp: 120, faction: { 'dust-collective': 15 } }
  },
  'bankroll-bone': {
    name: 'Bankroll & Bone Marrow', description: 'Borrow from Mr. Bleak and either repay — or face endless hunters.',
    type: 'survival', faction: null, steps: 7,
    rewards: { credits: 500, xp: 300 }
  },
  'laughter-fog': {
    name: 'Laughter in the Fog', description: 'Investigate missing traders tied to the mythic "Clownfather".',
    type: 'investigation', faction: null, steps: 3,
    rewards: { credits: 0, xp: 400, item: 'ringmaster-crown' }
  },
  'electric-prophet': {
    name: 'The Electric Prophet', description: 'Enter Dreamworld missions to uncover deep mutation secrets.',
    type: 'mutation', faction: 'digital-saints', steps: 4,
    rewards: { xp: 350, mutation: 'circuit-touched' }
  },
  'crash-77': {
    name: "Market Crash '77", description: 'Manipulate or ride a collapsing megacorp to earn life-changing profits.',
    type: 'market', faction: null, steps: 6,
    rewards: { credits: 3000, xp: 500 }
  }
};

const RECIPES_DB = {
  'synth-coke': { name: 'Synth-Coke', ingredients: { 'chem-vial': 3, 'relic-shard': 1 }, output: 5, category: 'drug', xp: 25 },
  'stim-pack': { name: 'Stim Pack', ingredients: { 'chem-vial': 2 }, output: 1, category: 'medical', xp: 15 },
  'adrenal-shot': { name: 'Adrenal Shot', ingredients: { 'chem-vial': 2, 'circuit-board': 1 }, output: 1, category: 'medical', xp: 20 },
  'hack-chip': { name: 'Hacker Chip', ingredients: { 'circuit-board': 3, 'data-frag': 2 }, output: 1, category: 'tech', xp: 40 },
  'neural-dampener': { name: 'Neural Dampener', ingredients: { 'circuit-board': 2, 'data-frag': 3, 'relic-shard': 1 }, output: 1, category: 'tech', xp: 50 }
};

const STOCKS_DB = {
  'NDC': { name: 'NeonData Corp', price: 145.2, volatility: 0.6 },
  'RSX': { name: 'RedSash Express', price: 78.8, volatility: 0.9 },
  'DEP': { name: 'Digital Ether Protocols', price: 312.5, volatility: 0.4 },
  'BKL': { name: "Bleak Financial Group", price: 89.1, volatility: 0.7 },
  'CRN': { name: 'Carnival Industries', price: 203.7, volatility: 0.8 }
};

const EVENTS_POOL = [
  { text: 'Dust Collective raids in Warehouse District', effect: { 'weapon': 1.15, 'tech': 0.95 }, type: 'danger' },
  { text: 'Red Sash Cartel flooding market with synth-coke', effect: { 'drug': 0.78 }, type: 'warning' },
  { text: 'Digital Saints hacked Banker\'s Row', effect: { 'tech': 1.2, 'financial-risk': 1.08 }, type: 'info' },
  { text: 'Mr. Bleak offering 12% interest loans for 48 hours', effect: { 'loan-available': true }, type: 'opportunity' },
  { text: 'Carnival Industries stock surges on relic discovery', effect: { 'CRN-stock': 1.25 }, type: 'opportunity' },
  { text: 'Warehouse fire destroys supply chain', effect: { 'drug': 1.2, 'component': 1.3 }, type: 'danger' },
  { text: 'New mutation outbreak reported in Digital Sewers', effect: { 'mutation-serum': 0.7 }, type: 'warning' },
  { text: 'Clownfather sighting reported near Carnival Grounds', effect: { 'relic': 1.15 }, type: 'info' },
  { text: 'Peace treaty between Red Sash and Dust Collective', effect: { 'drug': 1.1, 'weapon': 0.9 }, type: 'opportunity' },
  { text: 'Underground fighting ring busted in Ash Market', effect: { 'weapon': 1.1, 'medical': 0.85 }, type: 'danger' }
];

const NPCS_DB = {
  'madame-karna': { name: 'Madame Karna', role: 'Auctioneer', district: 'ash-market', quote: 'Every relic has a price. Every soul has a discount.' },
  'mr-bleak': { name: 'Mr. Bleak', role: 'Loan Shark King', district: 'bankers-row', quote: 'Interest compounds. So does suffering.' },
  'echo-93': { name: 'Echo-93', role: 'Dreamwalker AI', district: 'digital-sewers', quote: 'I exist between frequencies. Can you hear me?' },
  'the-clownfather': { name: 'The Clownfather', role: 'Mythic Auctioneer', district: 'carnival', quote: 'Laughter is the only honest currency.' }
};

// ===== GAME STATE =====
const DEFAULT_STATE = {
  player: {
    name: 'VEIL',
    class: 'Smuggler',
    level: 3,
    xp: 450,
    xpToNext: 1000,
    credits: 4720,
    hp: 80,
    maxHp: 100,
    statPoints: 0,
    stats: { charisma: 12, agility: 18, intelligence: 10, strength: 8, endurance: 14, luck: 15 }
  },
  inventory: [
    { id: 'synth-coke', qty: 5 },
    { id: 'hack-chip', qty: 1 },
    { id: 'warehouse-key', qty: 1 },
    { id: 'stim-pack', qty: 2 }
  ],
  mutations: ['night-vision', 'adaptive-reflexes'],
  quests: {
    active: [
      { id: 'painted-veil', progress: 2 },
      { id: 'bankroll-bone', progress: 3 },
      { id: 'laughter-fog', progress: 1 }
    ],
    completed: [],
    available: ['electric-prophet', 'crash-77']
  },
  factions: {
    'red-sash': { reputation: 0, status: 'Neutral' },
    'dust-collective': { reputation: 25, status: 'Friendly' },
    'digital-saints': { reputation: -10, status: 'Wary' },
    'independent-mercs': { reputation: 5, status: 'Neutral' }
  },
  market: {},
  stocks: {},
  currentDistrict: 'ash-market',
  unlockedDistricts: ['ash-market', 'warehouse', 'carnival', 'bankers-row'],
  safehouses: { 'ash-market': { owned: true, level: 1, bonus: 'Passive income: +50cr/day' } },
  loans: [{ lender: 'Mr. Bleak', amount: 1500, interest: 0.12, daysLeft: 4, dailyInterest: 180 }],
  day: 3,
  time: 8,
  events: [],
  auction: {
    currentItems: ['ringmaster-crown', 'circuit-heart', 'echo-revolver'],
    dialogue: []
  },
  combatLog: [],
  log: []
};

let GS = {};

function loadGame() {
  const saved = localStorage.getItem('euphoricdoom_save');
  if (saved) {
    try {
      GS = JSON.parse(saved);
      // Merge new properties from DEFAULT_STATE that might not exist in save
      for (const key in DEFAULT_STATE) {
        if (!(key in GS)) GS[key] = DEFAULT_STATE[key];
      }
      // Merge nested player properties
      for (const key in DEFAULT_STATE.player) {
        if (!(key in GS.player)) GS.player[key] = DEFAULT_STATE.player[key];
      }
    } catch (e) {
      GS = JSON.parse(JSON.stringify(DEFAULT_STATE));
    }
  } else {
    GS = JSON.parse(JSON.stringify(DEFAULT_STATE));
  }
  // Initialize market prices
  initMarketPrices();
  initStockPrices();
}

function saveGame() {
  localStorage.setItem('euphoricdoom_save', JSON.stringify(GS));
}

function resetGame() {
  if (confirm('Are you sure you want to reset all progress? This cannot be undone!')) {
    localStorage.removeItem('euphoricdoom_save');
    GS = JSON.parse(JSON.stringify(DEFAULT_STATE));
    initMarketPrices();
    initStockPrices();
    saveGame();
    refreshAllUI();
    showToast('Game reset! Fresh start.', 'warning');
  }
}

// ===== MARKET PRICE INITIALIZATION =====
function initMarketPrices() {
  Object.keys(ITEMS_DB).forEach(id => {
    if (!GS.market[id]) {
      const base = ITEMS_DB[id].basePrice;
      GS.market[id] = {
        currentPrice: base > 0 ? Math.round(base * (0.85 + Math.random() * 0.3)) : 0,
        supply: Math.floor(Math.random() * 20) + 5,
        demand: Math.floor(Math.random() * 20) + 5,
        trend: (Math.random() - 0.5) * 0.1
      };
    }
  });
}

function initStockPrices() {
  Object.keys(STOCKS_DB).forEach(id => {
    if (!GS.stocks[id]) {
      GS.stocks[id] = {
        price: STOCKS_DB[id].price,
        shares: 0,
        history: [STOCKS_DB[id].price]
      };
    }
  });
}

// ===== UTILITY =====
function random(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function formatCredits(n) { return n.toLocaleString(); }
function clamp(v, min, max) { return Math.max(min, Math.min(max, v)); }

// ===== TOAST NOTIFICATION =====
function showToast(message, type = 'info') {
  const colors = {
    info: 'border-[#05d9e8] text-[#05d9e8]',
    success: 'border-green-400 text-green-400',
    warning: 'border-yellow-400 text-yellow-400',
    danger: 'border-red-400 text-red-400',
    error: 'border-[#ff2a6d] text-[#ff2a6d]'
  };
  const existing = document.getElementById('toast-container');
  if (!existing) {
    const container = document.createElement('div');
    container.id = 'toast-container';
    container.className = 'fixed top-20 right-4 z-[200] flex flex-col gap-2 max-w-sm';
    document.body.appendChild(container);
  }
  const container = document.getElementById('toast-container');
  const toast = document.createElement('div');
  const colorClass = colors[type] || colors.info;
  toast.className = `border ${colorClass} bg-black bg-opacity-90 px-4 py-3 text-sm font-mono animate-slide-in pointer-events-auto cursor-pointer`;
  toast.style.animation = 'slideIn 0.3s ease, fadeOut 0.5s ease 3.5s forwards';
  toast.textContent = message;
  toast.onclick = () => toast.remove();
  container.appendChild(toast);
  setTimeout(() => { if (toast.parentNode) toast.remove(); }, 4000);
}

// Add animation styles
const styleEl = document.createElement('style');
styleEl.textContent = `
  @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
  @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }
  @keyframes modalIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
  .modal-animate { animation: modalIn 0.25s ease; }
  .tab-active { border-bottom: 2px solid #05d9e8; color: #05d9e8; }
  .tab-inactive { border-bottom: 2px solid transparent; color: #888; }
  .tab-inactive:hover { color: #aaa; }
`;
document.head.appendChild(styleEl);

// ===== MODAL SYSTEM =====
function openModal(title, contentHTML) {
  const overlay = document.getElementById('modal-overlay');
  const modalTitle = document.getElementById('modal-title');
  const modalBody = document.getElementById('modal-body');
  const modalContent = document.getElementById('modal-content');
  overlay.classList.remove('hidden');
  overlay.classList.add('flex');
  modalTitle.textContent = title;
  modalBody.innerHTML = contentHTML;
  modalContent.classList.add('modal-animate');
  setTimeout(() => modalContent.classList.remove('modal-animate'), 250);
}

function closeModal() {
  const overlay = document.getElementById('modal-overlay');
  overlay.classList.add('hidden');
  overlay.classList.remove('flex');
}

// ===== CHARACTER SYSTEM =====
function openCharacterPanel() {
  const p = GS.player;
  const totalStats = Object.values(p.stats).reduce((a, b) => a + b, 0);
  const statRows = Object.entries(p.stats).map(([stat, val]) => {
    const maxVal = 30;
    const pct = Math.round((val / maxVal) * 100);
    const hasPoints = p.statPoints > 0;
    return `
      <div class="mb-2">
        <div class="flex justify-between text-xs mb-1">
          <span class="neon-pink">${stat.toUpperCase()}</span>
          <span>${val} <span class="text-gray-500">/ ${maxVal}</span></span>
        </div>
        <div class="progress-bar">
          <div class="progress-bar-fill" style="width: ${pct}%"></div>
        </div>
        ${hasPoints ? `<button onclick="allocateStat('${stat}')" class="mt-1 text-xs bg-black border border-[#05d9e8] text-[#05d9e8] px-2 py-0.5 hover:bg-[#05d9e8] hover:text-black transition-colors">+ ADD POINT</button>` : ''}
      </div>`;
  }).join('');

  const classPerks = {
    'Smuggler': ['+20% evasion in encounters', 'Access to hidden trade routes', 'Reduced detection chance'],
    'Fixer': ['+15% better prices', 'Unlock exclusive deals', 'Faction reputation gains doubled'],
    'Enforcer': ['+30% combat damage', 'Intimidation dialogue options', 'Reduced combat injury'],
    'ChemCook': ['+25% crafting success', 'Craft rare compounds', 'Immunity to drug side-effects'],
    'Ghost Courier': ['Hack locked containers', 'Access Digital Sewers for free', 'Digital combat advantage'],
    'Anarch Broker': ['+20% market manipulation', 'Cause market crashes for profit', 'Access anarchist quests']
  };

  const mutationSlots = GS.mutations.map(m => {
    const data = MUTATIONS_DB[m];
    if (!data) return '';
    return `
      <div class="border border-[#d300c5] bg-gray-900 p-2 flex items-center gap-3">
        <div class="${data.color} text-2xl"><i class="fas ${data.icon}"></i></div>
        <div>
          <div class="text-sm font-bold neon-purple">${data.name}</div>
          <div class="text-xs text-gray-400">${data.description}</div>
        </div>
      </div>`;
  }).join('');

  const content = `
    <div class="space-y-6">
      <!-- Character Header -->
      <div class="flex items-center gap-4 flex-wrap">
        <div class="w-24 h-24 bg-gray-800 border-2 border-[#ff2a6d] flex items-center justify-center">
          <i class="fas fa-skull text-4xl text-[#ff2a6d]"></i>
        </div>
        <div>
          <h3 class="title-font text-2xl neon-pink">${p.name}</h3>
          <div class="text-gray-400 text-sm">Class: <span class="text-white">${p.class}</span></div>
          <div class="text-gray-400 text-sm">Level: <span class="neon-cyan">${p.level}</span> | XP: <span class="text-white">${p.xp}/${p.xpToNext}</span></div>
          <div class="text-gray-400 text-sm">Credits: <span class="text-yellow-400">${formatCredits(p.credits)}cr</span></div>
          <div class="text-gray-400 text-sm">HP: <span class="text-green-400">${p.hp}/${p.maxHp}</span>
            <div class="inline-block w-32 ml-2 progress-bar"><div class="progress-bar-fill" style="width:${(p.hp/p.maxHp)*}%; background: linear-gradient(90deg, #22c55e, #16a34a)"></div></div>
          </div>
        </div>
        <div class="ml-auto text-right">
          ${p.statPoints > 0 ? `<div class="text-yellow-400 text-sm font-bold pixel-font">STAT POINTS: ${p.statPoints}</div>` : ''}
          <div class="text-gray-500 text-xs">Day ${GS.day} | ${GS.time}:00h</div>
        </div>
      </div>

      <!-- Stats -->
      <div>
        <h3 class="neon-cyan text-lg font-bold mb-3 flex items-center"><i class="fas fa-chart-bar mr-2"></i> STATISTICS</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          ${statRows}
        </div>
      </div>

      <!-- Mutations -->
      <div>
        <h3 class="neon-purple text-lg font-bold mb-3 flex items-center"><i class="fas fa-dna mr-2"></i> ACTIVE MUTATIONS (${GS.mutations.length}/6)</h3>
        <div class="space-y-2">
          ${mutationSlots || '<div class="text-gray-500 text-sm">No mutations acquired yet.</div>'}
        </div>
      </div>

      <!-- Class Perks -->
      <div>
        <h3 class="neon-cyan text-lg font-bold mb-3 flex items-center"><i class="fas fa-star mr-2"></i> ${p.class.toUpperCase()} PERKS</h3>
        <div class="space-y-1">
          ${(classPerks[p.class] || []).map(perk => `<div class="text-sm text-gray-300"><i class="fas fa-check text-green-400 mr-2"></i>${perk}</div>`).join('')}
        </div>
      </div>

      <div class="flex gap-3 flex-wrap">
        <button onclick="openMutations()" class="neon-btn bg-black text-[#d300c5] border border-[#d300c5] px-4 py-2 text-sm">MANAGE MUTATIONS</button>
        <button onclick="openInventory()" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-4 py-2 text-sm">VIEW INVENTORY</button>
        <button onclick="resetGame()" class="neon-btn bg-black text-red-400 border border-red-400 px-4 py-2 text-sm">RESET GAME</button>
      </div>
    </div>`;
  openModal('CHARACTER SHEET', content);
}

function allocateStat(stat) {
  if (GS.player.statPoints <= 0) return;
  GS.player.stats[stat]++;
  GS.player.statPoints--;
  saveGame();
  openCharacterPanel();
  showToast(`${stat.toUpperCase()} increased to ${GS.player.stats[stat]}!`, 'success');
}

function gainXP(amount) {
  GS.player.xp += amount;
  while (GS.player.xp >= GS.player.xpToNext) {
    GS.player.xp -= GS.player.xpToNext;
    GS.player.level++;
    GS.player.xpToNext = Math.floor(GS.player.xpToNext * 1.5);
    GS.player.statPoints += 2;
    GS.player.maxHp += 10;
    GS.player.hp = GS.player.maxHp;
    showToast(`LEVEL UP! You are now Level ${GS.player.level}! +2 stat points, +10 max HP`, 'success');
  }
  saveGame();
}

// ===== MARKET SYSTEM =====
function openMarket() {
  const district = DISTRICTS_DB[GS.currentDistrict];
  const buyableItems = Object.keys(ITEMS_DB).filter(id => {
    const item = ITEMS_DB[id];
    return item.basePrice > 0 && item.tradeable !== false;
  });

  const sellableItems = GS.inventory.filter(inv => {
    return ITEMS_DB[inv.id] && ITEMS_DB[inv.id].basePrice > 0 && ITEMS_DB[inv.id].tradeable !== false;
  });

  const content = `
    <div>
      <!-- Market Tabs -->
      <div class="flex gap-4 mb-4 border-b border-gray-700">
        <button onclick="marketTab('buy')" id="tab-buy" class="tab-active pb-2 px-3 text-sm font-bold cursor-pointer">BLACK MARKET</button>
        <button onclick="marketTab('sell')" id="tab-sell" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">SELL ITEMS</button>
        <button onclick="marketTab('stocks')" id="tab-stocks" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">STOCK EXCHANGE</button>
        <button onclick="marketTab('options')" id="tab-options" class="tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer">OPTIONS</button>
      </div>

      <div class="mb-3 text-xs text-gray-400">
        <span class="neon-cyan">LOCATION:</span> ${district.name} | 
        <span class="neon-pink">PRICE MOD:</span> ${Math.round(district.priceModifier * 100)}% | 
        <span class="text-yellow-400">CREDITS:</span> ${formatCredits(GS.player.credits)}cr
      </div>

      <div id="market-content">
        ${renderMarketBuy(buyableItems, district)}
      </div>
    </div>`;
  openModal('MARKET', content);
}

function renderMarketBuy(items, district) {
  return `
    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[50vh] overflow-y-auto">
      ${items.map(id => {
        const item = ITEMS_DB[id];
        const market = GS.market[id];
        const price = Math.round(market.currentPrice * district.priceModifier);
        const canAfford = GS.player.credits >= price;
        return `
          <div class="border border-gray-700 bg-gray-900 p-3 flex gap-3 hover:border-[#05d9e8] transition-colors">
            <div class="${item.color} text-3xl self-center"><i class="fas ${item.icon}"></i></div>
            <div class="flex-1">
              <div class="text-sm font-bold neon-cyan">${item.name}</div>
              <div class="text-xs text-gray-400">${item.description}</div>
              <div class="flex justify-between items-center mt-1">
                <div>
                  <span class="text-yellow-400 text-sm">${formatCredits(price)}cr</span>
                  <span class="text-xs ${market.trend > 0 ? 'text-green-400' : market.trend < 0 ? 'text-red-400' : 'text-gray-500'} ml-2">
                    ${market.trend > 0 ? '▲' : market.trend < 0 ? '▼' : '●'} ${item.category}
                  </span>
                </div>
                <button onclick="buyItem('${id}')" class="neon-btn bg-black ${canAfford ? 'text-[#ff2a6d] border-[#ff2a6d]' : 'text-gray-600 border-gray-600 cursor-not-allowed'} border px-3 py-1 text-xs" ${canAfford ? '' : 'disabled'}>BUY</button>
              </div>
            </div>
          </div>`;
      }).join('')}
    </div>`;
}

function renderMarketSell() {
  const sellable = GS.inventory.filter(inv => ITEMS_DB[inv.id] && ITEMS_DB[inv.id].basePrice > 0 && ITEMS_DB[inv.id].tradeable !== false);
  const district = DISTRICTS_DB[GS.currentDistrict];
  if (sellable.length === 0) {
    return '<div class="text-center text-gray-500 py-8">No items to sell.</div>';
  }
  return `
    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[50vh] overflow-y-auto">
      ${sellable.map(inv => {
        const item = ITEMS_DB[inv.id];
        const market = GS.market[inv.id];
        const sellPrice = Math.round(market.currentPrice * district.priceModifier * 0.7);
        return `
          <div class="border border-gray-700 bg-gray-900 p-3 flex gap-3 hover:border-[#ff2a6d] transition-colors">
            <div class="${item.color} text-3xl self-center"><i class="fas ${item.icon}"></i></div>
            <div class="flex-1">
              <div class="text-sm font-bold neon-pink">${item.name} <span class="text-gray-400">x${inv.qty}</span></div>
              <div class="text-xs text-gray-400">${item.description}</div>
              <div class="flex justify-between items-center mt-1">
                <span class="text-yellow-400 text-sm">${formatCredits(sellPrice)}cr each</span>
                <div class="flex gap-1">
                  <button onclick="sellItem('${inv.id}', 1)" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-2 py-1 text-xs">SELL 1</button>
                  <button onclick="sellItem('${inv.id}', ${inv.qty})" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-2 py-1 text-xs">SELL ALL</button>
                </div>
              </div>
            </div>
          </div>`;
      }).join('')}
    </div>`;
}

function renderMarketStocks() {
  return `
    <div class="max-h-[50vh] overflow-y-auto">
      <div class="mb-3 text-xs text-gray-400">Invest in megacorp stocks. Prices fluctuate with market events and district conditions.</div>
      <table class="w-full text-sm">
        <thead>
          <tr class="border-b border-gray-700">
            <th class="text-left neon-cyan py-2">SYMBOL</th>
            <th class="text-left neon-cyan py-2">NAME</th>
            <th class="text-right neon-cyan py-2">PRICE</th>
            <th class="text-right neon-cyan py-2">OWNED</th>
            <th class="text-center neon-cyan py-2">ACTIONS</th>
          </tr>
        </thead>
        <tbody>
          ${Object.entries(GS.stocks).map(([id, stock]) => {
            const data = STOCKS_DB[id];
            const prevPrice = stock.history.length > 1 ? stock.history[stock.history.length - 2] : stock.price;
            const change = stock.price - prevPrice;
            const changePct = prevPrice ? ((change / prevPrice) * 100).toFixed(1) : '0.0';
            const isUp = change >= 0;
            return `
              <tr class="border-b border-gray-800 hover:bg-gray-900">
                <td class="py-2 font-bold ${isUp ? 'text-green-400' : 'text-red-400'}">${id}</td>
                <td class="py-2 text-gray-300">${data.name}</td>
                <td class="py-2 text-right text-white">${stock.price.toFixed(1)}cr <span class="text-xs ${isUp ? 'text-green-400' : 'text-red-400'}">${isUp ? '▲' : '▼'}${changePct}%</span></td>
                <td class="py-2 text-right text-yellow-400">${stock.shares}</td>
                <td class="py-2 text-center">
                  <button onclick="buyStock('${id}')" class="bg-black text-green-400 border border-green-400 px-2 py-0.5 text-xs mr-1 hover:bg-green-900">BUY</button>
                  <button onclick="sellStock('${id}')" class="bg-black text-red-400 border border-red-400 px-2 py-0.5 text-xs hover:bg-red-900" ${stock.shares > 0 ? '' : 'disabled style="opacity:0.3;cursor:not-allowed"'}>SELL</button>
                </td>
              </tr>`;
          }).join('')}
        </tbody>
      </table>
      <div class="mt-3 text-xs text-gray-500">Buy/Sell in lots of 10 shares. Prices update each game day.</div>
    </div>`;
}

function renderMarketOptions() {
  return `
    <div class="max-h-[50vh] overflow-y-auto">
      <div class="mb-4 text-xs text-gray-400">Speculate on price movements. Buy CALLS if you think prices will rise, PUTS if you think they'll fall.</div>
      <div class="space-y-3">
        ${Object.keys(STOCKS_DB).map(id => {
          const data = STOCKS_DB[id];
          const stock = GS.stocks[id];
          return `
            <div class="border border-gray-700 bg-gray-900 p-3">
              <div class="flex justify-between items-center mb-2">
                <span class="font-bold text-white">${id} - ${data.name}</span>
                <span class="text-yellow-400">${stock.price.toFixed(1)}cr</span>
              </div>
              <div class="text-xs text-gray-500 mb-2">Options expire in 3 game days. Premium: ${Math.round(stock.price * 0.15)}cr per contract.</div>
              <div class="flex gap-2">
                <button onclick="buyOption('${id}', 'call')" class="bg-black text-green-400 border border-green-400 px-3 py-1 text-xs hover:bg-green-900">BUY CALL (↑)</button>
                <button onclick="buyOption('${id}', 'put')" class="bg-black text-red-400 border border-red-400 px-3 py-1 text-xs hover:bg-red-900">BUY PUT (↓)</button>
              </div>
            </div>`;
          }).join('')}
      </div>
    </div>`;
}

function marketTab(tab) {
  ['buy', 'sell', 'stocks', 'options'].forEach(t => {
    const el = document.getElementById('tab-' + t);
    if (el) { el.className = t === tab ? 'tab-active pb-2 px-3 text-sm font-bold cursor-pointer' : 'tab-inactive pb-2 px-3 text-sm font-bold cursor-pointer'; }
  });
  const contentEl = document.getElementById('market-content');
  const district = DISTRICTS_DB[GS.currentDistrict];
  if (tab === 'buy') {
    const items = Object.keys(ITEMS_DB).filter(id => ITEMS_DB[id].basePrice > 0 && ITEMS_DB[id].tradeable !== false);
    contentEl.innerHTML = renderMarketBuy(items, district);
  } else if (tab === 'sell') {
    contentEl.innerHTML = renderMarketSell();
  } else if (tab === 'stocks') {
    contentEl.innerHTML = renderMarketStocks();
  } else if (tab === 'options') {
    contentEl.innerHTML = renderMarketOptions();
  }
}

function buyItem(itemId) {
  const district = DISTRICTS_DB[GS.currentDistrict];
  const price = Math.round(GS.market[itemId].currentPrice * district.priceModifier);
  if (GS.player.credits < price) {
    showToast('Not enough credits!', 'error');
    return;
  }
  GS.player.credits -= price;
  const existing = GS.inventory.find(i => i.id === itemId);
  if (existing) {
    existing.qty++;
  } else {
    GS.inventory.push({ id: itemId, qty: 1 });
  }
  gainXP(5);
  showToast(`Bought ${ITEMS_DB[itemId].name} for ${formatCredits(price)}cr`, 'success');
  saveGame();
  refreshAllUI();
  marketTab('buy');
}

function sellItem(itemId, qty) {
  const district = DISTRICTS_DB[GS.currentDistrict];
  const price = Math.round(GS.market[itemId].currentPrice * district.priceModifier * 0.7);
  const inv = GS.inventory.find(i => i.id === itemId);
  if (!inv || inv.qty <= 0) return;
  const sellQty = Math.min(qty, inv.qty);
  const total = price * sellQty;
  GS.player.credits += total;
  inv.qty -= sellQty;
  if (inv.qty <= 0) {
    GS.inventory = GS.inventory.filter(i => i.id !== itemId);
  }
  gainXP(3);
  showToast(`Sold ${sellQty}x ${ITEMS_DB[itemId].name} for ${formatCredits(total)}cr`, 'success');
  saveGame();
  refreshAllUI();
  marketTab('sell');
}

function buyStock(symbol) {
  const stock = GS.stocks[symbol];
  const cost = Math.round(stock.price * 10);
  if (GS.player.credits < cost) {
    showToast('Not enough credits! Need ' + formatCredits(cost) + 'cr for 10 shares.', 'error');
    return;
  }
  GS.player.credits -= cost;
  stock.shares += 10;
  showToast(`Bought 10 shares of ${symbol} for ${formatCredits(cost)}cr`, 'success');
  saveGame();
  refreshAllUI();
  marketTab('stocks');
}

function sellStock(symbol) {
  const stock = GS.stocks[symbol];
  if (stock.shares < 10) {
    showToast('Need at least 10 shares to sell.', 'error');
    return;
  }
  const revenue = Math.round(stock.price * 10);
  GS.player.credits += revenue;
  stock.shares -= 10;
  showToast(`Sold 10 shares of ${symbol} for ${formatCredits(revenue)}cr`, 'success');
  saveGame();
  refreshAllUI();
  marketTab('stocks');
}

function buyOption(symbol, type) {
  const stock = GS.stocks[symbol];
  const premium = Math.round(stock.price * 1.5);
  if (GS.player.credits < premium) {
    showToast('Not enough credits! Need ' + formatCredits(premium) + 'cr premium.', 'error');
    return;
  }
  GS.player.credits -= premium;
  showToast(`Bought ${type.toUpperCase()} option on ${symbol} for ${formatCredits(premium)}cr. Expires in 3 days.`, 'warning');
  saveGame();
  refreshAllUI();
}

// ===== DISTRICT SYSTEM =====
function openDistricts() {
  const content = `
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      ${Object.entries(DISTRICTS_DB).map(([id, d]) => {
        const isCurrent = id === GS.currentDistrict;
        const isUnlocked = GS.unlockedDistricts.includes(id);
        const borderColor = isCurrent ? '#05d9e8' : isUnlocked ? d.color : '#555';
        return `
          <div class="border-2 p-4 ${isCurrent ? 'bg-gray-800' : 'bg-gray-900'} transition-all hover:bg-gray-800" style="border-color:${borderColor}">
            <div class="flex items-center gap-3 mb-2">
              <div class="w-10 h-10 rounded-full flex items-center justify-center" style="background:${d.color};${isUnlocked && !isCurrent ? 'box-shadow:0 0 10px ' + d.color : ''}">
                <i class="fas ${d.icon} text-black"></i>
              </div>
              <div>
                <h3 class="font-bold ${isCurrent ? 'neon-cyan' : isUnlocked ? 'text-white' : 'text-gray-600'}">${d.name}</h3>
                ${isCurrent ? '<span class="text-xs neon-cyan">◆ CURRENT LOCATION</span>' : ''}
              </div>
            </div>
            <p class="text-xs text-gray-400 mb-2">${d.description}</p>
            <div class="flex justify-between text-xs mb-2">
              <span class="text-gray-500">Threat: <span style="color:${d.color}">${d.threatLevel}</span></span>
              <span class="text-gray-500">Price Mod: ${Math.round(d.priceModifier * 100)}%</span>
            </div>
            ${isUnlocked && !isCurrent ? `<button onclick="travelToDistrict('${id}')" class="neon-btn bg-black text-white border px-4 py-1 text-xs w-full" style="border-color:${d.color}">TRAVEL HERE</button>` : ''}
            ${!isUnlocked ? `<button onclick="unlockDistrict('${id}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-1 text-xs w-full">UNLOCK (${formatCredits(d.unlockCost)}cr)</button>` : ''}
          </div>`;
      }).join('')}
    </div>`;
  openModal('DISTRICTS', content);
}

function travelToDistrict(districtId) {
  if (GS.currentDistrict === districtId) return;
  GS.currentDistrict = districtId;
  GS.time += 2;
  if (GS.time >= 24) { advanceDay(); }
  showToast(`Traveled to ${DISTRICTS_DB[districtId].name}`, 'info');
  saveGame();
  refreshAllUI();
  openDistricts();
}

function unlockDistrict(districtId) {
  const district = DISTRICTS_DB[districtId];
  if (GS.player.credits < district.unlockCost) {
    showToast(`Need ${formatCredits(district.unlockCost)}cr to unlock this district!`, 'error');
    return;
  }
  GS.player.credits -= district.unlockCost;
  GS.unlockedDistricts.push(districtId);
  showToast(`Unlocked ${district.name}! You can now travel there.`, 'success');
  saveGame();
  refreshAllUI();
  openDistricts();
}

// ===== QUEST SYSTEM =====
function openQuestLog() {
  const content = `
    <div class="space-y-6">
      <!-- Active Quests -->
      <div>
        <h3 class="neon-pink text-lg font-bold mb-3"><i class="fas fa-scroll mr-2"></i>ACTIVE QUESTS</h3>
        ${GS.quests.active.length === 0 ? '<div class="text-gray-500 text-sm">No active quests. Check Available tab for new quests.</div>' : ''}
        <div class="space-y-3">
          ${GS.quests.active.map(q => {
            const quest = QUESTS_DB[q.id];
            if (!quest) return '';
            const pct = Math.round((q.progress / quest.steps) * 100);
            return `
              <div class="border border-gray-700 bg-gray-900 p-3">
                <div class="flex justify-between items-start mb-2">
                  <h4 class="text-sm font-bold neon-cyan">${quest.name}</h4>
                  <span class="text-xs text-gray-500">${quest.type.toUpperCase()}</span>
                </div>
                <p class="text-xs text-gray-400 mb-2">${quest.description}</p>
                <div class="progress-bar mb-1"><div class="progress-bar-fill" style="width:${pct}%"></div></div>
                <div class="flex justify-between text-xs">
                  <span class="text-gray-500">${q.progress}/${quest.steps} steps</span>
                  <span class="text-yellow-400">+${quest.rewards.credits}cr | +${quest.rewards.xp}XP</span>
                </div>
                ${q.progress >= quest.steps ? `<button onclick="completeQuest('${q.id}')" class="mt-2 neon-btn bg-black text-green-400 border border-green-400 px-4 py-1 text-xs w-full">COMPLETE QUEST</button>` : `<button onclick="advanceQuest('${q.id}')" class="mt-2 neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-4 py-1 text-xs w-full">ADVANCE (+1 step)</button>`}
              </div>`;
          }).join('')}
        </div>
      </div>

      <!-- Available Quests -->
      <div>
        <h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-plus-circle mr-2"></i>AVAILABLE QUESTS</h3>
        <div class="space-y-3">
          ${GS.quests.available.map(qId => {
            const quest = QUESTS_DB[qId];
            if (!quest) return '';
            return `
              <div class="border border-gray-700 bg-gray-900 p-3">
                <h4 class="text-sm font-bold neon-purple">${quest.name}</h4>
                <p class="text-xs text-gray-400 mb-2">${quest.description}</p>
                <div class="flex justify-between text-xs">
                  <span class="text-gray-500">${quest.steps} steps | ${quest.type}</span>
                  <span class="text-yellow-400">+${quest.rewards.credits}cr | +${quest.rewards.xp}XP</span>
                </div>
                <button onclick="acceptQuest('${qId}')" class="mt-2 neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-4 py-1 text-xs w-full">ACCEPT QUEST</button>
              </div>`;
          }).join('')}
          ${GS.quests.available.length === 0 ? '<div class="text-gray-500 text-sm">No new quests available right now.</div>' : ''}
        </div>
      </div>

      <!-- Completed Quests -->
      ${GS.quests.completed.length > 0 ? `
        <div>
          <h3 class="text-green-400 text-lg font-bold mb-3"><i class="fas fa-check-circle mr-2"></i>COMPLETED QUESTS</h3>
          <div class="space-y-2">
            ${GS.quests.completed.map(qId => {
              const quest = QUESTS_DB[qId];
              if (!quest) return '';
              return `<div class="text-xs text-gray-500 border-b border-gray-800 pb-1"><i class="fas fa-check text-green-400 mr-1"></i>${quest.name}</div>`;
            }).join('')}
          </div>
        </div>` : ''}
    </div>`;
  openModal('QUEST LOG', content);
}

function acceptQuest(questId) {
  const idx = GS.quests.available.indexOf(questId);
  if (idx === -1) return;
  GS.quests.available.splice(idx, 1);
  GS.quests.active.push({ id: questId, progress: 0 });
  showToast(`Accepted quest: ${QUESTS_DB[questId].name}`, 'success');
  saveGame();
  openQuestLog();
}

function advanceQuest(questId) {
  const quest = GS.quests.active.find(q => q.id === questId);
  if (!quest) return;
  quest.progress++;
  if (quest.progress >= QUESTS_DB[questId].steps) {
    showToast(`${QUESTS_DB[questId].name} is ready to complete!`, 'warning');
  } else {
    showToast(`${QUESTS_DB[questId].name}: Step ${quest.progress}/${QUESTS_DB[questId].steps}`, 'info');
  }
  saveGame();
  openQuestLog();
}

function completeQuest(questId) {
  const idx = GS.quests.active.findIndex(q => q.id === questId);
  if (idx === -1) return;
  GS.quests.active.splice(idx, 1);
  GS.quests.completed.push(questId);
  const quest = QUESTS_DB[questId];
  GS.player.credits += quest.rewards.credits;
  gainXP(quest.rewards.xp);
  if (quest.rewards.faction) {
    Object.entries(quest.rewards.faction).forEach(([fId, amt]) => {
      changeReputation(fId, amt);
    });
  }
  if (quest.rewards.item) {
    const existing = GS.inventory.find(i => i.id === quest.rewards.item);
    if (existing) existing.qty++;
    else GS.inventory.push({ id: quest.rewards.item, qty: 1 });
  }
  if (quest.rewards.mutation) {
    if (!GS.mutations.includes(quest.rewards.mutation)) {
      GS.mutations.push(quest.rewards.mutation);
      showToast(`NEW MUTATION: ${MUTATIONS_DB[quest.rewards.mutation].name}!`, 'success');
    }
  }
  showToast(`Quest completed: ${quest.name}! +${quest.rewards.credits}cr, +${quest.rewards.xp}XP`, 'success');
  saveGame();
  refreshAllUI();
  openQuestLog();
}

function changeReputation(factionId, amount) {
  if (!GS.factions[factionId]) return;
  GS.factions[factionId].reputation += amount;
  const rep = GS.factions[factionId].reputation;
  if (rep >= 50) GS.factions[factionId].status = 'Allied';
  else if (rep >= 25) GS.factions[factionId].status = 'Friendly';
  else if (rep > -25) GS.factions[factionId].status = 'Neutral';
  else if (rep >= -50) GS.factions[factionId].status = 'Wary';
  else GS.factions[factionId].status = 'Hostile';
}

// ===== INVENTORY SYSTEM =====
function openInventory() {
  const content = `
    <div>
      <div class="flex justify-between items-center mb-4">
        <div class="text-xs text-gray-400">Items: ${GS.inventory.reduce((a, i) => a + i.qty, 0)} | Credits: <span class="text-yellow-400">${formatCredits(GS.player.credits)}cr</span></div>
      </div>
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 max-h-[60vh] overflow-y-auto">
        ${GS.inventory.map(inv => {
          const item = ITEMS_DB[inv.id];
          if (!item) return '';
          const canUse = ['medical', 'drug', 'mutation-serum'].includes(item.category);
          return `
            <div class="border border-gray-700 bg-gray-900 p-3 hover:border-[#05d9e8] transition-colors">
              <div class="flex items-center gap-2 mb-2">
                <div class="${item.color} text-2xl"><i class="fas ${item.icon}"></i></div>
                <div>
                  <div class="text-sm font-bold text-white">${item.name} <span class="text-gray-500">x${inv.qty}</span></div>
                  <div class="text-xs text-gray-500">${item.category.toUpperCase()}</div>
                </div>
              </div>
              <div class="text-xs text-gray-400 mb-2">${item.description}</div>
              <div class="text-xs text-yellow-400 mb-2">Value: ~${formatCredits(Math.round(GS.market[inv.id]?.currentPrice * 0.7 || 0))}cr</div>
              <div class="flex gap-1">
                ${canUse ? `<button onclick="useItem('${inv.id}')" class="neon-btn bg-black text-green-400 border border-green-400 px-2 py-1 text-xs flex-1">USE</button>` : ''}
                ${item.basePrice > 0 && item.tradeable !== false ? `<button onclick="openMarket(); setTimeout(()=>marketTab('sell'), 100);" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-2 py-1 text-xs flex-1">SELL</button>` : ''}
                <button onclick="dropItem('${inv.id}')" class="neon-btn bg-black text-red-400 border border-red-400 px-2 py-1 text-xs">DROP</button>
              </div>
            </div>`;
        }).join('')}
      </div>
    </div>`;
  openModal('INVENTORY', content);
}

function useItem(itemId) {
  const inv = GS.inventory.find(i => i.id === itemId);
  if (!inv) return;
  const item = ITEMS_DB[itemId];

  if (item.category === 'medical') {
    if (itemId === 'stim-pack') {
      GS.player.hp = Math.min(GS.player.maxHp, GS.player.hp + 30);
      showToast('Used Stim Pack. +30 HP!', 'success');
    } else if (itemId === 'adrenal-shot') {
      Object.keys(GS.player.stats).forEach(s => GS.player.stats[s] += 3);
      showToast('Used Adrenal Shot! All stats +3 for this encounter!', 'success');
    }
  } else if (item.category === 'drug') {
    if (itemId === 'synth-coke') {
      GS.player.stats.agility += 2;
      GS.player.stats.endurance -= 1;
      showToast('Used Synth-Coke. Agility +2, Endurance -1.', 'warning');
    }
  } else if (item.category === 'mutation-serum') {
    const mKeys = Object.keys(MUTATIONS_DB).filter(m => !GS.mutations.includes(m));
    if (mKeys.length > 0) {
      const newMut = pick(mKeys);
      GS.mutations.push(newMut);
      showToast(`Acquired mutation: ${MUTATIONS_DB[newMut].name}!`, 'warning');
    }
  }

  inv.qty--;
  if (inv.qty <= 0) {
    GS.inventory = GS.inventory.filter(i => i.id !== itemId);
  }
  gainXP(2);
  saveGame();
  refreshAllUI();
  openInventory();
}

function dropItem(itemId) {
  if (!confirm('Are you sure you want to drop this item?')) return;
  GS.inventory = GS.inventory.filter(i => i.id !== itemId);
  showToast('Item dropped.', 'info');
  saveGame();
  refreshAllUI();
  openInventory();
}

// ===== FACTION / CONTACTS SYSTEM =====
function openFactions() {
  const statusColors = {
    'Allied': '#22c55e', 'Friendly': '#4ade80', 'Neutral': '#ffffff',
    'Wary': '#facc15', 'Hostile': '#ef4444', 'Indebted': '#ffd700'
  };
  // Add Mr. Bleak special
  const allFactions = { ...GS.factions };
  const content = `
    <div class="space-y-4">
      ${Object.entries(allFactions).map(([fId, faction]) => {
        const data = FACTIONS_DB[fId];
        if (!data) return '';
        const color = statusColors[faction.status] || '#ffffff';
        const repPct = clamp(((faction.reputation + 100) / 200) * 100, 0, 100);
        return `
          <div class="border border-gray-700 bg-gray-900 p-4">
            <div class="flex items-center gap-3 mb-3">
              <div class="w-12 h-12 ${data.color} rounded-full flex items-center justify-center text-white font-bold">${data.abbr}</div>
              <div>
                <h3 class="font-bold text-white">${data.name}</h3>
                <span class="text-xs" style="color:${color}">${faction.status.toUpperCase()}</span>
              </div>
            </div>
            <p class="text-xs text-gray-400 mb-2">${data.description}</p>
            <p class="text-xs text-gray-500 mb-2"><i class="fas fa-star text-yellow-400 mr-1"></i>${data.bonus}</p>
            <div class="progress-bar mb-1"><div class="progress-bar-fill" style="width:${repPct}%"></div></div>
            <div class="flex justify-between text-xs">
              <span class="text-gray-500">Reputation: ${faction.reputation}</span>
              <span style="color:${color}">${faction.status}</span>
            </div>
          </div>`;
      }).join('')}

      <!-- Mr. Bleak -->
      <div class="border-2 border-yellow-400 bg-gray-900 p-4" style="box-shadow:0 0 10px #ffd700">
        <div class="flex items-center gap-3 mb-3">
          <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center text-black font-bold text-sm">MB</div>
          <div>
            <h3 class="font-bold gold-text">MR. BLEAK</h3>
            <span class="text-xs gold-text">INDEBTED</span>
          </div>
        </div>
        <p class="text-xs text-gray-400 mb-2">Albino loan shark king. Defaulting triggers world events and hunter mini-boss fights.</p>
        ${GS.loans.length > 0 ? GS.loans.map((loan, i) => `
          <div class="border border-yellow-400 bg-black p-2 mt-2">
            <div class="text-xs text-yellow-400">Loan: ${formatCredits(loan.amount)}cr | ${Math.round(loan.interest*100)}% interest | ${loan.daysLeft} days left</div>
            <div class="text-xs text-gray-500">Owed: ${formatCredits(Math.round(loan.amount * (1 + loan.interest * (7 - loan.daysLeft) / 7)))}cr</div>
            <div class="flex gap-2 mt-1">
              <button onclick="repayLoan(${i})" class="bg-black text-green-400 border border-green-400 px-2 py-1 text-xs">REPAY</button>
              <button onclick="takeNewLoan()" class="bg-black text-yellow-400 border border-yellow-400 px-2 py-1 text-xs">BORROW MORE</button>
            </div>
          </div>
        `).join('') : '<button onclick="takeNewLoan()" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-2 text-xs mt-2">TAKE A LOAN</button>'}
      </div>
    </div>`;
  openModal('CONTACTS & FACTIONS', content);
}

function takeNewLoan() {
  const amounts = [500, 1000, 2000, 5000];
  const content = `
    <div class="space-y-3">
      <div class="text-sm text-gray-400 mb-4">Mr. Bleak offers loans at <span class="text-red-400">12% interest</span>. Repay within 7 days or face the consequences.</div>
      ${amounts.map(amt => `
        <button onclick="confirmLoan(${amt})" class="w-full border border-yellow-400 bg-gray-900 p-3 text-left hover:bg-gray-800">
          <div class="flex justify-between">
            <span class="text-yellow-400 font-bold">${formatCredits(amt)}cr</span>
            <span class="text-gray-400">Repay: ${formatCredits(Math.round(amt * 1.12))}cr in 7 days</span>
          </div>
        </button>
      `).join('')}
      <button onclick="openFactions()" class="w-full border border-gray-600 bg-black text-gray-400 p-2 text-sm">CANCEL</button>
    </div>`;
  openModal('MR. BLEAK LOANS', content);
}

function confirmLoan(amount) {
  GS.loans.push({ lender: 'Mr. Bleak', amount, interest: 0.12, daysLeft: 7, dailyInterest: Math.round(amount * 0.12 / 7) });
  GS.player.credits += amount;
  showToast(`Borrowed ${formatCredits(amount)}cr from Mr. Bleak. Repay within 7 days!`, 'warning');
  saveGame();
  refreshAllUI();
  openFactions();
}

function repayLoan(index) {
  const loan = GS.loans[index];
  if (!loan) return;
  const owed = Math.round(loan.amount * (1 + loan.interest));
  if (GS.player.credits < owed) {
    showToast(`You need ${formatCredits(owed)}cr to repay this loan!`, 'error');
    return;
  }
  GS.player.credits -= owed;
  GS.loans.splice(index, 1);
  showToast(`Loan repaid! ${formatCredits(owed)}cr deducted.`, 'success');
  changeReputation('dust-collective', 5);
  saveGame();
  refreshAllUI();
  openFactions();
}

// ===== MUTATION SYSTEM =====
function openMutations() {
  const activeMutations = GS.mutations.map(m => MUTATIONS_DB[m]).filter(Boolean);
  const availableMutations = Object.entries(MUTATIONS_DB).filter(([id]) => !GS.mutations.includes(id));

  const content = `
    <div class="space-y-6">
      <div>
        <h3 class="neon-purple text-lg font-bold mb-3"><i class="fas fa-dna mr-2"></i>ACTIVE MUTATIONS (${GS.mutations.length}/6)</h3>
        <div class="space-y-3">
          ${activeMutations.map(m => `
            <div class="border border-[#d300c5] bg-gray-900 p-3">
              <div class="flex items-center gap-3">
                <div class="${m.color} text-3xl"><i class="fas ${m.icon}"></i></div>
                <div class="flex-1">
                  <div class="font-bold neon-purple">${m.name}</div>
                  <div class="text-xs text-gray-400">${m.description}</div>
                  <div class="text-xs mt-1">
                    ${Object.entries(m.statBonus || {}).map(([s, v]) => `<span class="text-green-400">+${v} ${s}</span>`).join(' ')}
                    ${Object.entries(m.statPenalty || {}).map(([s, v]) => `<span class="text-red-400">${v} ${s}</span>`).join(' ')}
                  </div>
                </div>
              </div>
            </div>
          `).join('')}
          ${GS.mutations.length === 0 ? '<div class="text-gray-500 text-sm">No mutations active.</div>' : ''}
        </div>
      </div>

      <div>
        <h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-flask mr-2"></i>AVAILABLE MUTATIONS</h3>
        <div class="text-xs text-gray-400 mb-3">Acquire mutations through quests, exposure to relics, or mutation serums.</div>
        <div class="space-y-2">
          ${availableMutations.map(([id, m]) => `
            <div class="border border-gray-700 bg-gray-900 p-3 flex justify-between items-center">
              <div class="flex items-center gap-3">
                <div class="${m.color} text-2xl"><i class="fas ${m.icon}"></i></div>
                <div>
                  <div class="text-sm font-bold text-white">${m.name}</div>
                  <div class="text-xs text-gray-400">Risk: <span class="${m.risk === 'high' ? 'text-red-400' : m.risk === 'medium' ? 'text-yellow-400' : 'text-green-400'}">${m.risk.toUpperCase()}</span></div>
                </div>
              </div>
              ${GS.mutations.length < 6 ? `<button onclick="attemptMutation('${id}')" class="neon-btn bg-black text-[#d300c5] border border-[#d300c5] px-3 py-1 text-xs">ACQUIRE</button>` : '<span class="text-xs text-red-400">MAX MUTATIONS</span>'}
            </div>
          `).join('')}
        </div>
      </div>

      <div class="border border-yellow-400 bg-black p-3 text-xs text-yellow-400">
        <i class="fas fa-exclamation-triangle mr-1"></i> WARNING: Mutations have both benefits and side effects. High-risk mutations may cause permanent stat penalties. Max 6 mutations.
      </div>
    </div>`;
  openModal('MUTATIONS', content);
}

function attemptMutation(mutationId) {
  if (GS.mutations.length >= 6) {
    showToast('Maximum mutations reached (6/6)!', 'error');
    return;
  }
  if (GS.mutations.includes(mutationId)) return;
  const mut = MUTATIONS_DB[mutationId];
  const riskChance = mut.risk === 'high' ? 0.5 : mut.risk === 'medium' ? 0.25 : mut.risk === 'low' ? 0.1 : 0;
  if (Math.random() < riskChance) {
    // Bad outcome
    const statKeys = Object.keys(GS.player.stats);
    const randomStat = pick(statKeys);
    GS.player.stats[randomStat] = Math.max(1, GS.player.stats[randomStat] - 2);
    showToast(`Mutation attempt FAILED! -2 ${randomStat.toUpperCase()} due to side effects.`, 'error');
  }
  GS.mutations.push(mutationId);
  // Apply stat bonuses
  if (mut.statBonus) {
    Object.entries(mut.statBonus).forEach(([s, v]) => {
      if (GS.player.stats[s] !== undefined) GS.player.stats[s] += v;
    });
  }
  if (mut.statPenalty) {
    Object.entries(mut.statPenalty).forEach(([s, v]) => {
      if (GS.player.stats[s] !== undefined) GS.player.stats[s] += v;
    });
  }
  showToast(`Acquired mutation: ${mut.name}!`, 'success');
  gainXP(25);
  saveGame();
  refreshAllUI();
  openMutations();
}

// ===== CRAFTING SYSTEM =====
function openCrafting() {
  const content = `
    <div class="space-y-4">
      <div class="text-xs text-gray-400 mb-4">Combine components to craft valuable items. Required materials are deducted from your inventory.</div>
      ${Object.entries(RECIPES_DB).map(([id, recipe]) => {
        const output = ITEMS_DB[id];
        const canCraft = Object.entries(recipe.ingredients).every(([ingId, qty]) => {
          const inv = GS.inventory.find(i => i.id === ingId);
          return inv && inv.qty >= qty;
        });
        const ingredientList = Object.entries(recipe.ingredients).map(([ingId, qty]) => {
          const inv = GS.inventory.find(i => i.id === ingId);
          const have = inv ? inv.qty : 0;
          const enough = have >= qty;
          return `<span class="${enough ? 'text-green-400' : 'text-red-400'}">${ITEMS_DB[ingId]?.name || ingId}: ${have}/${qty}</span>`;
        }).join(', ');

        return `
          <div class="border ${canCraft ? 'border-[#05d9e8]' : 'border-gray-700'} bg-gray-900 p-4">
            <div class="flex items-center gap-3 mb-2">
              <div class="${output.color} text-3xl"><i class="fas ${output.icon}"></i></div>
              <div class="flex-1">
                <div class="font-bold neon-cyan">${recipe.name} <span class="text-gray-500 text-xs">(x${recipe.output})</span></div>
                <div class="text-xs text-gray-400 mb-1">${output.description}</div>
                <div class="text-xs">Materials: ${ingredientList}</div>
              </div>
              <div class="text-right">
                <div class="text-xs text-gray-500 mb-1">+${recipe.xp} XP</div>
                <button onclick="craftItem('${id}')" class="neon-btn bg-black ${canCraft ? 'text-green-400 border-green-400' : 'text-gray-600 border-gray-600 cursor-not-allowed'} border px-4 py-2 text-xs" ${canCraft ? '' : 'disabled'}>${canCraft ? 'CRAFT' : 'MISSING'}</button>
              </div>
            </div>
          </div>`;
      }).join('')}
    </div>`;
  openModal('CRAFTING', content);
}

function craftItem(recipeId) {
  const recipe = RECIPES_DB[recipeId];
  if (!recipe) return;
  // Check ingredients
  const canCraft = Object.entries(recipe.ingredients).every(([ingId, qty]) => {
    const inv = GS.inventory.find(i => i.id === ingId);
    return inv && inv.qty >= qty;
  });
  if (!canCraft) {
    showToast('Missing required materials!', 'error');
    return;
  }
  // Deduct ingredients
  Object.entries(recipe.ingredients).forEach(([ingId, qty]) => {
    const inv = GS.inventory.find(i => i.id === ingId);
    inv.qty -= qty;
    if (inv.qty <= 0) {
      GS.inventory = GS.inventory.filter(i => i.id !== ingId);
    }
  });
  // Add output
  const existing = GS.inventory.find(i => i.id === recipeId);
  if (existing) {
    existing.qty += recipe.output;
  } else {
    GS.inventory.push({ id: recipeId, qty: recipe.output });
  }
  gainXP(recipe.xp);
  showToast(`Crafted ${recipe.output}x ${recipe.name}! +${recipe.xp} XP`, 'success');
  saveGame();
  refreshAllUI();
  openCrafting();
}

// ===== SAFEHOUSE SYSTEM =====
function openSafehouse() {
  const owned = GS.safehouses[GS.currentDistrict];
  const allSafehouses = Object.entries(DISTRICTS_DB).filter(([id]) => GS.unlockedDistricts.includes(id));

  const content = `
    <div class="space-y-6">
      <div>
        <h3 class="neon-cyan text-lg font-bold mb-3"><i class="fas fa-home mr-2"></i>CURRENT SAFEHOUSE: ${DISTRICTS_DB[GS.currentDistrict].name}</h3>
        ${owned ? `
          <div class="border border-[#05d9e8] bg-gray-900 p-4">
            <div class="flex justify-between items-center mb-3">
              <div>
                <span class="text-yellow-400 font-bold">Level ${owned.level}</span>
                <span class="text-gray-400 text-sm ml-2">${owned.bonus}</span>
              </div>
              <button onclick="upgradeSafehouse('${GS.currentDistrict}')" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-3 py-1 text-xs">UPGRADE (${formatCredits(500 * owned.level)}cr)</button>
            </div>
            <div class="grid grid-cols-2 gap-3 text-sm">
              <div><span class="text-gray-500">Storage:</span> <span class="text-white">+${owned.level * 5} slots</span></div>
              <div><span class="text-gray-500">Income:</span> <span class="text-green-400">+${50 * owned.level}cr/day</span></div>
              <div><span class="text-gray-500">Defense:</span> <span class="text-white">${owned.level * 10}%</span></div>
              <div><span class="text-gray-500">Craft Bonus:</span> <span class="text-white">+${owned.level * 5}%</span></div>
            </div>
          </div>
        ` : `
          <div class="border border-gray-700 bg-gray-900 p-4 text-center">
            <div class="text-gray-500 mb-3">No safehouse in this district.</div>
            <button onclick="buySafehouse('${GS.currentDistrict}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-4 py-2 text-sm">BUY SAFEHOUSE (${formatCredits(2000)}cr)</button>
          </div>
        `}
      </div>

      <div>
        <h3 class="neon-pink text-lg font-bold mb-3"><i class="fas fa-building mr-2"></i>OTHER DISTRICT SAFEHOUSES</h3>
        <div class="space-y-2">
          ${allSafehouses.filter(([id]) => id !== GS.currentDistrict).map(([id, d]) => {
            const sh = GS.safehouses[id];
            return `
              <div class="border border-gray-700 bg-gray-900 p-3 flex justify-between items-center">
                <div>
                  <span class="text-white font-bold">${d.name}</span>
                  ${sh ? `<span class="text-xs text-green-400 ml-2">Level ${sh.level}</span>` : '<span class="text-xs text-red-400 ml-2">No safehouse</span>'}
                </div>
                ${!sh ? `<button onclick="buySafehouse('${id}')" class="neon-btn bg-black text-yellow-400 border border-yellow-400 px-3 py-1 text-xs">BUY (${formatCredits(2000)}cr)</button>` : `<button onclick="upgradeSafehouse('${id}')" class="neon-btn bg-black text-[#05d9e8] border border-[#05d9e8] px-3 py-1 text-xs">UPGRADE (L${sh.level + 1})</button>`}
              </div>`;
          }).join('')}
        </div>
      </div>

      <div class="border border-gray-700 bg-black p-3 text-xs text-gray-400">
        <i class="fas fa-info-circle mr-1"></i> Safehouses provide passive income, extra storage, crafting bonuses, and defense against raids. Upgrade to increase bonuses.
      </div>
    </div>`;
  openModal('SAFEHOUSE', content);
}

function buySafehouse(districtId) {
  const cost = 2000;
  if (GS.player.credits < cost) {
    showToast(`Need ${formatCredits(cost)}cr to buy a safehouse!`, 'error');
    return;
  }
  GS.player.credits -= cost;
  GS.safehouses[districtId] = { owned: true, level: 1, bonus: 'Passive income: +50cr/day' };
  showToast(`Purchased safehouse in ${DISTRICTS_DB[districtId].name}!`, 'success');
  saveGame();
  refreshAllUI();
  openSafehouse();
}

function upgradeSafehouse(districtId) {
  const sh = GS.safehouses[districtId];
  if (!sh) return;
  const cost = 500 * sh.level;
  if (GS.player.credits < cost) {
    showToast(`Need ${formatCredits(cost)}cr to upgrade!`, 'error');
    return;
  }
  GS.player.credits -= cost;
  sh.level++;
  sh.bonus = `Passive income: +${50 * sh.level}cr/day`;
  showToast(`Safehouse upgraded to Level ${sh.level}!`, 'success');
  saveGame();
  refreshAllUI();
  openSafehouse();
}

// ===== COMBAT / DISTRICT TAKEOVER =====
function openTakeover() {
  const district = DISTRICTS_DB[GS.currentDistrict];
  const content = `
    <div class="space-y-6">
      <div class="text-center border border-[#ff2a6d] bg-gray-900 p-6" style="box-shadow:0 0 15px #ff2a6d">
        <h3 class="title-font text-2xl neon-pink mb-2">DISTRICT TAKEOVER</h3>
        <p class="text-gray-400 text-sm">Attempt to seize control of <span class="text-white">${district.name}</span></p>
        <p class="text-xs text-gray-500 mt-2">Threat Level: <span style="color:${district.color}">${district.threatLevel}</span></p>
      </div>

      <div class="text-sm text-gray-300">
        <p>Launch a takeover attempt to gain control of this district. Success grants passive income, reduced prices, and faction reputation. Failure costs HP and credits.</p>
      </div>

      <div class="border border-gray-700 bg-gray-900 p-4">
        <h4 class="font-bold neon-cyan mb-2">YOUR COMBAT STATS</h4>
        <div class="grid grid-cols-3 gap-2 text-sm">
          <div>🤜 Attack: <span class="text-white">${GS.player.stats.strength + GS.player.stats.agility}</span></div>
          <div>🛡 Defense: <span class="text-white">${GS.player.stats.endurance + GS.player.stats.strength}</span></div>
          <div>🎲 Luck: <span class="text-white">${GS.player.stats.luck}</span></div>
          <div>❤ HP: <span class="text-green-400">${GS.player.hp}/${GS.player.maxHp}</span></div>
          <div>⚡ Agility: <span class="text-white">${GS.player.stats.agility}</span></div>
          <div>🎯 Charisma: <span class="text-white">${GS.player.stats.charisma}</span></div>
        </div>
      </div>

      <div>
        <h4 class="font-bold neon-pink mb-2">SELECT APPROACH</h4>
        <div class="space-y-2">
          <button onclick="startCombat('force')" class="w-full border border-red-400 bg-gray-900 p-3 text-left hover:bg-gray-800">
            <div class="font-bold text-red-400"><i class="fas fa-fist-raised mr-2"></i>BRUTE FORCE</div>
            <div class="text-xs text-gray-500">Strength-focused. High damage, high risk.</div>
          </button>
          <button onclick="startCombat('stealth')" class="w-full border border-[#05d9e8] bg-gray-900 p-3 text-left hover:bg-gray-800">
            <div class="font-bold neon-cyan"><i class="fas fa-eye-slash mr-2"></i>STEALTH INFILTRATION</div>
            <div class="text-xs text-gray-500">Agility-focused. Lower reward, lower risk.</div>
          </button>
          <button onclick="startCombat('diplomacy')" class="w-full border border-[#d300c5] bg-gray-900 p-3 text-left hover:bg-gray-800">
            <div class="font-bold neon-purple"><i class="fas fa-handshake mr-2"></i>DIPLOMATIC COUP</div>
            <div class="text-xs text-gray-500">Charisma-focused. Can gain allies, but slower.</div>
          </button>
        </div>
      </div>
    </div>`;
  openModal('DISTRICT TAKEOVER', content);
}

function startCombat(approach) {
  const district = DISTRICTS_DB[GS.currentDistrict];
  let stat, successRate;
  if (approach === 'force') { stat = GS.player.stats.strength + GS.player.stats.endurance; successRate = 0.3 + stat / 100; }
  else if (approach === 'stealth') { stat = GS.player.stats.agility + GS.player.stats.luck; successRate = 0.4 + stat / 100; }
  else { stat = GS.player.stats.charisma + GS.player.stats.intelligence; successRate = 0.35 + stat / 100; }

  const luckBonus = GS.player.stats.luck / 200;
  successRate = Math.min(0.85, successRate + luckBonus);
  const success = Math.random() < successRate;

  const content = `
    <div class="text-center space-y-4">
      <div class="text-6xl mb-4">${success ? '⚔️' : '💀'}</div>
      <h3 class="title-font text-2xl ${success ? 'neon-cyan' : 'neon-pink'}">${success ? 'TAKEOVER SUCCESSFUL!' : 'TAKEOVER FAILED!'}</h3>
      <div class="text-gray-400 text-sm">
        Approach: ${approach.toUpperCase()} | Success Rate: ${Math.round(successRate * 100)}%
      </div>
      ${success ? `
        <div class="border border-[#05d9e8] bg-gray-900 p-4">
          <div class="text-sm mb-2"><span class="neon-cyan">District Influence:</span> <span class="text-white">${district.name}</span></div>
          <div class="text-sm"><span class="text-yellow-400">Credits Earned:</span> <span class="text-white">+${random(200, 800)}cr</span></div>
          <div class="text-sm"><span class="text-green-400">XP Earned:</span> <span class="text-white">+150</span></div>
          <div class="text-sm"><span class="text-purple-400">Faction Bonus:</span> <span class="text-white">Varies by allegiance</span></div>
        </div>
      ` : `
        <div class="border border-[#ff2a6d] bg-gray-900 p-4">
          <div class="text-sm"><span class="neon-pink">HP Lost:</span> <span class="text-white">-${random(10, 30)}</span></div>
          <div class="text-sm"><span class="text-red-400">Credits Lost:</span> <span class="text-white">-${random(50, 200)}cr</span></div>
          <div class="text-sm mt-2 text-gray-500">Better prepare before your next attempt.</div>
        </div>
      `}
      <button onclick="closeModal()" class="neon-btn bg-black ${success ? 'text-[#05d9e8] border-[#05d9e8]' : 'text-[#ff2a6d] border-[#ff2a6d]'} border px-6 py-2">CONTINUE</button>
    </div>`;

  if (success) {
    const creditsEarned = random(200, 800);
    GS.player.credits += creditsEarned;
    gainXP(150);
  } else {
    GS.player.hp = Math.max(1, GS.player.hp - random(10, 30));
    GS.player.credits = Math.max(0, GS.player.credits - random(50, 200));
  }
  saveGame();
  refreshAllUI();
  openModal('COMBAT RESULT', content);
}

// ===== AUCTION SYSTEM =====
function bidOnAuction(itemId) {
  const item = ITEMS_DB[itemId];
  const currentBid = Math.round(GS.market[itemId]?.currentPrice || item.basePrice);
  const minBid = Math.round(currentBid * 1.05);

  const content = `
    <div class="space-y-4">
      <div class="flex items-center gap-4">
        <div class="${item.color} text-5xl"><i class="fas ${item.icon}"></i></div>
        <div>
          <h3 class="font-bold text-white text-lg">${item.name}</h3>
          <p class="text-gray-400 text-sm">${item.description}</p>
          <p class="text-xs text-gray-500 mt-1">Category: ${item.category.toUpperCase()}</p>
        </div>
      </div>
      <div class="border border-[#d300c5] bg-black p-4">
        <div class="flex justify-between mb-2">
          <span class="text-gray-400">Current Bid:</span>
          <span class="text-yellow-400 font-bold">${formatCredits(currentBid)}cr</span>
        </div>
        <div class="flex justify-between mb-2">
          <span class="text-gray-400">Minimum Bid:</span>
          <span class="text-white">${formatCredits(minBid)}cr</span>
        </div>
        <div class="flex justify-between">
          <span class="text-gray-400">Your Credits:</span>
          <span class="${GS.player.credits >= minBid ? 'text-green-400' : 'text-red-400'}">${formatCredits(GS.player.credits)}cr</span>
        </div>
      </div>
      <div class="flex gap-3">
        <input type="number" id="auction-bid-input" value="${minBid}" min="${minBid}" class="flex-1 bg-gray-800 border border-[#05d9e8] px-3 py-2 text-white focus:outline-none" style="color-scheme:dark">
        <button onclick="submitBid('${itemId}')" class="neon-btn bg-black text-[#ff2a6d] border border-[#ff2a6d] px-6 py-2">PLACE BID</button>
      </div>
      <div class="text-xs text-gray-500"><i class="fas fa-info-circle mr-1"></i> Winning bids are final. Failed bids are refunded minus a 5% fee.</div>
    </div>`;
  openModal('AUCTION: ' + item.name.toUpperCase(), content);
}

function submitBid(itemId) {
  const input = document.getElementById('auction-bid-input');
  const bidAmount = parseInt(input.value);
  const currentPrice = Math.round(GS.market[itemId]?.currentPrice || ITEMS_DB[itemId].basePrice);
  const minBid = Math.round(currentPrice * 1.05);

  if (isNaN(bidAmount) || bidAmount < minBid) {
    showToast(`Minimum bid is ${formatCredits(minBid)}cr!`, 'error');
    return;
  }
  if (bidAmount > GS.player.credits) {
    showToast('Not enough credits!', 'error');
    return;
  }

  // 70% chance to win
  const won = Math.random() < 0.7;
  if (won) {
    GS.player.credits -= bidAmount;
    const existing = GS.inventory.find(i => i.id === itemId);
    if (existing) existing.qty++;
    else GS.inventory.push({ id: itemId, qty: 1 });
    gainXP(50);
    showToast(`Won auction for ${ITEMS_DB[itemId].name}! Paid ${formatCredits(bidAmount)}cr`, 'success');
  } else {
    const fee = Math.round(bidAmount * 0.05);
    GS.player.credits -= fee;
    showToast(`Lost the auction for ${ITEMS_DB[itemId].name}. Fee: ${formatCredits(fee)}cr`, 'warning');
  }
  saveGame();
  refreshAllUI();
  closeModal();
}

// ===== DIALOGUE SYSTEM =====
function sendAuctionMessage() {
  const input = document.getElementById('auction-chat-input');
  if (!input) return;
  const message = input.value.trim();
  if (!message) return;
  input.value = '';

  const chatArea = document.getElementById('auction-chat');
  if (!chatArea) return;

  // Player message
  chatArea.innerHTML += `<p class="text-[#ff2a6d] mb-1">VEIL: <span class="text-gray-300">"${message}"</span></p>`;

  // NPC response
  const responses = [
    'MADAME KARNA: "An interesting offer... but I\'ve seen more convincing bids from street rats."',
    'MADAME KARNA: "Ah, you have spirit. But spirit doesn\'t pay the bills, does it?"',
    'MADAME KARNA: "The Clownfather himself whispered about this item. Are you sure you can afford such attention?"',
    'MADAME KARNA: "Interesting... The Digital Saints would pay triple for that information alone."',
    'MADAME KARNA: "Mr. Bleak\'s collectors are circling this auction like vultures. Bid wisely."',
    'MADAME KARNA: "I admire the ambition, darling. But ambition has a habit of getting people killed in this city."'
  ];
  setTimeout(() => {
    chatArea.innerHTML += `<p class="text-[#05d9e8] mb-1">${pick(responses)}</p>`;
    chatArea.scrollTop = chatArea.scrollHeight;
  }, 500);

  chatArea.scrollTop = chatArea.scrollHeight;
}

// ===== MARKET PRICE UPDATES =====
function updateMarketPrices() {
  Object.keys(GS.market).forEach(id => {
    const item = ITEMS_DB[id];
    if (!item || item.basePrice === 0) return;
    const market = GS.market[id];
    // Random walk
    market.trend = market.trend * 0.95 + (Math.random() - 0.5) * 0.1;
    const change = 1 + market.trend + (Math.random() - 0.5) * 0.05 * (item.volatile ? 3 : 1);
    market.currentPrice = Math.max(Math.round(item.basePrice * 0.5), Math.round(market.currentPrice * change));
    // Supply/demand shifts
    market.supply = clamp(market.supply + random(-2, 2), 1, 50);
    market.demand = clamp(market.demand + random(-2, 3), 1, 50);
  });
}

function updateStockPrices() {
  Object.keys(GS.stocks).forEach(id => {
    const stock = GS.stocks[id];
    const data = STOCKS_DB[id];
    const change = (Math.random() - 0.48) * data.volatility;
    stock.price = Math.max(5, stock.price * (1 + change));
    stock.history.push(stock.price);
    if (stock.history.length > 30) stock.history.shift();
  });
}

// ===== RANDOM EVENTS =====
function triggerRandomEvent() {
  const event = pick(EVENTS_POOL);
  const district = DISTRICTS_DB[GS.currentDistrict];

  // Apply market effects
  if (event.effect) {
    Object.entries(event.effect).forEach(([category, modifier]) => {
      Object.keys(ITEMS_DB).forEach(id => {
        if (ITEMS_DB[id].category === category && GS.market[id]) {
          GS.market[id].currentPrice = Math.round(GS.market[id].currentPrice * modifier);
          GS.market[id].trend = (modifier - 1) * 0.5;
        }
      });
    });
  }

  // Show event in ticker
  const tickerTexts = document.querySelectorAll('.market-ticker span');
  if (tickerTexts.length > 0) {
    const typeColors = { danger: '#ff2a6d', warning: '#ffd700', info: '#05d9e8', opportunity: '#22c55e' };
    const color = typeColors[event.type] || '#ffffff';
    const newSpan = document.createElement('span');
    newSpan.className = 'mx-4';
    newSpan.style.color = color;
    newSpan.textContent = event.text;
    const ticker = document.querySelector('.market-ticker');
    if (ticker) {
      ticker.prepend(newSpan);
    }
  }

  showToast(event.text, event.type === 'danger' ? 'error' : event.type === 'opportunity' ? 'success' : 'info');
}

// ===== TIME SYSTEM =====
function advanceDay() {
  GS.day++;
  GS.time = 8;
  updateMarketPrices();
  updateStockPrices();

  // Loan interest
  GS.loans.forEach(loan => {
    loan.daysLeft--;
    if (loan.daysLeft <= 0) {
      showToast(`⚠️ LOAN FROM ${loan.lender} OVERDUE! Hunters dispatched!`, 'error');
      loan.daysLeft = 0;
      // Spawn debt collectors as events
      changeReputation('dust-collective', -5);
    }
  });

  // Safehouse income
  Object.values(GS.safehouses).forEach(sh => {
    if (sh && sh.owned) {
      const income = 50 * sh.level;
      GS.player.credits += income;
      showToast(`Safehouse income: +${income}cr`, 'success');
    }
  });

  // Random event (30% chance)
  if (Math.random() < 0.3) {
    triggerRandomEvent();
  }

  saveGame();
  refreshAllUI();
}

// ===== REFRESH UI =====
function refreshAllUI() {
  // Player profile
  const profileEl = document.getElementById('player-profile');
  if (profileEl) {
    const levelXpPct = Math.round((GS.player.xp / GS.player.xpToNext) * 100);
    profileEl.innerHTML = `
      <div class="flex justify-between items-center mb-2">
        <h2 class="neon-cyan text-lg font-bold">PLAYER PROFILE</h2>
        <span class="text-xs gold-text">LEVEL ${GS.player.level}</span>
      </div>
      <div class="flex items-center space-x-3 mb-4">
        <div class="w-16 h-16 bg-gray-800 border-2 border-neon-pink relative overflow-hidden">
          <i class="fas fa-skull text-3xl text-[#ff2a6d] absolute inset-0 flex items-center justify-center"></i>
          <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-70 text-center py-1">
            <span class="text-xs neon-pink">${GS.player.class.toUpperCase()}</span>
          </div>
        </div>
        <div>
          <h3 class="neon-pink text-sm">ALIAS: <span class="text-white">"${GS.player.name}"</span></h3>
          <h3 class="neon-cyan text-sm">CREDITS: <span class="text-white">${formatCredits(GS.player.credits)}</span></h3>
          <h3 class="text-sm text-green-400">HP: <span class="text-white">${GS.player.hp}/${GS.player.maxHp}</span></h3>
        </div>
      </div>
      <div class="mb-3">
        <div class="flex justify-between text-xs mb-1">
          <span class="neon-pink">XP: ${GS.player.xp}/${GS.player.xpToNext}</span>
          <span class="neon-cyan">${levelXpPct}%</span>
        </div>
        <div class="progress-bar">
          <div class="progress-bar-fill" style="width: ${levelXpPct}%"></div>
        </div>
      </div>
      ${GS.player.statPoints > 0 ? `<div class="text-xs text-yellow-400 pixel-font mb-2">⬆ ${GS.player.statPoints} STAT POINTS AVAILABLE!</div>` : ''}`;
  }

  // Stats
  const statsEl = document.getElementById('player-stats');
  if (statsEl) {
    const statNames = { charisma: 'CHARISMA', agility: 'AGILITY', intelligence: 'INTELLIGENCE', strength: 'STRENGTH', endurance: 'ENDURANCE', luck: 'LUCK' };
    statsEl.innerHTML = Object.entries(GS.player.stats).map(([stat, val]) => `
      <div>
        <div class="flex justify-between text-xs">
          <span class="neon-pink">${statNames[stat] || stat.toUpperCase()}</span>
          <span>${val}</span>
        </div>
        <div class="progress-bar">
          <div class="progress-bar-fill" style="width: ${Math.min(100, Math.round((val / 30) * 100))}%"></div>
        </div>
      </div>`
    ).join('');
  }

  // Mutations count
  const mutCount = document.getElementById('mutation-count');
  if (mutCount) mutCount.textContent = GS.mutations.length;

  // Credits in footer
  const creditsFooter = document.getElementById('footer-credits');
  if (creditsFooter) creditsFooter.textContent = formatCredits(GS.player.credits);

  // Location in footer
  const locFooter = document.getElementById('footer-location');
  if (locFooter) locFooter.textContent = DISTRICTS_DB[GS.currentDistrict]?.name || 'Unknown';

  // Day in footer
  const dayFooter = document.getElementById('footer-day');
  if (dayFooter) dayFooter.textContent = `Day ${GS.day}`;

  saveGame();
}

// ===== INITIALIZATION =====
function init() {
  loadGame();

  // Wire up buttons
  const buttonMap = {
    'btn-character': () => openCharacterPanel(),
    'btn-market': () => openMarket(),
    'btn-districts': () => openDistricts(),
    'btn-mutations': () => openMutations(),
    'btn-quests': () => openQuestLog(),
    'btn-inventory': () => openInventory(),
    'btn-factions': () => openFactions(),
    'btn-buy': () => { openMarket(); setTimeout(() => marketTab('buy'), 50); },
    'btn-sell': () => { openMarket(); setTimeout(() => marketTab('sell'), 50); },
    'btn-craft': () => openCrafting(),
    'btn-safehouse': () => openSafehouse(),
    'btn-takeover': () => openTakeover()
  };

  Object.entries(buttonMap).forEach(([id, handler]) => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('click', handler);
  });

  // Wire up auction bid buttons
  document.querySelectorAll('[data-auction-bid]').forEach(btn => {
    btn.addEventListener('click', () => bidOnAuction(btn.dataset.auctionBid));
  });

  // Wire district markers
  document.querySelectorAll('[data-travel-district]').forEach(el => {
    el.addEventListener('click', () => travelToDistrict(el.dataset.travelDistrict));
  });

  // Refresh UI
  refreshAllUI();

  // Game loop - update every 60 seconds
  setInterval(() => {
    updateMarketPrices();
    updateStockPrices();
    if (Math.random() < 0.2) triggerRandomEvent();
  }, 60000);

  // Auto-save every 30 seconds
  setInterval(saveGame, 30000);
}

document.addEventListener('DOMContentLoaded', init);

// Close modal on overlay click
document.addEventListener('click', (e) => {
  if (e.target.id === 'modal-overlay') closeModal();
});

// Keyboard support
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') closeModal();
  if (e.key === 'Enter') {
    const auctionInput = document.getElementById('auction-chat-input');
    if (document.activeElement === auctionInput) {
      sendAuctionMessage();
    }
  }
});