File size: 73,047 Bytes
555b293
 
81da5db
 
 
 
 
 
555b293
105363a
3e9761e
81da5db
5ed1fa2
2a12cbe
3cd395e
 
 
 
 
81da5db
 
994713d
8e116a2
81da5db
139e933
fcb8024
 
97a45d5
 
 
 
 
 
 
fcb8024
 
 
 
555b293
81da5db
 
 
 
5996c15
 
 
bc6466d
3cd395e
 
105363a
a9ad353
 
 
 
 
 
 
 
 
5cd1971
 
81da5db
 
 
 
 
 
 
139e933
81da5db
9d47d53
81da5db
 
139e933
 
81da5db
 
 
 
 
 
cdd21bd
81da5db
cdd21bd
81da5db
 
 
 
 
9f2ab96
 
 
 
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555b293
2a12cbe
 
 
 
105363a
 
221a38b
105363a
221a38b
1ce2492
221a38b
 
 
 
 
 
1ce2492
221a38b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c911ed2
221a38b
9c02556
221a38b
 
 
 
 
c911ed2
221a38b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce2492
c911ed2
221a38b
 
 
 
 
c5293f0
 
e814645
da0174a
 
81da5db
 
 
 
da0174a
555b293
3cd395e
 
 
 
 
 
848abe5
3cd395e
 
848abe5
3cd395e
 
 
 
848abe5
3cd395e
 
 
 
848abe5
3cd395e
 
 
 
 
 
848abe5
3cd395e
 
 
 
 
848abe5
3cd395e
 
 
 
 
 
ca9c10d
3cd395e
 
ca9c10d
3cd395e
ca9c10d
 
 
3cd395e
 
ca9c10d
 
 
 
 
 
 
2a12cbe
ca9c10d
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd395e
ca9c10d
2a12cbe
ca9c10d
 
3cd395e
ca9c10d
3cd395e
ca9c10d
3cd395e
 
 
848abe5
81da5db
 
 
555b293
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
e814645
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e814645
81da5db
 
 
 
 
 
 
e814645
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e814645
555b293
 
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f67a6a
81da5db
 
 
 
 
9a11a2f
81da5db
 
 
 
 
 
 
 
9a11a2f
81da5db
9a11a2f
81da5db
9a11a2f
81da5db
9a11a2f
81da5db
9a11a2f
81da5db
9a11a2f
81da5db
9a11a2f
81da5db
 
 
 
 
 
 
 
 
 
555b293
81da5db
555b293
81da5db
 
 
 
555b293
7f47350
9a11a2f
 
 
555b293
fde1cba
9a11a2f
3f72e33
9a11a2f
e51062a
3f72e33
f9d15ce
3f72e33
 
e51062a
3f72e33
 
 
2800d14
9a11a2f
3f72e33
 
 
 
 
fde1cba
3f72e33
 
0aebc54
3f72e33
9a11a2f
 
e51062a
9a11a2f
 
14b5599
9a11a2f
 
81da5db
9a11a2f
 
 
2800d14
a2b4351
9a11a2f
 
22b65fd
c5bb23a
 
22b65fd
e51062a
22b65fd
14b5599
22b65fd
9a11a2f
94b25e3
c5bb23a
 
94b25e3
c5bb23a
 
 
 
94b25e3
22b65fd
14b5599
9a11a2f
c5bb23a
 
9a11a2f
22b65fd
 
c5bb23a
 
 
 
 
 
 
 
 
 
 
22b65fd
 
c5bb23a
 
 
 
 
 
 
9a11a2f
 
 
 
22b65fd
c5bb23a
 
 
 
 
 
 
9a11a2f
 
 
7f47350
91f3c41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f429f9
91f3c41
 
 
 
 
 
1f429f9
 
 
 
 
91f3c41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d12907
 
 
 
 
 
 
 
91f3c41
9d12907
7f47350
0bbc50b
aa54934
9d12907
 
 
 
 
 
 
9c02556
aa54934
0bbc50b
41009db
aa54934
9c02556
0bbc50b
 
9c02556
0bbc50b
aa54934
 
a5d0984
 
9d12907
aa54934
41009db
aa54934
 
 
 
 
 
 
 
a5d0984
aa54934
 
 
0bbc50b
 
0595b01
b0f5d5e
0595b01
 
b0842f4
0595b01
b0f5d5e
 
b0842f4
0bbc50b
 
a799e84
3f72e33
a20b089
e901433
 
3f72e33
e901433
 
 
1ab3f7b
e901433
1ab3f7b
7f47350
 
 
4c8b807
8e116a2
46b19ac
 
 
 
 
 
8e116a2
46b19ac
0bbc50b
8e116a2
46b19ac
9c02556
0bbc50b
 
9c02556
46b19ac
0bbc50b
46b19ac
41009db
9c02556
 
81da5db
 
8e116a2
81da5db
 
 
8e116a2
 
 
 
81da5db
 
 
8e116a2
81da5db
 
 
 
 
 
 
 
 
 
 
e814645
81da5db
 
 
 
 
 
 
 
 
 
 
 
8e116a2
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105363a
d16ea14
 
 
 
 
 
 
 
 
 
 
 
 
105363a
 
d16ea14
105363a
d16ea14
105363a
 
 
d16ea14
105363a
 
d16ea14
41009db
 
 
 
 
 
 
 
eb3d5b7
41009db
eb3d5b7
 
 
3cd395e
 
 
 
 
 
 
 
 
 
 
 
 
 
848abe5
 
 
3cd395e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848abe5
3cd395e
 
 
 
 
 
 
 
 
 
 
 
 
 
eb3d5b7
 
 
 
 
47b55f4
 
3cd395e
2a12cbe
 
3cd395e
eb3d5b7
47b55f4
2a12cbe
 
3cd395e
eb3d5b7
 
3cd395e
47b55f4
 
3cd395e
47b55f4
3cd395e
eb3d5b7
3cd395e
eb3d5b7
3cd395e
eb3d5b7
47b55f4
eb3d5b7
3cd395e
eb3d5b7
 
47b55f4
 
3cd395e
47b55f4
 
 
 
 
 
 
3cd395e
47b55f4
 
 
 
3cd395e
47b55f4
 
 
 
 
 
 
 
 
eb3d5b7
3cd395e
ef26709
 
 
eb3d5b7
913e5f1
 
 
 
 
 
 
 
 
 
809a66a
 
 
 
 
 
 
 
913e5f1
 
 
 
 
9b345ce
 
 
 
 
 
 
 
913e5f1
 
 
 
 
 
 
809a66a
913e5f1
 
809a66a
 
 
913e5f1
9b345ce
eb3d5b7
809a66a
f0f25b8
 
 
 
 
 
 
40343d3
f0f25b8
40343d3
 
 
 
 
f0f25b8
 
 
 
 
40343d3
f0f25b8
 
40343d3
f0f25b8
 
 
 
40343d3
f0f25b8
555b293
caedce1
 
 
40343d3
caedce1
 
 
 
 
 
 
 
 
 
 
81da5db
e16a379
caedce1
 
 
e16a379
caedce1
 
 
 
 
e16a379
caedce1
 
 
 
e16a379
caedce1
e16a379
81da5db
e16a379
81da5db
 
7863c9d
 
 
 
 
 
 
 
 
 
 
 
 
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4f5aaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105363a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81da5db
967620f
 
6472f13
81da5db
2800d14
c7d9e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5336d2b
b74c094
a9059d3
b74c094
0456a41
b74c094
0456a41
b74c094
0456a41
b74c094
 
 
6472f13
b74c094
 
a9059d3
c7d9e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0a3aaa
c7d9e3b
9a48bdb
af7cef1
3d797a0
146f2cf
3d797a0
 
f27e87a
146f2cf
f27e87a
3d797a0
146f2cf
3d797a0
f27e87a
146f2cf
 
 
 
f27e87a
146f2cf
 
 
 
 
 
 
 
 
 
f27e87a
146f2cf
 
 
 
5cd519d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82428ba
3d797a0
146f2cf
 
 
3d797a0
146f2cf
 
 
 
3d026b6
700dcad
f27e87a
146f2cf
 
 
 
3d797a0
e96e7b8
f27e87a
 
3d797a0
 
 
 
 
 
 
 
f27e87a
3d797a0
 
f27e87a
3d797a0
 
 
 
 
f27e87a
3d797a0
 
f27e87a
 
3d797a0
 
 
f27e87a
 
 
146f2cf
 
3d797a0
65ce545
3d797a0
65ce545
 
 
 
 
 
 
 
 
 
 
 
 
9f2ab96
65ce545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fcd476
65ce545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce199f
65ce545
9a11a2f
8c06610
add7eb9
8c06610
3ce199f
 
1ba983d
7c3bf03
8c06610
3ce199f
 
8c06610
3ce199f
 
1ba983d
3ce199f
caedce1
ffbea3b
3d026b6
 
 
 
 
1ba983d
 
74a361e
5336d2b
 
caedce1
9f2ab96
5336d2b
add7eb9
5336d2b
 
9a48bdb
add7eb9
 
8c06610
add7eb9
 
8c06610
add7eb9
 
8c06610
1ba983d
add7eb9
1ba983d
 
e16a379
1ba983d
e16a379
8c06610
add7eb9
 
5336d2b
 
8c06610
5336d2b
9f2ab96
8c06610
3ce199f
74a361e
9a48bdb
add7eb9
9a11a2f
 
 
 
 
 
add7eb9
5336d2b
add7eb9
9a11a2f
8c06610
5336d2b
8c06610
 
 
4fcd476
 
8c06610
 
4fcd476
 
 
5336d2b
 
7c3bf03
3d026b6
 
 
 
 
 
 
 
 
 
 
 
 
 
8c06610
7c3bf03
8c06610
3d026b6
 
 
 
 
 
 
 
 
 
 
9a11a2f
1ba983d
 
add7eb9
1ba983d
 
 
e16a379
8c06610
caedce1
65ce545
9a11a2f
 
caedce1
65ce545
 
 
 
 
 
 
 
 
 
 
 
 
 
9a48bdb
3ce199f
 
 
 
5336d2b
3ce199f
 
 
 
5336d2b
3ce199f
caedce1
9f2ab96
9a48bdb
 
9a11a2f
9a48bdb
 
 
9a11a2f
9a48bdb
 
9a11a2f
9a48bdb
 
 
add7eb9
2865022
 
 
 
