File size: 118,866 Bytes
0d749c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="mk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Igraj so Sila — Staza na Peharite</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/baloo-2@5.0.20/index.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/rubik@5.0.20/index.css">
<script type="importmap">

{

  "imports": {

    "three": "https://unpkg.com/three@0.160.0/build/three.module.js",

    "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"

  }

}

</script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
html,body{height:100%;overflow:hidden;background:#0b1020;font-family:'Rubik',system-ui,sans-serif;color:#fff;-webkit-user-select:none;user-select:none;touch-action:manipulation}
#game{position:fixed;inset:0;display:block}
.hidden{display:none!important}
.gold{color:#ffc531}
#hud{position:fixed;inset:0;pointer-events:none;z-index:10}
#topbar{position:absolute;top:10px;left:10px;right:10px;display:flex;justify-content:space-between;align-items:flex-start;gap:8px}
.cluster{display:flex;gap:8px;align-items:center;flex-wrap:wrap;max-width:52%}
#menuBtns{justify-content:flex-end}
.panel{background:rgba(16,22,40,.85);border:1px solid rgba(255,255,255,.08);border-radius:14px;backdrop-filter:blur(6px);box-shadow:0 6px 20px rgba(0,0,0,.35)}
.pill{display:flex;align-items:center;gap:8px;padding:8px 14px;font-weight:700;font-size:15px}
.pill .ico{font-size:18px}
#lvBadge{width:48px;height:48px;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;background:linear-gradient(135deg,#ffb52e,#ff5d5d);font-family:'Baloo 2';box-shadow:0 4px 0 #a33800,0 6px 14px rgba(0,0,0,.35);border:2px solid rgba(255,255,255,.25)}
#lvBadge span{font-size:18px;font-weight:800;line-height:1}
#lvBadge small{font-size:9px;opacity:.85;letter-spacing:1px}
#xpWrap{padding:8px 12px;min-width:150px}
#xpText{font-size:11px;font-weight:700;color:#cdd6f0}
#xpBarOuter{height:8px;background:rgba(255,255,255,.12);border-radius:99px;overflow:hidden;margin-top:5px}
#xpBar{height:100%;width:0%;background:linear-gradient(90deg,#ff5d5d,#ffb52e,#ffe066);border-radius:99px;transition:width .3s;box-shadow:0 0 10px rgba(255,181,46,.5)}
.iconbtn{pointer-events:auto;width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;cursor:pointer;background:rgba(16,22,40,.85);border:1px solid rgba(255,255,255,.1);box-shadow:0 4px 0 rgba(0,0,0,.4);transition:transform .08s}
.iconbtn:hover{border-color:#ffc531}
.iconbtn:active{transform:translateY(2px);box-shadow:0 2px 0 rgba(0,0,0,.4)}
.iconbtn.pulse{animation:pulse 1.2s infinite}
@keyframes pulse{0%,100%{box-shadow:0 4px 0 rgba(0,0,0,.4),0 0 0 0 rgba(255,193,7,.7)}50%{box-shadow:0 4px 0 rgba(0,0,0,.4),0 0 0 9px rgba(255,193,7,0)}}
.btn{font-family:'Baloo 2';border:none;border-radius:12px;padding:10px 20px;font-size:16px;font-weight:800;cursor:pointer;color:#fff;background:linear-gradient(180deg,#00b3ff,#0084ff);box-shadow:0 4px 0 #005ecb,0 6px 14px rgba(0,0,0,.3);transition:transform .08s}
.btn:active{transform:translateY(3px);box-shadow:0 1px 0 #005ecb}
.btn.green{background:linear-gradient(180deg,#2ee06e,#0fbf57);box-shadow:0 4px 0 #0a8a3e}
.btn.gold{background:linear-gradient(180deg,#ffd23f,#ff9a1f);box-shadow:0 4px 0 #c26a00;color:#3a2300}
.btn.gray{background:linear-gradient(180deg,#4b5577,#363f5e);box-shadow:0 4px 0 #232a44}
.btn.sm{padding:7px 14px;font-size:13px}
.btn.big{padding:14px 44px;font-size:20px}
.btn:disabled{filter:grayscale(.7);opacity:.55;cursor:not-allowed;transform:none}
.tag{display:inline-block;padding:4px 10px;border-radius:99px;background:#2a3354;font-size:12px;font-weight:700}
.tag.green{background:#0fbf57;color:#fff}
.tag.gold{background:#ffc531;color:#3a2300}
.tag.gray{opacity:.6}
#prompt{position:fixed;bottom:90px;left:50%;transform:translateX(-50%);z-index:15;padding:10px 18px;border-radius:12px;font-weight:700;display:none;background:rgba(16,22,40,.92);border:1px solid rgba(255,255,255,.12);box-shadow:0 6px 20px rgba(0,0,0,.4)}
#prompt .key{background:linear-gradient(180deg,#ffc531,#ff9a1f);color:#3a2300;border-radius:6px;padding:2px 10px;font-family:'Baloo 2';margin-right:10px;font-weight:800;box-shadow:0 2px 0 #c26a00}
#stageBanner{position:fixed;left:50%;top:68px;transform:translateX(-50%);z-index:9;font-family:'Baloo 2';font-size:13px;color:#ffd23f;background:linear-gradient(90deg,rgba(255,181,46,.1),rgba(255,181,46,.35),rgba(255,181,46,.1));padding:5px 20px;border-radius:99px;border:1px solid rgba(255,181,46,.45);letter-spacing:1px;white-space:nowrap;max-width:92vw;overflow:hidden;text-overflow:ellipsis;box-shadow:0 0 20px rgba(255,181,46,.25)}
#hints{position:fixed;right:12px;bottom:12px;z-index:12;padding:8px 14px;font-size:12px;color:#aab6d8;pointer-events:none}
#toasts{position:fixed;left:12px;bottom:12px;z-index:30;display:flex;flex-direction:column;gap:8px;pointer-events:none;max-width:320px}
.toast{display:flex;gap:8px;align-items:center;font-size:14px;padding:10px 14px;animation:slideIn .3s}
@keyframes slideIn{from{transform:translateX(-16px);opacity:0}}
.toast.out{opacity:0;transform:translateX(-10px);transition:all .4s}
#floaters{position:fixed;inset:0;pointer-events:none;z-index:20;overflow:hidden}
.floater{position:absolute;font-family:'Baloo 2';font-weight:800;font-size:18px;text-shadow:0 2px 4px rgba(0,0,0,.6);white-space:nowrap}
.floater span{display:inline-block;transform:translate(-50%,-50%);animation:floatUp 1.2s ease-out forwards}
@keyframes floatUp{0%{opacity:0;transform:translate(-50%,-50%) translateY(8px)}15%{opacity:1}100%{opacity:0;transform:translate(-50%,-50%) translateY(-56px)}}
#modalRoot{position:fixed;inset:0;z-index:50;display:none;align-items:center;justify-content:center;background:rgba(5,8,18,.6);backdrop-filter:blur(3px);padding:14px}
#modalRoot.open{display:flex}
.modal{width:min(620px,94vw);max-height:88vh;overflow:auto;border-radius:20px;padding:22px;background:linear-gradient(180deg,#1a2342,#131a33);border:1px solid rgba(255,255,255,.12);box-shadow:0 20px 60px rgba(0,0,0,.6);animation:pop .25s}
@keyframes pop{from{transform:scale(.85);opacity:0}}
.mhead{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
.mhead h2{font-family:'Baloo 2';font-size:24px;background:linear-gradient(180deg,#ffe259,#ff9a3d);-webkit-background-clip:text;background-clip:text;color:transparent}
.mclose{width:34px;height:34px;border-radius:10px;border:none;background:#2a3354;color:#fff;font-size:18px;cursor:pointer}
.sub{color:#9aa5c0;font-size:14px;margin-bottom:12px}
.mrow{display:flex;gap:10px;justify-content:center;margin-top:16px;flex-wrap:wrap}
.tabs{display:flex;gap:6px;margin-bottom:12px}
.tab{flex:1;padding:8px;border-radius:10px;background:#202a4d;border:none;color:#aab;font-weight:700;cursor:pointer;font-family:'Rubik'}
.tab.on{background:linear-gradient(180deg,#ffb52e,#ff5d5d);color:#fff;box-shadow:0 3px 0 #8a1818}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(118px,1fr));gap:10px}
.item{background:#1c2547;border:2px solid #2a3354;border-radius:14px;padding:12px 8px;text-align:center}
.item.eq{border-color:#ffc531;box-shadow:0 0 0 2px rgba(255,193,7,.25)}
.iprev{font-size:34px;height:42px;display:flex;align-items:center;justify-content:center}
.iname{font-size:13px;font-weight:700;margin:4px 0 8px}
.swrow{margin-bottom:14px}
.swlabel{font-size:13px;font-weight:700;color:#9aa5c0;margin-bottom:6px}
.sws{display:flex;gap:8px;flex-wrap:wrap}
.sw{width:38px;height:38px;border-radius:10px;border:3px solid transparent;cursor:pointer}
.sw.on{border-color:#fff;transform:scale(1.08)}
.pack{background:#1c2547;border:2px solid #2a3354;border-radius:14px;padding:14px;text-align:center}
.pack .pv{font-size:22px;font-weight:800;font-family:'Baloo 2'}
.pack .pp{color:#9aa5c0;font-size:12px;margin:4px 0 8px}
.pgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(128px,1fr));gap:10px}
.pcard{background:#1c2547;border:2px solid #2a3354;border-radius:14px;padding:12px 8px;text-align:center}
.pcard.eq{box-shadow:0 0 0 2px rgba(46,224,110,.35)}
.pcard.locked{opacity:.5}
.pemoji{font-size:38px;height:46px;display:flex;align-items:center;justify-content:center}
.pname{font-size:13px;font-weight:700;margin-top:2px}
.prarity{font-size:11px;font-weight:700;margin-top:2px}
.pmult{font-size:11px;color:#9aa5c0;margin:4px 0 8px}
.rc-Common{color:#c3cbd6}.rc-Rare{color:#5cb0ff}.rc-Epic{color:#c884ff}.rc-Legendary{color:#ffc531}.rc-Mythic{color:#ff6b8a}
.bc-Common{border-color:#5a6472}.bc-Rare{border-color:#3b9dff}.bc-Epic{border-color:#b45cff}.bc-Legendary{border-color:#ffb52e}.bc-Mythic{border-color:#ff4d6d}
.qrow{display:flex;gap:12px;align-items:center;background:#1c2547;border-radius:12px;padding:12px;margin-bottom:8px}
.qrow.done{opacity:.55}
.qico{font-size:26px}
.qmain{flex:1;min-width:0}
.qtxt{font-size:14px;font-weight:700}
.qbar{height:8px;background:#0e1430;border-radius:99px;overflow:hidden;margin:6px 0 4px}
.qbar i{display:block;height:100%;background:linear-gradient(90deg,#2ee06e,#00e5ff);border-radius:99px;transition:width .3s}
.qmeta{font-size:11px;color:#9aa5c0}
.srow{display:flex;gap:12px;align-items:center;background:#1c2547;border-radius:12px;padding:10px 12px;margin-bottom:6px}
.srow.done{opacity:.55}.srow.can{border:1px solid #2ee06e}
.snum{width:30px;height:30px;border-radius:50%;background:#2a3354;display:flex;align-items:center;justify-content:center;font-weight:800;font-family:'Baloo 2'}
.srew{flex:1;font-size:14px;font-weight:700}
.frow{display:flex;gap:12px;align-items:center;background:#1c2547;border-radius:12px;padding:12px;margin-bottom:8px}
.fava{width:42px;height:42px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-family:'Baloo 2';color:#1b2440}
.fmain{flex:1}
.fname{font-weight:700;font-size:14px}
.fstatus{font-size:11px;margin-left:6px}
.fstatus.on{color:#2ee06e}.fstatus.off{color:#7d87a8}
.fsub{font-size:12px;color:#9aa5c0;margin-top:2px}
.brow{display:flex;gap:12px;align-items:center;background:#1c2547;border-radius:10px;padding:9px 12px;margin-bottom:5px}
.brow.me{background:#243363;border:1px solid #ffc531}
.brank{width:34px;font-weight:800;font-family:'Baloo 2';text-align:center}
.bname{flex:1;font-weight:700}
.bval{font-weight:700;color:#ffe066}
.days{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;margin:12px 0}
.day{background:#1c2547;border-radius:10px;padding:8px 4px;text-align:center;position:relative;border:2px solid transparent}
.day.past{opacity:.45}.day.now{border-color:#ffc531;background:#2a3364}
.dnum{font-size:10px;color:#9aa5c0;font-weight:700}.drew{font-size:14px;font-weight:800;margin-top:4px}
.dtag{position:absolute;top:-8px;left:50%;transform:translateX(-50%);background:#ffc531;color:#3a2a00;font-size:9px;font-weight:800;padding:2px 6px;border-radius:99px;white-space:nowrap}
.miles{display:flex;gap:8px;margin-bottom:12px}
.mile{flex:1;background:#1c2547;border-radius:10px;padding:10px;text-align:center;font-size:12px}
.mile.locked{opacity:.55}
.streak{font-family:'Baloo 2';font-size:18px;text-align:center;margin-bottom:6px}
.statsline{margin-top:14px;padding-top:12px;border-top:1px solid rgba(255,255,255,.08);font-size:12px;color:#9aa5c0}
.reveal{text-align:center;padding:6px 0}
.raritytag{display:inline-block;padding:5px 16px;border-radius:99px;font-weight:800;font-size:12px;letter-spacing:1.5px;background:#0e1430;border:1px solid currentColor;box-shadow:0 0 20px currentColor}
.bigemoji{font-size:92px;margin:14px 0 6px;animation:floaty 2s ease-in-out infinite;text-shadow:0 0 40px currentColor}
@keyframes floaty{0%,100%{transform:translateY(0) scale(1)}50%{transform:translateY(-10px) scale(1.05)}}
.newtag{background:#2ee06e;color:#04331a;padding:3px 10px;border-radius:99px;font-weight:800;font-size:12px}
.rmult{color:#9aa5c0;margin:8px 0 4px}
.rsub{margin:8px 0;font-size:14px}
.rebirthbox{text-align:center}
.rebirthbox .rbig{font-family:'Baloo 2';font-size:26px;color:#ffc531;margin-bottom:8px}
.rebirthbox p{color:#c7d0e8;margin:8px 0;font-size:14px}
.rnums{font-family:'Baloo 2';font-size:20px;margin:10px 0}
.keep{font-size:12px;color:#9aa5c0}
.charGrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:18px}
.charCard{background:linear-gradient(180deg,#1c2547,#141a36);border:3px solid #2a3354;border-radius:16px;padding:14px 10px;text-align:center;cursor:pointer;transition:all .25s;position:relative}
.charCard:hover{transform:translateY(-4px);border-color:#ffc531}
.charCard.on{border-color:#ffc531;box-shadow:0 0 24px rgba(255,193,7,.4)}
.charPreview{height:110px;position:relative;margin-bottom:8px;display:flex;align-items:center;justify-content:center}
.charPreview canvas{width:100%;height:100%}
.charName{font-family:'Baloo 2';font-size:17px;font-weight:800;margin-bottom:2px}
.charTag{font-size:11px;font-weight:700;letter-spacing:1px;margin-bottom:6px}
.charDesc{font-size:11px;color:#9aa5c0;line-height:1.4;min-height:40px}
.charTrait{display:inline-block;background:#2a3354;padding:3px 8px;border-radius:99px;font-size:10px;font-weight:700;margin-top:6px;color:#ffc531}
#touchUI{display:none}
@media(pointer:coarse){#touchUI{display:block}#hints{display:none}}
#joyBase{position:fixed;left:22px;bottom:26px;width:120px;height:120px;border-radius:50%;background:rgba(255,255,255,.12);border:2px solid rgba(255,255,255,.25);z-index:25;touch-action:none;box-shadow:inset 0 0 20px rgba(255,255,255,.1)}
#joyKnob{position:absolute;left:50%;top:50%;width:52px;height:52px;margin:-26px;border-radius:50%;background:rgba(255,255,255,.5);pointer-events:none}
.tbtn{position:fixed;z-index:25;width:64px;height:64px;border-radius:50%;border:none;font-size:24px;font-weight:800;color:#fff;background:rgba(16,22,40,.7);border:2px solid rgba(255,255,255,.25);touch-action:none;font-family:'Baloo 2'}
#btnJump{right:26px;bottom:96px}
#btnAct{right:96px;bottom:26px}
#loader{position:fixed;inset:0;z-index:100;display:flex;flex-direction:column;align-items:center;justify-content:center;background:radial-gradient(ellipse at top,#1a2342,#050810 75%);transition:opacity .7s;overflow:hidden}
#loader::before{content:'';position:absolute;inset:-30%;background:
  radial-gradient(circle at 20% 30%,rgba(255,181,46,.25),transparent 45%),
  radial-gradient(circle at 80% 70%,rgba(255,93,93,.25),transparent 45%),
  radial-gradient(circle at 50% 50%,rgba(180,92,255,.2),transparent 50%),
  radial-gradient(circle at 70% 20%,rgba(0,229,255,.2),transparent 45%);
  animation:bgmove 12s ease-in-out infinite alternate;filter:blur(20px)}
#loader::after{content:'';position:absolute;inset:-10%;background:radial-gradient(circle at 50% 40%,rgba(255,197,49,.15),transparent 55%);animation:bgpulse 5s ease-in-out infinite alternate}
@keyframes bgmove{0%{transform:scale(1) rotate(0deg) translate(0,0)}50%{transform:scale(1.2) rotate(8deg) translate(2%,3%)}100%{transform:scale(1.08) rotate(-6deg) translate(-2%,-2%)}}
@keyframes bgpulse{0%{opacity:.3;transform:scale(0.9)}100%{opacity:.9;transform:scale(1.15)}}
#loader.done{opacity:0;pointer-events:none}
.lcontent{position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;text-align:center;padding:20px;max-width:min(760px,94vw)}
.logo{font-family:'Baloo 2';font-size:clamp(40px,8vw,74px);font-weight:800;letter-spacing:3px;filter:drop-shadow(0 4px 0 rgba(0,0,0,.5));line-height:1;margin-bottom:6px}
.l1{background:linear-gradient(180deg,#ffe259,#ff9a3d);-webkit-background-clip:text;background-clip:text;color:transparent;text-shadow:0 0 40px rgba(255,181,46,.5)}
.l2{background:linear-gradient(180deg,#ff5d5d,#b45cff);-webkit-background-clip:text;background-clip:text;color:transparent;text-shadow:0 0 40px rgba(255,93,93,.4)}
.tagline{color:#dbe4ff;margin-top:4px;font-size:14px;letter-spacing:1px}
.stageName{font-family:'Baloo 2';font-size:clamp(13px,2.2vw,17px);color:#ffc531;margin-top:10px;padding:6px 18px;background:rgba(255,181,46,.1);border:1px solid rgba(255,181,46,.4);border-radius:99px;letter-spacing:1px;box-shadow:0 0 30px rgba(255,181,46,.2)}
.chips{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin:18px 0}
.chip{background:rgba(10,14,28,.8);border:1px solid rgba(255,255,255,.15);padding:7px 14px;border-radius:99px;font-size:13px;font-weight:600;box-shadow:0 4px 12px rgba(0,0,0,.3)}
#nameInput{padding:13px 18px;border-radius:12px;border:2px solid rgba(255,255,255,.2);background:rgba(10,14,28,.9);color:#fff;font-size:16px;width:min(320px,86vw);text-align:center;font-family:'Rubik';margin-bottom:14px;outline:none;transition:border-color .2s}
#nameInput:focus{border-color:#ffc531;box-shadow:0 0 20px rgba(255,181,46,.25)}
.hint{margin-top:16px;color:#c7d0e8;font-size:13px}
.fineprint{margin-top:10px;color:#7d87a8;font-size:11px;max-width:86vw}
.npcBox{display:flex;flex-direction:column;gap:14px}
.npcHeader{display:flex;align-items:center;gap:12px;background:rgba(255,255,255,.05);padding:12px 14px;border-radius:14px;border:1px solid rgba(255,255,255,.1)}
.npcAvatarBadge{width:52px;height:52px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;box-shadow:0 4px 12px rgba(0,0,0,.3);border:2px solid rgba(255,255,255,.2);flex-shrink:0}
.npcMeta{flex:1;min-width:0}
.npcName{font-family:'Baloo 2';font-size:20px;font-weight:800;color:#ffc531;line-height:1.2}
.npcTitle{font-size:12px;color:#aab6d8;font-weight:600}
.npcCdTag{font-size:11px;font-weight:700;padding:4px 10px;border-radius:99px;background:#2a3354;color:#2ee06e}
.npcCdTag.wait{background:#3a2020;color:#ff6b6b}
.npcSpeechBubble{position:relative;background:#1a2548;border:2px solid #2e3c6e;border-radius:16px;padding:16px 18px;font-size:15px;line-height:1.5;color:#e8eeff;box-shadow:0 8px 24px rgba(0,0,0,.3);min-height:70px;display:flex;align-items:center}
.npcSpeechBubble::before{content:'';position:absolute;top:-10px;left:28px;border-width:0 10px 10px 10px;border-style:solid;border-color:transparent transparent #2e3c6e transparent}
.chatOptions{display:flex;flex-direction:column;gap:8px;margin-top:6px}
.chatBtn{text-align:left;display:flex;align-items:center;justify-content:flex-start;gap:10px;padding:12px 16px;font-size:15px;width:100%}
.triviaBox{display:flex;flex-direction:column;gap:10px}
.triviaTitle{font-weight:700;font-size:15px;color:#ffd23f;margin-bottom:4px}
.triviaOpt{width:100%;text-align:left;padding:10px 14px;font-size:14px}
@media(max-width:720px){.iconbtn{width:40px;height:40px;font-size:18px}#xpWrap{min-width:110px}.pill{padding:6px 10px;font-size:13px}.cluster{max-width:58%}}
</style>
</head>
<body>
<canvas id="game"></canvas>
<div id="hud">
  <div id="topbar">
    <div class="cluster">
      <div id="lvBadge" class="panel"><span id="lvNum">1</span><small>LV</small></div>
      <div id="xpWrap" class="panel"><div id="xpText">0/40 XP</div><div id="xpBarOuter"><div id="xpBar"></div></div></div>
      <div class="pill panel"><span class="ico">🪙</span><span id="coinVal">0</span></div>
      <div class="pill panel"><span class="ico">💠</span><span id="buxVal">0</span></div>
    </div>
    <div class="cluster" id="menuBtns">
      <button class="iconbtn" id="btnDaily" onclick="openDaily()" title="Daily Rewards">🎁</button>
      <button class="iconbtn" id="btnQuests" onclick="openQuests()" title="Quests">📜</button>
      <button class="iconbtn" onclick="openPets()" title="Pets">🐾</button>
      <button class="iconbtn" onclick="openShop('hats')" title="Shop">🛍️</button>
      <button class="iconbtn" onclick="openSeason()" title="Season Pass">🏆</button>
      <button class="iconbtn" onclick="openFriends()" title="Friends">👥</button>
      <button class="iconbtn" onclick="openBoard('daily')" title="Leaderboard">📊</button>
      <button class="iconbtn" onclick="openCharSelect()" title="Champions">🎭</button>
      <button class="iconbtn" id="btnRebirth" onclick="useStatueModal()" title="Rebirth" style="display:none">⭐</button>
      <button class="iconbtn" id="btnMute" onclick="toggleMute()" title="Sound">🔊</button>
    </div>
  </div>
</div>
<div id="stageBanner">🏆 STAZA NA PEHARITE I NAJDOBRITE IGRACI 🏆</div>
<div id="prompt"></div>
<div id="hints" class="panel">WASD move · SPACE jump · E interact</div>
<div id="floaters"></div>
<div id="toasts"></div>
<div id="touchUI">
  <div id="joyBase"><div id="joyKnob"></div></div>
  <button id="btnJump" class="tbtn">⬆</button>
  <button id="btnAct" class="tbtn">E</button>
</div>
<div id="modalRoot"></div>
<div id="loader">
  <div class="lcontent">
    <div class="logo"><span class="l1">IGRAJ</span> <span class="l2">SO SILA</span></div>
    <div class="tagline">PLAY WITH POWER · WALK THE PATH OF CHAMPIONS</div>
    <div class="stageName">🏆 STAZA NA PEHARITE I NAJDOBRITE IGRACI 🏆</div>
    <div class="chips"><span class="chip">🎭 7 Champions</span><span class="chip">🐾 15 Pets</span><span class="chip">🏆 Trophy Path</span><span class="chip">⭐ Rebirth</span></div>
    <input id="nameInput" maxlength="16" placeholder="Enter your champion name...">
    <button id="playBtn" class="btn gold big">▶ ENTER THE ARENA</button>
    <div class="hint">WASD to move · SPACE to jump · E to interact · All champions start with 🪙 1,000,000</div>
    <div class="fineprint">Fan-made playable demo inspired by Roblox · Progress saves locally · All purchases are simulated (no real money)</div>
  </div>
</div>
<script type="module">

import * as THREE from 'three';

import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';

import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';

import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';

import {OutlinePass} from 'three/addons/postprocessing/OutlinePass.js';

import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';

import {SSAOPass} from 'three/addons/postprocessing/SSAOPass.js';



const $=s=>document.querySelector(s);

const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));

const rand=(a,b)=>a+Math.random()*(b-a);

const ri=(a,b)=>Math.floor(rand(a,b+1));

const pick=a=>a[Math.floor(Math.random()*a.length)];

const fmt=n=>n>=1e9?(n/1e9).toFixed(1)+'B':n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?(n/1e3).toFixed(1)+'k':''+Math.floor(n);

const todayStr=()=>new Date().toDateString();

const mmss=s=>{s=Math.max(0,Math.ceil(s));return Math.floor(s/60)+':'+String(s%60).padStart(2,'0')};

const getWeek=()=>Math.floor(Date.now()/6048e5);

const dist2D=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z);

function lerpAngle(a,b,t){let d=(b-a)%(Math.PI*2);if(d>Math.PI)d-=Math.PI*2;if(d<-Math.PI)d+=Math.PI*2;return a+d*t}

function rr(x,a,b,w,h,r){x.beginPath();x.moveTo(a+r,b);x.arcTo(a+w,b,a+w,b+h,r);x.arcTo(a+w,b+h,a,b+h,r);x.arcTo(a,b+h,a,b,r);x.arcTo(a,b,a+w,b,r);x.closePath()}



const CHARACTERS=[

 {id:'sila',name:'SILA',tag:'⚔️ THE CHAMPION',color:'#ff5d5d',desc:'The hero of the Trophy Path. Sila carries the hopes of every challenger.',trait:'+20% Trophy Aura',skin:0xf2c58f,shirt:0xff5d5d,pants:0x3a0d0d,hair:0x8a1818,hat:'flame',eyes:0xffd23f,accent:0xffc531,cape:0xff5d5d,shoulder:true},

 {id:'jane',name:'JANE',tag:'🌸 THE COMPANION',color:'#f7a8d8',desc:'Sila\'s trusted friend. Jane heals hearts and boosts morale on the path.',trait:'+20% Friend Bonus',skin:0xffdbac,shirt:0xf7a8d8,pants:0x7a3d5a,hair:0xffd23f,hat:'halo',eyes:0x5db9ff,accent:0xffd23f,cape:null,shoulder:false},

 {id:'blaze',name:'BLAZE',tag:'🔥 FIRE WARRIOR',color:'#ff9a1f',desc:'Born in the volcano\'s heart, Blaze burns through every challenge.',trait:'+15% Fire Aura',skin:0xf2c58f,shirt:0xff5d5d,pants:0x3a0d0d,hair:0x8a1818,hat:'flame',eyes:0xffd23f,accent:0xff9a1f},

 {id:'frost',name:'FROST',tag:'❄️ ICE MAGE',color:'#5db9ff',desc:'Keeper of frozen secrets, Frost commands the eternal winter.',trait:'+15% Frost Shield',skin:0xe8d4b8,shirt:0x5db9ff,pants:0x1a3a6b,hair:0xffffff,hat:'crown',eyes:0x00e5ff,accent:0x7fd8ff},

 {id:'neon',name:'NEON',tag:'⚡ CYBER PUNK',color:'#c06bff',desc:'A glitch in the matrix, Neon hacks reality itself.',trait:'+15% Speed Boost',skin:0xd4b896,shirt:0x2a0845,pants:0x0a0418,hair:0xff5df2,hat:'visor',eyes:0x00ff88,accent:0xff5df2},

 {id:'golden',name:'GOLDEN',tag:'👑 TROPHY KING',color:'#ffc531',desc:'Crowned by victory, Golden walks the Trophy Path to legend.',trait:'+15% Trophy Aura',skin:0xf2c58f,shirt:0xffc531,pants:0x8a5c00,hair:0xffd768,hat:'crown',eyes:0x3a2300,accent:0xffe066},

 {id:'shadow',name:'SHADOW',tag:'🌙 NINJA',color:'#9b59f5',desc:'Silent as night, Shadow strikes before the enemy blinks.',trait:'+15% Stealth Strike',skin:0xc68642,shirt:0x1a1a2e,pants:0x0f0f1a,hair:0x1a1a2e,hat:'hood',eyes:0xff5d5d,accent:0x9b59f5}

];



const RARITY_ORDER=[['Common',55],['Rare',25],['Epic',12],['Legendary',6],['Mythic',2]];

const RARITY_HEX={Common:0x9aa5b1,Rare:0x3b9dff,Epic:0xb45cff,Legendary:0xffb52e,Mythic:0xff4d6d};

const RARITY_CSS={Common:'#c3cbd6',Rare:'#5cb0ff',Epic:'#c884ff',Legendary:'#ffc531',Mythic:'#ff6b8a'};

const PETS=[

 {id:'pup',name:'Blocky Pup',emoji:'🐶',rarity:'Common',mult:1.15,body:0xc98a5b},

 {id:'kit',name:'Pixel Kitty',emoji:'🐱',rarity:'Common',mult:1.20,body:0x9aa5b1},

 {id:'duk',name:'Quacko',emoji:'🦆',rarity:'Common',mult:1.10,body:0xffd23f},

 {id:'bun',name:'Hoppy',emoji:'🐰',rarity:'Common',mult:1.25,body:0xf5f0e8},

 {id:'fox',name:'Ember Fox',emoji:'🦊',rarity:'Rare',mult:1.50,body:0xff7a3d},

 {id:'pan',name:'Bamboo',emoji:'🐼',rarity:'Rare',mult:1.60,body:0xe8e8e8},

 {id:'bot',name:'B0T-4',emoji:'🤖',rarity:'Rare',mult:1.70,body:0x8fa3b8},

 {id:'frg',name:'Croak',emoji:'🐸',rarity:'Rare',mult:1.55,body:0x58c95c},

 {id:'drg',name:'Spark Dragon',emoji:'🐲',rarity:'Epic',mult:2.30,body:0x37b24d},

 {id:'uni',name:'Starlight',emoji:'🦄',rarity:'Epic',mult:2.50,body:0xf7a8d8},

 {id:'gho',name:'Boo',emoji:'👻',rarity:'Epic',mult:2.20,body:0xdfe6ee},

 {id:'gol',name:'Golden Golem',emoji:'🗿',rarity:'Legendary',mult:3.60,body:0xf5b73d},

 {id:'gal',name:'Galaxy Fox',emoji:'🌌',rarity:'Legendary',mult:4.00,body:0x5f3dc4},

 {id:'rbw',name:'Rainbow Slime',emoji:'🌈',rarity:'Mythic',mult:6.50,body:0xff5d8f},

 {id:'vod',name:'Void Wyvern',emoji:'🐉',rarity:'Mythic',mult:8.00,body:0x2b2f44}

];

const petById=id=>PETS.find(p=>p.id===id);

const HATS=[{id:'none',name:'No Hat',price:0},{id:'cap',name:'Red Cap',price:50},{id:'top',name:'Top Hat',price:120},{id:'prop',name:'Propeller',price:180},{id:'crown',name:'Royal Crown',price:250},{id:'halo',name:'Angel Halo',price:400}];

const HAT_EMOJI={none:'🚫',cap:'🧢',top:'🎩',prop:'🌀',crown:'👑',halo:'😇'};

const TRAILS=[{id:'none',name:'None',price:0},{id:'fire',name:'Fire Trail',price:150},{id:'ice',name:'Ice Trail',price:150},{id:'gold',name:'Gold Trail',price:200},{id:'rainbow',name:'Rainbow Trail',price:250}];

const TRAIL_EMOJI={none:'🚫',fire:'🔥',ice:'❄️',gold:'✨',rainbow:'🌈'};

const TRAIL_HEX={fire:0xff6b35,ice:0x7fd8ff,gold:0xffd700};

const SHIRT_COLORS=[0xe33b3b,0x3b9dff,0x2ee06e,0xffc531,0x9b59f5,0xff7a3d,0xf7a8d8,0x232734];

const SKINS=[0xf2c58f,0xe0ac69,0xc68642,0x8d5524,0xffdbac];

const PANTS_COLORS=[0x2e4a8f,0x232734,0x6b4a2f,0x557a3d,0x8f2e4a];

const SEASON=[{t:1,r:{coins:200}},{t:2,r:{bux:50}},{t:3,r:{coins:500}},{t:4,r:{bux:100}},{t:5,r:{pet:'uni'}},{t:6,r:{coins:1000}},{t:7,r:{bux:200}},{t:8,r:{coins:2000}},{t:9,r:{bux:300}},{t:10,r:{pet:'gal'}}];

const NPC_NAMES=['NoobMaster69','xX_Blazer_Xx','PixelPirate','CoolCarla','BuilderBob','ShadowNinja','GlitterQueen','TurboTurtle','MegaMason','QueenBee','DriftKing','StarFox','SilaFan1','PeharMaster','JaneFriend','TrophyHunter','RobloxianPro','VortexRunner'];

const FRIENDS=[

  {id:'luna',name:'Luna',color:'#f7a8d8',online:true,x:-28,z:18,wall:0xffd9a0,roof:0xe33b3b},

  {id:'max',name:'Max',color:'#4da3ff',online:true,x:28,z:-18,wall:0xa8d0f0,roof:0x2e4a8f},

  {id:'zoe',name:'Zoe',color:'#2ee06e',online:true,x:18,z:32,wall:0xc9f0c0,roof:0x2f9e44},

  {id:'blaze_h',name:'Blaze Lodge',color:'#ff9a1f',online:true,x:65,z:-45,wall:0x5a2010,roof:0xff5d5d},

  {id:'frost_h',name:'Frost Castle',color:'#5db9ff',online:true,x:-65,z:-45,wall:0x1a3a6b,roof:0x7fd8ff},

  {id:'shadow_h',name:'Shadow Dojo',color:'#9b59f5',online:true,x:-50,z:45,wall:0x1a1a2e,roof:0x9b59f5},

  {id:'golden_h',name:'Golden Palace',color:'#ffc531',online:true,x:50,z:45,wall:0x8a5c00,roof:0xffe066}

];

const SOCIAL=['{n} joined the server 👋','{n} opened a Legendary box! 🎁','{n} reached Level {l} 🎉','{n} adopted a Mythic pet! 🐉','{n} is dominating the leaderboard 📊','{n} found a Rainbow Slime! 🌈','{n} just walked the Trophy Path! 🏆'];

const PACKS=[{b:100,p:'$0.99'},{b:500,p:'$3.99'},{b:1200,p:'$7.99'}];

const FTUE=[

 {txt:'Welcome to <b>Igraj so Sila</b>! 🏆 Move with <b>WASD</b> and walk the <b>Trophy Path</b>.'},

 {txt:'Collect <b>5 coins</b> — just walk into them! <b>({n}/5)</b>'},

 {txt:'Open your <b>FREE Mystery Box</b> at the purple station to adopt your first pet! 🐾'},

 {txt:'Claim your <b>Daily Reward</b> — tap the 🎁 button up top.'},

 {txt:'Visit a friend! Walk to <b>Luna\'s</b> or <b>Zoe\'s</b> house and press <b>E</b> at the green door ring.'}

];

function dailyReward(day){const base=[{coins:100},{coins:150},{bux:50},{coins:250},{coins:300},{bux:75},{coins:1000,bux:100}];if(day<=7)return base[day-1];if(day===14)return {bux:200};if(day===30)return {pet:'rbw'};return {coins:200+day*10}}

function rwText(r){const p=[];if(r.coins)p.push('🪙 '+r.coins);if(r.bux)p.push('💠 '+r.bux);if(r.pet)p.push(petById(r.pet).emoji+' pet');return p.join('  +  ')}

function rwIcon(r){const p=[];if(r.coins)p.push('🪙'+fmt(r.coins));if(r.bux)p.push('💠'+fmt(r.bux));if(r.pet)p.push(petById(r.pet).emoji);return p.join(' ')}



const SAVE_KEY='igrajsosila_v3';

const DEF={name:'',coins:1000000,bux:1000,level:5,xp:0,totalCoins:0,coinsToday:0,pets:{},activePet:null,hats:['none','cap','top','prop','crown','halo'],hat:'none',trails:['none','fire','ice','gold','rainbow'],trail:'none',characterId:'sila',streak:1,lastLogin:'',dailyClaimedDate:'',questDate:'',qProg:{coins:0,boxes:0,houses:0},qClaim:{},qNotified:{},seasonPoints:5,seasonClaimed:[1,2,3,4,5],rebirths:0,firstBoxUsed:false,freeBoxAt:0,houseCd:{},boxesOpened:0,ftueStep:0,ftueDist:0,ftueCoins:0,ftueVisit:0,muted:false,npcCd:{},npcTalks:0};

let S=Object.assign({},DEF);

try{const p=JSON.parse(localStorage.getItem(SAVE_KEY)||'{}');for(const k in p)S[k]=p[k]}catch(e){}

if(!S.npcCd)S.npcCd={};

if(typeof S.npcTalks!=='number')S.npcTalks=0;

if(!S.hats||!S.hats.includes('crown'))S.hats=['none','cap','top','prop','crown','halo'];

if(!S.trails||!S.trails.includes('rainbow'))S.trails=['none','fire','ice','gold','rainbow'];

if(S.coins<1000000)S.coins=1000000;

if(S.bux<1000)S.bux=1000;

function save(){try{localStorage.setItem(SAVE_KEY,JSON.stringify(S))}catch(e){}}

function currentChar(){return CHARACTERS.find(c=>c.id===S.characterId)||CHARACTERS[0]}



let actx=null;

function audioInit(){if(!actx){try{actx=new (window.AudioContext||window.webkitAudioContext)()}catch(e){}}}

function tone(f,d,type,g,dl){if(!actx||S.muted)return;type=type||'square';g=g||.05;dl=dl||0;const t=actx.currentTime+dl,o=actx.createOscillator(),ga=actx.createGain();o.type=type;o.frequency.value=f;ga.gain.setValueAtTime(g,t);ga.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(ga);ga.connect(actx.destination);o.start(t);o.stop(t+d+.02)}

const sfx={coin(){tone(950,.06,'square',.04);tone(1420,.08,'square',.04,.05)},click(){tone(620,.04,'square',.03)},err(){tone(170,.18,'sawtooth',.06)},level(){[523,659,784,1046].forEach((f,i)=>tone(f,.12,'square',.05,i*.09))},box(){tone(240,.12,'sawtooth',.05);tone(180,.12,'sawtooth',.05,.1)},reveal(r){const base={Common:[660,880],Rare:[660,880,1100],Epic:[660,880,1100,1320],Legendary:[523,659,784,1046,1318],Mythic:[523,659,784,1046,1318,1568]}[r]||[660,880];base.forEach((f,i)=>tone(f,.14,'triangle',.06,i*.1))},visit(){tone(700,.08,'triangle',.05);tone(940,.1,'triangle',.05,.08)},buy(){tone(880,.07,'square',.04);tone(1174,.09,'square',.04,.06)},rebirth(){[262,330,392,523,659,784].forEach((f,i)=>tone(f,.2,'sawtooth',.05,i*.12))},select(){tone(700,.08,'triangle',.05);tone(1050,.1,'triangle',.05,.06)}};



const canvas=$('#game');

const renderer=new THREE.WebGLRenderer({canvas,antialias:true,powerPreference:'high-performance'});

renderer.setPixelRatio(Math.min(devicePixelRatio,1.75));

renderer.setSize(innerWidth,innerHeight);

renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;

renderer.toneMapping=THREE.ACESFilmicToneMapping;

renderer.toneMappingExposure=1.15;

renderer.outputColorSpace=THREE.SRGBColorSpace;

const scene=new THREE.Scene();

const camera=new THREE.PerspectiveCamera(60,innerWidth/innerHeight,.1,400);

camera.position.set(0,14,22);



const skyGeo=new THREE.SphereGeometry(500,32,16);

const skyMat=new THREE.ShaderMaterial({side:THREE.BackSide,uniforms:{topColor:{value:new THREE.Color(0x4a90e2)},midColor:{value:new THREE.Color(0xffd9b8)},botColor:{value:new THREE.Color(0xffb88a)},offset:{value:30},exponent:{value:.6}},vertexShader:`varying vec3 vPos;void main(){vPos=position;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}`,fragmentShader:`uniform vec3 topColor;uniform vec3 midColor;uniform vec3 botColor;uniform float offset;uniform float exponent;varying vec3 vPos;void main(){float h=normalize(vPos+offset).y;vec3 col=mix(botColor,midColor,smoothstep(-0.1,0.3,h));col=mix(col,topColor,smoothstep(0.2,0.8,h));gl_FragColor=vec4(col,1.0);}`});

scene.add(new THREE.Mesh(skyGeo,skyMat));



const envScene=new THREE.Scene();

envScene.add(new THREE.Mesh(skyGeo.clone(),skyMat.clone()));

const envSun=new THREE.Mesh(new THREE.SphereGeometry(20,16,8),new THREE.MeshBasicMaterial({color:0xffffcc}));

envSun.position.set(100,120,60);envScene.add(envSun);

for(let i=0;i<8;i++){const c=new THREE.Mesh(new THREE.SphereGeometry(rand(15,30),8,6),new THREE.MeshBasicMaterial({color:0xffffff}));c.position.set(rand(-150,150),rand(60,140),rand(-150,150));c.scale.y=.4;envScene.add(c)}

const pmrem=new THREE.PMREMGenerator(renderer);

pmrem.compileEquirectangularShader();

const envRT=pmrem.fromScene(envScene,0.04);

const envMap=envRT.texture;

scene.environment=envMap;

pmrem.dispose();



const sun=new THREE.DirectionalLight(0xfff2d6,1.15);

sun.position.set(30,55,20);sun.castShadow=true;

sun.shadow.mapSize.set(2048,2048);sun.shadow.camera.left=-70;sun.shadow.camera.right=70;sun.shadow.camera.top=70;sun.shadow.camera.bottom=-70;sun.shadow.camera.far=180;sun.shadow.bias=-.0003;sun.shadow.normalBias=.05;

scene.add(sun);

scene.add(new THREE.HemisphereLight(0xbfe3ff,0x3f7d3a,.55));

const rim=new THREE.DirectionalLight(0xffd9b8,.55);rim.position.set(-25,20,-30);scene.add(rim);

const fill=new THREE.DirectionalLight(0xbfe3ff,.25);fill.position.set(-15,10,25);scene.add(fill);

const world=new THREE.Group();scene.add(world);



const matCache={};

function mat(color,opts={}){const key=`${color}_${opts.roughness||0.6}_${opts.metalness||0}_${opts.clearcoat||0}_${opts.emissive||0}_${opts.emissiveIntensity||0}_${opts.transparent||0}_${opts.opacity||1}`;if(!matCache[key]){matCache[key]=new THREE.MeshPhysicalMaterial({color,roughness:opts.roughness??0.6,metalness:opts.metalness??0,clearcoat:opts.clearcoat??0,clearcoatRoughness:opts.clearcoatRoughness??0.3,emissive:opts.emissive??0x000000,emissiveIntensity:opts.emissiveIntensity??0,envMap:envMap,envMapIntensity:opts.envMapIntensity??0.8,transparent:opts.transparent??false,opacity:opts.opacity??1,side:opts.side??THREE.FrontSide})}return matCache[key]}

function pbr(color,rough=0.6,metal=0){return mat(color,{roughness:rough,metalness:metal})}

function glowMat(color,intensity=0.8){return mat(color,{roughness:0.3,metalness:0.1,emissive:color,emissiveIntensity:intensity,clearcoat:0.5})}

function goldMat(){return mat(0xffd23f,{roughness:0.15,metalness:1,clearcoat:1,clearcoatRoughness:0.1,emissive:0x5a3d00,emissiveIntensity:0.35,envMapIntensity:1.5})}



function grassTexture(){const c=document.createElement('canvas');c.width=c.height=512;const x=c.getContext('2d');const g=x.createRadialGradient(256,256,20,256,256,360);g.addColorStop(0,'#72cb57');g.addColorStop(.5,'#5db344');g.addColorStop(1,'#4a9838');x.fillStyle=g;x.fillRect(0,0,512,512);for(let i=0;i<350;i++){x.fillStyle=Math.random()<.5?'#5ab03a':'#79d061';const s=ri(4,14);x.fillRect(ri(0,500),ri(0,500),s,s)}const t=new THREE.CanvasTexture(c);t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(30,30);t.anisotropy=renderer.capabilities.getMaxAnisotropy();return t}

function grassBumpMap(){const c=document.createElement('canvas');c.width=c.height=256;const x=c.getContext('2d');x.fillStyle='#808080';x.fillRect(0,0,256,256);for(let i=0;i<500;i++){const b=ri(90,170);x.fillStyle='rgb('+b+','+b+','+b+')';x.fillRect(ri(0,250),ri(0,250),ri(2,6),ri(2,6))}const t=new THREE.CanvasTexture(c);t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(30,30);return t}

function qTexture(bg,fg,ch){const c=document.createElement('canvas');c.width=c.height=256;const x=c.getContext('2d');x.fillStyle=bg;x.fillRect(0,0,256,256);x.strokeStyle='rgba(255,255,255,.5)';x.lineWidth=8;x.strokeRect(10,10,236,236);x.fillStyle=fg;x.font='900 180px "Baloo 2",sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillText(ch,128,140);return new THREE.CanvasTexture(c)}

function signMesh(text,bg,fg,w,h){const c=document.createElement('canvas');c.width=512;c.height=128;const x=c.getContext('2d');x.fillStyle=bg;rr(x,6,10,500,108,26);x.fill();x.strokeStyle='rgba(255,255,255,.35)';x.lineWidth=4;rr(x,6,10,500,108,26);x.stroke();x.fillStyle=fg;x.font='800 56px "Baloo 2",sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillText(text,256,72);const t=new THREE.CanvasTexture(c);return new THREE.Mesh(new THREE.PlaneGeometry(w,h),new THREE.MeshBasicMaterial({map:t,transparent:true,side:THREE.DoubleSide}))}

function nameSprite(text,color,scale){const c=document.createElement('canvas');c.width=280;c.height=80;const x=c.getContext('2d');x.fillStyle='rgba(10,14,28,.82)';rr(x,4,8,272,64,18);x.fill();x.strokeStyle='rgba(255,255,255,.15)';x.lineWidth=2;rr(x,4,8,272,64,18);x.stroke();x.font='700 32px Rubik,sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillStyle=color||'#fff';x.fillText((text||'').slice(0,14),140,42);const t=new THREE.CanvasTexture(c);const s=new THREE.Sprite(new THREE.SpriteMaterial({map:t,transparent:true,depthTest:false}));s.scale.set(2.8*(scale||1),.8*(scale||1),1);s.renderOrder=999;return s}



const outlinedObjects=[];

function buildAvatar(cfg,isHero=false){

 const g=new THREE.Group();

 const skinMat=mat(cfg.skin||0xf2c58f,{roughness:0.75,clearcoat:0.2});

 const shirtMat=mat(cfg.shirt||0x3b9dff,{roughness:0.5,metalness:0.05,clearcoat:0.3,clearcoatRoughness:0.4});

 const pantsMat=mat(cfg.pants||0x2e4a8f,{roughness:0.7});

 const shoeMat=mat(0x1a1a2e,{roughness:0.5,metalness:0.1,clearcoat:0.4});

 const legGeo=new THREE.CapsuleGeometry(.22,.5,4,8);

 const ll=new THREE.Mesh(legGeo,pantsMat);ll.position.set(-.26,.7,0);

 const rl=new THREE.Mesh(legGeo,pantsMat);rl.position.set(.26,.7,0);

 const ls=new THREE.Mesh(new THREE.BoxGeometry(.48,.16,.54),shoeMat);ls.position.set(0,-.28,.05);ll.add(ls);

 const rs=new THREE.Mesh(new THREE.BoxGeometry(.48,.16,.54),shoeMat);rs.position.set(0,-.28,.05);rl.add(rs);

 const torso=new THREE.Mesh(new THREE.BoxGeometry(.98,1.08,.52),shirtMat);torso.position.y=1.54;

 const belt=new THREE.Mesh(new THREE.BoxGeometry(1.02,.12,.54),mat(0x1a1a2e,{roughness:0.4,metalness:0.3}));belt.position.y=-.48;torso.add(belt);

 const buckle=new THREE.Mesh(new THREE.BoxGeometry(.2,.08,.03),glowMat(cfg.accent||0xffc531,.7));buckle.position.set(0,-.48,.28);torso.add(buckle);

 const armGeo=new THREE.CapsuleGeometry(.2,.65,4,8);

 const la=new THREE.Mesh(armGeo,skinMat);la.position.set(-.72,1.98,0);

 const ra=new THREE.Mesh(armGeo,skinMat);ra.position.set(.72,1.98,0);

 const handGeo=new THREE.SphereGeometry(.18,8,6);

 la.add(new THREE.Mesh(handGeo,skinMat)).position.set(0,-.45,0);

 ra.add(new THREE.Mesh(handGeo,skinMat)).position.set(0,-.45,0);

 if(cfg.shoulder||isHero){const padMat=goldMat();const p1=new THREE.Mesh(new THREE.SphereGeometry(.22,10,8),padMat);p1.position.set(-.62,2.2,0);p1.scale.y=.7;torso.add(p1);const p2=new THREE.Mesh(new THREE.SphereGeometry(.22,10,8),padMat);p2.position.set(.62,2.2,0);p2.scale.y=.7;torso.add(p2)}

 let capeMesh=null;

 if(cfg.cape){const capeMat=mat(cfg.cape,{roughness:0.6,metalness:0.1,side:THREE.DoubleSide});capeMesh=new THREE.Mesh(new THREE.PlaneGeometry(1,1.3,4,6),capeMat);capeMesh.position.set(0,1.6,-.3);torso.add(capeMesh)}

 const head=new THREE.Mesh(new THREE.SphereGeometry(.4,16,12),skinMat);head.position.y=2.52;

 if(cfg.hair!==0x1a1a2e||cfg.hat==='hood'){const hairMat=mat(cfg.hair||0x3a2300,{roughness:0.8});const hairTop=new THREE.Mesh(new THREE.SphereGeometry(.42,14,8,0,Math.PI*2,0,Math.PI/2),hairMat);hairTop.position.y=.15;head.add(hairTop);const hairBack=new THREE.Mesh(new THREE.BoxGeometry(.82,.4,.2),hairMat);hairBack.position.set(0,-.02,-.3);head.add(hairBack)}

 const eyeMat=glowMat(cfg.eyes||0x1c1c1c,1.2);

 const le=new THREE.Mesh(new THREE.SphereGeometry(.06,8,6),eyeMat);le.position.set(-.15,.08,.35);

 const re=new THREE.Mesh(new THREE.SphereGeometry(.06,8,6),eyeMat);re.position.set(.15,.08,.35);

 const pupM=mat(0x000000,{roughness:0.1});

 const lp=new THREE.Mesh(new THREE.SphereGeometry(.025,6,5),pupM);lp.position.set(-.15,.08,.4);

 const rp=new THREE.Mesh(new THREE.SphereGeometry(.025,6,5),pupM);rp.position.set(.15,.08,.4);

 const mouth=new THREE.Mesh(new THREE.BoxGeometry(.18,.04,.03),mat(0x5a1818,{roughness:0.8}));mouth.position.set(0,-.12,.38);

 head.add(le,re,lp,rp,mouth);

 g.add(ll,rl,torso,la,ra,head);

 g.traverse(o=>{if(o.isMesh){o.castShadow=true;o.receiveShadow=true}});

 g.userData={ll,rl,la,ra,head,torso,cape:capeMesh};

 outlinedObjects.push(g);

 return g;

}

function buildHat(id,cfg){

 const h=new THREE.Group();const ac=cfg&&cfg.accent?cfg.accent:0xffc531;

 if(id==='cap'){const c=new THREE.Mesh(new THREE.SphereGeometry(.4,12,8,0,Math.PI*2,0,Math.PI/2),mat(0xe33b3b,{roughness:0.5}));c.position.y=.2;c.scale.y=.5;const brim=new THREE.Mesh(new THREE.CylinderGeometry(.42,.42,.05,14),mat(0xb52c2c,{roughness:0.5}));brim.position.set(0,.22,.28);h.add(c,brim)}

 else if(id==='top'){const b=new THREE.Mesh(new THREE.CylinderGeometry(.4,.44,.55,14),mat(0x22252e,{roughness:0.25,metalness:0.4,clearcoat:0.8}));b.position.y=.55;const br=new THREE.Mesh(new THREE.CylinderGeometry(.6,.6,.06,14),mat(0x22252e,{roughness:0.25,metalness:0.4,clearcoat:0.8}));br.position.y=.3;const band=new THREE.Mesh(new THREE.CylinderGeometry(.42,.42,.09,14),mat(ac,{roughness:0.3,metalness:0.5}));band.position.y=.4;h.add(b,br,band)}

 else if(id==='crown'){const base=new THREE.Mesh(new THREE.CylinderGeometry(.42,.46,.25,8),goldMat());base.position.y=.4;h.add(base);for(let i=0;i<6;i++){const s=new THREE.Mesh(new THREE.ConeGeometry(.08,.28,4),goldMat());const a=i/6*Math.PI*2;s.position.set(Math.cos(a)*.32,.7,Math.sin(a)*.32);h.add(s);const gem=new THREE.Mesh(new THREE.SphereGeometry(.05,8,6),glowMat(0xff5d5d,1.2));gem.position.set(Math.cos(a)*.32,.62,Math.sin(a)*.32);h.add(gem)}}

 else if(id==='prop'){const stick=new THREE.Mesh(new THREE.CylinderGeometry(.03,.03,.3,6),mat(0x888888,{roughness:0.2,metalness:0.7}));stick.position.y=.45;const blades=new THREE.Group();blades.position.y=.62;blades.add(new THREE.Mesh(new THREE.BoxGeometry(.95,.05,.12),mat(0xff5d5d,{roughness:0.3,clearcoat:0.8})));blades.add(new THREE.Mesh(new THREE.BoxGeometry(.12,.05,.95),mat(0x5db9ff,{roughness:0.3,clearcoat:0.8})));h.add(stick,blades);h.userData.spin=blades}

 else if(id==='halo'){const t=new THREE.Mesh(new THREE.TorusGeometry(.35,.06,10,24),glowMat(0xffe066,1.5));t.rotation.x=Math.PI/2;t.position.y=.55;h.add(t)}

 else if(id==='flame'){const cols=[0xff5d5d,0xff9a1f,0xffd23f];for(let i=0;i<9;i++){const col=cols[i%3];const h2=rand(.25,.55);const sp=new THREE.Mesh(new THREE.ConeGeometry(.12,h2,6),glowMat(col,1.4));const a=rand(0,Math.PI*2);const r=rand(0,.25);sp.position.set(Math.cos(a)*r,.4+h2/2,Math.sin(a)*r);sp.rotation.z=rand(-.3,.3);h.add(sp)}}

 else if(id==='visor'){const v=new THREE.Mesh(new THREE.BoxGeometry(.84,.2,.16),glowMat(cfg&&cfg.accent?cfg.accent:0x00ff88,1.5));v.position.set(0,.2,.35);const strap=new THREE.Mesh(new THREE.BoxGeometry(.86,.08,.82),mat(0x1a1a2e,{roughness:0.4,metalness:0.3}));strap.position.y=.3;h.add(v,strap)}

 else if(id==='hood'){const hood=new THREE.Mesh(new THREE.SphereGeometry(.44,14,10,0,Math.PI*2,0,Math.PI*.7),mat(0x1a1a2e,{roughness:0.7}));hood.position.y=.2;const band=new THREE.Mesh(new THREE.TorusGeometry(.44,.04,6,16),glowMat(ac,.8));band.rotation.x=Math.PI/2;band.position.y=.15;hood.add(band);h.add(hood)}

 h.traverse(o=>{if(o.isMesh)o.castShadow=true});

 return h;

}

function buildPet(def){

 const g=new THREE.Group();

 const bodyMat=mat(def.body,{roughness:0.45,metalness:0.05,clearcoat:0.5,clearcoatRoughness:0.3});

 const body=new THREE.Mesh(new THREE.SphereGeometry(.35,14,10),bodyMat);body.scale.set(1,.85,1.15);body.position.y=.4;

 const head=new THREE.Mesh(new THREE.SphereGeometry(.28,14,10),bodyMat);head.position.set(0,.82,.18);

 const eyeM=mat(0x1c1c1c,{roughness:0.1,metalness:0.6});

 const le=new THREE.Mesh(new THREE.SphereGeometry(.05,8,6),eyeM);le.position.set(-.12,.88,.4);

 const re=new THREE.Mesh(new THREE.SphereGeometry(.05,8,6),eyeM);re.position.set(.12,.88,.4);

 const e1=new THREE.Mesh(new THREE.ConeGeometry(.08,.22,4),bodyMat);e1.position.set(-.18,1.12,.15);e1.rotation.z=.3;

 const e2=new THREE.Mesh(new THREE.ConeGeometry(.08,.22,4),bodyMat);e2.position.set(.18,1.12,.15);e2.rotation.z=-.3;

 g.add(body,head,le,re,e1,e2);

 g.traverse(o=>{if(o.isMesh){o.castShadow=true;o.receiveShadow=true}});

 outlinedObjects.push(g);

 return g;

}

function setLimbSwing(p,s){if(!p)return;p.ll.rotation.x=s;p.rl.rotation.x=-s;p.la.rotation.x=-s*.8;p.ra.rotation.x=s*.8}



let waterMesh,waterGeo;

function buildWater(){waterGeo=new THREE.PlaneGeometry(800,800,90,90);waterGeo.rotateX(-Math.PI/2);waterMesh=new THREE.Mesh(waterGeo,new THREE.MeshPhysicalMaterial({color:0x2ea8e0,transparent:true,opacity:0.78,roughness:0.05,metalness:0.3,clearcoat:1,clearcoatRoughness:0.1,envMap:envMap,envMapIntensity:1.4}));waterMesh.position.y=-.55;waterMesh.receiveShadow=true;world.add(waterMesh)}



const obstacles=[];const interactables=[];const npcs=[];const coins=[];const parts=[];const floats=[];

const trophyLights=[];

const jumpPads=[];const speedPads=[];const chests=[];

let mysteryBoxMesh,giftBoxMesh,stationRing,giftRing;

const BOX_POS=new THREE.Vector3(-14,0,-12),GIFT_POS=new THREE.Vector3(14,0,-14),STATUE_POS=new THREE.Vector3(0,0,-42);

const ARENA_POS=new THREE.Vector3(0,0,-25);

const KEY_POINTS=[[0,6],[-14,-12],[14,-14],[0,-42],[0,-25],...FRIENDS.map(f=>[f.x,f.z])];

function farFromKey(x,z,min){return KEY_POINTS.every(p=>Math.hypot(x-p[0],z-p[1])>min)}



function buildWorld(){

 const gtex=grassTexture();const bump=grassBumpMap();

 const ground=new THREE.Mesh(new THREE.PlaneGeometry(280,280),new THREE.MeshPhysicalMaterial({map:gtex,bumpMap:bump,bumpScale:0.04,roughness:0.85,metalness:0,envMap:envMap,envMapIntensity:0.3}));

 ground.rotation.x=-Math.PI/2;ground.receiveShadow=true;world.add(ground);

 buildWater();

 const pad=new THREE.Mesh(new THREE.CylinderGeometry(4.5,4.8,.15,28),glowMat(0xffd23f,.45));pad.position.set(0,.08,6);pad.receiveShadow=true;world.add(pad);

 const padRing=new THREE.Mesh(new THREE.TorusGeometry(4.3,.08,8,32),glowMat(0xffc531,1));padRing.rotation.x=-Math.PI/2;padRing.position.set(0,.16,6);world.add(padRing);

 world.add(signMesh('SPAWN HUB','#1b2440','#7fd8ff',2.8,.65)).position.set(0,1.5,9.8);

 buildVictoryArch(0,0,2.5);

 buildTrophyArena();

 buildObbyCourse();

 buildVolcanoRidge();

 buildFrostPeak();

 buildCyberCircuit();

 buildJumpPads();

 buildSpeedPads();

 buildChests();



 const trees=[];

 for(let i=0;i<55;i++){let tries=0,x,z;do{x=rand(-100,108);z=rand(-100,108);tries++}while((!farFromKey(x,z,8)||trees.some(t=>Math.hypot(t.x-x,t.z-z)<4.5))&&tries<40);if(tries<40){trees.push({x,z});addTree(x,z)}}

 for(let i=0;i<120;i++){let x=rand(-105,105),z=rand(-105,105);if(farFromKey(x,z,3.5)){const f=new THREE.Mesh(new THREE.SphereGeometry(.2,6,5),glowMat(pick([0xff5d8f,0xffd23f,0xffffff,0xc06bff,0x5db9ff]),.5));f.position.set(x,.2,z);world.add(f)}}

 for(let i=0;i<30;i++){let x=rand(-100,100),z=rand(-100,100);if(farFromKey(x,z,4)){const r=new THREE.Mesh(new THREE.DodecahedronGeometry(rand(.6,1.4),0),mat(0x8a909c,{roughness:0.85}));r.position.set(x,.5,z);r.rotation.set(rand(0,3),rand(0,3),rand(0,3));r.castShadow=true;r.receiveShadow=true;world.add(r);obstacles.push({x,z,r:1.1})}}

 FRIENDS.forEach(buildHouse);

 buildStation(BOX_POS,'box');

 buildStation(GIFT_POS,'gift');

 buildTrophyStatue();

 const pl1=new THREE.PointLight(0xffc531,.6,22);pl1.position.set(0,4,-22);world.add(pl1);

 const pl2=new THREE.PointLight(0xb45cff,.6,22);pl2.position.set(BOX_POS.x,4,BOX_POS.z);world.add(pl2);

 const pl3=new THREE.PointLight(0x2ee06e,.6,22);pl3.position.set(GIFT_POS.x,4,GIFT_POS.z);world.add(pl3);

}



function buildObbyCourse(){

 const g=new THREE.Group();

 const waypoints=[{x:55,y:1.5,z:0},{x:62,y:3.5,z:10},{x:70,y:6,z:20},{x:80,y:9,z:12},{x:88,y:12,z:0},{x:80,y:15,z:-12},{x:70,y:18,z:-22},{x:58,y:21,z:-12}];

 waypoints.forEach((wp,i)=>{

  const p=new THREE.Mesh(new THREE.CylinderGeometry(2.8,3,.6,16),mat(i%2===0?0x3b9dff:0xc06bff,{roughness:0.3,metalness:0.4}));

  p.position.set(wp.x,wp.y,wp.z);p.receiveShadow=true;p.castShadow=true;g.add(p);

  const ring=new THREE.Mesh(new THREE.TorusGeometry(2.9,.08,8,24),glowMat(0x00e5ff,1.2));

  ring.rotation.x=-Math.PI/2;ring.position.set(wp.x,wp.y+.32,wp.z);g.add(ring);

 });

 const apex=new THREE.Mesh(new THREE.CylinderGeometry(4.5,5,1,20),goldMat());

 apex.position.set(58,24,0);g.add(apex);

 const trophy=new THREE.Mesh(new THREE.OctahedronGeometry(1.2,0),glowMat(0xffd23f,2));

 trophy.position.set(58,27,0);g.add(trophy);

 const sign=signMesh('☁️ SKY OBBY SUMMIT','#1b2440','#ffd23f',4.5,.9);

 sign.position.set(58,29.5,0);g.add(sign);

 world.add(g);

}



function buildVolcanoRidge(){

 const g=new THREE.Group();

 const vBase=new THREE.Mesh(new THREE.CylinderGeometry(12,18,6,20),mat(0x2a1a18,{roughness:0.9}));

 vBase.position.set(65,3,-65);g.add(vBase);

 const vLava=new THREE.Mesh(new THREE.CylinderGeometry(8,8,.2,16),glowMat(0xff3300,2));

 vLava.position.set(65,6,-65);g.add(vLava);

 const sign=signMesh('🔥 VOLCANO RIDGE','#3a0a00','#ff9a1f',4.8,1);

 sign.position.set(65,10,-65);g.add(sign);

 const pl=new THREE.PointLight(0xff5d5d,1.2,30);pl.position.set(65,8,-65);g.add(pl);

 world.add(g);obstacles.push({x:65,z:-65,r:14});

}



function buildFrostPeak(){

 const g=new THREE.Group();

 const fBase=new THREE.Mesh(new THREE.CylinderGeometry(10,16,7,18),mat(0xd9eaf7,{roughness:0.2,clearcoat:0.8}));

 fBase.position.set(-65,3.5,-65);g.add(fBase);

 for(let i=0;i<6;i++){

  const c=new THREE.Mesh(new THREE.ConeGeometry(rand(.8,1.4),rand(3,5),6),glowMat(0x00e5ff,1.5));

  const a=i/6*Math.PI*2;

  c.position.set(-65+Math.cos(a)*6,7.5,-65+Math.sin(a)*6);g.add(c);

 }

 const sign=signMesh('❄️ FROST PEAK','#0e2040','#7fd8ff',4.5,1);

 sign.position.set(-65,10,-65);g.add(sign);

 const pl=new THREE.PointLight(0x5db9ff,1.2,30);pl.position.set(-65,8,-65);g.add(pl);

 world.add(g);obstacles.push({x:-65,z:-65,r:12});

}



function buildCyberCircuit(){

 const g=new THREE.Group();

 const track=new THREE.Mesh(new THREE.TorusGeometry(32,1.8,8,64),mat(0x1a0f30,{roughness:0.2,metalness:0.8}));

 track.rotation.x=-Math.PI/2;track.position.set(0,.1,70);g.add(track);

 const ringGlow=new THREE.Mesh(new THREE.TorusGeometry(32.8,.12,8,64),glowMat(0xff00ff,1.5));

 ringGlow.rotation.x=-Math.PI/2;ringGlow.position.set(0,.15,70);g.add(ringGlow);

 const sign=signMesh('⚡ CYBER SPEEDWAY','#1a0033','#ff5df2',5,1);

 sign.position.set(0,5,38);g.add(sign);

 world.add(g);

}



function buildJumpPads(){

 const pos=[{x:0,z:18},{x:-38,z:0},{x:38,z:0},{x:55,z:0},{x:70,z:20},{x:80,z:-12},{x:-65,z:-52},{x:65,z:-52},{x:0,z:88}];

 pos.forEach(p=>{

  const padMesh=new THREE.Mesh(new THREE.CylinderGeometry(1.6,1.8,.2,16),glowMat(0x00ffff,1.5));

  padMesh.position.set(p.x,.1,p.z);world.add(padMesh);

  const ring=new THREE.Mesh(new THREE.RingGeometry(1.8,2.2,20),glowMat(0x00ff88,1.2));

  ring.rotation.x=-Math.PI/2;ring.position.set(p.x,.12,p.z);world.add(ring);

  jumpPads.push({x:p.x,z:p.z,mesh:padMesh});

 });

}



function buildSpeedPads(){

 const pos=[{x:0,z:42},{x:-20,z:70},{x:20,z:70},{x:0,z:102},{x:35,z:-20},{x:-35,z:-20}];

 pos.forEach(p=>{

  const sMesh=new THREE.Mesh(new THREE.BoxGeometry(2.4,.1,3.8),glowMat(0xffc531,1.8));

  sMesh.position.set(p.x,.1,p.z);world.add(sMesh);

  speedPads.push({x:p.x,z:p.z,mesh:sMesh});

 });

}



function buildChests(){

 const pos=[{x:58,y:25,z:0,name:'Sky Chest'},{x:65,y:7,z:-65,name:'Fire Chest'},{x:-65,y:7.5,z:-65,name:'Frost Chest'},{x:0,y:.8,z:102,name:'Cyber Chest'},{x:-50,y:.8,z:45,name:'Ninja Chest'},{x:50,y:.8,z:45,name:'Royal Chest'}];

 pos.forEach((p,i)=>{

  const cMesh=new THREE.Mesh(new THREE.BoxGeometry(1.4,1.1,1.0),goldMat());

  cMesh.position.set(p.x,p.y+.55,p.z);world.add(cMesh);

  const lid=new THREE.Mesh(new THREE.BoxGeometry(1.48,.3,1.08),mat(0x5a3d00,{roughness:0.3,metalness:0.8}));

  lid.position.set(p.x,p.y+1.15,p.z);world.add(lid);

  const chestObj={id:'chest_'+i,pos:new THREE.Vector3(p.x,p.y,p.z),mesh:cMesh,cd:0,name:p.name};

  chests.push(chestObj);

  interactables.push({id:chestObj.id,pos:chestObj.pos,r:3.8,label:()=>chestLabel(chestObj),onUse:()=>useChest(chestObj)});

 });

}

function buildTrophyArena(){

 const g=new THREE.Group();g.position.copy(ARENA_POS);

 const platform=new THREE.Mesh(new THREE.CylinderGeometry(11,11.5,.35,32),mat(0x2a2438,{roughness:0.3,metalness:0.6,clearcoat:0.6}));platform.position.y=.17;platform.receiveShadow=true;platform.castShadow=true;g.add(platform);

 const innerRing=new THREE.Mesh(new THREE.TorusGeometry(8,.15,8,48),goldMat());innerRing.rotation.x=-Math.PI/2;innerRing.position.y=.36;g.add(innerRing);

 const outerRing=new THREE.Mesh(new THREE.TorusGeometry(10.8,.1,8,48),glowMat(0xffc531,1.2));outerRing.rotation.x=-Math.PI/2;outerRing.position.y=.36;g.add(outerRing);

 const rarities=['Common','Rare','Epic','Legendary','Mythic','Legendary','Epic'];

 const trophyNames=['Rookie','Riser','Elite','Champion','Legend','Master','Hero'];

 for(let i=0;i<7;i++){const a=(i/7)*Math.PI*2;const x=Math.cos(a)*8.5,z=Math.sin(a)*8.5;g.add(addTrophyPedestal(x,0,z,i+1,rarities[i],trophyNames[i]))}

 const center=new THREE.Mesh(new THREE.CylinderGeometry(1.2,1.6,.6,12),mat(0x3a2a18,{roughness:0.4,metalness:0.5}));center.position.y=.6;center.castShadow=true;g.add(center);

 const pillar=new THREE.Mesh(new THREE.BoxGeometry(1,3,1),goldMat());pillar.position.y=2.4;pillar.castShadow=true;g.add(pillar);

 const topGem=new THREE.Mesh(new THREE.OctahedronGeometry(.55,0),glowMat(0xff5d5d,1.8));topGem.position.y=4.3;g.add(topGem);

 trophyLights.push({mesh:topGem,base:4.3,phase:0});

 const archSign=signMesh('STAZA NA PEHARITE','#1b2440','#ffd23f',6,1.1);archSign.position.set(0,7.5,11);g.add(archSign);

 const archSubSign=signMesh('I NAJDOBRITE IGRACI','#3a1470','#ffffff',4.5,.7);archSubSign.position.set(0,6.2,11);g.add(archSubSign);

 const pillarM=goldMat();

 const pL=new THREE.Mesh(new THREE.CylinderGeometry(.35,.4,8,10),pillarM);pL.position.set(-3.5,4,11);pL.castShadow=true;g.add(pL);

 const pR=new THREE.Mesh(new THREE.CylinderGeometry(.35,.4,8,10),pillarM);pR.position.set(3.5,4,11);pR.castShadow=true;g.add(pR);

 const topBar=new THREE.Mesh(new THREE.BoxGeometry(8,.5,1),pillarM);topBar.position.set(0,8.2,11);topBar.castShadow=true;g.add(topBar);

 const spL=new THREE.SpotLight(0xffc531,.6,20,Math.PI/5,.5);spL.position.set(-3.5,8,11);spL.target.position.set(0,2,0);g.add(spL);g.add(spL.target);

 const spR=new THREE.SpotLight(0xffc531,.6,20,Math.PI/5,.5);spR.position.set(3.5,8,11);spR.target.position.set(0,2,0);g.add(spR);g.add(spR.target);

 world.add(g);obstacles.push({x:ARENA_POS.x,z:ARENA_POS.z,r:2});

}

function addTrophyPedestal(x,y,z,num,rarity,name){

 const g=new THREE.Group();

 g.add(new THREE.Mesh(new THREE.CylinderGeometry(.9,1.05,.35,12),mat(0x2a2438,{roughness:0.3,metalness:0.6}))).position.y=.18;

 g.add(new THREE.Mesh(new THREE.CylinderGeometry(.65,.75,1.3,12),mat(0x3a2a18,{roughness:0.4,metalness:0.4}))).position.y=1;

 g.add(new THREE.Mesh(new THREE.CylinderGeometry(.95,.85,.15,12),goldMat())).position.y=1.75;

 const cup=new THREE.Group();

 cup.add(new THREE.Mesh(new THREE.CylinderGeometry(.28,.35,.5,10),goldMat())).position.y=2.15;

 cup.add(new THREE.Mesh(new THREE.CylinderGeometry(.4,.28,.1,10),goldMat())).position.y=2.45;

 cup.add(new THREE.Mesh(new THREE.BoxGeometry(.42,.1,.42),goldMat())).position.y=1.85;

 const h1=new THREE.Mesh(new THREE.TorusGeometry(.18,.04,6,10),goldMat());h1.position.set(-.32,2.15,0);h1.rotation.y=Math.PI/2;cup.add(h1);

 const h2=new THREE.Mesh(new THREE.TorusGeometry(.18,.04,6,10),goldMat());h2.position.set(.32,2.15,0);h2.rotation.y=Math.PI/2;cup.add(h2);

 const gemColor=RARITY_HEX[rarity]||0xffd23f;

 const gem=new THREE.Mesh(new THREE.OctahedronGeometry(.15,0),glowMat(gemColor,2));gem.position.y=2.7;cup.add(gem);

 trophyLights.push({mesh:gem,base:2.7,phase:num});

 const nc=document.createElement('canvas');nc.width=nc.height=128;const nx=nc.getContext('2d');

 const ng=nx.createLinearGradient(0,0,0,128);ng.addColorStop(0,'#1b2440');ng.addColorStop(1,'#0a0f22');

 nx.fillStyle=ng;nx.fillRect(0,0,128,128);nx.fillStyle='#ffd23f';nx.font='bold 70px Baloo 2';nx.textAlign='center';nx.textBaseline='middle';nx.fillText('#'+num,64,50);

 nx.fillStyle='#fff';nx.font='bold 22px Rubik';nx.fillText(name,64,95);

 const plate=new THREE.Mesh(new THREE.PlaneGeometry(.7,.7),new THREE.MeshBasicMaterial({map:new THREE.CanvasTexture(nc),transparent:true}));

 plate.position.set(0,.95,.48);g.add(plate);

 g.add(cup);

 const pl=new THREE.PointLight(gemColor,.6,5);pl.position.set(0,2.8,0);g.add(pl);

 g.position.set(x,y,z);

 g.traverse(o=>{if(o.isMesh){o.castShadow=true;o.receiveShadow=true}});

 return g;

}

function buildVictoryArch(x,y,z){

 const g=new THREE.Group();const pM=goldMat();

 const lp=new THREE.Mesh(new THREE.BoxGeometry(.8,5,.8),pM);lp.position.set(-2.5,2.5,0);lp.castShadow=true;

 const rp=new THREE.Mesh(new THREE.BoxGeometry(.8,5,.8),pM);rp.position.set(2.5,2.5,0);rp.castShadow=true;

 const arch=new THREE.Mesh(new THREE.BoxGeometry(5.8,.9,1),pM);arch.position.y=5.3;arch.castShadow=true;

 const trim=new THREE.Mesh(new THREE.BoxGeometry(6,.2,1.1),glowMat(0xffc531,1));trim.position.y=5.9;

 const archSign=signMesh('TROPHY PATH','#1b2440','#ffd23f',4.2,.7);archSign.position.set(0,6.6,0);

 const t1=new THREE.Mesh(new THREE.CylinderGeometry(.22,.28,.4,10),goldMat());t1.position.set(-2.5,5.3,0);

 const t2=t1.clone();t2.position.x=2.5;

 g.add(lp,rp,arch,trim,archSign,t1,t2);g.position.set(x,y,z);

 world.add(g);obstacles.push({x:x-2.5,z,r:.8});obstacles.push({x:x+2.5,z,r:.8});

}

function addTree(x,z){

 const s=rand(.85,1.5);const t=new THREE.Group();

 const trunk=new THREE.Mesh(new THREE.CylinderGeometry(.22*s,.32*s,1.9*s,8),mat(0x8a5a33,{roughness:0.9}));trunk.position.y=.95*s;trunk.castShadow=true;

 const leafMat=mat(pick([0x3f9b3f,0x57b849,0x2f8f4e,0x4aa840]),{roughness:0.75,clearcoat:0.2});

 const lv1=new THREE.Mesh(new THREE.SphereGeometry(1.2*s,12,8),leafMat);lv1.scale.y=.7;lv1.position.y=2.3*s;lv1.castShadow=true;

 const lv2=new THREE.Mesh(new THREE.SphereGeometry(.9*s,12,8),leafMat);lv2.scale.y=.7;lv2.position.y=3*s;lv2.castShadow=true;

 const lv3=new THREE.Mesh(new THREE.SphereGeometry(.6*s,10,6),leafMat);lv3.scale.y=.7;lv3.position.y=3.6*s;lv3.castShadow=true;

 t.add(trunk,lv1,lv2,lv3);t.position.set(x,0,z);world.add(t);obstacles.push({x,z,r:1.4*s});

}

function buildHouse(f){

 const g=new THREE.Group();

 const base=new THREE.Mesh(new THREE.BoxGeometry(6.5,4.2,6.5),mat(f.wall,{roughness:0.7,clearcoat:0.2}));base.position.y=2.1;base.castShadow=true;base.receiveShadow=true;

 const roof=new THREE.Mesh(new THREE.ConeGeometry(5,2.8,4),mat(f.roof,{roughness:0.55,clearcoat:0.3}));roof.position.y=5.6;roof.rotation.y=Math.PI/4;roof.castShadow=true;

 const door=new THREE.Mesh(new THREE.BoxGeometry(1.5,2.6,.28),mat(0x5a3d28,{roughness:0.7}));door.position.set(0,1.3,3.2);

 const knob=new THREE.Mesh(new THREE.SphereGeometry(.08,8,6),goldMat());knob.position.set(.55,1.3,3.35);door.add(knob);

 const w1=new THREE.Mesh(new THREE.BoxGeometry(1.2,1.2,.14),glowMat(0xbfe6ff,.55));w1.position.set(-2,2.6,3.22);

 const w2=w1.clone();w2.position.x=2;

 const ch=new THREE.Mesh(new THREE.BoxGeometry(.8,1.4,.8),mat(0x8a5a33,{roughness:0.8}));ch.position.set(-2,5.8,-1.5);ch.castShadow=true;

 g.add(base,roof,door,w1,w2,ch);

 const sign=signMesh(f.name+"'s House",'#1b2440','#ffffff',3.8,1);sign.position.set(0,5,3.5);g.add(sign);

 g.position.set(f.x,0,f.z);g.rotation.y=Math.atan2(-f.x,-f.z);

 world.add(g);obstacles.push({x:f.x,z:f.z,r:5});

 f.sign=sign;f.bounce=0;

 f.doorPos=new THREE.Vector3(f.x+Math.sin(g.rotation.y)*4.3,0,f.z+Math.cos(g.rotation.y)*4.3);

 const ring=new THREE.Mesh(new THREE.RingGeometry(.75,1.05,24),glowMat(0x2ee06e,1));ring.rotation.x=-Math.PI/2;ring.position.set(f.doorPos.x,.06,f.doorPos.z);world.add(ring);

 f.ringMesh=ring;

 interactables.push({id:'house_'+f.id,pos:f.doorPos,r:3.8,label:()=>houseLabel(f),onUse:()=>useHouse(f)});

}

function buildStation(pos,kind){

 const g=new THREE.Group();g.position.copy(pos);

 const ped=new THREE.Mesh(new THREE.CylinderGeometry(1.8,2,.65,22),mat(0xb9bcc4,{roughness:0.4,metalness:0.3,clearcoat:0.5}));ped.position.y=.33;ped.castShadow=true;ped.receiveShadow=true;

 const pedRing=new THREE.Mesh(new THREE.TorusGeometry(1.9,.06,8,24),glowMat(kind==='box'?0xb45cff:0x2ee06e,1.2));pedRing.rotation.x=-Math.PI/2;pedRing.position.y=.66;

 const ring=new THREE.Mesh(new THREE.RingGeometry(2.1,2.6,28),glowMat(kind==='box'?0xb45cff:0x2ee06e,.9));ring.rotation.x=-Math.PI/2;ring.position.y=.06;

 const boxMat=new THREE.MeshPhysicalMaterial({map:qTexture(kind==='box'?'#7b2ff2':'#12b76a','#fff',kind==='box'?'?':'!'),roughness:0.25,metalness:0.15,clearcoat:0.9,clearcoatRoughness:0.15,emissive:kind==='box'?0x3a1470:0x0a5a35,emissiveIntensity:0.55,envMap:envMap,envMapIntensity:0.9});

 const box=new THREE.Mesh(new THREE.BoxGeometry(1.4,1.4,1.4),boxMat);box.position.y=1.8;box.castShadow=true;

 const sign=signMesh(kind==='box'?'MYSTERY BOX':'FREE GIFT',kind==='box'?'#3a1470':'#0a5a35','#ffffff',3.2,.85);sign.position.y=3.4;

 g.add(ped,pedRing,ring,box,sign);world.add(g);

 if(kind==='box'){mysteryBoxMesh=box;stationRing=ring}else{giftBoxMesh=box;giftRing=ring}

 obstacles.push({x:pos.x,z:pos.z,r:2.4});

 interactables.push({id:kind,pos,r:3.8,label:()=>kind==='box'?boxLabel():giftLabel(),onUse:()=>kind==='box'?useBox():useGift()});

}

function buildTrophyStatue(){

 const g=new THREE.Group();g.position.copy(STATUE_POS);

 const step1=new THREE.Mesh(new THREE.CylinderGeometry(4.4,4.8,.25,24),mat(0x5a4028,{roughness:0.6,metalness:0.2}));step1.position.y=.13;step1.receiveShadow=true;step1.castShadow=true;g.add(step1);

 const base=new THREE.Mesh(new THREE.CylinderGeometry(3.6,4,1.1,20),mat(0x3a2a18,{roughness:0.4,metalness:0.4}));base.position.y=.8;base.castShadow=true;base.receiveShadow=true;g.add(base);

 const baseRing=new THREE.Mesh(new THREE.TorusGeometry(3.9,.1,8,28),glowMat(0xffc531,1.1));baseRing.rotation.x=-Math.PI/2;baseRing.position.y=1.35;g.add(baseRing);

 const ob=new THREE.Mesh(new THREE.BoxGeometry(1.3,5.2,1.3),goldMat());ob.position.y=3.95;ob.castShadow=true;g.add(ob);

 const giantCup=new THREE.Group();

 giantCup.add(new THREE.Mesh(new THREE.CylinderGeometry(.8,1.1,1.5,14),goldMat())).position.y=7.2;

 giantCup.add(new THREE.Mesh(new THREE.CylinderGeometry(1.1,.8,.25,14),goldMat())).position.y=8.1;

 giantCup.add(new THREE.Mesh(new THREE.BoxGeometry(1.3,.2,1.3),goldMat())).position.y=6.3;

 const star=new THREE.Mesh(new THREE.OctahedronGeometry(.4,0),glowMat(0xffe066,2));star.position.y=8.7;giantCup.add(star);

 trophyLights.push({mesh:star,base:8.7,phase:5});

 g.add(giantCup);

 const sign=signMesh('STATUE OF LEGENDS','#1b2440','#ffd700',4.2,.95);sign.position.y=9.7;g.add(sign);

 const ring=new THREE.Mesh(new THREE.RingGeometry(2.5,3,28),glowMat(0xffc531,1));ring.rotation.x=-Math.PI/2;ring.position.y=.07;g.add(ring);

 world.add(g);obstacles.push({x:0,z:-42,r:2.6});

 const sp=new THREE.SpotLight(0xffd23f,1,16,Math.PI/6,.5);sp.position.set(0,11,-42);sp.target.position.set(0,4,-42);world.add(sp);world.add(sp.target);

  interactables.push({id:'statue',pos:STATUE_POS,r:3.8,label:()=>statueLabel(),onUse:()=>useStatueModal()});

}



const coinGeo=new THREE.CylinderGeometry(.45,.45,.15,20);coinGeo.rotateZ(Math.PI/2);

const coinMat_=goldMat();

function spawnCoin(near){let x,z,tries=0;do{if(near){x=rand(-8,8);z=rand(1,14)}else{x=rand(-98,98);z=rand(-98,98)}tries++}while(!farFromKey(x,z,2.8)&&tries<25);const g=new THREE.Group();const m=new THREE.Mesh(coinGeo,coinMat_);m.castShadow=true;g.add(m);const halo=new THREE.Mesh(new THREE.RingGeometry(.55,.7,16),glowMat(0xffd23f,1.2));halo.rotation.y=Math.PI/2;g.add(halo);g.position.set(x,.78,z);world.add(g);coins.push({g,phase:rand(0,6)})}



const BOT_QUOTES=['Sila is leading the Trophy Path! 🏆','Jane gives a +20% Friend Bonus! 🌸','Try the Obby Sky Parkour! ☁️','I just unlocked a Golden Golem! 🗿','Rebirth gives +25% coin boost! ⭐','Speed pads are so fast! ⚡','Hit the Jump Pad for a high bounce! ⬆️','The Trophy Path is epic! ⚔️'];



function spawnNPC(name){

 const cfg={skin:pick([0xf2c58f,0xe0ac69,0xc68642,0x8d5524]),shirt:pick([0xe33b3b,0x3b9dff,0x2ee06e,0xffc531,0x9b59f5,0xff7a3d]),pants:pick([0x2e4a8f,0x232734,0x6b4a2f]),hair:pick([0x3a2300,0x8a5a33,0xffd23f,0xff5d5d,0x1a1a2e]),hat:pick(['none','none','cap','prop','top']),eyes:0x1c1c1c,accent:pick([0xffc531,0xff5d5d,0x5db9ff,0x2ee06e])};

 const av=buildAvatar(cfg,false);

 if(cfg.hat!=='none'){const hg=buildHat(cfg.hat,cfg);hg.position.y=2.92;av.add(hg);av.userData.hatSpin=hg.userData.spin||null}else av.userData.hatSpin=null;

 const spr=nameSprite(name,'#cfd6e4',.8);spr.position.y=3.7;av.add(spr);

 av.position.set(rand(-75,75),0,rand(-75,75));world.add(av);

 npcs.push({av,parts:av.userData,name,tgt:new THREE.Vector3(rand(-85,85),0,rand(-85,85)),idle:rand(0,3),speed:rand(2.8,4.2),walkT:0,coins:1000000,chatCd:rand(4,12)});

}

let janeNPC=null;

function spawnJane(){const cfg=CHARACTERS.find(c=>c.id==='jane');const av=buildAvatar(cfg,false);if(cfg.hat!=='none'){const hg=buildHat(cfg.hat,cfg);hg.position.y=2.92;av.add(hg);av.userData.hatSpin=hg.userData.spin||null}else av.userData.hatSpin=null;const spr=nameSprite('JANE 🌸','#f7a8d8',.9);spr.position.y=3.7;av.add(spr);av.position.set(3,0,4);world.add(av);janeNPC={av,parts:av.userData,name:'Jane',coins:1000000,phase:0}}



const particleTex=(()=>{const c=document.createElement('canvas');c.width=c.height=64;const x=c.getContext('2d');const g=x.createRadialGradient(32,32,0,32,32,32);g.addColorStop(0,'rgba(255,255,255,1)');g.addColorStop(.4,'rgba(255,255,255,.6)');g.addColorStop(1,'rgba(255,255,255,0)');x.fillStyle=g;x.fillRect(0,0,64,64);return new THREE.CanvasTexture(c)})();

const RAINBOW=[];for(let i=0;i<12;i++)RAINBOW.push(new THREE.Color().setHSL(i/12,1,.6).getHex());

function burst(pos,color,n,spd){if(parts.length>300)return;for(let i=0;i<n;i++){const sm=new THREE.SpriteMaterial({map:particleTex,color:color,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false});const s=new THREE.Sprite(sm);s.position.copy(pos);s.scale.setScalar(rand(.3,.6));const v=new THREE.Vector3(rand(-1,1),rand(.4,1.4),rand(-1,1)).normalize().multiplyScalar(rand(.5,1)*spd);parts.push({m:s,v,life:rand(.5,.9),max:.9});scene.add(s)}}

function confetti(pos,n){const cols=[0xffc531,0xff5d5d,0x5db9ff,0x2ee06e,0xc06bff,0xff7a3d];for(let i=0;i<n;i++)burst(pos,cols[i%cols.length],1,5)}

const _fv=new THREE.Vector3();

function floater(pos,text,color){const el=document.createElement('div');el.className='floater';el.innerHTML='<span>'+text+'</span>';el.style.color=color||'#ffe066';$('#floaters').appendChild(el);floats.push({el,p:pos.clone?pos.clone():new THREE.Vector3(pos.x,pos.y,pos.z),life:1.3})}



function xpNeed(l){return Math.floor(40*Math.pow(l,1.4))}

function petMultOf(d,l){return d.mult*(1+(l-1)*.15)}

function petMult(){if(!S.activePet)return 1;const d=petById(S.activePet);return petMultOf(d,S.pets[S.activePet]||1)}

function multTotal(){return petMult()*(1+.25*S.rebirths)}

function addCoins(n){S.coins+=n;S.totalCoins+=n;S.coinsToday+=n;S.qProg.coins+=n}

function gainXP(n){S.xp+=n;let need=xpNeed(S.level);while(S.xp>=need){S.xp-=need;S.level++;S.seasonPoints++;const rw=100*S.level;S.coins+=rw;S.coinsToday+=rw;S.totalCoins+=rw;sfx.level();toast('🎉 Level '+S.level+'! +'+rw+' coins');confetti(player.position.clone().add(new THREE.Vector3(0,2.5,0)),24);floater(player.position.clone().add(new THREE.Vector3(0,3,0)),'LEVEL UP!','#7CFF6B');need=xpNeed(S.level)}updateHUD()}

function rollRarity(){let r=Math.random()*100;for(const [name,odds] of RARITY_ORDER){if(r<odds)return name;r-=odds}return 'Common'}

function grantRewards(r){if(r.coins){S.coins+=r.coins;S.totalCoins+=r.coins;S.coinsToday+=r.coins}if(r.bux)S.bux+=r.bux;if(r.pet){grantPet(petById(r.pet),false,true)}}

function grantPet(def,viaBox,quiet){const before=S.pets[def.id]||0;S.pets[def.id]=before+1;const lvl=S.pets[def.id];if(!S.activePet){S.activePet=def.id;refreshPetMesh()}if(quiet){toast('🐾 New pet: '+def.emoji+' '+def.name+'!');updateHUD();save();return}sfx.reveal(def.rarity);burst(BOX_POS.clone().setY(1.5),RARITY_HEX[def.rarity],26,5);const isNew=before===0;openModal('<div class="reveal"><div class="raritytag rc-'+def.rarity+'">'+def.rarity.toUpperCase()+'</div><div class="bigemoji rc-'+def.rarity+'">'+def.emoji+'</div><h2 class="rc-'+def.rarity+'">'+def.name+'</h2><div class="rsub">'+(isNew?'<span class="newtag">NEW PET!</span>':'Level Up → Lv '+lvl+' (×'+petMultOf(def,lvl).toFixed(1)+' coins)')+'</div><div class="rmult">Coin multiplier ×'+petMultOf(def,lvl).toFixed(1)+'</div><div class="mrow"><button class="btn gold" onclick="closeModal();useBox()">Open Another'+(S.firstBoxUsed?' (250 🪙)':'')+'</button><button class="btn" onclick="closeModal();openPets()">My Pets</button><button class="btn gray" onclick="closeModal()">Close</button></div></div>');updateHUD();save()}

function collectCoin(c){const amt=Math.round(5*multTotal());addCoins(amt);gainXP(2);S.ftueCoins++;sfx.coin();floater(c.g.position,'+'+amt,'#ffe066');burst(c.g.position,0xffc531,8,3);world.remove(c.g);const i=coins.indexOf(c);if(i>=0)coins.splice(i,1);checkFTUE();checkQuests();updateHUD()}



function boxLabel(){if(!S.firstBoxUsed)return '🎁 FREE Mystery Box — adopt a pet!';return S.coins>=250?'🎁 Mystery Box — 250 🪙':'🎁 Mystery Box — need 250 🪙'}

function giftLabel(){const rem=(S.freeBoxAt-Date.now())/1000;return rem>0?'🎉 Gift recharging — '+mmss(rem):'🎉 Open your Free Gift!'}

function statueLabel(){return S.level>=15?'⭐ Statue of Legends — REBIRTH available!':'⭐ Statue of Legends — reach Lv 15 (now '+S.level+')'}

function houseLabel(f){if(!f.online)return '💤 '+f.name+' is away';const rem=(S.houseCd[f.id]||0)-Date.now();if(rem>0)return '🏠 '+f.name+"'s House — next visit in "+mmss(rem/1000);return '🏠 Visit '+f.name+"'s House"}

function chestLabel(c){const rem=(c.cd-Date.now())/1000;return rem>0?'🎁 '+c.name+' recharging — '+mmss(rem):'🎁 Open '+c.name}



function useChest(c){

 const now=Date.now();

 if(now<c.cd){sfx.err();toast('⏳ Chest recharging!');return}

 c.cd=now+120000;

 const reward=Math.round(ri(500,1200)*multTotal());

 addCoins(reward);gainXP(25);sfx.buy();

 confetti(c.mesh.position.clone().add(new THREE.Vector3(0,1.5,0)),20);

 floater(c.mesh.position.clone().add(new THREE.Vector3(0,2,0)),'+'+fmt(reward)+' 🪙','#ffe066');

 toast('🎁 '+c.name+' Opened! +'+fmt(reward)+' coins');

 updateHUD();save();

}



function useBox(){const cost=S.firstBoxUsed?250:0;if(S.coins<cost){sfx.err();toast('Not enough coins! Collect more 🪙');return}S.coins-=cost;S.boxesOpened++;S.qProg.boxes++;if(!S.firstBoxUsed)S.firstBoxUsed=true;sfx.box();const rar=rollRarity();grantPet(pick(PETS.filter(p=>p.rarity===rar)),true,false);checkQuests();checkFTUE();updateHUD();save()}

let giftNotified=false;

function useGift(){const now=Date.now();if(now<S.freeBoxAt){sfx.err();toast('⏳ Gift recharging — '+mmss((S.freeBoxAt-now)/1000));return}S.freeBoxAt=now+120000;giftNotified=false;sfx.buy();burst(GIFT_POS.clone().setY(1.5),0x2ee06e,18,4);if(Math.random()<.15){grantPet(pick(PETS.filter(p=>p.rarity==='Common'||p.rarity==='Rare')),false,true)}else{const amt=ri(75,200);addCoins(amt);gainXP(8);floater(GIFT_POS.clone().setY(1.5),'+'+amt,'#7CFF6B');toast('🎉 Free gift: +'+amt+' coins!')}checkQuests();updateHUD();save()}

function useHouse(f){if(!f.online){toast(f.name+' is away right now 💤');sfx.err();return}const now=Date.now();const cd=S.houseCd[f.id]||0;if(now<cd){sfx.err();return}S.houseCd[f.id]=now+90000;const amt=Math.round(30*multTotal());addCoins(amt);gainXP(15);S.qProg.houses++;S.ftueVisit++;sfx.visit();toast('🏠 '+f.name+' thanks you! +'+amt+' coins');floater(f.doorPos.clone().setY(1.5),'+'+amt,'#ffe066');f.bounce=2.5;checkQuests();checkFTUE();updateHUD();save()}

function useStatueModal(){if(S.level>=15)openRebirth();else toast('Reach Level 15 to Rebirth ⭐')}



const NPC_INFO = {

 Jane: { title: '🌸 Companion & Healer', emoji: '🌸', hint: 'Standing near me or friends gives you extra coin multipliers! Sila and I are cheering for you on the Trophy Path.', trivia: { q: 'What bonus does Jane provide?', a: ['+20% Friend Bonus', '+100% Speed', 'Free Pets'], correct: 0 } },

 NoobMaster69: { title: '🎮 Pet Collector & Pro', emoji: '🐶', hint: 'Did you know opening duplicate pets levels them up? Higher level pets give way bigger coin multipliers!', trivia: { q: 'What happens when you get a duplicate pet?', a: ['It levels up!', 'It gets deleted', 'You lose coins'], correct: 0 } },

 BuilderBob: { title: '🧱 Master Obby Architect', emoji: '☁️', hint: 'The Sky Obby Summit has floating platforms! Use Jump Pads around the map to get a massive vertical boost.', trivia: { q: 'What lies at the top of Sky Obby?', a: ['Sky Obby Summit & Chest', 'Lava Pool', 'Nothing'], correct: 0 } },

 xX_Blazer_Xx: { title: '🔥 Volcano Explorer', emoji: '🔥', hint: 'The Volcano Ridge in the southeast has a hot lava pit and the Fire Chest. Open it for big coin rewards!', trivia: { q: 'Where is the Fire Chest located?', a: ['Volcano Ridge', 'Frost Peak', 'Spawn Hub'], correct: 0 } },

 ShadowNinja: { title: '🌙 Stealth Ninja Master', emoji: '🥷', hint: 'Shadow Dojo is located near the west hills. Reaching Level 15 unlocks Rebirth at the Statue of Legends!', trivia: { q: 'At what level can you Rebirth?', a: ['Level 15', 'Level 5', 'Level 100'], correct: 0 } },

 GlitterQueen: { title: '✨ Blox Mart Stylist', emoji: '👑', hint: 'Visit Blox Mart using the shop icon! You can equip cool hats, glowing trails, and custom clothing colors.', trivia: { q: 'Where can you buy cosmetics?', a: ['Blox Mart Shop', 'Volcano Ridge', 'Statue of Legends'], correct: 0 } },

 TurboTurtle: { title: '⚡ Cyber Speedway Racer', emoji: '🏎️', hint: 'Step on the glowing yellow Speed Pads to activate a 3.5-second Speed Surge! Neon champion gets a passive speed boost too.', trivia: { q: 'How long does a Speed Pad boost last?', a: ['3.5 seconds', '1 minute', 'Forever'], correct: 0 } },

 TrophyHunter: { title: '🏆 Path Champion', emoji: '🥇', hint: 'The Trophy Arena features 7 pedestals representing ranks from Rookie to Hero. Collecting coins fills your XP bar!', trivia: { q: 'How many trophy pedestals are in the arena?', a: ['7 pedestals', '3 pedestals', '10 pedestals'], correct: 0 } },

 StarFox: { title: '🌌 Galaxy Navigator', emoji: '🦊', hint: 'Mythic pets like Rainbow Slime and Void Wyvern give up to 8x coin multipliers! Look out for daily rewards on day 30.', trivia: { q: 'Which rarity is higher than Legendary?', a: ['Mythic', 'Common', 'Rare'], correct: 0 } },

 SilaFan1: { title: '⚔️ Sila Superfan', emoji: '📣', hint: 'Sila is the main hero of the Trophy Path! Equipping Sila gives a +20% Trophy Aura.', trivia: { q: 'Who is the hero of the Trophy Path?', a: ['Sila', 'NoobMaster', 'Bob'], correct: 0 } },

 PeharMaster: { title: '🥇 Trophy Lore Master', emoji: '📜', hint: 'Check your Daily Quests every day for extra coins and Bux! Completing all 3 quests gives maximum rewards.', trivia: { q: 'How often do Daily Quests reset?', a: ['Every day', 'Every hour', 'Never'], correct: 0 } },

 CoolCarla: { title: '😎 Chill Vibe Master', emoji: '🎧', hint: 'Daily login streaks give bigger rewards every day! Day 7 gives 1,000 coins and 100 Bux.', trivia: { q: 'What happens if you log in every day?', a: ['Your streak grows & rewards increase', 'Nothing', 'Your coins reset'], correct: 0 } },

 MegaMason: { title: '🏰 Castle Builder', emoji: '🏰', hint: 'Visit Frost Peak in the northwest to find the icy Frost Chest and crystal pillars!', trivia: { q: 'Which peak holds the Frost Chest?', a: ['Frost Peak', 'Volcano Ridge', 'Cyber Speedway'], correct: 0 } },

 QueenBee: { title: '🐝 Hive Ruler', emoji: '👑', hint: 'Bux (💠) can be earned from quests, season passes, and daily rewards! Use them to unlock exclusive hats and trails.', trivia: { q: 'What can you spend Bux on?', a: ['Hats & Trails in Shop', 'Nothing', 'Level resets'], correct: 0 } },

 DriftKing: { title: '🏎️ Drift Legend', emoji: '💨', hint: 'Cyber Speedway encircles the south side. Run along the outer ring for high-speed coin collecting!', trivia: { q: 'Which track surrounds the south side?', a: ['Cyber Speedway', 'Volcano Ridge', 'Sky Obby'], correct: 0 } },

 VortexRunner: { title: '🌀 Speedster', emoji: '⚡', hint: 'Season Pass awards free Tier rewards as you level up! Check the Trophy button in the top menu.', trivia: { q: 'How do you gain Season Pass points?', a: ['By leveling up', 'By losing coins', 'By standing still'], correct: 0 } }

};



function getNPCInfo(name){

 return NPC_INFO[name] || {

  title: '⚔️ Arena Explorer',

  emoji: '🎮',

  hint: 'Walk the Trophy Path to gain experience, level up, and earn massive coins!',

  trivia: { q: 'What is the main goal in Igraj so Sila?', a: ['Walk the Trophy Path!', 'Stay in spawn', 'Do nothing'], correct: 0 }

 };

}



function talkToNPC(n){

 if(!n) return;

 n.idle = 12;

 const dx = player.position.x - n.av.position.x;

 const dz = player.position.z - n.av.position.z;

 n.av.rotation.y = Math.atan2(dx, dz);

 

 S.npcTalks = (S.npcTalks || 0) + 1;

 sfx.click();

 

 const info = getNPCInfo(n.name);

 const cd = S.npcCd[n.name] || 0;

 const now = Date.now();

 const canReward = now >= cd;

 const cdRem = Math.max(0, Math.ceil((cd - now) / 1000));

 

 const greetings = [

  `Hey there, ${S.name || 'Champion'}! Welcome to the Trophy Path! How can I help you today?`,

  `Greetings! Great seeing you out here in the arena!`,

  `Hey champion! Looking for hints or special rewards?`,

  `Welcome! The Trophy Path is full of secrets today!`

 ];

 const speech = greetings[Math.floor(Math.random() * greetings.length)];

 renderNPCModal(n.name, info, speech, canReward, cdRem);

}



function renderNPCModal(name, info, speechText, canReward, cdRem){

 const cdBadge = canReward 

  ? '<span class="npcCdTag">🎁 Gift Ready!</span>' 

  : '<span class="npcCdTag wait">⏳ Cooldown: ' + mmss(cdRem) + '</span>';

  

 const html = `

  <div class="npcBox">

   <div class="npcHeader">

    <div class="npcAvatarBadge" style="background:${info.emoji === '🌸' ? '#7a3d5a' : '#2a3354'}">${info.emoji}</div>

    <div class="npcMeta">

     <div class="npcName">${name}</div>

     <div class="npcTitle">${info.title}</div>

    </div>

    <div>${cdBadge}</div>

   </div>

   <div class="npcSpeechBubble" id="npcSpeechText">

    "${speechText}"

   </div>

   <div class="chatOptions" id="npcChatOpts">

    <button class="btn gold chatBtn" onclick="npcAction('${name}', 'hint')">💡 Ask for a Map Hint</button>

    <button class="btn green chatBtn" onclick="npcAction('${name}', 'reward')" ${canReward ? '' : 'disabled'}>

     🎁 Claim Special Gift ${canReward ? '' : '(' + mmss(cdRem) + ')'}

    </button>

    <button class="btn chatBtn" onclick="npcAction('${name}', 'blessing')">⚡ Request Speed Surge Blessing</button>

    <button class="btn chatBtn" onclick="npcAction('${name}', 'trivia')">🧩 Play Quiz for Bonus Coins</button>

    <button class="btn gray chatBtn" onclick="closeModal()">👋 Goodbye!</button>

   </div>

  </div>

 `;

 openModal(mh('💬 Talking with ' + name) + html);

}



function npcAction(name, action){

 const info = getNPCInfo(name);

 const speechEl = document.getElementById('npcSpeechText');

 const optsEl = document.getElementById('npcChatOpts');

 const npc = npcs.find(x => x.name === name) || (janeNPC && janeNPC.name === name ? janeNPC : null);



 if(action === 'hint'){

  sfx.click();

  if(speechEl) speechEl.innerHTML = `💡 <b>Tip from ${name}:</b> "${info.hint}"`;

 } else if(action === 'reward'){

  const cd = S.npcCd[name] || 0;

  if(Date.now() < cd){

   sfx.err();

   toast('⏳ Reward is on cooldown!');

   return;

  }

  S.npcCd[name] = Date.now() + 180000;

  const coinsAmt = Math.round(ri(400, 1000) * multTotal());

  const buxAmt = ri(8, 22);

  addCoins(coinsAmt);

  S.bux += buxAmt;

  gainXP(15);

  sfx.buy();

  

  if(npc){

   confetti(npc.av.position.clone().add(new THREE.Vector3(0, 1.5, 0)), 18);

   floater(npc.av.position.clone().add(new THREE.Vector3(0, 2, 0)), '+' + fmt(coinsAmt) + ' 🪙', '#ffe066');

  }

  toast(`🎁 ${name} gave you +${fmt(coinsAmt)} Coins & +${buxAmt} Bux!`);

  updateHUD();

  save();



  if(speechEl) speechEl.innerHTML = `🎁 <b>Thank you!</b> "Here is your special reward: 🪙 <b>${fmt(coinsAmt)}</b> coins and 💠 <b>${buxAmt}</b> Bux! Come back in 3 minutes for another gift!"`;

  if(optsEl){

   optsEl.innerHTML = `

    <button class="btn gold chatBtn" onclick="npcAction('${name}', 'hint')">💡 Ask for a Map Hint</button>

    <button class="btn chatBtn" onclick="npcAction('${name}', 'blessing')">⚡ Request Speed Surge Blessing</button>

    <button class="btn chatBtn" onclick="npcAction('${name}', 'trivia')">🧩 Play Quiz for Bonus Coins</button>

    <button class="btn gray chatBtn" onclick="closeModal()">👋 Goodbye!</button>

   `;

  }

 } else if(action === 'blessing'){

  sfx.click();

  speedBoostTime = 12.0;

  if(npc){

   burst(npc.av.position.clone().add(new THREE.Vector3(0, 1, 0)), 0xffc531, 15, 4);

   floater(npc.av.position.clone().add(new THREE.Vector3(0, 2, 0)), '⚡ SPEED SURGE!', '#ffc531');

  }

  toast(`⚡ ${name} blessed you with a 12s Speed Surge!`);

  if(speechEl) speechEl.innerHTML = `⚡ <b>Speed Surge Activated!</b> "Feel the power of speed! You move +85% faster for the next 12 seconds!"`;

 } else if(action === 'trivia'){

  sfx.click();

  const t = info.trivia;

  let opts = t.a.map((optText, idx) => `

   <button class="btn sm chatBtn triviaOpt" onclick="answerTrivia('${name}', ${idx})">

    ${idx === 0 ? 'A' : idx === 1 ? 'B' : 'C'}. ${optText}

   </button>

  `).join('');

  if(speechEl){

   speechEl.innerHTML = `

    <div class="triviaBox">

     <div class="triviaTitle">🧩 Quiz from ${name}:</div>

     <div><b>${t.q}</b></div>

    </div>

   `;

  }

  if(optsEl) optsEl.innerHTML = opts + `<button class="btn gray chatBtn" onclick="talkToNPC(npcs.find(x=>x.name==='${name}')||janeNPC)">Back to Chat</button>`;

 }

}



function answerTrivia(name, idx){

 const info = getNPCInfo(name);

 const t = info.trivia;

 const speechEl = document.getElementById('npcSpeechText');

 const optsEl = document.getElementById('npcChatOpts');

 

 if(idx === t.correct){

  const prize = Math.round(500 * multTotal());

  addCoins(prize);

  S.bux += 10;

  gainXP(20);

  sfx.level();

  toast(`🎉 Correct answer! +${fmt(prize)} coins & +10 Bux!`);

  floater(player.position.clone().add(new THREE.Vector3(0,2,0)), '+' + fmt(prize) + ' 🪙', '#7CFF6B');

  confetti(player.position.clone().add(new THREE.Vector3(0,2,0)), 20);

  updateHUD();

  save();

  

  if(speechEl) speechEl.innerHTML = `🎉 <b>Correct!</b> "Outstanding knowledge, champion! You won 🪙 <b>${fmt(prize)}</b> coins and 💠 <b>10</b> Bux!"`;

 } else {

  sfx.err();

  toast('❌ Oops! Wrong answer. Try again!');

  if(speechEl) speechEl.innerHTML = `❌ <b>Not quite right!</b> "Don't worry, keep exploring the Trophy Path and try again anytime!"`;

 }

 if(optsEl){

  optsEl.innerHTML = `

   <button class="btn gold chatBtn" onclick="npcAction('${name}', 'hint')">💡 Ask for a Map Hint</button>

   <button class="btn chatBtn" onclick="npcAction('${name}', 'blessing')">⚡ Request Speed Surge Blessing</button>

   <button class="btn gray chatBtn" onclick="closeModal()">👋 Goodbye!</button>

  `;

 }

}



function nearestInteract(){

 let best=null,bd=16;

 for(const it of interactables){

  const d=dist2D(player.position,it.pos);

  if(d<it.r&&d<bd){bd=d;best=it}

 }

 for(const n of npcs){

  const d=dist2D(player.position,n.av.position);

  if(d<3.8&&d<bd){

   bd=d;

   const cd=S.npcCd[n.name]||0;

   const canReward=Date.now()>=cd;

   best={

    id:'npc_'+n.name,

    pos:n.av.position,

    r:3.8,

    label:()=>(canReward?'🎁 Talk to ':'💬 Talk to ')+n.name,

    onUse:()=>talkToNPC(n)

   };

  }

 }

 if(janeNPC){

  const d=dist2D(player.position,janeNPC.av.position);

  if(d<3.8&&d<bd){

   bd=d;

   const cd=S.npcCd['Jane']||0;

   const canReward=Date.now()>=cd;

   best={

    id:'npc_jane',

    pos:janeNPC.av.position,

    r:3.8,

    label:()=>(canReward?'🎁 Talk to ':'💬 Talk to ') + 'Jane 🌸',

    onUse:()=>talkToNPC(janeNPC)

   };

  }

 }

 return best;

}

function tryInteract(){if(!gameStarted||modalOpen)return;const it=nearestInteract();if(it)it.onUse()}



const modalRoot=$('#modalRoot');let modalOpen=false;let shopTab='hats',boardTab='daily';

function mh(t){return '<div class="mhead"><h2>'+t+'</h2><button class="mclose" onclick="closeModal()">✕</button></div>'}

function openModal(html){modalRoot.innerHTML='<div class="modal">'+html+'</div>';modalRoot.classList.add('open');modalOpen=true;sfx.click()}

function closeModal(){modalRoot.classList.remove('open');modalRoot.innerHTML='';modalOpen=false}

modalRoot.addEventListener('click',e=>{if(e.target===modalRoot)closeModal()});

function openShop(tab){shopTab=tab||'hats';let body='';if(shopTab==='hats'){body='<div class="grid">'+HATS.map(h=>{const owned=S.hats.includes(h.id);const eq=S.hat===h.id;return '<div class="item '+(eq?'eq':'')+'"><div class="iprev">'+HAT_EMOJI[h.id]+'</div><div class="iname">'+h.name+'</div><div>'+(eq?'<span class="tag green">EQUIPPED</span>':owned?'<button class="btn sm" onclick="buyItem(\'hat\',\''+h.id+'\')">Equip</button>':'<button class="btn sm gold" onclick="buyItem(\'hat\',\''+h.id+'\')">'+h.price+' 💠</button>')+'</div></div>'}).join('')+'</div>'}else if(shopTab==='trails'){body='<div class="grid">'+TRAILS.map(t=>{const owned=S.trails.includes(t.id);const eq=S.trail===t.id;return '<div class="item '+(eq?'eq':'')+'"><div class="iprev">'+TRAIL_EMOJI[t.id]+'</div><div class="iname">'+t.name+'</div><div>'+(eq?'<span class="tag green">EQUIPPED</span>':owned?'<button class="btn sm" onclick="buyItem(\'trail\',\''+t.id+'\')">Equip</button>':'<button class="btn sm gold" onclick="buyItem(\'trail\',\''+t.id+'\')">'+t.price+' 💠</button>')+'</div></div>'}).join('')+'</div>'}else if(shopTab==='colors'){body=swatchRow('Shirt','shirt',SHIRT_COLORS)+swatchRow('Skin','skin',SKINS)+swatchRow('Pants','pants',PANTS_COLORS)}else{body='<div class="sub">Simulated store — no real money is charged.</div><div class="grid">'+PACKS.map((p,i)=>'<div class="pack"><div class="pv">💠 '+p.b+'</div><div class="pp">'+p.p+' (simulated)</div><button class="btn gold sm" onclick="buyBux('+i+')">Get Bux</button></div>').join('')+'</div>'}const tabs='<div class="tabs">'+['hats','trails','colors','bux'].map(t=>'<button class="tab '+(shopTab===t?'on':'')+'" onclick="openShop(\''+t+'\')">'+(t==='bux'?'Get Bux':t[0].toUpperCase()+t.slice(1))+'</button>').join('')+'</div>';openModal(mh('🛍️ Blox Mart')+'<div class="sub">Cosmetics only — no pay-to-win. You have <b class="gold">'+fmt(S.bux)+' 💠</b></div>'+tabs+body)}

function swatchRow(label,kind,colors){return '<div class="swrow"><div class="swlabel">'+label+'</div><div class="sws">'+colors.map(c=>'<button class="sw '+(S[kind]===c?'on':'')+'" style="background:#'+c.toString(16).padStart(6,'0')+'" onclick="setColor(\''+kind+'\','+c+')"></button>').join('')+'</div></div>'}

function setColor(kind,val){S[kind]=val;sfx.click();refreshAvatar();openShop('colors');save()}

function buyItem(kind,id){const list=kind==='hat'?HATS:TRAILS;const it=list.find(x=>x.id===id);const owned=(kind==='hat'?S.hats:S.trails).includes(id);if(owned){if(kind==='hat')S.hat=id;else S.trail=id;sfx.click();refreshAvatar();openShop(shopTab);save();return}if(S.bux<it.price){sfx.err();toast('Not enough Bux! 💠');return}S.bux-=it.price;(kind==='hat'?S.hats:S.trails).push(id);if(kind==='hat')S.hat=id;else S.trail=id;sfx.buy();toast('🛍️ Purchased '+it.name+'!');refreshAvatar();updateHUD();openShop(shopTab);save()}

function buyBux(i){S.bux+=PACKS[i].b;sfx.buy();toast('💠 +'+PACKS[i].b+' Bux — simulated!');confetti(player.position.clone().add(new THREE.Vector3(0,2.5,0)),16);updateHUD();openShop('bux');save()}

function openPets(){const owned=Object.keys(S.pets).length;const cards=PETS.map(d=>{const has=!!S.pets[d.id];const lvl=S.pets[d.id]||0;const eq=S.activePet===d.id;if(!has)return '<div class="pcard locked"><div class="pemoji">❓</div><div class="pname">???</div><div class="prarity rc-'+d.rarity+'">'+d.rarity+'</div></div>';return '<div class="pcard bc-'+d.rarity+' '+(eq?'eq':'')+'"><div class="pemoji">'+d.emoji+'</div><div class="pname">'+d.name+'</div><div class="prarity rc-'+d.rarity+'">'+d.rarity+' · Lv '+lvl+'</div><div class="pmult">×'+petMultOf(d,lvl).toFixed(1)+' coins</div><div>'+(eq?'<span class="tag green">ACTIVE</span>':'<button class="btn sm" onclick="equipPet(\''+d.id+'\')">Equip</button>')+'</div></div>'}).join('');openModal(mh('🐾 Pet Collection')+'<div class="sub">'+owned+'/'+PETS.length+' collected · Active ×'+petMult().toFixed(1)+' · Duplicates level pets up!</div><div class="pgrid">'+cards+'</div>')}

function equipPet(id){S.activePet=id;refreshPetMesh();sfx.click();openPets();save()}

function openSeason(){const pts=S.seasonPoints;const rows=SEASON.map(t=>{const claimed=S.seasonClaimed.includes(t.t);const can=pts>=t.t&&!claimed;return '<div class="srow '+(claimed?'done':can?'can':'')+'"><div class="snum">'+t.t+'</div><div class="srew">'+rwText(t.r)+'</div><div>'+(claimed?'<span class="tag">✓</span>':can?'<button class="btn sm green" onclick="claimSeason('+t.t+')">Claim</button>':'<span class="tag gray">🔒 '+t.t+' pt'+(t.t>1?'s':'')+'</span>')+'</div></div>'}).join('');openModal(mh('🏆 Season 3 · Summer Splash')+'<div class="sub">Earn 1 Tier Point per level-up · You have <b class="gold">'+pts+'</b> point'+(pts===1?'':'s')+'</div><div class="strack">'+rows+'</div>')}

function claimSeason(t){const tier=SEASON.find(x=>x.t===t);if(!tier||S.seasonPoints<t||S.seasonClaimed.includes(t))return;S.seasonClaimed.push(t);grantRewards(tier.r);sfx.buy();toast('🏆 Tier '+t+' reward claimed!');updateHUD();save();openSeason()}

function openQuests(){const rows=questDefs().map(q=>{const done=q.prog>=q.target;const claimed=S.qClaim[q.id];return '<div class="qrow '+(claimed?'done':'')+'"><div class="qico">'+q.ico+'</div><div class="qmain"><div class="qtxt">'+q.txt+'</div><div class="qbar"><i style="width:'+clamp(q.prog/q.target*100,0,100)+'%"></i></div><div class="qmeta">'+Math.min(q.prog,q.target)+'/'+q.target+' · '+rwText(q.rw)+'</div></div><div>'+(claimed?'<span class="tag">DONE</span>':done?'<button class="btn sm green" onclick="claimQuest(\''+q.id+'\')">Claim</button>':'<span class="tag gray">IN&nbsp;PROGRESS</span>')+'</div></div>'}).join('');openModal(mh('📜 Daily Quests')+'<div class="sub">Resets daily · players with goals retain longer!</div>'+rows+'<div class="statsline">Lifetime: 🪙 '+fmt(S.totalCoins)+' · Today: 🪙 '+fmt(S.coinsToday)+' · Boxes: '+S.boxesOpened+' · Rebirths: ⭐ '+S.rebirths+'</div>')}

function questDefs(){const t1=100+S.level*20;return[{id:'coins',ico:'🪙',txt:'Collect '+t1+' coins',target:t1,prog:S.qProg.coins,rw:{coins:200,bux:15}},{id:'boxes',ico:'🎁',txt:'Open 2 Mystery Boxes',target:2,prog:S.qProg.boxes,rw:{coins:300,bux:20}},{id:'houses',ico:'🏠',txt:'Visit 2 friend houses',target:2,prog:S.qProg.houses,rw:{coins:250,bux:15}}]}

function claimQuest(id){const q=questDefs().find(x=>x.id===id);if(!q||q.prog<q.target||S.qClaim[id])return;S.qClaim[id]=true;grantRewards(q.rw);gainXP(30);sfx.buy();toast('✅ Quest reward claimed!');updateHUD();save();openQuests();checkQuests()}

function checkQuests(){let any=false;for(const q of questDefs()){if(q.prog>=q.target&&!S.qClaim[q.id]){any=true;if(!S.qNotified[q.id]){S.qNotified[q.id]=true;toast('📜 Quest complete: '+q.txt);sfx.click()}}}$('#btnQuests').classList.toggle('pulse',any)}

function dailyAvailable(){return S.dailyClaimedDate!==todayStr()}

function openDaily(){const day=S.streak;const claimed=!dailyAvailable();const cur=clamp(day,1,7);let cells='';for(let d=1;d<=7;d++){let cls='future';if(d<cur)cls='past';else if(d===cur)cls=claimed?'past':'now';const r=dailyReward(d);cells+='<div class="day '+cls+'"><div class="dnum">Day '+d+'</div><div class="drew">'+rwIcon(r)+'</div>'+(d===cur&&!claimed?'<div class="dtag">TODAY</div>':'')+'</div>'}const m14=S.streak>=14,m30=S.streak>=30;openModal(mh('🎁 Daily Rewards')+'<div class="streak">🔥 '+day+'-day streak</div>'+(day>7?'<div class="sub">Beyond 7 days keeps paying! '+(m30?'Day 30 ✓':m14?'Day 30 ('+day+'/30)':'Day 14 ('+day+'/14)')+'</div>':'<div class="sub">Log in daily — streak resets if you miss a day.</div>')+'<div class="days">'+cells+'</div><div class="miles"><div class="mile '+(m14?'':'locked')+'">Day 14<br>💠 200 '+(m14?'✓':'('+day+'/14)')+'</div><div class="mile '+(m30?'':'locked')+'">Day 30<br>🌈 Mythic '+(m30?'✓':'('+day+'/30)')+'</div></div><button class="btn gold big" onclick="claimDaily()" '+(claimed?'disabled':'')+'>'+(claimed?'✓ Claimed today':'Claim Day '+day+' Reward')+'</button>')}

function claimDaily(){if(!dailyAvailable())return;const day=S.streak;grantRewards(dailyReward(day));S.dailyClaimedDate=todayStr();sfx.buy();toast('🎁 Day '+day+' reward claimed!');confetti(player.position.clone().add(new THREE.Vector3(0,2.5,0)),16);updateHUD();save();closeModal();checkFTUE()}

function openFriends(){const rows=FRIENDS.map(f=>{const rem=(S.houseCd[f.id]||0)-Date.now();return '<div class="frow"><div class="fava" style="background:'+f.color+'">'+f.name[0]+'</div><div class="fmain"><div class="fname">'+f.name+'<span class="fstatus '+(f.online?'on':'off')+'">'+(f.online?'● Online':'○ Offline')+'</span></div><div class="fsub">'+(f.online?(rem>0?'Visit ready in '+mmss(rem/1000):'🏠 Visit for a gift!'):'House locked')+'</div></div><div>'+(f.online?'<button class="btn sm" onclick="locate(\''+f.id+'\')">📍</button>':'')+'</div></div>'}).join('');openModal(mh('👥 Friends')+'<div class="sub">Players with friends retain 3–5× better!</div>'+rows)}

function locate(id){const f=FRIENDS.find(x=>x.id===id);if(!f)return;f.bounce=2.5;sfx.click();toast('📍 '+f.name+"'s house marked!");closeModal()}



function boardData(tab){const seedStr=tab+(tab==='daily'?todayStr():tab==='weekly'?getWeek():'all');let s=0;for(let i=0;i<seedStr.length;i++)s=(s*31+seedStr.charCodeAt(i))>>>0;const rng=()=>{s=(s*1664525+1013904223)>>>0;return s/4294967296};const pool=[...NPC_NAMES];for(let i=pool.length-1;i>0;i--){const j=Math.floor(rng()*(i+1));[pool[i],pool[j]]=[pool[j],pool[i]]}const names=pool.slice(0,9);const ranges={daily:[2000,90000],weekly:[20000,420000],all:[120000,2600000]}[tab];const rows=names.map(n=>({name:n,v:Math.floor(ranges[0]+rng()*(ranges[1]-ranges[0]))}));const myV=tab==='daily'?S.coinsToday:tab==='weekly'?Math.floor(S.coinsToday*2+S.level*400):S.totalCoins;rows.push({name:S.name||'You',v:myV,me:true});rows.sort((a,b)=>b.v-a.v);return rows}

function openBoard(tab){boardTab=tab||'daily';const data=boardData(boardTab);const me=data.findIndex(r=>r.me);const rows=data.map((r,i)=>'<div class="brow '+(r.me?'me':'')+'"><div class="brank">'+(i===0?'🥇':i===1?'🥈':i===2?'🥉':'#'+(i+1))+'</div><div class="bname">'+r.name+(r.me?' <span class="tag gold">YOU</span>':'')+'</div><div class="bval">🪙 '+fmt(r.v)+'</div></div>').join('');const tabs='<div class="tabs">'+['daily','weekly','all'].map(t=>'<button class="tab '+(boardTab===t?'on':'')+'" onclick="openBoard(\''+t+'\')">'+(t==='all'?'All-Time':t[0].toUpperCase()+t.slice(1))+'</button>').join('')+'</div>';openModal(mh('📊 Leaderboard')+tabs+'<div class="sub">Your rank: <b class="gold">#'+(me+1)+'</b></div><div class="blist">'+rows+'</div>')}

function openRebirth(){const cur=(1+.25*S.rebirths),next=(1+.25*(S.rebirths+1));openModal(mh('⭐ Rebirth')+'<div class="rebirthbox"><div class="rbig">Become a Legend</div><p>Reset <b>Level</b> and <b>Coins</b> to gain a permanent <b class="gold">+25% coin multiplier</b>.</p><div class="rnums">×'+cur.toFixed(2)+' → <b class="gold">×'+next.toFixed(2)+'</b></div><p class="keep">You keep: Pets · Bux · Cosmetics · Season progress</p><div class="mrow"><button class="btn gold big" onclick="doRebirth()">⭐ REBIRTH</button><button class="btn gray" onclick="closeModal()">Not yet</button></div></div>')}

function doRebirth(){S.rebirths++;S.level=1;S.xp=0;S.coins=1000000;sfx.rebirth();for(let i=0;i<5;i++)burst(player.position.clone().add(new THREE.Vector3(rand(-1,1),rand(1,3),rand(-1,1))),pick([0xffc531,0xff5d5d,0x5db9ff,0x2ee06e,0xc06bff]),14,6);toast('⭐ REBIRTH '+S.rebirths+'! ×'+(1+.25*S.rebirths).toFixed(2));closeModal();updateHUD();save()}



function openCharSelect(){const cards=CHARACTERS.map(c=>{const eq=S.characterId===c.id;return '<div class="charCard '+(eq?'on':'')+'" onclick="selectChar(\''+c.id+'\')" style="color:'+c.color+'"><div class="charPreview"><canvas id="cv_'+c.id+'" width="160" height="160"></canvas></div><div class="charName" style="color:'+c.color+'">'+c.name+'</div><div class="charTag">'+c.tag+'</div><div class="charDesc">'+c.desc+'</div><div class="charTrait">'+c.trait+'</div>'+(eq?'<div class="tag gold" style="margin-top:8px">SELECTED</div>':'')+'</div>'}).join('');openModal(mh('🎭 Choose Your Champion')+'<div class="sub">Every champion starts with 🪙 1,000,000 coins. Sila and Jane await you!</div><div class="charGrid">'+cards+'</div><div class="mrow"><button class="btn" onclick="closeModal()">Confirm</button></div>');setTimeout(renderCharPreviews,50)}

function renderCharPreviews(){CHARACTERS.forEach(c=>{const cv=document.getElementById('cv_'+c.id);if(!cv)return;const x=cv.getContext('2d');x.clearRect(0,0,160,160);const cx=80,baseY=140;x.fillStyle='rgba(0,0,0,.35)';x.beginPath();x.ellipse(cx,baseY,24,6,0,0,Math.PI*2);x.fill();if(c.cape){x.fillStyle='#'+c.cape.toString(16).padStart(6,'0');x.beginPath();x.moveTo(cx-16,baseY-60);x.lineTo(cx+16,baseY-60);x.lineTo(cx+20,baseY-20);x.lineTo(cx-20,baseY-20);x.closePath();x.fill()}x.fillStyle='#'+c.pants.toString(16).padStart(6,'0');x.fillRect(cx-14,baseY-32,11,30);x.fillRect(cx+3,baseY-32,11,30);x.fillStyle='#1a1a2e';x.fillRect(cx-15,baseY-6,13,6);x.fillRect(cx+2,baseY-6,13,6);x.fillStyle='#'+c.shirt.toString(16).padStart(6,'0');x.fillRect(cx-18,baseY-62,36,32);x.fillStyle='#1a1a2e';x.fillRect(cx-18,baseY-34,36,3);x.fillStyle='#'+c.accent.toString(16).padStart(6,'0');x.fillRect(cx-3,baseY-34,6,3);if(c.shoulder){x.fillStyle='#ffc531';x.beginPath();x.arc(cx-20,baseY-55,6,0,Math.PI*2);x.fill();x.beginPath();x.arc(cx+20,baseY-55,6,0,Math.PI*2);x.fill()}x.fillStyle='#'+c.skin.toString(16).padStart(6,'0');x.fillRect(cx-26,baseY-60,8,26);x.fillRect(cx+18,baseY-60,8,26);x.fillStyle='#'+c.skin.toString(16).padStart(6,'0');x.beginPath();x.arc(cx,baseY-80,16,0,Math.PI*2);x.fill();x.fillStyle='#'+c.hair.toString(16).padStart(6,'0');x.beginPath();x.arc(cx,baseY-84,17,Math.PI,Math.PI*2);x.fill();x.fillRect(cx-17,baseY-86,34,5);if(c.hat==='flame'){x.fillStyle='#ff5d5d';x.fillRect(cx-14,baseY-98,6,12);x.fillStyle='#ff9a1f';x.fillRect(cx-6,baseY-102,6,16);x.fillStyle='#ffd23f';x.fillRect(cx+2,baseY-98,6,12);x.fillStyle='#ff5d5d';x.fillRect(cx+9,baseY-96,5,10)}else if(c.hat==='crown'){x.fillStyle='#ffc531';x.fillRect(cx-14,baseY-94,28,8);x.fillRect(cx-12,baseY-102,5,8);x.fillRect(cx-2,baseY-102,5,8);x.fillRect(cx+8,baseY-102,5,8);x.fillStyle='#ff5d5d';x.fillRect(cx-10,baseY-100,2,2);x.fillRect(cx,baseY-100,2,2);x.fillRect(cx+10,baseY-100,2,2)}else if(c.hat==='visor'){x.fillStyle='#'+c.accent.toString(16).padStart(6,'0');x.fillRect(cx-14,baseY-78,28,5);x.fillStyle='#1a1a2e';x.fillRect(cx-16,baseY-84,32,4)}else if(c.hat==='hood'){x.fillStyle='#1a1a2e';x.beginPath();x.arc(cx,baseY-82,20,Math.PI,0);x.fill();x.fillStyle='#'+c.accent.toString(16).padStart(6,'0');x.fillRect(cx-20,baseY-80,40,3)}else if(c.hat==='halo'){x.strokeStyle='#ffe066';x.lineWidth=3;x.beginPath();x.ellipse(cx,baseY-96,14,4,0,0,Math.PI*2);x.stroke()}x.fillStyle='#'+c.eyes.toString(16).padStart(6,'0');x.fillRect(cx-9,baseY-82,5,7);x.fillRect(cx+4,baseY-82,5,7);x.fillStyle='#000';x.fillRect(cx-7,baseY-80,2,3);x.fillRect(cx+6,baseY-80,2,3);x.fillStyle='#5a1818';x.fillRect(cx-4,baseY-72,8,2);const grad=x.createRadialGradient(cx,baseY-60,10,cx,baseY-60,70);grad.addColorStop(0,c.color+'40');grad.addColorStop(1,'transparent');x.globalCompositeOperation='screen';x.fillStyle=grad;x.fillRect(0,0,160,160)})}

function selectChar(id){S.characterId=id;sfx.select();refreshAvatar();openCharSelect();save()}



function ftueDone(step){switch(step){case 0:return S.ftueDist>12;case 1:return S.ftueCoins>=5;case 2:return S.firstBoxUsed;case 3:return S.dailyClaimedDate===todayStr();case 4:return S.ftueVisit>=1}return true}

function checkFTUE(){if(S.ftueStep>=FTUE.length)return;if(ftueDone(S.ftueStep)){S.ftueStep++;if(S.ftueStep>=FTUE.length){S.bux+=25;toast('🏆 All set! +25 💠 bonus');updateHUD()}save()}}

function updateHUD(){$('#coinVal').textContent=fmt(S.coins);$('#buxVal').textContent=fmt(S.bux);$('#lvNum').textContent=S.level;const need=xpNeed(S.level);$('#xpBar').style.width=clamp(S.xp/need*100,0,100)+'%';$('#xpText').textContent=Math.floor(S.xp)+'/'+need+' XP';$('#btnRebirth').style.display=S.level>=15?'flex':'none';$('#btnDaily').classList.toggle('pulse',dailyAvailable());$('#btnMute').textContent=S.muted?'🔇':'🔊'}

function toast(msg){const el=document.createElement('div');el.className='toast panel';el.textContent=msg;$('#toasts').appendChild(el);while($('#toasts').children.length>4)$('#toasts').firstChild.remove();setTimeout(()=>{el.classList.add('out');setTimeout(()=>el.remove(),400)},3600)}

function scheduleSocial(){setTimeout(()=>{if(!gameStarted)return;toast(pick(SOCIAL).replace('{n}',pick(NPC_NAMES)).replace('{l}',ri(5,40)));scheduleSocial()},ri(22000,42000))}



let player,playerParts,hatSpin=null,petMesh=null;

function refreshAvatar(){const pos=player?player.position.clone():new THREE.Vector3(0,0,6);const rot=player?player.rotation.y:0;if(player){world.remove(player);const i=outlinedObjects.indexOf(player);if(i>=0)outlinedObjects.splice(i,1)}const ch=currentChar();player=buildAvatar(ch,true);player.position.copy(pos);player.rotation.y=rot;playerParts=player.userData;if(ch.hat&&ch.hat!=='none'){const hg=buildHat(ch.hat,ch);hg.position.y=2.92;hatSpin=hg.userData.spin||null;player.add(hg)}else if(S.hat!=='none'){const hg=buildHat(S.hat,ch);hg.position.y=2.92;hatSpin=hg.userData.spin||null;player.add(hg)}else hatSpin=null;const spr=nameSprite(S.name||'You','#ffe066',1);spr.position.y=3.8;player.add(spr);world.add(player);if(outlinePass)outlinePass.selectedObjects=outlinedObjects.filter(o=>o.parent)}

function refreshPetMesh(){if(petMesh){world.remove(petMesh);const i=outlinedObjects.indexOf(petMesh);if(i>=0)outlinedObjects.splice(i,1);petMesh=null}if(!S.activePet)return;const d=petById(S.activePet);petMesh=buildPet(d);const ring=new THREE.Mesh(new THREE.RingGeometry(.34,.5,20),glowMat(RARITY_HEX[d.rarity],1));ring.rotation.x=-Math.PI/2;ring.position.y=.03;petMesh.add(ring);const spr=nameSprite(d.emoji+' '+d.name,RARITY_CSS[d.rarity],.7);spr.position.y=1.85;petMesh.add(spr);world.add(petMesh);if(outlinePass)outlinePass.selectedObjects=outlinedObjects.filter(o=>o.parent)}



const keys={};let touchJump=false;

const PREVENT=['Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'];

addEventListener('keydown',e=>{if(PREVENT.includes(e.code)&&!(e.target instanceof HTMLInputElement))e.preventDefault();keys[e.code]=true;if(e.code==='KeyE')tryInteract();if(e.code==='Escape')closeModal()});

addEventListener('keyup',e=>{keys[e.code]=false});

const joy={active:false,x:0,y:0};

const jb=$('#joyBase'),jk=$('#joyKnob');

function moveJoy(e){const r=jb.getBoundingClientRect();let dx=(e.clientX-(r.left+r.width/2))/(r.width/2),dy=(e.clientY-(r.top+r.height/2))/(r.height/2);const l=Math.hypot(dx,dy);if(l>1){dx/=l;dy/=l}joy.x=dx;joy.y=dy;jk.style.transform='translate('+dx*34+'px,'+dy*34+'px)'}

jb.addEventListener('pointerdown',e=>{joy.active=true;jb.setPointerCapture(e.pointerId);moveJoy(e)});

jb.addEventListener('pointermove',e=>{if(joy.active)moveJoy(e)});

jb.addEventListener('pointerup',()=>{joy.active=false;joy.x=joy.y=0;jk.style.transform='translate(0,0)'});

jb.addEventListener('pointercancel',()=>{joy.active=false;joy.x=joy.y=0;jk.style.transform='translate(0,0)'});

$('#btnJump').addEventListener('pointerdown',e=>{e.preventDefault();touchJump=true});

$('#btnJump').addEventListener('pointerup',()=>touchJump=false);

$('#btnJump').addEventListener('pointerleave',()=>touchJump=false);

$('#btnAct').addEventListener('pointerdown',e=>{e.preventDefault();tryInteract()});



let camYaw=0,camPitch=0.45,camDist=16,isDragging=false,lastMouseX=0,lastMouseY=0;

let speedBoostTime=0;



addEventListener('mousedown',e=>{if(e.button===2||(e.button===0&&e.shiftKey)){isDragging=true;lastMouseX=e.clientX;lastMouseY=e.clientY}});

addEventListener('mousemove',e=>{if(isDragging){const dx=e.clientX-lastMouseX;const dy=e.clientY-lastMouseY;camYaw-=dx*0.005;camPitch=clamp(camPitch+dy*0.005,0.1,1.2);lastMouseX=e.clientX;lastMouseY=e.clientY}});

addEventListener('mouseup',()=>isDragging=false);

addEventListener('contextmenu',e=>e.preventDefault());

addEventListener('wheel',e=>{camDist=clamp(camDist+e.deltaY*0.015,8,32)});



const composer=new EffectComposer(renderer);

composer.addPass(new RenderPass(scene,camera));

let ssaoPass=null;

try{ssaoPass=new SSAOPass(scene,camera,innerWidth,innerHeight);ssaoPass.kernelRadius=8;ssaoPass.minDistance=0.005;ssaoPass.maxDistance=0.1;composer.addPass(ssaoPass)}catch(e){console.warn('SSAO disabled:',e)}

const outlinePass=new OutlinePass(new THREE.Vector2(innerWidth,innerHeight),scene,camera);

outlinePass.edgeStrength=3.5;outlinePass.edgeGlow=0.4;outlinePass.edgeThickness=1.5;outlinePass.pulsePeriod=0;

outlinePass.visibleEdgeColor.set(0x0a0f22);outlinePass.hiddenEdgeColor.set(0x1a2448);

outlinePass.selectedObjects=[];

composer.addPass(outlinePass);

const bloomPass=new UnrealBloomPass(new THREE.Vector2(innerWidth,innerHeight),0.55,0.45,0.82);

composer.addPass(bloomPass);

composer.addPass(new OutputPass());



let gameStarted=false,T=0,walkT=0,moveF=0,vy=0,grounded=true,coinTimer=1,lastLabel='',trailTimer=0;

const clock=new THREE.Clock();

const camTarget=new THREE.Vector3(),camLook=new THREE.Vector3();

const promptEl=$('#prompt');



function updatePlayer(dt){

 let jx=0,jz=0;if(joy.active){jx=joy.x;jz=joy.y}

 let ix=((keys.KeyD||keys.ArrowRight)?1:0)-((keys.KeyA||keys.ArrowLeft)?1:0)+jx;

 let iz=((keys.KeyS||keys.ArrowDown)?1:0)-((keys.KeyW||keys.ArrowUp)?1:0)+jz;

 const len=Math.hypot(ix,iz);if(len>1){ix/=len;iz/=len}

 if(modalOpen||!gameStarted){ix=0;iz=0}

 const moving=Math.hypot(ix,iz)>0.05;

 if(speedBoostTime>0)speedBoostTime-=dt;

 const baseSpd=(speedBoostTime>0?16.5:9.0)*(currentChar().id==='neon'?1.15:1.0);

 if(moving){

  const moveAngle=Math.atan2(ix,iz)+camYaw;

  const moveX=Math.sin(moveAngle),moveZ=Math.cos(moveAngle);

  player.position.x=clamp(player.position.x+moveX*baseSpd*dt,-110,110);

  player.position.z=clamp(player.position.z+moveZ*baseSpd*dt,-110,110);

  player.rotation.y=lerpAngle(player.rotation.y,moveAngle,1-Math.exp(-14*dt));

  walkT+=dt*12;moveF+=(1-moveF)*(1-Math.exp(-10*dt));

 }else moveF+=(0-moveF)*(1-Math.exp(-8*dt));

 for(const o of obstacles){

  const dx=player.position.x-o.x,dz=player.position.z-o.z;

  const d=Math.hypot(dx,dz);const min=o.r+.6;

  if(d<min&&d>0.001){player.position.x=o.x+dx/d*min;player.position.z=o.z+dz/d*min}

 }

 for(const jp of jumpPads){

  if(dist2D(player.position,jp)<2.2&&grounded){

   vy=17.5;grounded=false;sfx.click();toast('⬆️ HIGH JUMP!');

   burst(jp.mesh.position,0x00e5ff,18,5);

  }

 }

 for(const sp of speedPads){

  if(dist2D(player.position,sp)<2.2&&speedBoostTime<=0){

   speedBoostTime=3.5;sfx.click();toast('⚡ SPEED BOOST!');

   burst(sp.mesh.position,0xffc531,18,5);

  }

 }

 if((keys.Space||touchJump)&&grounded){vy=10.2;grounded=false}

 vy-=26*dt;player.position.y+=vy*dt;

 if(player.position.y<=0){player.position.y=0;vy=0;grounded=true}

 setLimbSwing(playerParts,Math.sin(walkT)*.8*moveF);

 if(hatSpin)hatSpin.rotation.y+=dt*12;

 if(S.ftueStep===0){S.ftueDist+=Math.hypot(ix,iz)*baseSpd*dt;checkFTUE()}

 if(S.trail!=='none'&&moving){

  trailTimer-=dt;

  if(trailTimer<=0){trailTimer=.05;const col=S.trail==='rainbow'?RAINBOW[Math.floor(T*8)%12]:TRAIL_HEX[S.trail];burst(player.position.clone().setY(.2),col,1,1.2)}

 }

}



function updateNPCs(dt){

 for(const n of npcs){

  n.chatCd-=dt;

  if(n.chatCd<=0){

   n.chatCd=rand(10,22);

   floater(n.av.position.clone().add(new THREE.Vector3(0,3.5,0)),pick(BOT_QUOTES),'#ffffff');

  }

  if(n.idle>0){n.idle-=dt;setLimbSwing(n.parts,0)}

  else{

   const d=dist2D(n.av.position,n.tgt);

   if(d<1.5){n.idle=rand(1.5,5);n.tgt.set(rand(-85,85),0,rand(-85,85))}

   else{

    const dx=(n.tgt.x-n.av.position.x)/d,dz=(n.tgt.z-n.av.position.z)/d;

    n.av.position.x+=dx*n.speed*dt;n.av.position.z+=dz*n.speed*dt;

    for(const o of obstacles){

     const ox=n.av.position.x-o.x,oz=n.av.position.z-o.z;

     const od=Math.hypot(ox,oz);const mn=o.r+.5;

     if(od<mn&&od>0.001){n.av.position.x=o.x+ox/od*mn;n.av.position.z=o.z+oz/od*mn}

    }

    n.av.rotation.y=lerpAngle(n.av.rotation.y,Math.atan2(dx,dz),1-Math.exp(-8*dt));

    n.walkT+=dt*9;setLimbSwing(n.parts,Math.sin(n.walkT)*.7);

    if(n.parts.hatSpin)n.parts.hatSpin.rotation.y+=dt*12;

   }

  }

 }

 if(janeNPC){

  janeNPC.phase+=dt;

  const dx=player.position.x+2.2-janeNPC.av.position.x;

  const dz=player.position.z-2.2-janeNPC.av.position.z;

  const d=Math.hypot(dx,dz);

  if(d>2.5){

   const nx=dx/d,nz=dz/d;

   janeNPC.av.position.x+=nx*5*dt;janeNPC.av.position.z+=nz*5*dt;

   janeNPC.av.rotation.y=lerpAngle(janeNPC.av.rotation.y,Math.atan2(nx,nz),1-Math.exp(-8*dt));

   janeNPC.walkT=(janeNPC.walkT||0)+dt*9;

   setLimbSwing(janeNPC.parts,Math.sin(janeNPC.walkT)*.7);

  }else{

   setLimbSwing(janeNPC.parts,Math.sin(T*1.5)*.1);

   if(Math.random()<.008){

    burst(janeNPC.av.position.clone().add(new THREE.Vector3(0,1.5,0)),0xf7a8d8,5,2);

   }

  }

 }

}



function updateCoins(dt){for(let i=coins.length-1;i>=0;i--){const c=coins[i];c.g.rotation.y+=dt*2.6;c.g.position.y=.78+Math.sin(T*2+c.phase)*.14;if(gameStarted&&dist2D(c.g.position,player.position)<1.6)collectCoin(c)}coinTimer-=dt;if(coinTimer<=0){coinTimer=1.0;if(coins.length<40)spawnCoin(false)}}

function updatePet(dt){if(!petMesh)return;const rot=player.rotation.y;const fx=Math.sin(rot),fz=Math.cos(rot);const rx=Math.cos(rot),rz=-Math.sin(rot);const tx=player.position.x-fx*1.5+rx*.6,tz=player.position.z-fz*1.5+rz*.6;petMesh.position.x+=(tx-petMesh.position.x)*(1-Math.exp(-6*dt));petMesh.position.z+=(tz-petMesh.position.z)*(1-Math.exp(-6*dt));petMesh.position.y=Math.sin(T*3)*.08;petMesh.rotation.y=lerpAngle(petMesh.rotation.y,rot,1-Math.exp(-6*dt))}

function updateParticles(dt){for(let i=parts.length-1;i>=0;i--){const p=parts[i];p.v.y-=16*dt;p.m.position.addScaledVector(p.v,dt);p.life-=dt;const s=clamp(p.life/p.max,0,1);p.m.material.opacity=Math.max(s,0);p.m.scale.setScalar(Math.max(s,.01)*.5);if(p.life<=0){scene.remove(p.m);p.m.material.dispose();parts.splice(i,1)}}}

function updateFloaters(dt){for(let i=floats.length-1;i>=0;i--){const f=floats[i];f.life-=dt;_fv.copy(f.p).project(camera);if(_fv.z<1){f.el.style.left=(_fv.x*.5+.5)*innerWidth+'px';f.el.style.top=(-_fv.y*.5+.5)*innerHeight+'px'}if(f.life<=0){f.el.remove();floats.splice(i,1)}}}

function updateStations(dt){

 if(mysteryBoxMesh){mysteryBoxMesh.rotation.y+=dt*1.2;mysteryBoxMesh.position.y=1.8+Math.sin(T*1.5)*.14;stationRing.scale.setScalar(1+Math.sin(T*2)*.06)}

 if(giftBoxMesh){giftBoxMesh.rotation.y-=dt*1.2;giftBoxMesh.position.y=1.8+Math.sin(T*1.5+1)*.14;giftRing.scale.setScalar(1+Math.sin(T*2+1)*.06)}

 FRIENDS.forEach(f=>{if(f.bounce>0){f.bounce-=dt;f.sign.scale.setScalar(1+Math.sin(T*10)*.15)}else f.sign.scale.setScalar(1);if(f.ringMesh)f.ringMesh.rotation.z+=dt*.5});

 trophyLights.forEach(tl=>{if(tl.mesh&&tl.mesh.parent)tl.mesh.position.y=tl.base+Math.sin(T*2+tl.phase)*.08});

 const now=Date.now();if(now>=S.freeBoxAt&&!giftNotified){giftNotified=true;if(gameStarted)toast('🎉 Free Gift is ready — press E!')}

}

function updateWater(dt){if(!waterGeo)return;const pos=waterGeo.attributes.position;for(let i=0;i<pos.count;i++){const x=pos.getX(i),z=pos.getZ(i);pos.setY(i,Math.sin(x*.05+T*1.2)*.25+Math.cos(z*.05+T*1.1)*.25+Math.sin((x+z)*.04+T*1.5)*.15-.55)}pos.needsUpdate=true;waterGeo.computeVertexNormals()}

function updatePrompt(){const it=nearestInteract();if(it&&gameStarted&&!modalOpen){const l=it.label();if(l!==lastLabel){promptEl.innerHTML='<span class="key">E</span>'+l;lastLabel=l}promptEl.style.display='block'}else{promptEl.style.display='none';lastLabel=''}}



function animate(){

 requestAnimationFrame(animate);

 const dt=Math.min(clock.getDelta(),.05);T+=dt;

 if(gameStarted){updatePlayer(dt);updateNPCs(dt);updateCoins(dt);updatePet(dt)}

 updateParticles(dt);updateFloaters(dt);updateStations(dt);updateWater(dt);updatePrompt();

 if(player){

  camLook.set(player.position.x,player.position.y+2.2,player.position.z);

  const cx=player.position.x+Math.sin(camYaw)*Math.cos(camPitch)*camDist;

  const cy=player.position.y+Math.sin(camPitch)*camDist+1.5;

  const cz=player.position.z+Math.cos(camYaw)*Math.cos(camPitch)*camDist;

  camTarget.set(cx,Math.max(cy,1.0),cz);

  camera.position.lerp(camTarget,1-Math.exp(-8*dt));

  camera.lookAt(camLook);

 }

 composer.render();

}



function processLogin(){const t=todayStr();if(S.lastLogin!==t){const y=new Date(Date.now()-864e5).toDateString();S.streak=(S.lastLogin===y)?S.streak+1:1;S.lastLogin=t;S.coinsToday=0;regenQuests()}}

function regenQuests(){S.questDate=todayStr();S.qProg={coins:0,boxes:0,houses:0};S.qClaim={};S.qNotified={}}

function startGame(){if(gameStarted)return;gameStarted=true;processLogin();if(S.ftueStep===0){S.bux=Math.max(S.bux,1000);if(S.coins<1000000)S.coins=1000000;addCoins(50);gainXP(5);toast('🎁 Welcome champion! 🪙 1,000,000 coins unlocked!')}updateHUD();$('#loader').classList.add('done');setTimeout(()=>{const l=$('#loader');if(l)l.remove()},700);setTimeout(()=>{if(dailyAvailable()&&!modalOpen&&gameStarted)openDaily()},1600);scheduleSocial();save()}

$('#playBtn').onclick=()=>{audioInit();if(actx&&actx.state==='suspended')actx.resume();const nm=($('#nameInput').value||'').trim().replace(/[<>]/g,'');if(nm)S.name=nm;else if(!S.name)S.name='Champion'+ri(100,999);$('#playBtn').disabled=true;startGame()};

$('#nameInput').addEventListener('keydown',e=>{if(e.key==='Enter')$('#playBtn').click()});

function toggleMute(){S.muted=!S.muted;updateHUD();save()}



addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);composer.setSize(innerWidth,innerHeight);outlinePass.resolution.set(innerWidth,innerHeight);if(ssaoPass)ssaoPass.setSize(innerWidth,innerHeight)});

setInterval(save,8000);

addEventListener('beforeunload',save);

document.addEventListener('visibilitychange',()=>{if(document.hidden)save()});



window.openDaily=openDaily;window.openQuests=openQuests;window.openPets=openPets;

window.openShop=openShop;window.openSeason=openSeason;window.openFriends=openFriends;

window.openBoard=openBoard;window.openCharSelect=openCharSelect;window.useStatueModal=useStatueModal;

window.toggleMute=toggleMute;window.closeModal=closeModal;window.buyItem=buyItem;

window.setColor=setColor;window.buyBux=buyBux;window.equipPet=equipPet;

window.claimSeason=claimSeason;window.claimQuest=claimQuest;window.claimDaily=claimDaily;

window.locate=locate;window.doRebirth=doRebirth;window.selectChar=selectChar;

window.useBox=useBox;window.talkToNPC=talkToNPC;window.npcAction=npcAction;

window.answerTrivia=answerTrivia;window.S=S;



buildWorld();

refreshAvatar();

refreshPetMesh();

spawnJane();

for(let i=0;i<16;i++)spawnNPC(NPC_NAMES[i%NPC_NAMES.length]);

for(let i=0;i<8;i++)spawnCoin(true);

for(let i=0;i<32;i++)spawnCoin(false);

updateHUD();

animate();

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