1ba983d
2865022
1ba983d
add7eb9
1ba983d
 
2865022
9f2ab96
01325f6
c5bb23a
 
 
0465e0d
c5bb23a
ffe0b04
 
 
 
c5bb23a
 
 
ffe0b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5bb23a
ffe0b04
c5bb23a
2800d14
caedce1
84315a3
9f2ab96
0465e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0f25b8
f27e87a
e96e7b8
 
 
 
f27e87a
f0f25b8
 
0465e0d
 
 
 
f27e87a
8071a92
 
 
 
f27e87a
 
 
 
 
 
 
 
8071a92
0465e0d
 
 
 
f27e87a
0465e0d
 
 
 
 
 
e96e7b8
0465e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8071a92
0465e0d
 
 
 
 
 
f0f25b8
0465e0d
f0f25b8
 
 
 
 
0465e0d
f0f25b8
8071a92
f0f25b8
 
e16a379
8071a92
f0f25b8
e16a379
 
81da5db
f0f25b8
 
8071a92
f27e87a
8071a92
0465e0d
8071a92
 
 
 
f27e87a
8071a92
 
 
0465e0d
3d026b6
4fcd476
 
 
 
 
 
 
 
 
 
 
3d026b6
 
 
0465e0d
3d026b6
 
0465e0d
8071a92
 
 
 
 
 
 
 
0465e0d
8071a92
 
 
 
 
 
 
 
 
 
f27e87a
 
8071a92
 
 
 
 
 
 
f27e87a
8071a92
0465e0d
d269c51
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e116a2
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e814645
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da0174a
b0842f4
f1df12f
 
 
 
 
 
 
 
360a944
02fee20
454f76e
f991544
700dcad
454f76e
 
4a03285
454f76e
 
 
 
 
 
 
 
 
50329b8
360a944
454f76e
 
 
360a944
50329b8
454f76e
 
 
 
a9059d3
 
454f76e
f2b8e62
454f76e
 
f2b8e62
454f76e
 
 
 
 
 
4593f63
454f76e
 
 
f1df12f
454f76e
 
 
 
 
 
 
 
f1cc623
454f76e
060b94c
383d961
 
454f76e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060b94c
454f76e
 
 
060b94c
454f76e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a799e84
46b19ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a799e84
3d1ed1b
81da5db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da0174a
81da5db
 
 
 
 
 
 
 
 
 
555b293
81da5db
 
555b293
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
# app.py
"""
Unified Online/Offline AI Quiz Game with Friends, Chat, Presence, Invites.

- Offline: uses local JSON files under ./data/
- Online: uses Firebase Realtime Database when configured (optional)
- Put your Firebase service account JSON next to this file and name it serviceAccountKey.json
- FIREBASE_DB_URL is set to your Firebase project's Realtime DB (from your screenshot)
"""
import requests
import csv
import uuid
import os
import fitz  # PyMuPDF
from PyPDF2 import PdfReader
import docx
import pytesseract
from PIL import Image
import re
import time
import json
from groq import Groq
from datetime import datetime, timedelta, UTC

import streamlit as st


# โœ… FIRST STREAMLIT COMMAND (VERY IMPORTANT)
st.set_page_config(
    page_title="AI Quiz Game",
    layout="wide"
)

# โœ… THEN YOUR PWA CODE
st.markdown("""
<link rel="manifest" href="/static/manifest.json">
<meta name="theme-color" content="#4CAF50">
""", unsafe_allow_html=True)
import pandas as pd
import random
from streamlit.components.v1 import html
import plotly.express as px

# ุจุงู‚ูŠ code
st.title("Welcome")

LEADERBOARD_FILE = "leaderboard.csv"
if "uploaded_questions_db" not in st.session_state:
    st.session_state.uploaded_questions_db = {}

if not os.path.exists(LEADERBOARD_FILE):
    df = pd.DataFrame(columns=[
        "name",
        "score",
        "mode",
        "timestamp"
    ])
    df.to_csv(LEADERBOARD_FILE, index=False)



# Try to import firebase-admin (optional). If unavailable, app will run Offline.
try:
    import firebase_admin
    from firebase_admin import credentials, db
    FIREBASE_AVAILABLE = True
except Exception:
    FIREBASE_AVAILABLE = False

# ---------------- Page config ----------------


# ---------------- Configuration ----------------
DATA_DIR = "data"
os.makedirs(DATA_DIR, exist_ok=True)

# Local filenames
GAMES_FILE = os.path.join(DATA_DIR, "games.json")
PLAYERS_FILE = os.path.join(DATA_DIR, "players.json")
MESSAGES_FILE = os.path.join(DATA_DIR, "messages.json")
SESSIONS_FILE = os.path.join(DATA_DIR, "sessions.json")
LEADERBOARD_FILE = "leaderboard.csv"
FRIENDS_FILE = os.path.join(DATA_DIR, "friends.json")
INBOX_FILE = "inbox.json"  # friend requests & invitations

# Firebase defaults (you provided project)
FIREBASE_CREDENTIALS = os.getenv("FIREBASE_CREDENTIALS", "serviceAccountKey.json")
FIREBASE_DB_URL = os.getenv("FIREBASE_DB_URL", "https://real-time-database-fe632-default-rtdb.firebaseio.com/")

# Heartbeat threshold (seconds) to consider a session active
HEARTBEAT_THRESHOLD_SECONDS = 30


# Heartbeat threshold (seconds) to consider a session active

# ---------------- Example Questions DB (expand as needed) ----------------
questions_db = {
    "Geography": [
        ("What is the capital of France?", ["Paris", "London", "Berlin", "Madrid"], "Paris"),
        ("Largest country by area?", ["Canada", "USA", "Russia", "China"], "Russia"),
        ("River through Egypt?", ["Nile", "Amazon", "Ganges", "Yangtze"], "Nile"),
        ("Mount Everest is in which country?", ["Nepal", "India", "China", "Bhutan"], "Nepal"),
        ("Which ocean is the largest?", ["Atlantic", "Pacific", "Indian", "Arctic"], "Pacific"),
        ("Which country has the most population?", ["China", "India", "USA", "Indonesia"], "China"),
        ("Capital of Japan?", ["Tokyo", "Kyoto", "Osaka", "Hiroshima"], "Tokyo"),
        ("Longest river in the world?", ["Nile", "Amazon", "Yangtze", "Mississippi"], "Nile"),
        ("Which desert is the largest?", ["Sahara", "Gobi", "Kalahari", "Arctic"], "Sahara"),
        ("Capital of Australia?", ["Sydney", "Melbourne", "Canberra", "Brisbane"], "Canberra")
    ],
    "Math": [
        ("5 * 12?", ["50", "60", "55", "70"], "60"),
        ("sqrt(64)?", ["6","7","8","9"], "8"),
        ("What is 15 + 25?", ["35","40","45","50"], "40"),
        ("100 รท 4?", ["20", "25", "30", "24"], "25"),
        ("If x+5=12, x=?", ["5","6","7","8"], "7"),
        ("Area of a circle with radius 7?", ["154", "144", "160", "150"], "154"),
        ("7^2 = ?", ["49","42","56","36"], "49"),
        ("10% of 200?", ["10","20","15","25"], "20"),
        ("Solve: 3x = 15, x = ?", ["4","5","6","7"], "5"),
        ("What is 9 * 8?", ["72","81","64","69"], "72")
    ],
    "Science": [
        ("H2O is?", ["Water","CO2","O2","H2"], "Water"),
        ("Who developed relativity?", ["Newton","Einstein","Tesla","Curie"], "Einstein"),
        ("Sun is a?", ["Star","Planet","Moon","Asteroid"], "Star"),
        ("Light speed is approximately?", ["3x10^8 m/s","3x10^6 m/s","3x10^5 km/s","3x10^7 km/s"], "3x10^8 m/s"),
        ("Which gas do plants absorb?", ["Oxygen","CO2","Nitrogen","Helium"], "CO2"),
        ("The human brain weighs about?", ["1kg","1.4kg","2kg","2.5kg"], "1.4kg"),
        ("Chemical symbol for Gold?", ["Au","Ag","Go","Gd"], "Au"),
        ("Which planet is called Red Planet?", ["Mars","Venus","Jupiter","Mercury"], "Mars"),
        ("Which part of the plant conducts photosynthesis?", ["Root","Stem","Leaf","Flower"], "Leaf"),
        ("What is the boiling point of water?", ["90ยฐC","100ยฐC","120ยฐC","80ยฐC"], "100ยฐC")
    ],
    "IPL": [
        ("2020 IPL winner?", ["Mumbai Indians","Delhi Capitals","RCB","CSK"], "Mumbai Indians"),
        ("Which team is called Yellow Army?", ["CSK","MI","DC","SRH"], "CSK"),
        ("Who won the Orange Cap in 2021 IPL?", ["KL Rahul","Faf du Plessis","Ruturaj Gaikwad","Shikhar Dhawan"], "Ruturaj Gaikwad"),
        ("Which team has won the most IPL titles?", ["MI","CSK","RCB","KKR"], "MI"),
        ("Who is known as Mr. IPL?", ["MS Dhoni","Rohit Sharma","Virat Kohli","AB de Villiers"], "MS Dhoni"),
        ("First IPL season was in?", ["2007","2008","2009","2010"], "2008"),
        ("Which team represents Bangalore?", ["RCB","MI","KKR","SRH"], "RCB"),
        ("Purple Cap is for?", ["Highest scorer","Best bowler","Best fielder","Best captain"], "Best bowler"),
        ("Which team plays at Eden Gardens?", ["KKR","CSK","MI","RCB"], "KKR"),
        ("Who scored fastest 50 in IPL?", ["KL Rahul","Chris Gayle","Andre Russell","AB de Villiers"], "Chris Gayle")
    ],
    "History": [
        ("Who was the first President of the USA?", ["George Washington","Abraham Lincoln","Thomas Jefferson","John Adams"], "George Washington"),
        ("In which year did India gain independence?", ["1945","1947","1950","1952"], "1947"),
        ("The Great Wall is in which country?", ["China","Japan","Korea","Mongolia"], "China"),
        ("Who discovered America?", ["Columbus","Magellan","Vasco da Gama","Cook"], "Columbus"),
        ("French Revolution started in?", ["1789","1776","1800","1799"], "1789"),
        ("First man on the moon?", ["Neil Armstrong","Buzz Aldrin","Yuri Gagarin","John Glenn"], "Neil Armstrong"),
        ("Who invented the printing press?", ["Gutenberg","Edison","Tesla","Newton"], "Gutenberg"),
        ("World War II ended in?", ["1943","1945","1947","1950"], "1945"),
        ("Who was known as Iron Man of India?", ["Sardar Patel","Nehru","Gandhi","Tilak"], "Sardar Patel"),
        ("Which empire built the Colosseum?", ["Roman Empire","Greek Empire","Egyptian Empire","Persian Empire"], "Roman Empire")
    ],
    "Technology": [
        ("Who is the founder of Microsoft?", ["Steve Jobs","Bill Gates","Elon Musk","Mark Zuckerberg"], "Bill Gates"),
        ("HTML stands for?", ["Hyper Text Markup Language","High Text Markup Language","Hyperlinks Text Mark Language","None"], "Hyper Text Markup Language"),
        ("Python is a type of?", ["Snake","Programming Language","Car","Game"], "Programming Language"),
        ("CPU stands for?", ["Central Process Unit","Central Processing Unit","Control Processing Unit","Computer Processing Unit"], "Central Processing Unit"),
        ("Java is a?", ["Programming Language","Coffee","Operating System","Browser"], "Programming Language"),
        ("WWW stands for?", ["World Wide Web","Wide World Web","Web World Wide","None"], "World Wide Web"),
        ("What is 1 Gigabyte in MB?", ["512MB","1024MB","2048MB","1000MB"], "1024MB"),
        ("Google was founded in?", ["1996","1998","2000","2002"], "1998"),
        ("First computer virus was?", ["Creeper","ILOVEYOU","Michelangelo","Morris"], "Creeper"),
        ("Linux OS was developed by?", ["Linus Torvalds","Bill Gates","Steve Jobs","Tim Berners-Lee"], "Linus Torvalds")
    ],
    "Sports": [
        ("How many players in a football team?", ["9","10","11","12"], "11"),
        ("Olympics are held every?", ["2 years","4 years","3 years","5 years"], "4 years"),
        ("Tennis player known as โ€˜Federerโ€™?", ["Roger Federer","Rafael Nadal","Novak Djokovic","Andy Murray"], "Roger Federer"),
        ("Cricket World Cup held every?", ["2","4","5","3"], "4"),
        ("Which country won the first football World Cup?", ["Brazil","Uruguay","Germany","Italy"], "Uruguay"),
        ("Formula 1 world champion 2020?", ["Hamilton","Verstappen","Vettel","Leclerc"], "Hamilton"),
        ("Number of players in a basketball team?", ["5","6","7","8"], "5"),
        ("Which country hosts Wimbledon?", ["USA","UK","France","Australia"], "UK"),
        ("Who holds most Olympic golds?", ["Michael Phelps","Usain Bolt","Carl Lewis","Mark Spitz"], "Michael Phelps"),
        ("Which sport uses the term 'love'?", ["Tennis","Badminton","Squash","Golf"], "Tennis")
    ]
}
# ๐Ÿ”ฅ MERGE CUSTOM TOPICS INTO MAIN DB (FIX)
if "custom_topics" in st.session_state:
    for t, qs in st.session_state["custom_topics"].items():
        questions_db[t] = qs
# ----------------- JSON helpers ---------------

client = Groq(api_key=st.secrets["GROQ_API_KEY"].strip())

MODEL_NAME = "openai/gpt-oss-20b"

def generate_ai_questions(topic, num_questions=5, gid=None, questions_db=None):
    """
    Generate MCQs using Groq AI for a topic.
    Fallback to questions_db if AI fails or no data returned.
    Returns list of dicts: {"question":..., "options": [...], "answer":...}
    """

    # Ensure fallback exists
    if questions_db is None:
        questions_db = {}

    prompt = f"""
    Generate {num_questions} high-quality MCQ questions for the topic "{topic}".

    STRICT FORMAT:
    [
      {{
        "topic": "{topic}",
        "question": "Question text",
        "options": ["Option 1", "Option 2", "Option 3", "Option 4"],
        "answer": "Correct option text"
      }}
    ]

    RULES:
    -Different questions
    - ONLY valid JSON array.
    - No extra text.
    - No markdown.
    - No explanations.
    """

    try:
        st.info(f"Generating AI questions for topic '{topic}'...")
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[{"role": "user", "content": prompt}],
            temperature=0.2,
            max_tokens=800,
        )

        raw = response.choices[0].message.content.strip()

        # Remove code blocks if AI adds them
        if raw.startswith("```"):
            raw = raw.split("```")[1].replace("json", "").strip()

        data = json.loads(raw)

        # Optional: save Excel if gid provided
        if gid:
            os.makedirs("ai_questions_excel", exist_ok=True)
            rows = []
            for q in data:
                rows.append({
                    "topic": q.get("topic", topic),
                    "question": q.get("question", ""),
                    "option_1": q.get("options", [""]*4)[0],
                    "option_2": q.get("options", [""]*4)[1],
                    "option_3": q.get("options", [""]*4)[2],
                    "option_4": q.get("options", [""]*4)[3],
                    "answer": q.get("answer", "")
                })
            df = pd.DataFrame(rows)
            df.to_excel(f"ai_questions_excel/{gid}_questions.xlsx", index=False)

        return data[:num_questions]

    except Exception as e:
        st.warning(f"AI generation failed for topic '{topic}': {e}")
        st.info("Using fallback questions from questions_db if available.")
        # Fallback to static questions_db
        fallback = questions_db.get(topic.lower(), questions_db.get("default", []))
        return fallback[:num_questions]


def load_json(path, default):
    if os.path.exists(path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            return default
    return default

def extract_text_from_pdf(file):
    reader = PdfReader(file)
    text = ""
    for page in reader.pages:
        text += page.extract_text() + "\n"
    return text

def extract_text_from_file(uploaded_file):
    text = ""

    if uploaded_file.type == "application/pdf":
        pdf = fitz.open(stream=uploaded_file.read(), filetype="pdf")
        for page in pdf:
            text += page.get_text()

    elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
        doc = docx.Document(uploaded_file)
        for para in doc.paragraphs:
            text += para.text + "\n"

    elif "image" in uploaded_file.type:
        image = Image.open(uploaded_file)
        text = pytesseract.image_to_string(image)

    elif uploaded_file.type == "text/plain":
        text = uploaded_file.read().decode("utf-8")

    return text
def extract_text_from_docx(file):
    doc = docx.Document(file)
    text = "\n".join([p.text for p in doc.paragraphs])
    return text


def extract_text_from_image(file):
    img = Image.open(file)
    text = pytesseract.image_to_string(img)
    return text
    

def parse_questions(raw_text, topic):
    questions = []
    
    try:
        # Split question blocks
        blocks = re.split(r'\n\d+[\).]|\nQ\d+[\).]?', raw_text)
        
        for b in blocks:
            lines = [l.strip() for l in b.split("\n") if l.strip()]
            
            if len(lines) >= 5:
                q = lines[0]
                options = []
                
                # Collect first 4 options
                for l in lines[1:]:
                    if len(options) < 4:
                        options.append(l)
                
                # Default answer
                answer = options[0]
                
                # Find actual answer
                for l in lines:
                    if "answer" in l.lower():
                        ans = l.split(":")[-1].strip().lower()
                        
                        for opt in options:
                            if ans in opt.lower():
                                answer = opt
                
                questions.append({
                    "question": q,
                    "options": options[:4],
                    "answer": answer,
                    "topic": topic
                })
        
        return questions
    
    except Exception as e:
        print("Parse error:", e)
        return []

def save_json(path, data):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

# Ensure base files exist (local)
base_defaults = {
    GAMES_FILE: {},
    PLAYERS_FILE: {},
    MESSAGES_FILE: {},
    SESSIONS_FILE: {},
    FRIENDS_FILE: {},
    INBOX_FILE: {}
}
for p, d in base_defaults.items():
    if not os.path.exists(p):
        save_json(p, d)
if not os.path.exists(LEADERBOARD_FILE):
    pd.DataFrame(columns=['name','score','game_id','topics','timestamp','avatar','questions','answers','correct_flags']).to_csv(LEADERBOARD_FILE, index=False)

# ----------------- Firebase init -----------------
def init_firebase_if_needed():
    """Initialize Firebase Admin if available and credentials present. Return (ok,msg)."""
    global FIREBASE_AVAILABLE
    if not FIREBASE_AVAILABLE:
        return False, "firebase-admin not installed"
    if not FIREBASE_DB_URL:
        return False, "FIREBASE_DB_URL not set"
    if not os.path.exists(FIREBASE_CREDENTIALS):
        return False, f"Service account file not found at {FIREBASE_CREDENTIALS}"
    try:
        if not firebase_admin._apps:
            cred = credentials.Certificate(FIREBASE_CREDENTIALS)
            firebase_admin.initialize_app(cred, {"databaseURL": FIREBASE_DB_URL})
        return True, "Firebase initialized"
    except Exception as e:
        return False, f"Firebase init error: {e}"

# Firebase helpers
def fb_get(path):
    try:
        ref = db.reference(path)
        return ref.get()
    except Exception:
        return None

def fb_set(path, value):
    ref = db.reference(path)
    ref.set(value)

def fb_push(path, value):
    ref = db.reference(path).push()
    ref.set(value)
    return ref.key

# ----------------- Unified DB API (Online or Offline) -----------------
def local_get(collection):
    if collection == "games":
        return load_json(GAMES_FILE, {})
    if collection == "players":
        return load_json(PLAYERS_FILE, {})
    if collection == "messages":
        return load_json(MESSAGES_FILE, {})
    if collection == "sessions":
        return load_json(SESSIONS_FILE, {})
    if collection == "friends":
        return load_json(FRIENDS_FILE, {})
    if collection == "inbox":
        return load_json(INBOX_FILE, {})
    if collection == "leaderboard":
        try:
            df = pd.read_csv(LEADERBOARD_FILE)
            return df.to_dict(orient="records")
        except Exception:
            return []
    return {}

def local_set(collection, value):
    if collection == "games":
        save_json(GAMES_FILE, value)
    elif collection == "players":
        save_json(PLAYERS_FILE, value)
    elif collection == "messages":
        save_json(MESSAGES_FILE, value)
    elif collection == "sessions":
        save_json(SESSIONS_FILE, value)
    elif collection == "friends":
        save_json(FRIENDS_FILE, value)
    elif collection == "inbox":
        save_json(INBOX_FILE, value)
    elif collection == "leaderboard":
        try:
            df = pd.DataFrame(value)
            df.to_csv(LEADERBOARD_FILE, index=False)
        except Exception:
            pass

def unified_get(collection):
    mode = st.session_state.get("mode_selection", "Offline")
    if mode == "Online":
        ok, msg = init_firebase_if_needed()
        if not ok:
            return local_get(collection)
        # map collection to firebase path
        if collection == "games":
            return fb_get("/games") or {}
        if collection == "players":
            return fb_get("/players") or {}
        if collection == "messages":
            return fb_get("/messages") or {}
        if collection == "sessions":
            return fb_get("/active_sessions") or {}
        if collection == "friends":
            return fb_get("/friends") or {}
        if collection == "inbox":
            return fb_get("/inbox") or {}
        if collection == "leaderboard":
            raw = fb_get("/leaderboard_online") or {}
            if isinstance(raw, dict):
                return list(raw.values())
            return raw
    else:
        return local_get(collection)

def unified_set(collection, data):
    mode = st.session_state.get("mode_selection", "Offline")
    if mode == "Online":
        ok, msg = init_firebase_if_needed()
        if not ok:
            local_set(collection, data)
            return
        if collection == "games":
            fb_set("/games", data); return
        if collection == "players":
            fb_set("/players", data); return
        if collection == "messages":
            fb_set("/messages", data); return
        if collection == "sessions":
            fb_set("/active_sessions", data); return
        if collection == "friends":
            fb_set("/friends", data); return
        if collection == "inbox":
            fb_set("/inbox", data); return
        if collection == "leaderboard":
            local_set(collection, data); return
    else:
        local_set(collection, data)

def unified_push_message(game_id, msg_obj):
    mode = st.session_state.get("mode_selection", "Offline")
    if mode == "Online":
        ok, _ = init_firebase_if_needed()
        if ok:
            fb_push(f"/messages/{game_id}", msg_obj)
            return
    all_msgs = unified_get("messages") or {}
    game_msgs = all_msgs.get(game_id, [])
    game_msgs.append(msg_obj)
    if len(game_msgs) > 500:
        game_msgs = game_msgs[-500:]
    all_msgs[game_id] = game_msgs
    unified_set("messages", all_msgs)


# ---------------------------
# ---------------------------

def unified_push_leaderboard(row):

    row = row.copy()

    mode = st.session_state.get("mode_selection", "Offline")

    ok, msg = init_firebase_if_needed()

    if ok:
        try:

            # ONLINE MODE
            if mode == "Online":
                db.reference("/leaderboard_online").push(row)
                db.reference(f"/games/{row['game_id']}/scores").push(row)

            # OFFLINE MODE
            else:
                db.reference("/leaderboard").push(row)

            st.success("๐Ÿ”ฅ Score saved to Firebase!")

        except Exception as e:
            st.error(f"Firebase push failed: {e}")

    # Local CSV backup
    try:
        file_exists = os.path.isfile(LEADERBOARD_FILE)

        with open(LEADERBOARD_FILE, "a", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=row.keys())

            if not file_exists:
                writer.writeheader()

            writer.writerow(row)

    except Exception as e:
        st.warning(f"Local CSV backup failed: {e}")



def show_game_leaderboard(game_id):

    st.subheader(f"๐Ÿ† Leaderboard - Game {game_id}")

    mode = st.session_state.get("mode_selection", "Offline")
    rows = []

    if mode == "Online":
        ok, _ = init_firebase_if_needed()

        if ok:
            raw = fb_get(f"/games/{game_id}/scores") or {}

            if isinstance(raw, dict):
                rows = list(raw.values())
            else:
                rows = raw

    else:
        try:
            df = pd.read_csv(LEADERBOARD_FILE)
            rows = df.to_dict("records")
        except:
            rows = []

    if not rows:
        st.info("No scores yet.")
        return

    df = pd.DataFrame(rows)

    # filter by game
    if "game_id" in df.columns:
        df = df[df["game_id"] == game_id]

    if df.empty:
        st.info("No results submitted yet.")
        return

    # convert score
    df["score"] = pd.to_numeric(df["score"], errors="coerce").fillna(0)

    # sort
    df = df.sort_values(by="score", ascending=False)

    for i, r in df.iterrows():

        avatar = r.get("avatar", "๐ŸŽฎ")
        name = r.get("name", "Unknown")
        score = r.get("score", 0)

        ts = r.get("timestamp", "")
        try:
            ts = pd.to_datetime(ts).strftime("%d %b %Y %H:%M:%S")
        except:
            pass

        st.write(f"{avatar} **{name}** โ€” {score} pts โฑ๏ธ {ts}")


# ---------------------------
# Get weekly leaderboard
def weekly_leaderboard_section():

    st.subheader("๐Ÿ“… Weekly Leaderboard")

    mode = st.session_state.get("mode_selection", "Offline")
    rows = []

    # -------- LOAD DATA --------
    if mode == "Online":
        ok, _ = init_firebase_if_needed()
        if ok:
            raw = fb_get("/leaderboard_online")
            if raw:
                rows = list(raw.values()) if isinstance(raw, dict) else raw
    else:
        try:
            df_csv = pd.read_csv(LEADERBOARD_FILE)
            rows = df_csv.to_dict("records")
        except:
            rows = []

    if not rows:
        st.info("No scores yet.")
        return

    df = pd.DataFrame(rows)

    if "timestamp" not in df.columns:
        st.warning("No timestamp data available.")
        return

    # Safe conversions
    df["score"] = pd.to_numeric(df.get("score", 0), errors="coerce").fillna(0)
    df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce", utc=True)

    # -------- ADD WEEK + MONTH --------
    df["week"] = df["timestamp"].dt.isocalendar().week
    df["month"] = df["timestamp"].dt.month
    df["year"] = df["timestamp"].dt.year

    now = pd.Timestamp.now(tz="UTC")
    
    current_year = now.year
    current_week = now.isocalendar().week
    current_month = now.month

    # -------- SELECT OPTIONS --------
    col1, col2 = st.columns(2)

    with col1:
        selected_month = st.selectbox(
            "Select Month",
            sorted(df["month"].dropna().unique()),
            index=list(sorted(df["month"].unique())).index(current_month)
            if current_month in df["month"].values else 0
        )

    with col2:
        selected_week = st.selectbox(
            "Select Week",
            sorted(df["week"].dropna().unique()),
            index=list(sorted(df["week"].unique())).index(current_week)
            if current_week in df["week"].values else 0
        )

    # -------- FILTER --------
    filtered = df[
        (df["month"] == selected_month) &
        (df["week"] == selected_week) &
        (df["year"] == current_year)
    ]

    if filtered.empty:
        st.warning("No data for selected week.")
        return

    # -------- SORT --------
    filtered = filtered.sort_values(by="score", ascending=False)

    st.markdown(f"### ๐Ÿ† Week {selected_week} - Month {selected_month}")

    # -------- DISPLAY TABLE --------
    display_df = filtered[["name", "score", "timestamp"]]
    display_df = display_df.rename(columns={
        "name": "Player",
        "score": "Score",
        "timestamp": "Date"
    })

    st.dataframe(display_df.head(10), use_container_width=True)

    # -------- USER SELECT --------
    selected_user = st.selectbox(
        "Select Player to Check Score",
        filtered["name"].unique()
    )

    user_data = filtered[filtered["name"] == selected_user]

    if not user_data.empty:
        total_score = int(user_data["score"].sum())
        st.success(f"{selected_user} Total Weekly Score: {total_score} pts")

        # -------- SMALL PIE CHART --------
        st.markdown("### ๐Ÿ“Š Weekly Score Distribution")

        pie_df = user_data.groupby("game_id")["score"].sum().reset_index()

        st.markdown("### ๐Ÿ“Š Weekly Score Distribution")
        pie_df = user_data.groupby("game_id")["score"].sum().reset_index()
        
        fig = px.pie(
            pie_df,
            values="score",
            names="game_id",
            title="Game-wise Score Share"
        )
        st.plotly_chart(fig, use_container_width=True)
# ---------------------------
def get_weekly_leaderboard():

    mode = st.session_state.get("mode_selection", "Offline")

    # ๐Ÿ”ฅ Load only selected mode
    if mode == "Online":
        rows = get_online_leaderboard()
    else:
        rows = get_offline_leaderboard()

    if not rows:
        return pd.DataFrame()

    df = pd.DataFrame(rows)

    if "timestamp" not in df.columns:
        return pd.DataFrame()

    df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce")
    df = df.dropna(subset=["timestamp"])

    df["score"] = pd.to_numeric(df["score"], errors="coerce").fillna(0)

    current_week = pd.Timestamp.now().isocalendar().week
    current_year = pd.Timestamp.now().year

    df["week"] = df["timestamp"].dt.isocalendar().week
    df["year"] = df["timestamp"].dt.year

    weekly_df = df[
        (df["week"] == current_week) &
        (df["year"] == current_year)
    ]

    return weekly_df.sort_values(
        by="score",
        ascending=False
    ).head(10)
def get_online_leaderboard():
    try:
        raw = fb_get("/leaderboard_online") or {}

        if isinstance(raw, dict):
            return list(raw.values())

        return raw

    except Exception as e:
        st.error(f"Firebase Error: {e}")
        return []
def get_offline_leaderboard():

    raw = fb_get("/leaderboard") or {}

    rows = []

    if isinstance(raw, dict):
        for key, value in raw.items():
            if isinstance(value, dict):
                rows.append(value)

    return rows

# ---------------------------
# Get all-time leaderboard
# ---------------------------
def get_alltime_leaderboard():

    mode = st.session_state.get("mode_selection", "Offline")

    if mode == "Online":
        rows = get_online_leaderboard()
    else:
        rows = get_offline_leaderboard()

    if not rows:
        return pd.DataFrame()

    df = pd.DataFrame(rows)

    if "score" not in df.columns:
        return pd.DataFrame()

    df["score"] = pd.to_numeric(df["score"], errors="coerce").fillna(0)

    return df.sort_values(by="score", ascending=False)



# ----------------- Session & Presence helpers -----------------
def now_iso():
    return datetime.now(UTC).isoformat()

def parse_iso(s):
    try:
        dt = datetime.fromisoformat(s)
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=UTC)
        return dt
    except Exception:
        return None


def ensure_session_ids():
    if "uid" not in st.session_state:
        st.session_state['uid'] = str(uuid.uuid4())
    if "session_id" not in st.session_state:
        st.session_state['session_id'] = str(uuid.uuid4())
ensure_session_ids()

def claim_session_unified(game_id, username):
    sessions = unified_get("sessions") or {}
    game_sessions = sessions.get(game_id, {})
    rec = game_sessions.get(username)
    now = now_iso()
    if rec is None:
        game_sessions[username] = {"session_id": st.session_state['session_id'], "last_heartbeat": now}
        sessions[game_id] = game_sessions
        unified_set("sessions", sessions)
        return True, ""
    last = parse_iso(rec.get("last_heartbeat"))
    if rec.get("session_id") == st.session_state['session_id']:
        rec["last_heartbeat"] = now
        game_sessions[username] = rec
        sessions[game_id] = game_sessions
        unified_set("sessions", sessions)
        return True, ""
    if last and (datetime.now(UTC) - last) < timedelta(seconds=HEARTBEAT_THRESHOLD_SECONDS):
        return False, "You are active in another tab/device. Return to that tab or wait."
    # override stale
    game_sessions[username] = {"session_id": st.session_state['session_id'], "last_heartbeat": now}
    sessions[game_id] = game_sessions
    unified_set("sessions", sessions)
    return True, ""

def heartbeat_unified(game_id, username):
    sessions = unified_get("sessions") or {}
    game_sessions = sessions.get(game_id, {})
    rec = game_sessions.get(username, {})
    rec["session_id"] = st.session_state['session_id']
    rec["last_heartbeat"] = now_iso()
    game_sessions[username] = rec
    sessions[game_id] = game_sessions
    unified_set("sessions", sessions)

# ----------------- Friends & Inbox helpers -----------------
def get_friends_map():
    return unified_get("friends") or {}

def save_friends_map(m):
    unified_set("friends", m)

def get_inbox():
    return unified_get("inbox") or {}

def save_inbox(i):
    unified_set("inbox", i)

def send_friend_request(from_user, to_user):
    inbox = get_inbox()
    user_inbox = inbox.get(to_user, [])
    user_inbox.append({"type":"friend_request","from":from_user,"ts":now_iso()})
    inbox[to_user] = user_inbox
    save_inbox(inbox)

def accept_friend_request(current_user, from_user):
    friends = get_friends_map()
    friends.setdefault(current_user, [])
    friends.setdefault(from_user, [])
    if from_user not in friends[current_user]:
        friends[current_user].append(from_user)
    if current_user not in friends[from_user]:
        friends[from_user].append(current_user)
    save_friends_map(friends)
    # remove request
    inbox = get_inbox()
    entries = inbox.get(current_user, [])
    entries = [e for e in entries if not (e.get('type')=='friend_request' and e.get('from')==from_user)]
    inbox[current_user] = entries
    save_inbox(inbox)

def send_game_invite(from_user, to_user, game_id):
    inbox = get_inbox()
    user_inbox = inbox.get(to_user, [])
    user_inbox.append({"type":"invite","from":from_user,"game_id":game_id,"ts":now_iso()})
    inbox[to_user] = user_inbox
    save_inbox(inbox)

# ----------------- Game helpers -----------------
def compute_winners(game_id):
    mode = st.session_state.get("mode_selection", "Offline")

    if mode == "Online":
        ok, _ = init_firebase_if_needed()
        if ok:
            raw = fb_get("/leaderboard_online") or {}
            rows = list(raw.values()) if isinstance(raw, dict) else raw
        else:
            rows = []
    else:
        rows = local_get("leaderboard")

    if not rows:
        return []

    df = pd.DataFrame(rows)
    df = df[df["game_id"] == game_id]

    if df.empty:
        return []

    df = df.sort_values(by=["score", "timestamp"], ascending=[False, True])
    return df.head(3).to_dict(orient="records")


#------Total players--------------------
def get_total_online_players():
    players = unified_get("players") or {}
    total = 0
    for gid in players:
        total += len(players[gid])
    return total

# ----------------- Create Game Page -----------------

def create_game_page():
    st.header("Create Game")

    # ---------------- SESSION STORAGE FIX ----------------
    if "custom_topics" not in st.session_state:
        st.session_state["custom_topics"] = {}

    # ---------------- UPLOAD SECTION ----------------
    st.markdown("### ๐Ÿ“ฅ Upload Question Bank (Text / PDF / Word / Image)")

    uploaded_file = st.file_uploader(
        "Upload file",
        type=["txt", "pdf", "docx", "png", "jpg", "jpeg"]
    )

    raw_text = st.text_area("OR Paste Questions")
    topic_name = st.text_input("Topic Name")

    if st.button("๐Ÿš€ Add Question Bank"):

        if not topic_name:
            st.warning("Enter topic name")
            return

        text_data = ""

        # 1๏ธโƒฃ FILE
        if uploaded_file:
            text_data = extract_text_from_file(uploaded_file)

        # 2๏ธโƒฃ TEXT
        elif raw_text:
            text_data = raw_text

        if text_data:
            parsed = parse_questions(text_data, topic_name)

            if parsed:
                # โœ… SAVE TO SESSION + GLOBAL
                st.session_state["custom_topics"][topic_name] = parsed
                questions_db[topic_name] = parsed

                st.success(f"โœ… {len(parsed)} questions added to '{topic_name}'")

                # ๐Ÿ”ฅ FORCE UI REFRESH
                st.rerun()

            else:
                st.error("โŒ Parsing failed")

    # ---------------- HOST ----------------
    host = st.text_input(
        "Host name",
        value=st.session_state.get("username", "")
    )

    mode = st.session_state.get("mode_selection", "Offline")

    # ๐Ÿ”ฅ MERGE DEFAULT + CUSTOM TOPICS
    # Ensure latest topics always loaded
    all_topics = sorted(list(questions_db.keys()))

    topics = st.multiselect(
        "Select Topics",
        options=all_topics,
        default=[],
        key="topic_selector"
    )

    # ---------------- AI ----------------
    ai_topic = None
    if mode == "Online":
        ai_topic = st.text_input("AI Topic (optional)")

    num_questions = st.number_input("Number of Questions", 1, 20, 5)

    auto_close = st.checkbox("Auto-close game?", True)

    # ---------------- CREATE GAME ----------------
    if st.button("Create Game"):

        if not host:
            st.warning("Enter host name")
            return

        if mode == "Offline":
            if not topics:
                st.warning("Select at least one topic")
                return

            gid = create_game(
                host=host,
                topics=topics,
                num_questions=num_questions,
                auto_close=auto_close,
                ai_topic=None
            )

        else:
            if not topics and not ai_topic:
                st.warning("Select topic or AI topic")
                return

            gid = create_game(
                host=host,
                topics=topics,
                num_questions=num_questions,
                auto_close=auto_close,
                ai_topic=ai_topic
            )

        st.success(f"๐ŸŽ‰ Game Created! ID: {gid}")
        st.session_state["username"] = host

# DO NOT redirect or rerun

def save_score_to_csv(
    name,
    score,
    game_id,
    topics,
    avatar="๐ŸŽฎ",
    questions=None,
    answers=None,
    correct_flags=None
):
    file_exists = os.path.isfile(LEADERBOARD_FILE)

    with open(
        LEADERBOARD_FILE,
        "a",
        newline="",
        encoding="utf-8"
    ) as f:
        writer = csv.writer(f)

        # Write header only once
        if not file_exists:
            writer.writerow([
                "name",
                "score",
                "game_id",
                "topics",
                "timestamp",
                "avatar",
                "questions",
                "answers",
                "correct_flags"
            ])

        writer.writerow([
            name,
            score,
            game_id,
            ", ".join(topics) if isinstance(topics, list) else topics,
            datetime.now().isoformat(),
            avatar,
            questions,
            answers,
            correct_flags
        ])



# 1๏ธโƒฃ Define join_game first
def join_game(game_id, username, avatar):
    games = unified_get("games") or {}
    if game_id not in games:
        return False, "Invalid Game ID"
    if games[game_id].get("closed"):
        return False, "Game is closed"
    
    players = unified_get("players") or {}
    if game_id not in players:
        players[game_id] = {}

    game_players = players[game_id]

    if username in game_players:
        game_players[username]['avatar'] = avatar
        game_players[username]['last_joined'] = now_iso()
    else:
        game_players[username] = {"avatar": avatar, "joined_at": now_iso(), "submitted": False}

    players[game_id] = game_players
    unified_set("players", players)

    ok, msg = claim_session_unified(game_id, username)
    if ok:
        players[game_id][username]['last_heartbeat'] = now_iso()
        unified_set("players", players)

    return ok, msg

def compute_score(questions, answers, times=None):
    """
    Compute the total score and correctness flags for each question.

    Args:
        questions (list): List of question dicts. Each dict must have 'answer' key.
        answers (list): List of user's answers corresponding to questions.
        times (list, optional): Time taken for each question (in seconds).

    Returns:
        score (int): Total score.
        flags (list): List of correctness flags: True if correct, False if incorrect.
    """
    score_per_question = 15
    score = 0
    flags = []

    for idx, q in enumerate(questions):
        correct_ans = q.get("answer")
        user_ans = answers[idx] if idx < len(answers) else None

        if user_ans == correct_ans:
            score += score_per_question
            flags.append(True)
        else:
            flags.append(False)

        # Optional: implement time-based penalties if needed
        # if times:
        #     if times[idx] > 15:  # example: 15 sec limit
        #         score -= 5  # penalty

    return score, flags



# ----------------- UI -----------------
st.sidebar.title("Mode & Profile")
# ---- MODE SELECTION FIX ----
if "mode_selection" not in st.session_state:
    st.session_state["mode_selection"] = "Online"

mode_choice = st.sidebar.selectbox(
    "Mode",
    ["Offline (local JSON)", "Online (Firebase)"],
    index=1 if st.session_state["mode_selection"] == "Online" else 0
)

st.session_state["mode_selection"] = (
    "Online" if mode_choice.startswith("Online") else "Offline"
)

# If user chose Online, attempt to init and show feedback
if st.session_state['mode_selection'] == "Online":
    ok, msg = init_firebase_if_needed()
    if not ok:
        st.sidebar.error(f"Online init failed: {msg}. Working Offline.")
        st.session_state['mode_selection'] = "Offline"
    else:
        st.sidebar.success("Online (Firebase) ready.")

# Sidebar inputs
st.sidebar.markdown("### You")
username = st.sidebar.text_input("Your name", value=st.session_state.get("username",""), key="sidebar_username")
avatar = st.sidebar.selectbox("Avatar", ["๐ŸŽฎ","๐Ÿฑ","๐Ÿถ","๐Ÿฆ„","๐Ÿ‘ฝ","๐ŸŽฉ"], index=0, key="sidebar_avatar")

# ---------------- PAGE CONTROL ----------------
if "page" not in st.session_state:
    st.session_state["page"] = "Home"

pages = ["Home","Create Game","Join Game","Play","Friends","Inbox","Leaderboard"]

page = st.sidebar.selectbox(
    "Page",
    pages,
    index=pages.index(st.session_state["page"])
)

# Sync
st.session_state["page"] = page

# Save to session_state
st.session_state['username'] = username or st.session_state.get("username","")
st.session_state['avatar'] = avatar or st.session_state.get("avatar","๐ŸŽฎ")


if st.sidebar.button("Refresh"):
    st.rerun()

st.title("AI Quiz Game โ€” Online/Offline (Friends & Chat)")

def render_copy_button(val, key):
    copy_html = f'''
    <div style="display:flex;gap:8px;align-items:center;">
      <input id="gid_{key}" value="{val}" readonly style="padding:6px;border:1px solid #ddd;border-radius:6px;">
      <button onclick="navigator.clipboard.writeText(document.getElementById('gid_{key}').value)" style="padding:6px 10px;border-radius:6px;cursor:pointer;">Copy</button>
    </div>
    '''
    html(copy_html)

def get_top3_and_player_count(game_id):
    rows = unified_get("leaderboard") or []
    if not rows:
        return [], 0

    df = pd.DataFrame(rows)
    df = df[df["game_id"] == game_id]

    if df.empty:
        return [], 0

    df = df.sort_values(
        by=["score", "timestamp"],
        ascending=[False, True]  # stable winner
    )

    top3 = df.head(3).to_dict(orient="records")
    total_players = df["name"].nunique()

    return top3, total_players


# Home page

HEARTBEAT_THRESHOLD_SECONDS = 60  # adjust if needed

def home_page():
    _ = st.session_state.get("force_refresh", None)
    st.markdown("""
    <style>
    .game-card {
        background: linear-gradient(135deg, #1f2937, #111827);
        padding: 20px;
        border-radius: 15px;
        margin-bottom: 15px;
        color: white;
        box-shadow: 0 8px 20px rgba(0,0,0,0.4);
        transition: 0.3s;
    }
    .game-card:hover {
        transform: scale(1.02);
        box-shadow: 0 12px 25px rgba(0,0,0,0.6);
    }
    .metric-box {
        background: rgba(255,255,255,0.05);
        padding: 10px;
        border-radius: 10px;
        text-align: center;
    }
    </style>
    """, unsafe_allow_html=True)

    st.title("๐Ÿ  AI Quiz CRM Dashboard")

    mode = st.session_state.get("mode_selection", "Offline")

    # ================= LOAD DATA =================
    if mode == "Online":
        rows = get_online_leaderboard()
    else:
        rows = get_offline_leaderboard()

    if not rows:
        st.info("No game data available yet.")
        return

    df = pd.DataFrame(rows)
    df["score"] = pd.to_numeric(df["score"], errors="coerce").fillna(0)

    # ================= GROUP BY GAME =================
    game_groups = df.groupby("game_id")

    st.subheader("๐ŸŽฎ Game Wise Analytics")

    for game_id, game_df in game_groups:

        total_players = game_df["name"].nunique()
        total_attempts = len(game_df)
        avg_score = int(game_df["score"].mean())
        top_score = int(game_df["score"].max())
        top_player = game_df.sort_values(by="score", ascending=False).iloc[0]["name"]

        with st.container():
            st.markdown(f"""
            <div class="game-card">
                <h3>๐ŸŽฏ Game ID: {game_id}</h3>
                <div style="display:flex; gap:20px;">
                    <div class="metric-box">
                        ๐Ÿ‘ฅ Players<br><b>{total_players}</b>
                    </div>
                    <div class="metric-box">
                        ๐Ÿ“ Attempts<br><b>{total_attempts}</b>
                    </div>
                    <div class="metric-box">
                        ๐Ÿ“Š Avg Score<br><b>{avg_score}</b>
                    </div>
                    <div class="metric-box">
                        ๐Ÿ† Top Player<br><b>{top_player}</b>
                    </div>
                </div>
            </div>
            """, unsafe_allow_html=True)

        # ================= EXPANDABLE PLAYER DETAILS =================
        with st.expander(f"๐Ÿ” View Results for Game {game_id}"):

            sorted_df = game_df.sort_values(by="score", ascending=False)

            st.dataframe(
                sorted_df[["name", "score", "timestamp"]],
                use_container_width=True
            )

            st.success(f"๐Ÿ† Top Player: {top_player} ({top_score} points)")
        


def create_game(host=None, topics=[], num_questions=5, auto_close=True, ai_topic=None):
    import time, uuid, urllib.parse
    import streamlit as st

    games = unified_get("games") or {}

    # ๐Ÿ”ฅ CREATE IDS
    gid = f"GAME{int(time.time())}"
    host_id = f"HOST{str(uuid.uuid4())[:8].upper()}"

    host = host or st.session_state.get("username", "Host")

    questions = []

    # 1๏ธโƒฃ AI questions
    if ai_topic:
        ai_questions = generate_ai_questions(ai_topic, num_questions=num_questions)
        if ai_questions:
            for q in ai_questions:
                questions.append({
                    "question": q.get("question", ""),
                    "options": q.get("options", []),
                    "answer": q.get("answer", "")
                })

    # 2๏ธโƒฃ Static fallback
    if not questions:
        for topic in topics:
            qs = questions_db.get(topic, [])
            for q in qs[:num_questions]:
                # โœ… NEW FORMAT (dict)
                if isinstance(q, dict):
                    questions.append({
                        "question": q.get("question", ""),
                        "options": q.get("options", []),
                        "answer": q.get("answer", "")
                    })
                    
                    # โœ… OLD FORMAT (tuple)
                else:
                    questions.append({
                        "question": q[0],
                        "options": q[1],
                        "answer": q[2]
                    })

    # ๐Ÿ”น STORE GAME
    games[gid] = {
        "game_id": gid,
        "host": host,
        "host_id": host_id,   # โœ… IMPORTANT
        "topics": topics,
        "questions": questions,
        "created_at": now_iso(),
        "closed": False,
        "started": False,
        "auto_close": auto_close,
        "mode": st.session_state.get("mode_selection", "Offline")
    }

    unified_set("games", games)

    # โœ… STORE IN SESSION (IMPORTANT)
    st.session_state["created_game_id"] = gid
    st.session_state["created_host_id"] = host_id

    # โŒ REMOVE AUTO REDIRECT (IMPORTANT CHANGE)
    st.session_state['game_id'] = gid
    st.session_state['active_game_id'] = gid

    # ---------- SHOW OUTPUT ----------
    st.success("๐ŸŽ‰ Game Created Successfully!")

    st.markdown("### ๐ŸŽฎ Game Details")

    st.info(f"๐Ÿ†” Game ID (Players use this): {gid}")
    st.warning(f"๐Ÿ”‘ Host ID (Only you use this): {host_id}")

    if topics:
        st.write(f"๐Ÿ“š Topics: {', '.join(topics)}")

    # ---------- WHATSAPP SHARE ----------
    share_text = f"Join my Quiz Game!\nGame ID: {gid}"
    encoded = urllib.parse.quote(share_text)

    whatsapp_url = f"https://wa.me/?text={encoded}"

    st.markdown(f"""
    <a href="{whatsapp_url}" target="_blank">
        <button style="background-color:#25D366;color:white;padding:10px 20px;border:none;border-radius:8px;font-weight:bold;">
            ๐Ÿ“ค Share on WhatsApp
        </button>
    </a>
    """, unsafe_allow_html=True)

    return gid

# ๐Ÿ”ฅ ADD HERE (above play_page)

def enable_exam_mode():
    st.markdown("""
    <script>
    let violationCount = 0;

    function enterFullscreen() {
        let el = document.documentElement;
        if (el.requestFullscreen) el.requestFullscreen();
    }

    function exitFullscreen() {
        if (document.exitFullscreen) document.exitFullscreen();
    }

    document.addEventListener('copy', e => e.preventDefault());
    document.addEventListener('cut', e => e.preventDefault());
    document.addEventListener('paste', e => e.preventDefault());
    document.addEventListener('contextmenu', e => e.preventDefault());

    document.addEventListener("visibilitychange", function() {
        if (document.hidden) {
            alert("โš ๏ธ Tab switch detected!");
        }
    });

    document.addEventListener("fullscreenchange", function() {
        if (!document.fullscreenElement && !window.examSubmitted) {
            enterFullscreen();
        }
    });

    document.addEventListener("keydown", function(e) {
        if (e.ctrlKey && ["c","v","x","u"].includes(e.key.toLowerCase())) {
            e.preventDefault();
        }
        if (e.key === "F12") e.preventDefault();
    });

    

    window.examSubmitted = false;

    window.unlockExam = function() {
        window.examSubmitted = true;
        setTimeout(() => {
            exitFullscreen();
            alert("โœ… Exam finished. Fullscreen unlocked.");
        }, 10000);
    };
    </script>
    """, unsafe_allow_html=True)


# ๐Ÿ‘‡ YOUR play_page() comes AFTER this
def play_page():
    enable_exam_mode()
    import time, json
    import streamlit as st

    # ---------------- BASIC CHECKS ----------------
    gid = st.session_state.get("active_game_id")
    uname = st.session_state.get("username")

    if not gid or not uname:
        st.error("No active game or username found. Please join or create a game first.")
        return

    # ---------------- LOAD GAME ----------------
    games = unified_get("games") or {}
    game = games.get(gid)

    if not game:
        st.error("Game not found.")
        return
    # ๐Ÿš€ START CHECK
    if not game.get("started"):
        host = game.get("host", "Host")
        st.warning(f"Game not started yet. Waiting for host **{host}** to start the game.")
        return

    if game.get("closed"):
        st.warning("This game is closed.")
        return

    questions = game.get("questions", [])

    if not questions:
        st.info("No questions available.")
        return

    # ---------------- INIT SESSION STATE ----------------
    n = len(questions)

    if "answers" not in st.session_state or not isinstance(st.session_state.answers, list):
        st.session_state.answers = [""] * n

    if "answer_times" not in st.session_state or not isinstance(st.session_state.answer_times, list):
        st.session_state.answer_times = [0] * n

    if "current_index" not in st.session_state or not isinstance(st.session_state.current_index, int):
        st.session_state.current_index = 0

    if "question_started_at" not in st.session_state:
        st.session_state.question_started_at = time.time()

    idx = st.session_state.current_index

    # ---------------- FINISHED ----------------
    if idx >= n:
        st.success("All questions completed.")
        return

    # ---------------- QUESTION UI ----------------
    q = questions[idx]

    st.subheader(f"Question {idx + 1} / {n}")
    st.write(q["question"])

    # ---------------- TIMER ----------------
    now = time.time()
    start_time = st.session_state.get("question_started_at")

    if start_time is None:
        start_time = now
        st.session_state.question_started_at = now

    elapsed = int(now - start_time)
    time_limit = 15
    remaining = max(0, time_limit - elapsed)

    st.markdown(f"**โฑ Time left:** {remaining} seconds")

    # ---------------- ANSWER ----------------
    choice = st.radio(
        "Choose an answer:",
        ["-- Select an option --"] + q["options"],
        index=0,
        key=f"choice_{gid}_{idx}"
    )
    
    if choice == "-- Select an option --":
        choice = None

    col1, col2 = st.columns(2)

    if idx < n - 1:
        with col1:
            next_disabled = choice is None
            
            if st.button(
                "Next",
                key=f"next_{gid}_{idx}",
                disabled=next_disabled
            ):
                st.session_state.answers[idx] = choice
                st.session_state.answer_times[idx] = elapsed
                st.session_state.current_index += 1
                st.session_state.question_started_at = time.time()
                st.rerun()
    # ---------------- NEXT ----------------

    # ---------------- SUBMIT ----------------
    if idx == n - 1:
        with col2:
            submit_disabled = choice is None
            
            if st.button(
                "Submit Quiz",
                key=f"submit_{gid}_{idx}",
                disabled=submit_disabled
            ):
                st.session_state.answers[idx] = choice
                st.session_state.answer_times[idx] = elapsed

                # Save last answer
                st.session_state.answers[idx] = choice
                st.session_state.answer_times[idx] = elapsed

                answers = st.session_state.answers
                times = st.session_state.answer_times

                # Compute score
                score, flags = compute_score(questions, answers, times)
                
                max_score = n * 15
                percentage = int((score / max_score) * 100) if max_score > 0 else 0

                st.subheader("๐Ÿ“Š Your Result")
                st.write(f"Score: {score}")
                st.write(f"Percentage: {percentage}%")

                st.info("โณ Please wait 10 seconds... Unlocking screen")
                
                # ๐Ÿ”“ UNLOCK FULLSCREEN AFTER 10s
                st.markdown("""
                <script>
                if (window.unlockExam){
                    window.unlockExam();
                }</script>
                """, unsafe_allow_html=True)

                # ---------------- UPDATE PLAYERS COLLECTION ----------------
                players = unified_get("players") or {}
                players.setdefault(gid, {})
                players[gid][uname] = {
                    "submitted": True,
                    "score": score,
                    "percentage": percentage,
                    "answers": answers,
                    "avatar": st.session_state.get("avatar", "๐ŸŽฎ"),
                    "timestamp": now_iso()
                }
                unified_set("players", players)

                # ---------------- UPDATE GAMES STRUCTURE ----------------
                games = unified_get("games") or {}
                game_data = games.get(gid, {})

                game_data.setdefault("players", [])
                if uname not in game_data["players"]:
                    game_data["players"].append(uname)

                game_data.setdefault("submissions", {})
                game_data["submissions"][uname] = score

                games[gid] = game_data
                unified_set("games", games)

                # ---------------- SAVE LEADERBOARD ----------------
                row = {
                    "name": uname,
                    "score": score,
                    "game_id": gid,
                    "topics": ",".join(game.get("topics", [])),
                    "timestamp": now_iso(),
                    "avatar": st.session_state.get("avatar", "๐ŸŽฎ"),
                    "questions": n,
                    "answers": json.dumps(answers),
                    "correct_flags": json.dumps(flags),
                }

                unified_push_leaderboard(row)

                # ---------------- WAIT FOR OTHER PLAYERS ----------------
                scores = fb_get(f"/games/{gid}/scores") or {}
                rows = fb_get("/leaderboard_online") or {}
                submitted = []
                if isinstance(rows, dict):
                    for r in rows.values():
                        if r.get("game_id") == gid:
                            submitted.append(r)
                players = unified_get("players") or {}
                game_players = players.get(gid, [])

                submitted_count = len(submitted)
                total_players = len(game_players)
                remaining_players = total_players - submitted_count
                
                st.markdown("### ๐Ÿ‘ฅ Player Status")
                
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    st.info(f"๐Ÿ‘ค Total Players: {total_players}")
                    
                with col2:
                    st.success(f"โœ… Submitted: {submitted_count}")
                
                with col3:
                    st.warning(f"โณ Remaining: {remaining_players}")
                    
                if submitted_count < total_players:
                    st.warning(f"Waiting for other players to submit ({submitted_count}/{total_players})")
                
                else:
                    st.success("๐ŸŽ‰ All players submitted!")
                    show_game_leaderboard(gid)
                st.session_state["force_refresh"] = str(time.time())

                

def join_game_page():
    import streamlit as st
    import time

    # ---------- CSS ----------
    st.markdown("""
    <style>
    [data-testid="stAppViewContainer"]{
        background:linear-gradient(135deg,#1c92d2,#f2fcfe);
    }
    .player-card{
        background:white;
        padding:12px;
        border-radius:10px;
        margin-bottom:6px;
        box-shadow:0px 2px 8px rgba(0,0,0,0.2);
    }
    .chat-box{
        background:white;
        padding:12px;
        border-radius:10px;
        height:250px;
        overflow-y:auto;
        box-shadow:0px 2px 10px rgba(0,0,0,0.2);
    }
    .stButton>button{
        background:#2e7d32;
        color:white;
        font-weight:bold;
        border-radius:8px;
    }
    </style>
    """, unsafe_allow_html=True)

    st.header("๐ŸŽฎ Join Game")

    # ---------- INPUTS ----------
    game_id = st.text_input(
        "Enter Game ID",
        value=st.session_state.get("created_game_id", "")
    )

    username = st.text_input("Your Name")

    avatar = st.selectbox(
        "Choose Avatar",
        ["๐ŸŽฎ","๐Ÿค–","๐Ÿงฉ","๐Ÿ›ก๏ธ","๐Ÿ‘‘","๐Ÿ”ฅ"]
    )

    host_id_input = st.text_input("Enter Host ID (Only for Host)")

    st.session_state["username"] = username

    # ---------- LOAD GAME ----------
    games = unified_get("games") or {}
    g = games.get(game_id, {})

    # ---------- SHOW GAME INFO ----------
    if g:
        st.markdown("### ๐ŸŽฏ Game Info")
        st.info(f"Host: {g.get('host','Unknown')}")
        st.write(f"Topics: {', '.join(g.get('topics', []))}")

    # ---------- SHOW JOINED PLAYERS ----------
    if game_id:
        players = unified_get("players") or {}
        game_players = players.get(game_id, {})

        st.markdown("### ๐Ÿ‘ฅ Joined Players")

        if game_players:
            st.success(f"{len(game_players)} Players Joined")

            for p in game_players.keys():
                st.markdown(f"""
                <div class="player-card">
                ๐Ÿง‘ {p}
                </div>
                """, unsafe_allow_html=True)
        else:
            st.info("No players joined yet")

    # ---------- CHAT ----------
    if game_id:
        st.markdown("### ๐Ÿ’ฌ Game Chat")

        chat_path = f"/messages/{game_id}"
        messages = fb_get(chat_path) or {}

        st.markdown('<div class="chat-box">', unsafe_allow_html=True)

        if isinstance(messages, dict):
            for m in messages.values():
                user = m.get("user", "Player")
                msg = m.get("msg", "")
                st.write(f"**{user}** : {msg}")

        st.markdown('</div>', unsafe_allow_html=True)

        msg = st.text_input("Type message")

        if st.button("Send Message"):
            if msg.strip():
                fb_push(chat_path,{
                    "user": username or "Player",
                    "msg": msg,
                    "time": time.time()
                })
                st.rerun()

    # ---------- JOIN GAME ----------
    if st.button("Join Game"):

        if not game_id or not username:
            st.warning("Enter both Game ID and Username")
            return

        ok, msg = join_game(game_id, username, avatar)

        if ok:
            st.success(f"Joined game {game_id}")

            st.session_state['game_id'] = game_id
            st.session_state['active_game_id'] = game_id
            st.session_state['username'] = username
            st.session_state['avatar'] = avatar

            st.rerun()
        else:
            st.error(msg)

    # ---------- HOST LOGIC ----------
    real_host_id = g.get("host_id")
    real_host_name = g.get("host")

    is_host = (
        host_id_input == real_host_id
        and username == real_host_name
    )

    # HOST START BUTTON
    if is_host and not g.get("started"):
        st.success("๐Ÿ‘‘ You are the host")

        if st.button("๐Ÿš€ Start Game"):
            
            st.markdown("""
            <script>
            function startExam(){
                let el = document.documentElement;
                if (el.requestFullscreen) el.requestFullscreen();
                }
            startExam();
            </script>
            """, unsafe_allow_html=True)

            g["started"] = True
            games[game_id] = g
            unified_set("games", games)

            st.success("Game Started!")
            st.rerun()

    # WAIT FOR HOST
    elif not g.get("started"):
        st.info(f"Waiting for host **{real_host_name}** to start the game...")

    # ---------- ๐Ÿ”ฅ AUTO REDIRECT ----------
    if g.get("started"):

        st.success("๐Ÿš€ Game Started! Redirecting...")

        # Load questions
        st.session_state['game_questions'] = g.get('questions', [])
        st.session_state['game_id'] = game_id
        st.session_state['active_game_id'] = game_id

        # Reset play state
        st.session_state['current_index'] = 0
        st.session_state['answers'] = [""] * len(st.session_state['game_questions'])
        st.session_state['answer_times'] = [None] * len(st.session_state['game_questions'])
        st.session_state['question_started_at'] = None

        st.session_state["page"] = "Play"

        time.sleep(1)
        st.rerun()

    # ---------- AUTO REFRESH ----------
    if game_id:
        time.sleep(2)
        st.rerun()
       

    
# Friends page
def friends_page():
    st.header("Friends")
    user = st.session_state.get('username')
    if not user:
        st.info("Enter your name in the sidebar to use Friends.")
        return
    friends_map = get_friends_map()
    your_friends = friends_map.get(user, [])
    st.subheader("Your friends")
    if your_friends:
        for f in your_friends:
            sessions = unified_get("sessions") or {}
            status = "offline"
            for gid, users in (sessions or {}).items():
                rec = users.get(f)
                if rec:
                    last = parse_iso(rec.get('last_heartbeat'))
                    if last and (datetime.now(UTC) - last) < timedelta(seconds=HEARTBEAT_THRESHOLD_SECONDS):
                        status = "online"
                        break
            st.write(f"โ€ข {f} โ€” **{status}**")
            if st.button(f"Invite {f} to a game", key=f"invitebtn_{f}"):
                gid = st.text_input(f"Enter game id to invite {f} (or leave blank to create)", key=f"inviteinput_{f}")
                if gid:
                    send_game_invite(st.session_state['username'], f, gid)
                    st.success(f"Invite sent to {f} for game {gid}")
                else:
                    topics = list(questions_db.keys())[:1]
                    new_id = create_game(st.session_state['username'], topics, num_questions=5)
                    send_game_invite(st.session_state['username'], f, new_id)
                    st.success(f"Invite sent to {f} for new game {new_id}")
    else:
        st.write("You have no friends yet.")

    st.markdown("---")
    st.subheader("Find / Add friends")
    all_users = set()
    players = unified_get("players") or {}
    for gid, users in (players or {}).items():
        for u in (users or {}).keys():
            all_users.add(u)
    all_users = all_users.union(set(get_friends_map().keys()))
    all_users.discard(user)
    candidate = st.text_input("Search user to add (exact name)", value="")
    if st.button("Send Friend Request"):
        if not candidate:
            st.error("Enter user name")
        else:
            send_friend_request(user, candidate)
            st.success("Friend request sent.")

# Inbox page
def inbox_page():
    st.header("Inbox")
    user = st.session_state.get('username')
    if not user:
        st.info("Enter your name in the sidebar to view Inbox.")
        return
    inbox = get_inbox()
    items = inbox.get(user, [])
    if not items:
        st.write("No messages.")
        return
    for idx, item in enumerate(items[:50]):
        t = item.get('type')
        if t == "friend_request":
            fr = item.get('from')
            st.write(f"Friend request from **{fr}** at {item.get('ts')}")
            if st.button(f"Accept {idx}"):
                accept_friend_request(user, fr)
                st.success(f"You are now friends with {fr}")
                st.rerun()
            if st.button(f"Reject {idx}"):
                entries = [it for it in items if not (it.get('type')=='friend_request' and it.get('from')==fr)]
                inbox[user] = entries
                save_inbox(inbox)
                st.success("Rejected")
                st.rerun()
        elif t == "invite":
            fr = item.get('from'); gid = item.get('game_id')
            st.write(f"Invite from **{fr}** to join game **{gid}** at {item.get('ts')}")
            if st.button(f"Join Invite {idx}"):
                ok, msg = join_game(gid, user, st.session_state.get('avatar','๐ŸŽฎ'))
                if ok:
                    st.success(f"Joined game {gid}")
                    items = [it for it in items if not (it.get('type')=='invite' and it.get('from')==fr and it.get('game_id')==gid)]
                    inbox[user] = items
                    save_inbox(inbox)
                    st.session_state['game_id'] = gid
                    st.session_state['username'] = user
                    st.rerun()
                else:
                    st.error(msg)


import streamlit as st
import pandas as pd
import plotly.express as px
from datetime import datetime
import os

LEADERBOARD_FILE = "leaderboard.csv"

def leaderboard_page():

    # ================= CSS =================
    st.markdown("""
    <style>
    [data-testid="stAppViewContainer"] {
        background: linear-gradient(135deg, #141e30, #243b55);
    }

    .card {
        background: rgba(255,255,255,0.08);
        padding: 20px;
        border-radius: 15px;
        box-shadow: 0 8px 20px rgba(0,0,0,0.3);
        backdrop-filter: blur(10px);
        text-align: center;
        transition: 0.3s;
        color: white;
    }

    .card:hover {
        transform: translateY(-5px);
    }

    h1, h2, h3, h4 {
        color: white !important;
    }
    </style>
    """, unsafe_allow_html=True)

    st.markdown("## ๐Ÿ† Leaderboard Dashboard")

    # ================= MODE =================
    mode = st.session_state.get("mode_selection", "Offline")

    if mode == "Online":
        st.subheader("๐ŸŒ Online Leaderboard")
        rows = get_online_leaderboard()
    else:
        st.subheader("๐Ÿ’พ Offline Leaderboard")
        rows = get_offline_leaderboard()

    if not rows:
        st.warning("No leaderboard data found.")
        return

    df = pd.DataFrame(rows)

    # ================= COLUMN FIX =================
    if "username" in df.columns:
        df.rename(columns={"username": "name"}, inplace=True)

    # ================= TIMESTAMP CHECK =================
    if "timestamp" not in df.columns:
        df["timestamp"] = pd.Timestamp.utcnow()

    df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce", utc=True)
    # Fill missing timestamps instead of removing rows
    df["timestamp"] = df["timestamp"].fillna(pd.Timestamp.utcnow())

    if df.empty:
        st.warning("No valid timestamp data available.")
        return

    df["score"] = pd.to_numeric(df["score"], errors="coerce").fillna(0)

    # ================= FILTER =================
    filter_type = st.selectbox(
        "๐Ÿ“… Select Filter",
        ["All Time", "This Week", "This Month"]
    )

    now = datetime.now()

    if filter_type == "This Week":
        start_week = datetime.now(UTC) - timedelta(days=7)
        df = df[df["timestamp"] >= start_week]

    elif filter_type == "This Month":
        start_month = datetime.now(UTC).replace(day=1)
        df = df[df["timestamp"] >= start_month]

    if df.empty:
        st.warning("No data for selected filter.")
        return

    df = df.sort_values(by="score", ascending=False)

    # ================= KPI CARDS =================
    col1, col2, col3 = st.columns(3)

    with col1:
        st.markdown(f"""
        <div class="card">
            <h3>Total Players</h3>
            <h2>{df['name'].nunique()}</h2>
        </div>
        """, unsafe_allow_html=True)

    with col2:
        st.markdown(f"""
        <div class="card">
            <h3>Highest Score</h3>
            <h2>{int(df['score'].max())}</h2>
        </div>
        """, unsafe_allow_html=True)

    with col3:
        st.markdown(f"""
        <div class="card">
            <h3>Average Score</h3>
            <h2>{round(df['score'].mean(), 2)}</h2>
        </div>
        """, unsafe_allow_html=True)

    st.markdown("---")

    # ================= TOP 10 TABLE =================
    st.markdown("### ๐Ÿ… Top 10 Players")

    st.dataframe(
        df[["name", "score", "timestamp"]].head(10),
        use_container_width=True
    )

    # ================= PIE CHART =================
    st.markdown("### ๐Ÿฅง Score Distribution (Top 5)")

    top5 = df.head(5)

    fig_pie = px.pie(
        top5,
        values="score",
        names="name",
        title="Top 5 Players Score Share"
    )

    st.plotly_chart(fig_pie, use_container_width=True)

    # ================= BAR CHART =================
    st.markdown("### ๐Ÿ“Š Score Comparison")

    fig_bar = px.bar(
        top5,
        x="name",
        y="score",
        text="score",
        title="Top 5 Score Comparison"
    )

    fig_bar.update_traces(textposition="outside")
    st.plotly_chart(fig_bar, use_container_width=True)

    # ================= PLAYER DETAILS =================
    st.markdown("### ๐Ÿ” Player Detailed Analysis")

    selected_player = st.selectbox(
        "Select Player",
        df["name"].unique()
    )

    player_df = df[df["name"] == selected_player]

    if not player_df.empty:
        total_score = int(player_df["score"].sum())
        avg_score = round(player_df["score"].mean(), 2)

        st.success(
            f"{selected_player} โ€” Total Score: {total_score} | Avg Score: {avg_score}"
        )

        fig_line = px.line(
            player_df.sort_values("timestamp"),
            x="timestamp",
            y="score",
            title=f"{selected_player} Score Trend",
            markers=True
        )

        st.plotly_chart(fig_line, use_container_width=True)

def save_leaderboard_score(game_id, username, score):

    mode = st.session_state.get("mode_selection", "Offline")

    entry = {
        "game_id": game_id,
        "username": username,
        "score": score,
        "timestamp": time.time()
    }

    # ๐Ÿ“ด OFFLINE
    if mode == "Offline":
        leaderboard = load_json("data/offline_leaderboard.json", [])
        leaderboard.append(entry)
        save_json("data/offline_leaderboard.json", leaderboard)

    # ๐ŸŒ ONLINE
    else:
        unified_push("leaderboard", entry)


# Route pages
if page == "Home":
    home_page()
elif page == "Create Game":
    create_game_page()
elif page == "Join Game":
    join_game_page()
elif page == "Play":
    play_page()
elif page == "Friends":
    friends_page()
elif page == "Inbox":
    inbox_page()
elif page == "Leaderboard":
    leaderboard_page()

# Resume quick action
if st.session_state.get('game_id') and st.session_state.get('username'):
    players = unified_get("players") or {}
    info = players.get(st.session_state['game_id'], {}).get(st.session_state['username'], {}) if players.get(st.session_state.get('game_id')) else {}
    if info and info.get('submitted'):
        st.info("You already submitted this game.")
    else:
        with st.expander("Resume Game"):
            if st.button("Go to Play"):
                st.rerun()

st.markdown("---")
st.write("Notes: Online mode requires firebase-admin and service account JSON named 'serviceAccountKey.json' placed next to app.py. Offline mode stores data in ./data/.")