File size: 115,098 Bytes
07ccf39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29b445b
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
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
#!/usr/bin/env python3
"""
Tag Collector Game
A gamified version of the Image Tagger application where users collect tags
to earn currency that can be used to lower thresholds and discover rarer tags.
"""

import streamlit as st
import os
import sys
import tempfile
import time
import math
import json
import random
from PIL import Image
from collections import Counter
import torch
import importlib
import traceback

# Import storage system
import tag_storage
import state_manager

# Import constants and utility modules
from game_constants import (
    TAG_CURRENCY_NAME, TAG_ANIMATIONS, TAG_POWER_BONUSES, ENKEPHALIN_CURRENCY_NAME, ENKEPHALIN_ICON, RARITY_LEVELS, ACHIEVEMENTS, 
    STARTING_THRESHOLD, MIN_THRESHOLD,
    THRESHOLD_UPGRADES
)
from tag_categories import (
    TAG_CATEGORIES, initialize_progression_system, get_unlocked_categories,
    get_max_detectable_tags, get_collection_power_level
)
from tag_mosaic import display_tag_mosaic, RevealMosaic
from series_mosaics import display_series_mosaics
from scan_handler import enhanced_scan_button_handler
from library_system import initialize_library_system, display_library_extraction
from dev_tools import display_dev_tools

# =============================================================================
# SET PAGE CONFIG AS THE FIRST STREAMLIT COMMAND
# =============================================================================
st.set_page_config(layout="wide", page_title="Camie Collector", page_icon="🎮")

# =============================================================================
# DATA LOADING FUNCTIONS
# =============================================================================

@st.cache_data
def load_tag_rarity_metadata():
    """
    Load the tag rarity metadata from the JSON file.
    Returns the tag_rarity dictionary or None if the file doesn't exist.
    
    Returns:
        dict: Tag rarity metadata or None if not found
    """
    try:
        parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        
        metadata_path = os.path.join(parent_dir, "model", "tag_rarity_metadata.json")
        if os.path.exists(metadata_path):
            with open(metadata_path, 'r') as f:
                metadata = json.load(f)
            print(f"Loaded tag rarity metadata for {len(metadata['tag_rarity'])} tags")
            return metadata["tag_rarity"]
        else:
            print(f"Warning: {metadata_path} not found.")
            print("No metadata file found.")
            return None
    except Exception as e:
        print(f"Error loading tag rarity metadata: {str(e)}")
        traceback.print_exc()
        return None

# =============================================================================
# MODEL LOADING UTILITIES
# =============================================================================

def is_windows():
    """Check if the system is Windows"""
    import platform
    return platform.system() == "Windows"

def load_model():
    """
    Load the image tagger model for the game
    
    Returns:
        tuple: (model, thresholds, metadata)
    """
    # Make sure parent directory is in path to find the model
    if '.' not in sys.path:
        sys.path.append('.')
    
    current_dir = os.path.dirname(os.path.abspath(__file__))
    parent_dir = os.path.dirname(current_dir)
    
    model_dir = os.path.join(parent_dir, "model")  
    
    # If no model directory found, show detailed error
    if not model_dir:
        st.error("Model directory not found. Searched in:")
        st.write(f"- {os.path.abspath(model_dir)}")
        st.info("Please make sure you've exported the model first.")
        st.stop()
    
    # Get appropriate model type for the platform
    model_type = "initial_only"
    
    try:             
        # Load the model
        with st.spinner(f"Loading model for Tag Collector Game..."):
            model, thresholds, metadata = load_exported_model(model_dir, model_type)
            return model, thresholds, metadata
            
    except Exception as e:
        st.error(f"Error loading model: {str(e)}")
        st.code(traceback.format_exc())
        st.stop()

def load_exported_model(model_dir, model_type):
    """
    Load the exported model from the given directory.
    
    Args:
        model_dir: Path to the model directory
        model_type: Type of model to load ('initial_only' or 'full')
        
    Returns:
        tuple: (model, thresholds, metadata)
    """
    import torch
    import json
    import sys
    import importlib.util
    
    # Add model directory to path
    if model_dir not in sys.path:
        sys.path.append(model_dir)
    
    # Load metadata
    with open(os.path.join(model_dir, "metadata.json"), "r") as f:
        metadata = json.load(f)
    
    # Load thresholds
    with open(os.path.join(model_dir, "thresholds.json"), "r") as f:
        thresholds = json.load(f)
    
    # Import model_code.py
    model_code_path = os.path.join(model_dir, "model_code.py")
    if os.path.exists(model_code_path):
        # Import the module
        spec = importlib.util.spec_from_file_location("model_code", model_code_path)
        model_code = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(model_code)
        
        # Create dummy dataset class to use with model
        class ModelDataset:
            def __init__(self, metadata):
                self.total_tags = metadata['total_tags']
                self.idx_to_tag = {int(k): v for k, v in metadata['idx_to_tag'].items()}
                self.tag_to_category = metadata.get('tag_to_category', {})
            
            def get_tag_info(self, idx):
                tag = self.idx_to_tag.get(idx, f"unknown_{idx}")
                category = self.tag_to_category.get(tag, "general")
                return tag, category
        
        # Create dataset
        dataset = ModelDataset(metadata)
        
        # Determine model type and file to load
        if model_type == "initial_only":
            # Check for model_initial_only.pt
            if os.path.exists(os.path.join(model_dir, "model_initial_only.pt")):
                model_path = os.path.join(model_dir, "model_initial_only.pt")
            else:
                model_path = os.path.join(model_dir, "model_initial.pt")
                
            # Load model_info for initial_only if available
            if os.path.exists(os.path.join(model_dir, "model_info_initial_only.json")):
                with open(os.path.join(model_dir, "model_info_initial_only.json"), "r") as f:
                    model_info = json.load(f)
            else:
                model_info = {"tag_context_size": 256, "num_heads": 16}
                
            # Create initial_only model
            if hasattr(model_code, 'InitialOnlyImageTagger'):
                model = model_code.InitialOnlyImageTagger(
                    total_tags=metadata['total_tags'],
                    dataset=dataset,
                    pretrained=False
                )
            else:
                # Fallback to regular tagger
                model = model_code.ImageTagger(
                    total_tags=metadata['total_tags'],
                    dataset=dataset,
                    pretrained=False,
                    tag_context_size=model_info.get('tag_context_size', 256),
                    num_heads=model_info.get('num_heads', 16)
                )
        else:
            # Load full model - check for model_refined.pt or model.pt
            if os.path.exists(os.path.join(model_dir, "model_refined.pt")):
                model_path = os.path.join(model_dir, "model_refined.pt")
            else:
                model_path = os.path.join(model_dir, "model.pt")
                
            # Load model_info
            if os.path.exists(os.path.join(model_dir, "model_info.json")):
                with open(os.path.join(model_dir, "model_info.json"), "r") as f:
                    model_info = json.load(f)
            else:
                model_info = {"tag_context_size": 256, "num_heads": 16}
            
            # Create full model
            model = model_code.ImageTagger(
                total_tags=metadata['total_tags'],
                dataset=dataset,
                pretrained=False,
                tag_context_size=model_info.get('tag_context_size', 256),
                num_heads=model_info.get('num_heads', 16)
            )
        
        # Load state dict
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        state_dict = torch.load(model_path, map_location=device)
        model.load_state_dict(state_dict, strict=False)
        
        # Set to evaluation mode and move to device
        model.to(device)
        model.eval()
        
        # Attach dataset to model
        model.dataset = dataset
        
        return model, thresholds, metadata
    else:
        st.error(f"model_code.py not found at {model_code_path}")
        st.stop()

# =============================================================================
# GAME STATE MANAGEMENT
# =============================================================================

def initialize_game_state():
    """Initialize the game state in session state if not already present."""
    if 'game_initialized' not in st.session_state:
        st.session_state.game_initialized = True
        
        # Initialize state version counter
        st.session_state.state_version = 0
        
        # Try to load from storage first
        loaded_tags, tag_history, _ = tag_storage.load_tag_collection()
        
        if loaded_tags:
            # If we have saved data, use it
            st.session_state.collected_tags = loaded_tags
            st.session_state.tag_history = tag_history
        else:
            # Otherwise initialize with defaults
            st.session_state.collected_tags = {}  # {tag_name: {"count": int, "rarity": str}}
            st.session_state.tag_history = []  # List of recent tag acquisitions
            
        # Initialize other state variables with defaults
        initialize_default_state()

    if 'tag_rarity_metadata' not in st.session_state:
        st.session_state.tag_rarity_metadata = load_tag_rarity_metadata()

def initialize_default_state():
    """Initialize default state variables"""
    # Core game mechanics
    st.session_state.threshold = STARTING_THRESHOLD
    st.session_state.tag_currency = 0
    st.session_state.enkephalin = 0
    st.session_state.purchased_upgrades = []
    st.session_state.achievements = set()
    st.session_state.current_scan = None
    
    # Game statistics
    st.session_state.game_stats = {
        "images_processed": 0,
        "total_tags_found": 0,
        "total_currency_earned": 0,
        "currency_spent": 0,
        "enkephalin_generated": 0,
        "enkephalin_spent": 0,
        "tags_sacrificed": 0,
        "essences_generated": 0
    }
    
    # Tag power features
    st.session_state.tag_power_bonus = 0
    st.session_state.coin_multiplier = 1.0
    st.session_state.unlocked_combinations = set()
    st.session_state.combination_bonuses = {"threshold_reduction": 0, "coin_bonus": 0}
    
    # Sacrificed tags tracking
    st.session_state.sacrificed_tags = {}

def save_game():
    """Save the game state to files using the enhanced tag storage system."""
    try:
        # Use the enhanced tag storage system to save all game data
        import tag_storage
        success = tag_storage.save_game(st.session_state)
        return success
    except Exception as e:
        st.error(f"Failed to save game: {str(e)}")
        return False

def load_game():
    """
    Load the game state from files using the enhanced tag storage system.
    
    Returns:
        bool: True if load was successful, False otherwise
    """
    try:
        # Use the enhanced tag storage system to load all game data
        import tag_storage
        success = tag_storage.load_game(st.session_state)
        return success
    except Exception as e:
        st.error(f"Failed to load game: {str(e)}")
        return False

# =============================================================================
# USER INTERFACE FUNCTIONS
# =============================================================================

def get_discovered_rarities():
    """
    Helper function to get a set of all rarities the player has discovered
    Returns:
        set: Set of discovered rarity names
    """
    # Start with Canard as always discovered
    discovered_rarities = set(["Canard"])
    
    # Add rarities from collected tags
    if hasattr(st.session_state, 'collected_tags') and st.session_state.collected_tags:
        for tag_info in st.session_state.collected_tags.values():
            if "rarity" in tag_info and tag_info["rarity"]:
                discovered_rarities.add(tag_info["rarity"])
    
    return discovered_rarities

def apply_tag_animations():
    """Apply CSS animations for special tag rarities from the game constants"""
    # Create CSS styles for animations
    css = ""
    
    # Add animations from TAG_ANIMATIONS
    for rarity, animation_info in TAG_ANIMATIONS.items():
        css += animation_info["animation"]
    
    # Apply the CSS
    st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)

def create_sidebar():
    """Create a simplified sidebar without game stats"""
    with st.sidebar:
        # Save/Load controls
        display_save_load_controls()
        
        # Rarity legend
        display_rarity_legend()
        
        # # Developer mode toggle
        # display_developer_mode_toggle()
        
        # Support info
        display_support_info()

def display_save_load_controls():
    """Display save/load game controls"""
    st.subheader("Save/Load Game")
    save_col, load_col = st.columns(2)
    with save_col:
        if st.button("Save Game"):
            if save_game():
                st.success("Game saved!")
                # Force refresh
                st.rerun()
    with load_col:
        if st.button("Load Game"):
            if load_game():
                st.success("Game loaded!")
                # Force refresh
                st.rerun()
            else:
                st.info("No saved game found.")

def display_rarity_legend():
    """Display a legend explaining the rarity levels with TagCoins and Enkephalin rewards, with undiscovered rarities blacked out and special effects for rare rarities"""
    st.sidebar.subheader("Tag Rarity Legend")
    
    # Add animations for the sidebar
    st.sidebar.markdown("""
    <style>
    /* Star of the City animation */
    @keyframes sidebar-glow {
        0% { text-shadow: 0 0 2px gold; }
        50% { text-shadow: 0 0 6px gold; }
        100% { text-shadow: 0 0 2px gold; }
    }
    
    .sidebar-star {
        animation: sidebar-glow 2s infinite;
        font-weight: bold;
    }
    
    /* Impuritas Civitas animation */
    @keyframes sidebar-rainbow {
        0% { color: red; }
        14% { color: orange; }
        28% { color: yellow; }
        42% { color: green; }
        57% { color: blue; }
        71% { color: indigo; }
        85% { color: violet; }
        100% { color: red; }
    }
    
    .sidebar-impuritas {
        animation: sidebar-rainbow 4s linear infinite;
        font-weight: bold;
    }
    
    /* Urban Nightmare animation */
    @keyframes sidebar-pulse {
        0% { opacity: 0.8; }
        50% { opacity: 1; }
        100% { opacity: 0.8; }
    }
    
    .sidebar-nightmare {
        animation: sidebar-pulse 3s infinite;
        font-weight: bold;
    }
    
    /* Urban Plague subtle effect */
    .sidebar-plague {
        text-shadow: 0 0 2px #9C27B0;
        font-weight: bold;
    }
    
    /* Special Effect for Enkephalin */
    @keyframes enkephalin-glow {
        0% { text-shadow: 0 0 2px cyan; }
        50% { text-shadow: 0 0 5px cyan; }
        100% { text-shadow: 0 0 2px cyan; }
    }
    
    .enkephalin-value {
        color: #00BCD4;
        animation: enkephalin-glow 2s infinite;
        font-weight: bold;
    }
    
    /* Reward row styling */
    .rewards-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        padding: 5px;
        border-radius: 4px;
    }
    
    .rewards-row:hover {
        background-color: rgba(0,0,0,0.05);
    }
    
    .rarity-name {
        flex: 0 0 35%;
        font-weight: bold;
    }
    
    .coin-value {
        flex: 0 0 30%;
        color: #FFD700;
    }
    
    .enkephalin-value {
        flex: 0 0 35%;
        color: #00BCD4;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Get the rarities the player has discovered
    discovered_rarities = get_discovered_rarities()
    
    # Create a header explaining the values
    st.sidebar.markdown("""
    <div style="display: flex; margin-bottom: 10px; font-weight: bold;">
        <div style="flex: 0 0 35%;">Rarity</div>
        <div style="flex: 0 0 30%;">TagCoins</div>
        <div style="flex: 0 0 35%;">Enkephalin</div>
    </div>
    """, unsafe_allow_html=True)
    
    # Display in order from most common to most rare
    for rarity, info in RARITY_LEVELS.items():
        # Get the enkephalin reward from TAG_POWER_BONUSES
        enkephalin_reward = TAG_POWER_BONUSES.get(rarity, {}).get("enkephalin_reward", 0)
        
        # Check if this rarity has been discovered
        if rarity in discovered_rarities:
            # Apply special styling based on rarity
            if rarity == "Impuritas Civitas":
                # Rainbow animation for Impuritas Civitas
                st.sidebar.markdown(
                    f"""
                    <div class="rewards-row">
                        <div class="rarity-name">
                            <span class='sidebar-impuritas'>{rarity}</span>
                        </div>
                        <div class="coin-value">
                            {info['value']} {TAG_CURRENCY_NAME}
                        </div>
                        <div class="enkephalin-value">
                            +{enkephalin_reward} {ENKEPHALIN_ICON}
                        </div>
                    </div>
                    """,
                    unsafe_allow_html=True
                )
            elif rarity == "Star of the City":
                # Glowing effect for Star of the City
                st.sidebar.markdown(
                    f"""
                    <div class="rewards-row">
                        <div class="rarity-name">
                            <span class='sidebar-star' style='color:{info['color']}'>{rarity}</span>
                        </div>
                        <div class="coin-value">
                            {info['value']} {TAG_CURRENCY_NAME}
                        </div>
                        <div class="enkephalin-value">
                            +{enkephalin_reward} {ENKEPHALIN_ICON}
                        </div>
                    </div>
                    """,
                    unsafe_allow_html=True
                )
            elif rarity == "Urban Nightmare":
                # Pulsing effect for Urban Nightmare
                st.sidebar.markdown(
                    f"""
                    <div class="rewards-row">
                        <div class="rarity-name">
                            <span class='sidebar-nightmare' style='color:{info['color']}'>{rarity}</span>
                        </div>
                        <div class="coin-value">
                            {info['value']} {TAG_CURRENCY_NAME}
                        </div>
                        <div class="enkephalin-value">
                            +{enkephalin_reward} {ENKEPHALIN_ICON}
                        </div>
                    </div>
                    """,
                    unsafe_allow_html=True
                )
            elif rarity == "Urban Plague":
                # Subtle glow for Urban Plague
                st.sidebar.markdown(
                    f"""
                    <div class="rewards-row">
                        <div class="rarity-name">
                            <span class='sidebar-plague' style='color:{info['color']}'>{rarity}</span>
                        </div>
                        <div class="coin-value">
                            {info['value']} {TAG_CURRENCY_NAME}
                        </div>
                        <div class="enkephalin-value">
                            +{enkephalin_reward} {ENKEPHALIN_ICON}
                        </div>
                    </div>
                    """,
                    unsafe_allow_html=True
                )
            else:
                # Standard display for common rarities
                st.sidebar.markdown(
                    f"""
                    <div class="rewards-row">
                        <div class="rarity-name">
                            <span style='color:{info['color']}'>{rarity}</span>
                        </div>
                        <div class="coin-value">
                            {info['value']} {TAG_CURRENCY_NAME}
                        </div>
                        <div class="enkephalin-value">
                            {'+' + str(enkephalin_reward) + ' ' + ENKEPHALIN_ICON if enkephalin_reward > 0 else '-'}
                        </div>
                    </div>
                    """,
                    unsafe_allow_html=True
                )
        else:
            # Show blacked out version for undiscovered rarities
            st.sidebar.markdown(
                f"""
                <div class="rewards-row">
                    <div class="rarity-name">
                        <span style='color:#333333;'>?????</span>
                    </div>
                    <div class="coin-value">
                        ??? {TAG_CURRENCY_NAME}
                    </div>
                    <div class="enkephalin-value">
                        ??? {ENKEPHALIN_ICON}
                    </div>
                </div>
                """,
                unsafe_allow_html=True
            )

# def display_developer_mode_toggle():
#     """Display developer mode toggle"""
#     if 'show_dev_tools' not in st.session_state:
#         st.session_state.show_dev_tools = False

#     if st.sidebar.checkbox("Developer Mode", value=st.session_state.show_dev_tools, key="dev_mode_toggle"):
#         st.session_state.show_dev_tools = True
#     else:
#         st.session_state.show_dev_tools = False

def display_support_info():
    # Add separator for visual clarity
    st.markdown("---")
    
    # Support information
    st.subheader("💡 Notes")
    
    st.markdown("""
    This tagger was trained on a subset of the available data and for limited epochs due to hardware limitations.
    
    A more comprehensive model trained on the full 3+ million image dataset and many more epochs would provide:
    - More recent characters and tags.
    - Improved accuracy.
    
    If you find this tool useful and would like to support future development:
    """)
    
    # Add Buy Me a Coffee button with Star of the City-like glow effect
    st.markdown("""
    <style>
    @keyframes coffee-button-glow {
        0% { box-shadow: 0 0 5px #FFD700; }
        50% { box-shadow: 0 0 15px #FFD700; }
        100% { box-shadow: 0 0 5px #FFD700; }
    }
    
    .coffee-button {
        display: inline-block;
        animation: coffee-button-glow 2s infinite;
        border-radius: 5px;
        transition: transform 0.3s ease;
    }
    
    .coffee-button:hover {
        transform: scale(1.05);
    }
    </style>
    
    <a href="https://buymeacoffee.com/camais" target="_blank" class="coffee-button">
        <img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" 
            alt="Buy Me A Coffee" 
            style="height: 45px; width: 162px; border-radius: 5px;" />
    </a>
    """, unsafe_allow_html=True)
    
    st.markdown("""
    Your support helps with:
    - GPU costs for training
    - Storage for larger datasets
    - Development of new features
    - Future projects
    
    Thank you! 🙏
                
    Full Details: https://huggingface.co/Camais03/camie-tagger
    """)

def display_scan_interface():
    """Display the scan interface tab"""
    st.subheader("Scan Images for Tags")
    
    # Create two columns
    col1, col2 = st.columns([1, 1])
    
    with col1:
        # Image uploader
        uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
        
        image_path = None
        if uploaded_file:
            # Create a temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
                tmp_file.write(uploaded_file.getvalue())
                image_path = tmp_file.name
            
            # Display the image
            image = Image.open(uploaded_file)
            st.image(image, use_container_width=True)
            
            # Scan button with special key to avoid rerun loop
            button_key = f"scan_btn_{st.session_state.get('state_version', 0)}"
            if st.button("Scan for Tags", key=button_key):
                # Run scan
                with st.spinner("Scanning image..."):
                    success = enhanced_scan_button_handler(image_path)
                    if success:
                        # Save state
                        import tag_storage
                        tag_storage.update_tag_storage_from_session(st.session_state)
                        
                        # Force rerun to update UI everywhere
                        st.rerun()
    
    with col2:
        display_scanner_settings()
    
    # Display scan results if available
    if hasattr(st.session_state, 'current_scan') and st.session_state.current_scan:
        display_scan_results(st.session_state.current_scan)

def display_scan_results(scan_data):
    """Display scan results from session state with improved tag categorization and special effects for rare tags"""
    if not scan_data:
        return
        
    found_tags = scan_data.get("found_tags", [])
    all_tags = scan_data.get("all_tags", {})
    total_currency_earned = scan_data.get("total_currency_earned", 0)
    total_enkephalin_earned = scan_data.get("total_enkephalin_earned", 0)
    new_tag_count = scan_data.get("new_tag_count", 0)
    
    # Check for extremely rare new discoveries and celebrate them first
    new_rare_tags = [t for t in found_tags if t.get("is_new", False) and 
                     t.get("rarity") in ["Star of the City", "Impuritas Civitas"]]
    
    if new_rare_tags:
        # Sort by rarity (most rare first)
        rarity_order = ["Impuritas Civitas", "Star of the City"]
        new_rare_tags.sort(key=lambda x: rarity_order.index(x["rarity"]) if x["rarity"] in rarity_order else 999)
        
        # Display a celebration for the rarest tag found
        rarest_tag = new_rare_tags[0]
        if rarest_tag["rarity"] == "Impuritas Civitas":
            st.markdown(f"""
            <style>
            @keyframes rainbow-bg {{
                0% {{ background-color: rgba(255,0,0,0.1); }}
                14% {{ background-color: rgba(255,165,0,0.1); }}
                28% {{ background-color: rgba(255,255,0,0.1); }}
                42% {{ background-color: rgba(0,128,0,0.1); }}
                57% {{ background-color: rgba(0,0,255,0.1); }}
                71% {{ background-color: rgba(75,0,130,0.1); }}
                85% {{ background-color: rgba(238,130,238,0.1); }}
                100% {{ background-color: rgba(255,0,0,0.1); }}
            }}
            
            .rare-discovery-banner {{
                background-color: rgba(0,0,0,0.1);
                border: 3px solid red;
                border-radius: 10px;
                padding: 20px;
                margin: 20px 0;
                text-align: center;
                animation: rainbow-bg 4s linear infinite;
            }}
            </style>
            
            <div class="rare-discovery-banner">
                <h2>✨ EXTRAORDINARY DISCOVERY! ✨</h2>
                <h3>You found the ultra-rare Impuritas Civitas tag</h3>
                <p>This is one of the rarest tags in the game!</p>
                <p>Rewards: +{RARITY_LEVELS[rarest_tag["rarity"]]["value"]} {TAG_CURRENCY_NAME} and +25 {ENKEPHALIN_ICON}</p>
            </div>
            """, unsafe_allow_html=True)
            # # Show balloons for the extraordinary discovery
            # st.balloons()
        elif rarest_tag["rarity"] == "Star of the City":
            st.markdown(f"""
            <style>
            @keyframes glow-bg {{
                0% {{ box-shadow: 0 0 10px #FFD700; }}
                50% {{ box-shadow: 0 0 30px #FFD700; }}
                100% {{ box-shadow: 0 0 10px #FFD700; }}
            }}
            
            .star-discovery-banner {{
                background-color: rgba(255,215,0,0.1);
                border: 2px solid gold;
                border-radius: 10px;
                padding: 20px;
                margin: 20px 0;
                text-align: center;
                box-shadow: 0 0 10px #FFD700;
                animation: glow-bg 2s infinite;
            }}
            </style>
            
            <div class="star-discovery-banner">
                <h2>🌟 EXCEPTIONAL DISCOVERY! 🌟</h2>
                <h3>You found a Star of the City tag</h3>
                <p>This is a very rare and valuable tag!</p>
                <p>Rewards: +{RARITY_LEVELS[rarest_tag["rarity"]]["value"]} {TAG_CURRENCY_NAME} and +10 {ENKEPHALIN_ICON}</p>
            </div>
            """, unsafe_allow_html=True)
    
    if found_tags:
        st.success(f"Found {len(found_tags)} tags! {f'({new_tag_count} new discoveries)' if new_tag_count > 0 else ''}")
        
        # Count tags by rarity
        rarity_counts = {}
        for tag_info in found_tags:
            rarity = tag_info.get("rarity", "Unknown")
            is_new = tag_info.get("is_new", False)
            
            if rarity not in rarity_counts:
                rarity_counts[rarity] = {"total": 0, "new": 0}
            
            rarity_counts[rarity]["total"] += 1
            if is_new:
                rarity_counts[rarity]["new"] += 1
        
        # Get valid rarity order
        rarity_order = list(RARITY_LEVELS.keys())
        
        # Display rarity distribution
        for rarity, counts in sorted(rarity_counts.items(), 
                             key=lambda x: rarity_order.index(x[0]) if x[0] in rarity_order else 999):
            color = RARITY_LEVELS.get(rarity, {}).get("color", "#AAAAAA")
            total = counts["total"]
            new_count = counts["new"]
            
            # Create two columns for showing the rarity count and new count
            col1, col2 = st.columns([3, 1])
            with col1:
                st.markdown(f"<span style='color:{color};font-weight:bold;'>{rarity}:</span> {total} tags", unsafe_allow_html=True)
            with col2:
                if new_count > 0:
                    st.write(f"({new_count} new)")
        
        st.divider()
        
        # Show earned currency and enkephalin
        col1, col2, col3 = st.columns([1, 1, 1])
        with col1:
            st.write("**Earned:**")
        with col2:
            st.write(f"**{total_currency_earned} {TAG_CURRENCY_NAME}**")
        with col3:
            if total_enkephalin_earned > 0:
                st.write(f"**{total_enkephalin_earned} {ENKEPHALIN_ICON}**")
        
        # Show current stats after this scan
        st.divider()
        col1, col2 = st.columns(2)
        with col1:
            st.write("**Images Processed:**")
            st.write("**Total Tags Found:**")
            st.write("**Current TagCoins:**")
            st.write(f"**Current {ENKEPHALIN_CURRENCY_NAME}:**")
        with col2:
            st.write(f"**{st.session_state.game_stats['images_processed']}**")
            st.write(f"**{st.session_state.game_stats['total_tags_found']}**")
            st.write(f"**{st.session_state.tag_currency}**")
            st.write(f"**{st.session_state.enkephalin} {ENKEPHALIN_ICON}**")
        
        # Display found tags by category
        st.subheader("Found Tags by Category")
        
        # Check if we have any rare tags (rarer than Urban Myth)
        rare_rarities = ["Urban Legend", "Urban Plague", "Urban Nightmare", "Star of the City", "Impuritas Civitas"]
        has_rare_tags = any(tag_info.get("rarity") in rare_rarities for tag_info in found_tags)
        
        # Display category expanders
        for category, tags in all_tags.items():
            # Only display categories with collected tags
            collected_tags = [(tag, prob, rarity, any(t["tag"] == tag and t["is_new"] for t in found_tags)) 
                             for tag, prob, rarity, status in tags if status == "collected"]
            
            if not collected_tags:
                continue
                
            # Split into new and existing tags
            new_tags = [(tag, prob, rarity, True) for tag, prob, rarity, is_new in collected_tags if is_new]
            existing_tags = [(tag, prob, rarity, False) for tag, prob, rarity, is_new in collected_tags if not is_new]
            
            # Sort each group by rarity (rarest first)
            new_tags.sort(key=lambda x: rarity_order.index(x[2]) if x[2] in rarity_order else 999, reverse=True)
            existing_tags.sort(key=lambda x: rarity_order.index(x[2]) if x[2] in rarity_order else 999, reverse=True)
            
            # Combine with new tags first
            ordered_tags = new_tags + existing_tags
            
            # Check if this category has any rare tags
            category_has_rare = any(rarity in rare_rarities for _, _, rarity, _ in collected_tags)
            
            # Determine if this category should be expanded by default
            default_expanded = category == None or (category_has_rare and has_rare_tags) or len(new_tags) > 0
            
            # Create category title with badge for new tags
            category_title = f"{category.capitalize()} ({len(collected_tags)} tags)"
            if new_tags:
                category_title += f" 🆕 {len(new_tags)} new!"
            
            # Add special indicator for categories with rare tags
            if any(tag[2] in ["Star of the City", "Impuritas Civitas"] for tag in ordered_tags):
                category_title += " ✨ RARE!"
            
            with st.expander(category_title, expanded=default_expanded):
                # Display new tags section if any
                if new_tags:
                    st.markdown("### ✨ New Discoveries")
                    for tag, prob, rarity, _ in new_tags:
                        # Find the corresponding tag in found_tags to get enkephalin reward
                        tag_info = next((t for t in found_tags if t["tag"] == tag), None)
                        enkephalin_reward = tag_info.get("enkephalin", 0) if tag_info else 0
                        
                        # Get enkephalin reward if not available in tag_info
                        if enkephalin_reward == 0 and rarity in TAG_POWER_BONUSES:
                            enkephalin_reward = TAG_POWER_BONUSES[rarity]["enkephalin_reward"]
                            
                        display_tag_with_effects(tag, prob, rarity, is_new=True, enkephalin=enkephalin_reward)
                    
                    # Add separator if we have both new and existing tags
                    if existing_tags:
                        st.markdown("---")
                
                # Display existing tags
                if existing_tags:
                    if new_tags:  # Only show this header if we have new tags above
                        st.markdown("### Previously Discovered")
                    for tag, prob, rarity, _ in existing_tags:
                        display_tag_with_effects(tag, prob, rarity, is_new=False)
    else:
        st.warning("No tags found above the current threshold.")

def display_tag_with_effects(tag, prob, rarity, is_new=False, enkephalin=0):
    """
    Display a tag with special effects based on rarity, including animations for the rarest tags,
    sample count, and both TagCoins and Enkephalin rewards for new discoveries.
    """
    if rarity is None:
        rarity = "Unknown"
        
    # Get color and determine if this is a rare tag
    color = RARITY_LEVELS.get(rarity, {}).get("color", "#AAAAAA")
    
    # Get rewards for this tag's rarity
    coin_value = RARITY_LEVELS.get(rarity, {}).get("value", 0)
    
    # Get sample count if available
    sample_count = None
    if hasattr(st.session_state, 'tag_rarity_metadata') and st.session_state.tag_rarity_metadata:
        if tag in st.session_state.tag_rarity_metadata:
            tag_info = st.session_state.tag_rarity_metadata[tag]
            if isinstance(tag_info, dict) and "sample_count" in tag_info:
                sample_count = tag_info["sample_count"]
    
    # Format sample count for display
    sample_display = ""
    if sample_count is not None:
        if sample_count >= 1000000:
            sample_display = f"({sample_count/1000000:.1f}M samples)"
        elif sample_count >= 1000:
            sample_display = f"({sample_count/1000:.1f}K samples)"
        else:
            sample_display = f"({sample_count} samples)"
    
    # Add custom CSS for animations
    st.markdown("""
    <style>
    @keyframes glowing {
        0% { box-shadow: 0 0 5px #FFD700; }
        50% { box-shadow: 0 0 20px #FFD700; }
        100% { box-shadow: 0 0 5px #FFD700; }
    }
    
    @keyframes rainbow-border {
        0% { border-color: red; }
        14% { border-color: orange; }
        28% { border-color: yellow; }
        42% { border-color: green; }
        57% { border-color: blue; }
        71% { border-color: indigo; }
        85% { border-color: violet; }
        100% { border-color: red; }
    }
    
    @keyframes rainbow-text {
        0% { color: red; }
        14% { color: orange; }
        28% { color: yellow; }
        42% { color: green; }
        57% { color: blue; }
        71% { color: indigo; }
        85% { color: violet; }
        100% { color: red; }
    }
    
    @keyframes pulse-border {
        0% { border-color: #FF9800; }
        50% { border-color: #FF5722; }
        100% { border-color: #FF9800; }
    }
    
    @keyframes enkephalin-glow {
        0% { text-shadow: 0 0 2px cyan; }
        50% { text-shadow: 0 0 5px cyan; }
        100% { text-shadow: 0 0 2px cyan; }
    }
    
    @keyframes coin-glow {
        0% { text-shadow: 0 0 2px gold; }
        50% { text-shadow: 0 0 5px gold; }
        100% { text-shadow: 0 0 2px gold; }
    }
    
    .star-of-city {
        background-color: rgba(255, 215, 0, 0.2);
        padding: 8px;
        border-radius: 5px;
        border: 2px solid gold;
        animation: glowing 2s infinite;
    }
    
    .impuritas-civitas {
        background-color: rgba(0, 0, 0, 0.1);
        padding: 10px;
        border-radius: 5px;
        border: 3px solid red;
        animation: rainbow-border 4s linear infinite;
    }
    
    .impuritas-text {
        font-weight: bold;
        animation: rainbow-text 4s linear infinite;
    }
    
    .urban-nightmare {
        background-color: rgba(255, 152, 0, 0.1);
        padding: 6px;
        border-radius: 5px;
        border: 2px solid #FF9800;
        animation: pulse-border 3s infinite;
    }
    
    .urban-plague {
        background-color: rgba(156, 39, 176, 0.08);
        padding: 5px;
        border-radius: 5px;
        border: 1px solid #9C27B0;
        box-shadow: 0 0 3px #9C27B0;
    }
    
    .sample-count {
        font-size: 0.8em;
        color: #666;
        margin-left: 5px;
    }
    
    .enkephalin-reward {
        font-size: 0.9em;
        color: #00BCD4;
        margin-left: 5px;
        animation: enkephalin-glow 2s infinite;
        font-weight: bold;
    }
    
    .coin-reward {
        font-size: 0.9em;
        color: #FFD700;
        margin-left: 5px;
        animation: coin-glow 2s infinite;
        font-weight: bold;
    }
    
    .rewards-container {
        display: inline-block;
        background-color: rgba(0, 0, 0, 0.05);
        border-radius: 4px;
        padding: 2px 6px;
        margin-left: 5px;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Style based on rarity
    rare_rarities = {
        "Urban Legend": {"style": "background-color:rgba(33, 150, 243, 0.1); padding:5px; border-radius:5px;", "emoji": "🔮"},
        "Urban Plague": {"style": "class='urban-plague'", "emoji": "⚔️"},
        "Urban Nightmare": {"style": "class='urban-nightmare'", "emoji": "👑"},
        "Star of the City": {"style": "class='star-of-city'", "emoji": "🌟"},
        "Impuritas Civitas": {"style": "class='impuritas-civitas'", "emoji": "✨"}
    }
    
    # Determine if this is a rare tag
    is_rare = rarity in rare_rarities
    style = ""
    emoji_prefix = ""
    
    if is_rare:
        style = rare_rarities[rarity]["style"]
        emoji_prefix = rare_rarities[rarity]["emoji"] + " "
    
    # Create rewards display if new discovery
    rewards_display = ""
    if is_new:
        coin_display = f"<span class='coin-reward'>+{coin_value} {TAG_CURRENCY_NAME}</span>"
        enkephalin_display = ""
        if enkephalin > 0:
            enkephalin_display = f"<span class='enkephalin-reward'>+{enkephalin} {ENKEPHALIN_ICON}</span>"
            
        if enkephalin > 0:
            rewards_display = f"<span class='rewards-container'>{coin_display} {enkephalin_display}</span>"
        else:
            rewards_display = f"<span class='rewards-container'>{coin_display}</span>"
    
    # Create the tag display
    if is_new:
        if rarity == "Impuritas Civitas":
            tag_html = f"""
            <div {style}>
                {emoji_prefix}<span class="impuritas-text">{tag}</span> - 
                <span style="color:{color};font-weight:bold;">{rarity}</span> ({prob:.2f}) 
                <span style="background-color:#4CAF50;color:white;padding:2px 6px;border-radius:10px;font-size:0.8em;">NEW</span>
                {rewards_display}
                <span class="sample-count">{sample_display}</span>
            </div>
            """
        else:
            tag_html = f"""
            <div {style}>
                {emoji_prefix}<strong>{tag}</strong> - 
                <span style="color:{color};font-weight:bold;">{rarity}</span> ({prob:.2f}) 
                <span style="background-color:#4CAF50;color:white;padding:2px 6px;border-radius:10px;font-size:0.8em;">NEW</span>
                {rewards_display}
                <span class="sample-count">{sample_display}</span>
            </div>
            """
    else:
        if rarity == "Impuritas Civitas":
            tag_html = f"""
            <div {style}>
                {emoji_prefix}<span class="impuritas-text">{tag}</span> - 
                <span style="color:{color};font-weight:bold;">{rarity}</span> ({prob:.2f})
                <span class="sample-count">{sample_display}</span>
            </div>
            """
        else:
            tag_html = f"""
            <div {style}>
                {emoji_prefix}{tag} - 
                <span style="color:{color};font-weight:bold;">{rarity}</span> ({prob:.2f})
                <span class="sample-count">{sample_display}</span>
            </div>
            """
    
    # Add notification sound/confetti for very rare tags
    if is_new and rarity in ["Star of the City", "Impuritas Civitas"]:
        # Add confetti effect for extremely rare tags
        # st.balloons()
        
        # Add special notification
        if rarity == "Impuritas Civitas":
            st.markdown(f"""
            <div style="border:3px solid red; padding:10px; margin:10px 0; text-align:center; background-color:rgba(0,0,0,0.1); animation:rainbow-border 4s linear infinite;">
                <h3>🎉 EXTRAORDINARY DISCOVERY! 🎉</h3>
                <p>You found an ultra-rare Impuritas Civitas tag!</p>
                <p>Rewards: +{RARITY_LEVELS[rarity]["value"]} {TAG_CURRENCY_NAME} and +25 {ENKEPHALIN_ICON}</p>
            </div>
            """, unsafe_allow_html=True)
        elif rarity == "Star of the City":
            st.markdown(f"""
            <div style="border:2px solid gold; padding:10px; margin:10px 0; text-align:center; background-color:rgba(255,215,0,0.2); animation:glowing 2s infinite;">
                <h3>🌟 EXCEPTIONAL DISCOVERY! 🌟</h3>
                <p>You found a very rare Star of the City tag!</p>
                <p>Rewards: +{RARITY_LEVELS[rarity]["value"]} {TAG_CURRENCY_NAME} and +10 {ENKEPHALIN_ICON}</p>
            </div>
            """, unsafe_allow_html=True)
    
    st.markdown(tag_html, unsafe_allow_html=True)

def display_scanner_settings():
    """Display scanner settings and help"""
    st.write("### Scanner Settings")
    
    # Get threshold values
    base_threshold = st.session_state.threshold
    tag_power = st.session_state.tag_power_bonus if hasattr(st.session_state, 'tag_power_bonus') else 0
    effective_threshold = max(MIN_THRESHOLD, base_threshold - tag_power)
    
    # Display threshold info
    if tag_power > 0:
        st.write(f"Base Threshold: **{base_threshold:.3f}**")
        st.write(f"Tag Power Bonus: **-{tag_power:.4f}**")
        st.write(f"Effective Threshold: **{effective_threshold:.3f}**")
    else:
        st.write(f"Current Threshold: **{base_threshold:.3f}**")
                  
    if hasattr(st.session_state, 'coin_multiplier') and st.session_state.coin_multiplier > 1.0:
        st.info(f"Your Tag Power gives a coin multiplier of {st.session_state.coin_multiplier:.2f}x for new discoveries!")
    
    # Instruction box
    st.markdown(
        """
        ### How to Play
        1. Upload an image
        2. Scan for tags to discover them
        3. Earn TagCoins for new discoveries
        4. Spend TagCoins on upgrades to lower the threshold
        5. Lower thresholds reveal rarer tags!
        6. Collect sets of related tags for bonuses and reveal unique mosaics!
        7. Visit the Library System to discover unique tags (not collect)
        8. Use collected tags to either inspire new searches or generate essence
        9. Use Enkephalin to generate Tag Essences
        10. Use the Tag Essence Generator to collect the tag and related tags to it.
        """
    )

def display_game_stats_panel():
    """Display a prominent game stats panel at the top of the main content area"""
    # Force read latest values from session state
    tag_currency = st.session_state.tag_currency
    enkephalin = st.session_state.enkephalin
    images_processed = st.session_state.game_stats.get('images_processed', 0)
    total_tags_found = st.session_state.game_stats.get('total_tags_found', 0)
    total_currency_earned = st.session_state.game_stats.get('total_currency_earned', 0)
    unique_tags = len(st.session_state.collected_tags) if hasattr(st.session_state, 'collected_tags') else 0
    
    # Get threshold values
    base_threshold = st.session_state.threshold
    tag_power = st.session_state.tag_power_bonus if hasattr(st.session_state, 'tag_power_bonus') else 0
    effective_threshold = max(MIN_THRESHOLD, base_threshold - tag_power)
    
    # Prepare the container
    st.markdown('<div class="stats-panel">', unsafe_allow_html=True)
    
    # Primary stats row
    cols = st.columns([1, 1, 1, 1])
    
    with cols[0]:
        st.markdown(f'<div class="stats-value">{tag_currency}</div>', unsafe_allow_html=True)
        st.markdown(f'<div class="stats-label">{TAG_CURRENCY_NAME}</div>', unsafe_allow_html=True)
    
    with cols[1]:
        st.markdown(f'<div class="stats-value">{enkephalin} {ENKEPHALIN_ICON}</div>', unsafe_allow_html=True)
        st.markdown(f'<div class="stats-label">{ENKEPHALIN_CURRENCY_NAME}</div>', unsafe_allow_html=True)
    
    with cols[2]:
        if tag_power > 0:
            st.markdown(f'<div class="stats-value">{effective_threshold:.3f}</div>', unsafe_allow_html=True)
            st.markdown(f'<div class="stats-label">Effective Threshold (Base: {base_threshold:.3f})</div>', unsafe_allow_html=True)
        else:
            st.markdown(f'<div class="stats-value">{base_threshold:.3f}</div>', unsafe_allow_html=True)
            st.markdown(f'<div class="stats-label">Threshold</div>', unsafe_allow_html=True)
    
    with cols[3]:
        st.markdown(f'<div class="stats-value">{unique_tags}</div>', unsafe_allow_html=True)
        st.markdown(f'<div class="stats-label">Unique Tags</div>', unsafe_allow_html=True)
    
    # Add a secondary row with collapsible additional stats
    with st.expander("More Game Stats"):
        cols2 = st.columns(3)
        
        with cols2[0]:
            st.markdown("### Collection Stats")
            st.write(f"Images Processed: **{images_processed}**")
            st.write(f"Total Tags Found: **{total_tags_found}**")
            st.write(f"Unique Tags: **{unique_tags}**")
        
        with cols2[1]:
            st.markdown("### Economy Stats")
            st.write(f"Total Earned: **{total_currency_earned}** {TAG_CURRENCY_NAME}")
            if hasattr(st.session_state.game_stats, 'currency_spent'):
                st.write(f"Currency Spent: **{st.session_state.game_stats.get('currency_spent', 0)}** {TAG_CURRENCY_NAME}")
            if hasattr(st.session_state.game_stats, 'enkephalin_generated'):
                st.write(f"Enkephalin Generated: **{st.session_state.game_stats.get('enkephalin_generated', 0)}**")
        
        with cols2[2]:
            st.markdown("### Bonuses")
            if hasattr(st.session_state, 'tag_power_bonus') and st.session_state.tag_power_bonus > 0:
                st.write(f"Tag Power Bonus: **-{st.session_state.tag_power_bonus:.4f}**")
            if hasattr(st.session_state, 'coin_multiplier') and st.session_state.coin_multiplier > 1.0:
                st.write(f"Coin Multiplier: **{st.session_state.coin_multiplier:.2f}x**")
            if hasattr(st.session_state, 'unlocked_combinations'):
                st.write(f"Unlocked Combinations: **{len(st.session_state.unlocked_combinations)}**")
    
    # Close the container
    st.markdown('</div>', unsafe_allow_html=True)

def display_tag_collection():
    """Display the user's tag collection with stats and analysis."""
    st.subheader("Your Tag Collection")
    
    # Create tabs for different views
    list_tab, stats_tab, analysis_tab, mosaic_tab = st.tabs([
        "Tag List", 
        "Collection Stats",
        "Category Analysis",
        "Collection Mosaic"
    ])
     
    with list_tab:
        display_tag_list()
    
    with stats_tab:
        display_collection_stats()
    
    with analysis_tab:
        display_category_stats()

    with mosaic_tab:
        # Display the tag mosaic
        display_tag_mosaic()

def display_tag_list():
    """Display a simple list view of tags with improved sorting options"""
    # Show total unique tags
    unique_tags = len(st.session_state.collected_tags)
    st.write(f"You have collected {unique_tags} unique tags.")
    
    # Count tags by rarity
    rarity_counts = get_rarity_counts()
    
    # Only display rarity categories that have tags
    active_rarities = {r: c for r, c in rarity_counts.items() if c > 0}
    
    # If there are active rarities to display
    if active_rarities:
        display_rarity_distribution(active_rarities)
    
    # Add a sorting option
    sort_options = ["Category (rarest first)", "Rarity"]
    selected_sort = st.selectbox("Sort tags by:", sort_options)
    
    # Group tags by the selected method
    if selected_sort == "Category (rarest first)":
        categories = group_tags_by_category()
        
        # Display tags by category in expanders
        for category, tags in sorted(categories.items()):
            # Get rarity order for sorting
            rarity_order = list(RARITY_LEVELS.keys())
            
            # Sort tags by rarity (rarest first)
            def get_rarity_index(tag_tuple):
                tag, info = tag_tuple
                rarity = info.get("rarity", "Unknown")
                if rarity in rarity_order:
                    return len(rarity_order) - rarity_order.index(rarity)
                return 0
            
            sorted_tags = sorted(tags, key=get_rarity_index, reverse=True)
            
            # Check if category has any rare tags
            has_rare_tags = any(info.get("rarity") in ["Impuritas Civitas", "Star of the City"] 
                               for _, info in sorted_tags)
            
            # Get category info if available
            category_display = category.capitalize()
            if category in TAG_CATEGORIES:
                category_info = TAG_CATEGORIES[category]
                category_icon = category_info.get("icon", "")
                category_color = category_info.get("color", "#888888")
                category_display = f"<span style='color:{category_color};'>{category_icon} {category.capitalize()}</span>"
            
            # Create header with information about rare tags if present
            header = f"{category_display} ({len(tags)} tags)"
            if has_rare_tags:
                header += " ✨ Contains rare tags!"
                
            # Display the header and expander
            st.markdown(header, unsafe_allow_html=True)
            with st.expander("Show/Hide"):
                # Group by rarity within category
                rarity_groups = {}
                for tag, info in sorted_tags:
                    rarity = info.get("rarity", "Unknown")
                    if rarity not in rarity_groups:
                        rarity_groups[rarity] = []
                    rarity_groups[rarity].append((tag, info))
                
                # Display each rarity group in order (rarest first)
                for rarity in reversed(rarity_order):
                    if rarity in rarity_groups:
                        tags_in_rarity = rarity_groups[rarity]
                        if tags_in_rarity:
                            color = RARITY_LEVELS[rarity]["color"]
                            
                            # Special styling for rare rarities
                            if rarity == "Impuritas Civitas":
                                rarity_style = f"animation:rainbow-text 4s linear infinite;font-weight:bold;"
                            elif rarity == "Star of the City":
                                rarity_style = f"color:{color};text-shadow:0 0 3px gold;font-weight:bold;"
                            elif rarity == "Urban Nightmare":
                                rarity_style = f"color:{color};text-shadow:0 0 1px #FF5722;font-weight:bold;"
                            else:
                                rarity_style = f"color:{color};font-weight:bold;"
                            
                            st.markdown(f"<span style='{rarity_style}'>{rarity.capitalize()}</span> ({len(tags_in_rarity)} tags)", unsafe_allow_html=True)
                            display_tag_grid(tags_in_rarity)
                            st.markdown("---")
                
    elif selected_sort == "Rarity":
        # Group tags by rarity level
        rarity_groups = {}
        for tag, info in st.session_state.collected_tags.items():
            rarity = info.get("rarity", "Unknown")
            if rarity not in rarity_groups:
                rarity_groups[rarity] = []
            rarity_groups[rarity].append((tag, info))
        
        # Get ordered rarities (rarest first)
        ordered_rarities = list(RARITY_LEVELS.keys())
        ordered_rarities.reverse()  # Reverse to show rarest first
        
        # Display tags by rarity
        for rarity in ordered_rarities:
            if rarity in rarity_groups:
                tags = rarity_groups[rarity]
                color = RARITY_LEVELS[rarity]["color"]
                
                # Add special styling for rare rarities
                rarity_html = f"<span style='color:{color};font-weight:bold;'>{rarity.capitalize()}</span>"
                if rarity == "Impuritas Civitas":
                    rarity_html = f"<span style='animation:rainbow-text 4s linear infinite;font-weight:bold;'>{rarity.capitalize()}</span>"
                elif rarity == "Star of the City":
                    rarity_html = f"<span style='color:{color};text-shadow:0 0 3px gold;font-weight:bold;'>{rarity.capitalize()}</span>"
                elif rarity == "Urban Nightmare":
                    rarity_html = f"<span style='color:{color};text-shadow:0 0 1px #FF5722;font-weight:bold;'>{rarity.capitalize()}</span>"
                
                # First create the title with HTML, then use it in the expander
                st.markdown(f"### {rarity_html} ({len(tags)} tags)", unsafe_allow_html=True)
                with st.expander("Show/Hide"):
                    # Group by category within rarity
                    category_groups = {}
                    for tag, info in tags:
                        category = info.get("category", "unknown")
                        if category not in category_groups:
                            category_groups[category] = []
                        category_groups[category].append((tag, info))
                    
                    # Display each category within this rarity level
                    for category, category_tags in sorted(category_groups.items()):
                        # Get category info if available
                        category_display = category.capitalize()
                        if category in TAG_CATEGORIES:
                            category_info = TAG_CATEGORIES[category]
                            category_icon = category_info.get("icon", "")
                            category_color = category_info.get("color", "#888888")
                            category_display = f"<span style='color:{category_color};'>{category_icon} {category.capitalize()}</span>"
                        
                        st.markdown(f"#### {category_display} ({len(category_tags)} tags)", unsafe_allow_html=True)
                        display_tag_grid(category_tags)
                        st.markdown("---")

def get_rarity_counts():
    """Count tags by rarity levels"""
    rarity_counts = {
        "Canard": 0, 
        "Urban Myth": 0, 
        "Urban Legend": 0, 
        "Urban Plague": 0, 
        "Urban Nightmare": 0, 
        "Star of the City": 0, 
        "Impuritas Civitas": 0,
        "Unknown": 0  # Add an "Unknown" category for handling None or invalid rarities
    }
    
    for tag_info in st.session_state.collected_tags.values():
        rarity = tag_info.get("rarity")
        if rarity is None:
            rarity = "Unknown"
        
        if rarity in rarity_counts:
            rarity_counts[rarity] += 1
        else:
            # Handle any unexpected rarity values
            rarity_counts["Unknown"] += 1
            
    return rarity_counts

def display_rarity_distribution(active_rarities):
    """Display distribution of tags by rarity with themed animations for rare tags"""
    # Add the necessary CSS for animations
    st.markdown("""
    <style>
    @keyframes grid-glow {
        0% { text-shadow: 0 0 2px gold; }
        50% { text-shadow: 0 0 6px gold; }
        100% { text-shadow: 0 0 2px gold; }
    }
    
    @keyframes grid-rainbow {
        0% { color: red; }
        14% { color: orange; }
        28% { color: yellow; }
        42% { color: green; }
        57% { color: blue; }
        71% { color: indigo; }
        85% { color: violet; }
        100% { color: red; }
    }
    
    @keyframes grid-pulse {
        0% { opacity: 0.8; }
        50% { opacity: 1; }
        100% { opacity: 0.8; }
    }
    
    .grid-star {
        text-shadow: 0 0 3px gold;
        animation: grid-glow 2s infinite;
    }
    
    .grid-impuritas {
        animation: grid-rainbow 4s linear infinite;
    }
    
    .grid-nightmare {
        text-shadow: 0 0 1px #FF5722;
        animation: grid-pulse 3s infinite;
    }
    
    .grid-plague {
        text-shadow: 0 0 1px #9C27B0;
    }
    </style>
    """, unsafe_allow_html=True)
    
    rarity_cols = st.columns(len(active_rarities))
    for i, (rarity, count) in enumerate(active_rarities.items()):
        with rarity_cols[i]:
            # Get color with fallback
            color = RARITY_LEVELS.get(rarity, {}).get("color", "#888888")
            
            # Apply special styling based on rarity
            style = f"color:{color};font-weight:bold;"
            class_name = ""
            
            if rarity == "Impuritas Civitas":
                class_name = "grid-impuritas"
            elif rarity == "Star of the City":
                class_name = "grid-star"
            elif rarity == "Urban Nightmare":
                class_name = "grid-nightmare"
            elif rarity == "Urban Plague":
                class_name = "grid-plague"
            
            if class_name:
                st.markdown(
                    f"<div style='text-align:center;'><span class='{class_name}' style='font-weight:bold;'>{rarity.capitalize()}</span><br>{count}</div>",
                    unsafe_allow_html=True
                )
            else:
                st.markdown(
                    f"<div style='text-align:center;'><span style='{style}'>{rarity.capitalize()}</span><br>{count}</div>",
                    unsafe_allow_html=True
                )

def group_tags_by_category():
    """Group tags by their categories"""
    categories = {}
    for tag, info in st.session_state.collected_tags.items():
        category = info.get("category", "unknown")
        if category not in categories:
            categories[category] = []
        categories[category].append((tag, info))
    return categories

def display_tag_grid(tags):
    """Display tags in a grid layout with sample count information"""
    # Create a grid layout for tags
    cols = st.columns(3)
    for i, (tag, info) in enumerate(sorted(tags)):
        col_idx = i % 3
        with cols[col_idx]:
            rarity = info.get("rarity")
            if rarity is None:
                rarity = "Unknown"
            
            count = info.get("count", 1)
            color = RARITY_LEVELS.get(rarity, {}).get("color", "#888888")
            
            # Get sample count if available
            sample_count = None
            if hasattr(st.session_state, 'tag_rarity_metadata') and st.session_state.tag_rarity_metadata:
                if tag in st.session_state.tag_rarity_metadata:
                    tag_info = st.session_state.tag_rarity_metadata[tag]
                    if isinstance(tag_info, dict) and "sample_count" in tag_info:
                        sample_count = tag_info["sample_count"]
            
            # Format sample count
            sample_display = ""
            if sample_count is not None:
                if sample_count >= 1000000:
                    sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count/1000000:.1f}M)</span>"
                elif sample_count >= 1000:
                    sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count/1000:.1f}K)</span>"
                else:
                    sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count})</span>"
            
            # Apply special styling for rare tags
            tag_html = tag
            if rarity == "Impuritas Civitas":
                tag_html = f"<span style='animation: rainbow-text 4s linear infinite;'>{tag}</span>"
            elif rarity == "Star of the City":
                tag_html = f"<span style='text-shadow: 0 0 3px gold;'>{tag}</span>"
            elif rarity == "Urban Nightmare":
                tag_html = f"<span style='text-shadow: 0 0 1px #FF9800;'>{tag}</span>"
            
            # Display tag with rarity badge, count, and sample count
            st.markdown(
                f"{tag_html} <span style='background-color:{color};color:white;padding:2px 6px;border-radius:10px;font-size:0.8em;'>{rarity.capitalize()}</span> (×{count}) {sample_display}",
                unsafe_allow_html=True
            )

def display_collection_stats():
    """Display overall collection statistics with themed animations"""
    st.subheader("Collection Overview")
    
    # Check if we have collected tags
    if not hasattr(st.session_state, 'collected_tags') or not st.session_state.collected_tags:
        st.info("Start scanning images to collect tags!")
        return
    
    # Add the necessary CSS for animations
    st.markdown("""
    <style>
    @keyframes grid-glow {
        0% { text-shadow: 0 0 2px gold; }
        50% { text-shadow: 0 0 6px gold; }
        100% { text-shadow: 0 0 2px gold; }
    }
    
    @keyframes grid-rainbow {
        0% { color: red; }
        14% { color: orange; }
        28% { color: yellow; }
        42% { color: green; }
        57% { color: blue; }
        71% { color: indigo; }
        85% { color: violet; }
        100% { color: red; }
    }
    
    @keyframes grid-pulse {
        0% { opacity: 0.8; }
        50% { opacity: 1; }
        100% { opacity: 0.8; }
    }
    
    @keyframes gradient-shift {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    
    .grid-star {
        text-shadow: 0 0 3px gold;
        animation: grid-glow 2s infinite;
    }
    
    .grid-impuritas {
        animation: grid-rainbow 4s linear infinite;
    }
    
    .grid-nightmare {
        text-shadow: 0 0 1px #FF5722;
        animation: grid-pulse 3s infinite;
    }
    
    .grid-plague {
        text-shadow: 0 0 1px #9C27B0;
    }
    
    /* Custom styles for collection metrics */
    .metric-container {
        background-color: #f8f9fa;
        border-radius: 5px;
        padding: 10px;
        text-align: center;
        border: 1px solid #dee2e6;
    }
    
    .metric-value {
        font-size: 24px;
        font-weight: bold;
    }
    
    .metric-label {
        font-size: 14px;
        color: #6c757d;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Rarity breakdown
    display_rarity_breakdown()
    
    # Most common tags
    display_common_tags()
    
    # Recently discovered tags
    display_recent_discoveries()

def display_rarity_breakdown():
    """Display rarity breakdown with progress bar visualization showing collected vs total tags"""
    st.subheader("Rarity Collection Progress")
    
    # Get counts of collected tags by rarity
    collected_counts = {}
    for tag_info in st.session_state.collected_tags.values():
        rarity = tag_info["rarity"]
        if rarity not in collected_counts:
            collected_counts[rarity] = 0
        collected_counts[rarity] += 1
    
    # Get total possible tags by rarity from metadata
    total_counts = {}
    if hasattr(st.session_state, 'tag_rarity_metadata') and st.session_state.tag_rarity_metadata:
        for tag, info in st.session_state.tag_rarity_metadata.items():
            if isinstance(info, dict) and "rarity" in info:
                rarity = info["rarity"]
                if rarity not in total_counts:
                    total_counts[rarity] = 0
                total_counts[rarity] += 1
    
    # Get ordered rarities
    ordered_rarities = list(RARITY_LEVELS.keys())
    
    # Create a progress bar for each rarity
    for rarity in ordered_rarities:
        if rarity in collected_counts:
            collected = collected_counts[rarity]
            total = total_counts.get(rarity, 0)
            
            # If total is not available or 0, use collected as total
            if total <= 0:
                total = collected
            
            # Calculate percentage
            percentage = (collected / total) * 100 if total > 0 else 0
            
            # Get color for this rarity
            color = RARITY_LEVELS[rarity]["color"]
            
            # Special styling based on rarity
            rarity_span = f"<span style='color:{color};font-weight:bold;'>{rarity}</span>"
            bar_style = f"background-color: {color};"
            
            if rarity == "Impuritas Civitas":
                rarity_span = f"<span class='grid-impuritas' style='font-weight:bold;'>{rarity}</span>"
                bar_style = "background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); background-size: 400% 400%; animation: gradient-shift 4s linear infinite;"
            elif rarity == "Star of the City":
                rarity_span = f"<span class='grid-star' style='color:{color};font-weight:bold;'>{rarity}</span>"
                bar_style = f"background-color: {color}; box-shadow: 0 0 5px #FFD700;"
            elif rarity == "Urban Nightmare":
                rarity_span = f"<span class='grid-nightmare' style='color:{color};font-weight:bold;'>{rarity}</span>"
                bar_style = f"background-color: {color}; animation: grid-pulse 3s infinite;"
            elif rarity == "Urban Plague":
                rarity_span = f"<span class='grid-plague' style='color:{color};font-weight:bold;'>{rarity}</span>"
            
            # Create progress bar with appropriate styling
            st.markdown(
                f"""
                <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <div style="width: 150px;">{rarity_span}</div>
                    <div style="flex-grow: 1; background-color: #f0f0f0; border-radius: 5px; height: 20px;">
                        <div style="width: {percentage}%; {bar_style} height: 20px; border-radius: 5px;"></div>
                    </div>
                    <div style="width: 120px; text-align: right;">{collected}/{total} ({percentage:.1f}%)</div>
                </div>
                """,
                unsafe_allow_html=True
            )
            
    # Add the necessary CSS for animations if not already added
    st.markdown("""
    <style>
    @keyframes gradient-shift {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    </style>
    """, unsafe_allow_html=True)

def display_common_tags():
    """Display the most common tags with themed animations"""
    st.subheader("Most Common Tags")
    
    # Sort tags by count
    sorted_tags = sorted(
        st.session_state.collected_tags.items(),
        key=lambda x: x[1]["count"],
        reverse=True
    )
    
    # Display top 10
    for i, (tag, info) in enumerate(sorted_tags[:10]):
        rarity = info["rarity"]
        count = info["count"]
        color = RARITY_LEVELS[rarity]["color"]
        
        # Special styling based on rarity
        rarity_span = f"<span style='color:{color};'>{rarity}</span>"
        
        if rarity == "Impuritas Civitas":
            rarity_span = f"<span class='grid-impuritas'>{rarity}</span>"
        elif rarity == "Star of the City":
            rarity_span = f"<span class='grid-star' style='color:{color};'>{rarity}</span>"
        elif rarity == "Urban Nightmare":
            rarity_span = f"<span class='grid-nightmare' style='color:{color};'>{rarity}</span>"
        elif rarity == "Urban Plague":
            rarity_span = f"<span class='grid-plague' style='color:{color};'>{rarity}</span>"
        
        # Get sample count if available
        sample_display = ""
        if hasattr(st.session_state, 'tag_rarity_metadata') and st.session_state.tag_rarity_metadata:
            if tag in st.session_state.tag_rarity_metadata:
                tag_info = st.session_state.tag_rarity_metadata[tag]
                if isinstance(tag_info, dict) and "sample_count" in tag_info:
                    sample_count = tag_info["sample_count"]
                    if sample_count >= 1000000:
                        sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count/1000000:.1f}M samples)</span>"
                    elif sample_count >= 1000:
                        sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count/1000:.1f}K samples)</span>"
                    else:
                        sample_display = f"<span style='font-size:0.8em;color:#666;'>({sample_count} samples)</span>"
        
        st.markdown(
            f"**{i+1}.** {tag} - {rarity_span} ({count} occurrences) {sample_display}",
            unsafe_allow_html=True
        )

def display_recent_discoveries():
    """Display recently discovered tags with themed animations"""
    st.subheader("Recent Discoveries")
    
    # Get recently discovered tags from tag history
    if hasattr(st.session_state, 'tag_history') and st.session_state.tag_history:
        # Get last 10 new discoveries
        new_discoveries = [entry for entry in st.session_state.tag_history if entry.get("is_new", False)]
        for entry in new_discoveries[-10:]:
            tag = entry["tag"]
            rarity = entry["rarity"]
            time = entry["time"]
            color = RARITY_LEVELS[rarity]["color"]
            
            # Special styling based on rarity
            rarity_span = f"<span style='color:{color};'>{rarity}</span>"
            
            if rarity == "Impuritas Civitas":
                rarity_span = f"<span class='grid-impuritas'>{rarity}</span>"
            elif rarity == "Star of the City":
                rarity_span = f"<span class='grid-star' style='color:{color};'>{rarity}</span>"
            elif rarity == "Urban Nightmare":
                rarity_span = f"<span class='grid-nightmare' style='color:{color};'>{rarity}</span>"
            elif rarity == "Urban Plague":
                rarity_span = f"<span class='grid-plague' style='color:{color};'>{rarity}</span>"
            
            st.markdown(
                f"{tag} - {rarity_span} (at {time})",
                unsafe_allow_html=True
            )

def display_category_stats():
    """Display stats and details about tag categories"""
    st.subheader("Category Analysis")
    
    # Check if we have collected tags
    if not hasattr(st.session_state, 'collected_tags') or not st.session_state.collected_tags:
        st.info("Start scanning images to collect tags!")
        return
    
    # Count tags by category
    category_counts = {}
    for tag, info in st.session_state.collected_tags.items():
        category = info.get("category", "general")
        if category not in category_counts:
            category_counts[category] = {"count": 0, "tags": []}
        category_counts[category]["count"] += 1
        category_counts[category]["tags"].append(tag)
    
    # Create category bar visualization
    display_category_bars(category_counts)
    
    st.divider()

def display_category_bars(category_counts):
    """Display category distribution with bar visualization"""
    total_tags = len(st.session_state.collected_tags)
    st.subheader("Category Distribution")
    
    # Sort categories by count
    sorted_categories = sorted(
        category_counts.items(),
        key=lambda x: x[1]["count"],
        reverse=True
    )
    
    max_count = max(cat_info["count"] for _, cat_info in sorted_categories) if sorted_categories else 1
    
    for category, cat_info in sorted_categories:
        count = cat_info["count"]
        percentage = (count / total_tags) * 100
        
        if category in TAG_CATEGORIES:
            color = TAG_CATEGORIES[category]["color"]
            icon = TAG_CATEGORIES[category]["icon"]
            name = TAG_CATEGORIES[category]["name"]
        else:
            color = "#888888"
            icon = "❓"
            name = category.capitalize()
        
        # Create bar
        st.markdown(
            f"""
            <div style="display: flex; align-items: center; margin-bottom: 10px;">
                <div style="width: 150px;">{icon} <span style="color:{color};font-weight:bold;">{name}</span></div>
                <div style="flex-grow: 1; background-color: #f0f0f0; border-radius: 5px; height: 20px;">
                    <div style="width: {(count/max_count)*100}%; background-color: {color}; height: 20px; border-radius: 5px;"></div>
                </div>
                <div style="width: 100px; text-align: right;">{count} ({percentage:.1f}%)</div>
            </div>
            """,
            unsafe_allow_html=True
        )

def display_achievements_tab():
    """Display the user's achievements in a dedicated tab"""
    st.subheader("🏆 Achievements")
    
    # Count unlocked achievements
    unlocked_count = len(st.session_state.achievements)
    total_count = len(ACHIEVEMENTS)
    
    # Create a progress bar for overall achievement completion
    progress_percentage = unlocked_count / total_count
    st.progress(progress_percentage, text=f"Unlocked {unlocked_count} of {total_count} achievements ({int(progress_percentage * 100)}%)")
    
    # Group achievements by category
    achievement_categories = group_achievements_by_category()
    
    # Create tabs for different achievement categories
    category_tabs = st.tabs(list(achievement_categories.keys()))
    
    # Display achievements in each category tab
    for i, (category, tab) in enumerate(zip(achievement_categories.keys(), category_tabs)):
        with tab:
            display_category_achievements(category, achievement_categories[category])

def group_achievements_by_category():
    """Group achievements into categories"""
    achievement_categories = {
        "Collection": [],
        "Rarity": [],
        "Progression": [],
        "Special": []
    }
    
    # Categorize achievements
    for achievement_id, achievement in ACHIEVEMENTS.items():
        if "collector" in achievement_id or "Collector" in achievement.get("name", ""):
            category = "Collection"
        elif any(rarity in achievement_id for rarity in ["canard", "myth", "legend", "plague", "nightmare", "star", "impuritas"]):
            category = "Rarity"
        elif any(term in achievement_id for term in ["milestone", "master", "threshold"]):
            category = "Progression"
        else:
            category = "Special"
        
        achievement_categories[category].append((achievement_id, achievement))
        
    return achievement_categories

def display_category_achievements(category, achievements_in_category):
    """Display achievements for a specific category"""
    # If no achievements in this category, show a message
    if not achievements_in_category:
        st.info(f"No {category} achievements available yet.")
        return
    
    # Otherwise, display achievements in a grid
    cols_per_row = 3
    for j in range(0, len(achievements_in_category), cols_per_row):
        cols = st.columns(cols_per_row)
        
        for k in range(cols_per_row):
            idx = j + k
            if idx < len(achievements_in_category):
                achievement_id, achievement = achievements_in_category[idx]
                with cols[k]:
                    display_achievement_card(achievement_id, achievement)

def display_achievement_card(achievement_id, achievement):
    """Display a single achievement card"""
    # Create a card-like container for each achievement
    is_unlocked = achievement_id in st.session_state.achievements
    
    # Set the card style based on unlock status
    if is_unlocked:
        card_style = "border:2px solid #4CAF50; border-radius:10px; padding:10px; margin:5px; background-color:rgba(76, 175, 80, 0.1);"
        icon = "✅"
    else:
        card_style = "border:2px solid #cccccc; border-radius:10px; padding:10px; margin:5px; background-color:rgba(0, 0, 0, 0.05);"
        icon = "🔒"
    
    # Display achievement card
    st.markdown(f"""
    <div style="{card_style}">
        <p style="font-size:18px; margin:0;">{icon} <b>{achievement.get('name', 'Unknown')}</b></p>
        <p style="font-size:14px; margin:5px 0;">{achievement.get('description', '')}</p>
        {f"<p style='font-size:12px; color:#666;'>Requires: {achievement.get('requirement', '')}</p>" if 'requirement' in achievement else ""}
        {f"<p style='font-size:12px; color:#4CAF50;'>Reward: {', '.join([f'{k}: {v}' for k, v in achievement.get('reward', {}).items()])}</p>" if 'reward' in achievement and is_unlocked else ""}
    </div>
    """, unsafe_allow_html=True)

def check_achievements(session_state):
    """
    Check for achievement completion based on the current game state.
    Adds newly completed achievements to the session_state.achievements set
    and applies their rewards.
    
    Args:
        session_state: Streamlit session state containing game data
    
    Returns:
        list: List of newly unlocked achievement names (empty if none)
    """
    from game_constants import ACHIEVEMENTS, RARITY_LEVELS
    
    # Ensure achievements set exists
    if not hasattr(session_state, 'achievements'):
        session_state.achievements = set()
    
    newly_unlocked = []
    
    # Helper function to apply achievement rewards
    def apply_reward(achievement_id):
        reward = ACHIEVEMENTS[achievement_id].get("reward", {})
        
        # Apply tagcoin reward
        if "tagcoins" in reward:
            session_state.tag_currency += reward["tagcoins"]
            
        # Apply coin bonus
        if "coin_bonus" in reward:
            if not hasattr(session_state, 'achievement_coin_bonus'):
                session_state.achievement_coin_bonus = 0
            session_state.achievement_coin_bonus += reward["coin_bonus"]
            
        # Apply enkephalin reward
        if "enkephalin" in reward:
            session_state.enkephalin += reward["enkephalin"]
            
        # Apply essence cost reduction
        if "essence_cost_reduction" in reward:
            if not hasattr(session_state, 'essence_cost_reduction'):
                session_state.essence_cost_reduction = 0
            session_state.essence_cost_reduction += reward["essence_cost_reduction"]
            
        # Apply library cost reduction
        if "library_cost_reduction" in reward:
            if not hasattr(session_state, 'library_cost_reduction'):
                session_state.library_cost_reduction = 0
            session_state.library_cost_reduction += reward["library_cost_reduction"]
            
        # Apply enkephalin bonus
        if "enkephalin_bonus" in reward:
            if not hasattr(session_state, 'enkephalin_bonus'):
                session_state.enkephalin_bonus = 0
            session_state.enkephalin_bonus += reward["enkephalin_bonus"]
    
    # Check collection achievements
    tag_count = len(session_state.collected_tags) if hasattr(session_state, 'collected_tags') else 0
    
    for achievement_id, achievement in ACHIEVEMENTS.items():
        # Skip already unlocked achievements
        if achievement_id in session_state.achievements:
            continue
            
        # Check if this is a collection size achievement
        if achievement_id.startswith("tag_collector_") or achievement_id.startswith("collection_milestone_") or achievement_id == "tag_master":
            requirement = achievement.get("requirement", 0)
            if tag_count >= requirement:
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check rarity-based achievements
        elif achievement_id.endswith("_collector") or achievement_id == "legendary_hunter" or achievement_id == "multi_legendary":
            # Count tags by rarity
            rarity_counts = {}
            for tag_info in session_state.collected_tags.values():
                rarity = tag_info.get("rarity", "Unknown")
                if rarity not in rarity_counts:
                    rarity_counts[rarity] = 0
                rarity_counts[rarity] += 1
            
            # Check for specific rarity achievements
            if achievement_id == "canard_collector" and rarity_counts.get("Canard", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "urban_myth_collector" and rarity_counts.get("Urban Myth", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "urban_legend_collector" and rarity_counts.get("Urban Legend", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "urban_plague_collector" and rarity_counts.get("Urban Plague", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "urban_nightmare_collector" and rarity_counts.get("Urban Nightmare", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "star_collector" and rarity_counts.get("Star of the City", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "impuritas_collector" and rarity_counts.get("Impuritas Civitas", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "legendary_hunter" and rarity_counts.get("Impuritas Civitas", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
            elif achievement_id == "multi_legendary" and rarity_counts.get("Impuritas Civitas", 0) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
        # Check threshold achievements
        elif achievement_id == "perfect_scanner":
            effective_threshold = session_state.threshold
            if hasattr(session_state, 'tag_power_bonus'):
                effective_threshold -= session_state.tag_power_bonus
            if effective_threshold <= 0.1:  # MIN_THRESHOLD
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
                
        elif achievement_id == "optimal_threshold":
            if abs(session_state.threshold - 0.32857141) < 0.001:  # Within 0.001 of optimal F1 score
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check essence achievements
        elif achievement_id == "essence_creator" or achievement_id == "essence_master":
            essence_count = session_state.game_stats.get("essences_generated", 0)
            if essence_count >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check tag explorer achievement
        elif achievement_id == "tag_explorer":
            explored_tiers = session_state.explored_library_tiers if hasattr(session_state, 'explored_library_tiers') else set()
            if len(explored_tiers) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check enkephalin master achievement
        elif achievement_id == "enkephalin_master" or achievement_id == "enkephalin_harvester":
            enkephalin_generated = session_state.game_stats.get("enkephalin_generated", 0)
            if enkephalin_generated >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check sacrifice devotee achievement
        elif achievement_id == "sacrifice_devotee":
            tags_sacrificed = session_state.game_stats.get("tags_sacrificed", 0)
            if tags_sacrificed >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check category explorer achievement
        elif achievement_id == "category_explorer":
            # Count unique categories
            categories = set()
            for tag_info in session_state.collected_tags.values():
                category = tag_info.get("category", "unknown")
                categories.add(category)
            
            if len(categories) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check series collector achievement
        elif achievement_id == "series_collector":
            completed_series = session_state.completed_series if hasattr(session_state, 'completed_series') else set()
            if len(completed_series) >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check rapid tagger achievement
        elif achievement_id == "rapid_tagger":
            images_processed = session_state.game_stats.get("images_processed", 0)
            if images_processed >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check library scholar achievement
        elif achievement_id == "library_scholar":
            extracted_tags = session_state.tags_extracted if hasattr(session_state, 'tags_extracted') else 0
            if extracted_tags >= achievement.get("requirement", 0):
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check rarity hunter achievement
        elif achievement_id == "rarity_hunter":
            # Count tags by rarity
            rarity_counts = {}
            for tag_info in session_state.collected_tags.values():
                rarity = tag_info.get("rarity", "Unknown")
                if rarity not in rarity_counts:
                    rarity_counts[rarity] = 0
                rarity_counts[rarity] += 1
            
            # Check if player has at least one tag of each rarity
            has_all_rarities = all(rarity in rarity_counts and rarity_counts[rarity] > 0 
                                  for rarity in RARITY_LEVELS.keys())
            
            if has_all_rarities:
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
        
        # Check legendary librarian achievement
        elif achievement_id == "legendary_librarian":
            extracted_legendary = session_state.extracted_impuritas if hasattr(session_state, 'extracted_impuritas') else False
            if extracted_legendary:
                session_state.achievements.add(achievement_id)
                apply_reward(achievement_id)
                newly_unlocked.append(achievement["name"])
    
    return newly_unlocked


def display_achievement_notifications(newly_unlocked):
    """
    Display notifications for newly unlocked achievements.
    
    Args:
        newly_unlocked: List of newly unlocked achievement names
    """
    import streamlit as st
    
    if not newly_unlocked:
        return
    
    # Add CSS for achievement notifications
    st.markdown("""
    <style>
    @keyframes slide-in {
        0% { transform: translateX(100%); opacity: 0; }
        10% { transform: translateX(0); opacity: 1; }
        90% { transform: translateX(0); opacity: 1; }
        100% { transform: translateX(100%); opacity: 0; }
    }
    
    .achievement-notification {
        position: fixed;
        top: 70px;
        right: 20px;
        background-color: #4CAF50;
        color: white;
        padding: 15px;
        border-radius: 5px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        z-index: 9999;
        animation: slide-in 5s ease-in-out;
        animation-fill-mode: forwards;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Generate notification for each achievement
    for i, achievement_name in enumerate(newly_unlocked):
        delay = i * 0.5  # Stagger notifications
        notification_html = f"""
        <div class="achievement-notification" style="animation-delay: {delay}s; top: {70 + i*70}px;">
            <div>🏆 Achievement Unlocked!</div>
            <div><strong>{achievement_name}</strong></div>
        </div>
        """
        st.markdown(notification_html, unsafe_allow_html=True)


def update_tag_power_bonuses():
    """
    Update tag power bonuses based on the player's collection.
    This affects threshold reduction and coin multiplier.
    """
    import streamlit as st
    from game_constants import TAG_POWER_BONUSES, RARITY_LEVELS
    
    # Initialize tag power variables if they don't exist
    if not hasattr(st.session_state, 'tag_power_bonus'):
        st.session_state.tag_power_bonus = 0
    
    if not hasattr(st.session_state, 'coin_multiplier'):
        st.session_state.coin_multiplier = 1.0
    
    # Reset to defaults
    st.session_state.tag_power_bonus = 0
    coin_multiplier_bonus = 0
    
    # Calculate bonuses from rare tags
    if hasattr(st.session_state, 'collected_tags'):
        for tag, info in st.session_state.collected_tags.items():
            rarity = info.get("rarity")
            if rarity in TAG_POWER_BONUSES:
                bonus = TAG_POWER_BONUSES[rarity]
                
                # Accumulate coin multiplier bonus
                coin_multiplier_bonus += bonus["coin_multiplier"]
    
    # Apply coin multiplier (base 1.0 + bonuses)
    st.session_state.coin_multiplier = 1.0 + coin_multiplier_bonus
    
    # Apply achievement bonuses if they exist
    if hasattr(st.session_state, 'achievement_coin_bonus'):
        st.session_state.coin_multiplier += st.session_state.achievement_coin_bonus
    
    return st.session_state.tag_power_bonus, st.session_state.coin_multiplier

def display_upgrade_shop():
    """Display the upgrade shop with preset threshold levels and visual enhancements"""
    # Display header with visually appealing styling
    st.markdown("""
    <style>
    .upgrade-shop-header {
        background: linear-gradient(90deg, #0d6efd, #6610f2);
        color: white;
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    .currency-display {
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 8px 15px;
        margin-top: 10px;
        font-size: 1.2em;
    }
    </style>
    
    <div class="upgrade-shop-header">
        <h2>🧪 Neural Scanner Upgrade Lab 🧪</h2>
        <div>Enhance your scanner's capabilities to discover rarer tags!</div>
    </div>
    """, unsafe_allow_html=True)
    
    # Add introduction if player has no purchased upgrades
    purchased = set(st.session_state.purchased_upgrades) if hasattr(st.session_state, 'purchased_upgrades') else set()

    # Get base threshold and tag power bonus
    base_threshold = st.session_state.threshold
    tag_power_bonus = st.session_state.tag_power_bonus if hasattr(st.session_state, 'tag_power_bonus') else 0
    effective_threshold = max(MIN_THRESHOLD, base_threshold - tag_power_bonus)
    
    st.divider()
    
    # Create upgrade cards
    display_available_upgrades(base_threshold, tag_power_bonus, purchased)

def display_available_upgrades(base_threshold, tag_power_bonus, purchased):
    """Display available upgrade options with progressive unlocking and visual effects"""
    # Add CSS for upgrade card effects
    st.markdown("""
    <style>
    @keyframes glow-effect {
        0% { box-shadow: 0 0 5px rgba(0,123,255,0.5); }
        50% { box-shadow: 0 0 15px rgba(0,123,255,0.8); }
        100% { box-shadow: 0 0 5px rgba(0,123,255,0.5); }
    }
    
    .upgrade-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        background-color: #f8f9fa;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    
    .upgrade-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    /* Rarity-based animations - matching the tag rarities */
    @keyframes rainbow-border {
        0% { border-color: red; }
        14% { border-color: orange; }
        28% { border-color: yellow; }
        42% { border-color: green; }
        57% { border-color: blue; }
        71% { border-color: indigo; }
        85% { border-color: violet; }
        100% { border-color: red; }
    }
    
    @keyframes star-glow {
        0% { box-shadow: 0 0 5px #FFD700; }
        50% { box-shadow: 0 0 20px #FFD700; }
        100% { box-shadow: 0 0 5px #FFD700; }
    }
    
    @keyframes nightmare-pulse {
        0% { border-color: #FF9800; }
        50% { border-color: #FF5722; }
        100% { border-color: #FF9800; }
    }
    
    /* Upgrade card variants */
    .upgrade-card-available {
        border: 1px solid #2196F3;  /* Urban Legend blue */
        background-color: rgba(33, 150, 243, 0.05);
    }
    
    .upgrade-card-affordable {
        border: 2px solid #9C27B0;  /* Urban Plague purple */
        background-color: rgba(156, 39, 176, 0.08);
        box-shadow: 0 0 3px #9C27B0;
    }
    
    .upgrade-card-purchased {
        border: 2px solid #5D9C59;  /* Urban Myth green */
        background-color: rgba(93, 156, 89, 0.08);
    }
    
    .upgrade-card-locked {
        border: 1px solid #AAAAAA;  /* Canard gray */
        background-color: rgba(170, 170, 170, 0.05);
        filter: grayscale(100%);
        opacity: 0.7;
    }
    
    /* Special cards for high-tier upgrades */
    .upgrade-card-nightmare {
        border: 2px solid #FF9800;  /* Urban Nightmare orange */
        background-color: rgba(255, 152, 0, 0.08);
        animation: nightmare-pulse 3s infinite;
    }
    
    .upgrade-card-star {
        border: 2px solid #FFEB3B;  /* Star of the City yellow/gold */
        background-color: rgba(255, 235, 59, 0.08);
        animation: star-glow 2s infinite;
    }
    
    .upgrade-card-impuritas {
        border: 3px solid red;  /* Impuritas Civitas red/rainbow */
        background-color: rgba(0, 0, 0, 0.1);
        animation: rainbow-border 4s linear infinite;
    }
    
    .upgrade-name {
        font-weight: bold;
        font-size: 1.1em;
        margin-bottom: 5px;
    }
    
    .level-indicator {
        display: flex;
        margin-bottom: 10px;
    }
    
    .level-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 5px;
        background-color: #dee2e6;
    }
    
    .level-dot-filled {
        background-color: #0d6efd;
    }
    
    .level-dot-current {
        background-color: #28a745;
        box-shadow: 0 0 5px #28a745;
    }
    
    .locked-overlay {
        font-size: 1.2em;
        color: #6c757d;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # Display purchased upgrades first
    if purchased:
        with st.expander("Your Purchased Upgrades", expanded=False):
            for i, upgrade in enumerate(THRESHOLD_UPGRADES):
                if upgrade["name"] in purchased:
                    # Create a completed upgrade card with appropriate rarity styling
                    card_class = "upgrade-card-purchased"
                    
                    # Apply special styling based on upgrade level
                    if i >= 6:  # Technological Singularity
                        card_class = "upgrade-card-impuritas"
                    elif i >= 5:  # Consciousness Emulation
                        card_class = "upgrade-card-star"
                    elif i >= 4:  # Recursive Self-Improvement
                        card_class = "upgrade-card-nightmare"
                    
                    upgrade_html = f"""
                    <div class="upgrade-card {card_class}">
                        <div class="level-indicator">
                            {create_level_dots(i, len(THRESHOLD_UPGRADES), purchased)}
                        </div>
                        <div class="upgrade-name">{upgrade["name"]} ✓</div>
                        <p>{upgrade["description"]}</p>
                        <p><strong>Threshold setting:</strong> {upgrade["threshold_setting"]:.4f}</p>
                    </div>
                    """
                    st.markdown(upgrade_html, unsafe_allow_html=True)
    
    # Find the next available upgrade (first unpurchased)
    next_available_index = None
    for i, upgrade in enumerate(THRESHOLD_UPGRADES):
        if upgrade["name"] not in purchased:
            next_available_index = i
            break
    
    # Display if all upgrades are purchased
    if next_available_index is None:
        st.success("🎉 Congratulations! You've unlocked all available scanner upgrades!")
        return
    
    # Display available and locked upgrades
    st.subheader("Available Upgrades")
    
    # Show only next available upgrade and a preview of what's next
    for i, upgrade in enumerate(THRESHOLD_UPGRADES):
        # Skip if already purchased
        if upgrade["name"] in purchased:
            continue
        
        # Only show the current upgrade and the next one
        if i > next_available_index + 1:
            continue
        
        # Determine if this is the next available upgrade or a future one
        is_next_upgrade = (i == next_available_index)
        can_afford = st.session_state.tag_currency >= upgrade["cost"]
        
        if is_next_upgrade:
            # Create a card-like container for the next available upgrade
            with st.container():
                # Use the direct threshold setting
                new_threshold = upgrade["threshold_setting"]
                
                # Determine threshold change direction and create text
                threshold_change = abs(new_threshold - base_threshold)
                if new_threshold < base_threshold:
                    change_text = f"Lowers threshold to {new_threshold:.4f} (↓ {threshold_change:.4f})"
                    change_emoji = "⬇️"
                else:
                    change_text = f"Raises threshold to {new_threshold:.4f} (↑ {threshold_change:.4f})"
                    change_emoji = "⬆️"
                
                # Determine card class based on upgrade tier and affordability
                card_class = ""
                
                # First set base affordability class
                base_class = "upgrade-card-affordable" if can_afford else "upgrade-card-available"
                
                # Then add special rarity class based on upgrade level
                if i >= 6:  # Technological Singularity (highest level)
                    card_class = "upgrade-card-impuritas"  # Impuritas Civitas style
                elif i >= 5:  # Consciousness Emulation
                    card_class = "upgrade-card-star"  # Star of the City style
                elif i >= 4:  # Recursive Self-Improvement
                    card_class = "upgrade-card-nightmare"  # Urban Nightmare style
                else:
                    card_class = base_class
                
                # Create the upgrade card HTML
                upgrade_html = f"""
                <div class="upgrade-card {card_class}">
                    <div class="level-indicator">
                        {create_level_dots(i, len(THRESHOLD_UPGRADES), purchased)}
                    </div>
                    <div class="upgrade-name">{upgrade["name"]}</div>
                    <p>{upgrade["description"]}</p>
                    <p><strong>{change_emoji} {change_text}</strong></p>
                </div>
                """
                st.markdown(upgrade_html, unsafe_allow_html=True)
                
                # Show effective threshold with tag power bonus
                if tag_power_bonus > 0:
                    effective_upgrade_threshold = max(MIN_THRESHOLD, new_threshold - tag_power_bonus)
                    st.info(f"Effective threshold: {effective_upgrade_threshold:.4f} with your Tag Power bonus of {tag_power_bonus:.4f}")
                
                # Purchase button
                col1, col2 = st.columns([3, 1])
                with col1:
                    st.write(f"**Cost:** {upgrade['cost']} {TAG_CURRENCY_NAME}")
                with col2:
                    if st.button("Purchase", key=f"upgrade_{i}", disabled=not can_afford, use_container_width=True):
                        purchase_upgrade(i)
        else:
            # Create a preview of the next locked upgrade
            # Add a hint of the upgrade's rarity styling for locked cards
            locked_class = "upgrade-card-locked"
            rarity_hint = ""
            
            if i >= 6:  # Technological Singularity
                rarity_hint = f'<div style="height: 3px; width: 50px; background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); margin: 5px 0;"></div>'
            elif i >= 5:  # Consciousness Emulation
                rarity_hint = f'<div style="height: 3px; width: 50px; background: #FFEB3B; box-shadow: 0 0 3px #FFD700; margin: 5px 0;"></div>'
            elif i >= 4:  # Recursive Self-Improvement
                rarity_hint = f'<div style="height: 3px; width: 50px; background: #FF9800; margin: 5px 0;"></div>'
            
            locked_html = f"""
            <div class="upgrade-card {locked_class}">
                <div class="level-indicator">
                    {create_level_dots(i, len(THRESHOLD_UPGRADES), purchased)}
                </div>
                <div class="upgrade-name">{upgrade["name"]}</div>
                {rarity_hint}
                <p style="color: #6c757d;">Complete previous upgrade to unlock</p>
                <p><strong>Cost:</strong> {upgrade['cost']} {TAG_CURRENCY_NAME}</p>
            </div>
            """
            st.markdown(locked_html, unsafe_allow_html=True)
    
    # Add a hint about next upgrades
    if next_available_index + 2 < len(THRESHOLD_UPGRADES):
        remaining = len(THRESHOLD_UPGRADES) - (next_available_index + 2)
        st.markdown(f"<div style='text-align:center;color:#6c757d;'>{remaining} more upgrades will be revealed as you progress</div>", unsafe_allow_html=True)

def create_level_dots(current_level, total_levels, purchased):
    """Create HTML for level indicator dots"""
    dots_html = ""
    for i in range(total_levels):
        if f"Pattern Recognition Module" in purchased and i == 0:
            # First upgrade is purchased
            dot_class = "level-dot level-dot-filled"
        elif i < current_level:
            # Previous levels are filled
            dot_class = "level-dot level-dot-filled"
        elif i == current_level:
            # Current level is highlighted
            dot_class = "level-dot level-dot-current"
        else:
            # Future levels are empty
            dot_class = "level-dot"
        
        dots_html += f'<div class="{dot_class}"></div>'
    
    return dots_html

def purchase_upgrade(upgrade_index):
    """Purchase a threshold upgrade"""
    upgrade = THRESHOLD_UPGRADES[upgrade_index]
    
    # Check if we have enough currency
    if st.session_state.tag_currency >= upgrade["cost"]:
        # Purchase the upgrade
        st.session_state.tag_currency -= upgrade["cost"]
        st.session_state.game_stats["currency_spent"] += upgrade["cost"]
        
        # Apply new threshold setting directly instead of reduction
        st.session_state.threshold = upgrade["threshold_setting"]
        
        # Add to purchased upgrades
        st.session_state.purchased_upgrades.append(upgrade["name"])
        
        # Save immediately
        save_game()
        
        # Update state version to force a refresh
        if 'state_version' in st.session_state:
            st.session_state.state_version += 1
        
        # Force refresh the UI to show updated state
        st.rerun()
    else:
        st.error("Not enough currency!")

def display_neural_specialization():
    """Display neural specialization grid"""
    st.subheader("Neural Specialization")
    
    # Count tags by category
    categories_count = {}
    if hasattr(st.session_state, 'collected_tags'):
        for tag, info in st.session_state.collected_tags.items():
            category = info.get("category", "general")
            if category not in categories_count:
                categories_count[category] = 0
            categories_count[category] += 1
    
    # Check for mastered categories
    mastered = st.session_state.mastered_categories if hasattr(st.session_state, 'mastered_categories') else {}
    
    # Make a grid of category stats
    cols = st.columns(3)
    col_idx = 0
    
    for category, info in TAG_CATEGORIES.items():
        with cols[col_idx]:
            count = categories_count.get(category, 0)
            is_mastered = category in mastered
            
            # Get color and status
            if is_mastered:
                color = info['color']
                status = "MASTERED"
            else:
                color = "#AAAAAA"  # Gray
                status = "Active"
            
            # Display category stats
            st.markdown(f"""
            <div style="border: 1px solid {color}; border-radius: 5px; padding: 10px; margin-bottom: 10px;">
                <p style="margin: 0; font-weight: bold;">{info['icon']} {info['name']}</p>
                <p style="margin: 0; font-size: 0.9em;">Tags: {count}</p>
                <p style="margin: 0; font-size: 0.9em; color: {color};">{status}</p>
            </div>
            """, unsafe_allow_html=True)
            
            # Move to next column
            col_idx = (col_idx + 1) % 3

def display_discovery_tips():
    """Display tag discovery tips"""
    with st.expander("💡 Tag Discovery Tips"):
        st.write("""
        **How to improve your model's cognitive abilities:**
        
        1. **Collect diverse tags** across many categories to increase your collection level
        2. **Master categories** by collecting many tags within each category
        3. **Find tag combinations** by collecting specific sets of related tags
        4. **Keep rare tags** in your collection to maintain tag power
        5. **Extract tags** from the Library System to discover new tags
        6. **Generate tag essences** to gain insight into what the AI recognizes
        """)

# =============================================================================
# MAIN APPLICATION FUNCTION
# =============================================================================

def create_app_tabs():
    tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
    "Scan Images", 
    "Tag Collection",
    "Series Collections", 
    "Upgrade Shop", 
    "Library", 
    "Essence Generator"  # New tab for the essence generator
    ])
   
    return tab1, tab2, tab3, tab4, tab5, tab6

def main():
    """Main application function."""
    # Set up title with emoji
    st.title("🎮 Tag Collector Game")
    
    # Apply tag animations and themes
    apply_tag_animations()

    load_game()
    
    # Initialize game state
    initialize_game_state()
    initialize_library_system()  # Initialize the library system
    
    # Try to load the model
    if 'model' not in st.session_state:
        try:
            model, thresholds, metadata = load_model()
            st.session_state.model = model
            st.session_state.thresholds = thresholds
            st.session_state.metadata = metadata
        except Exception as e:
            st.error(f"Error loading model: {str(e)}")
            st.info("Please make sure the model is properly exported.")
            st.stop()
    
    # Create game stats panel at the top
    display_game_stats_panel()
    
    # Create a simplified sidebar without game stats
    create_sidebar()
    
    # Create app tabs
    tab1, tab2, tab3, tab4, tab5, tab6 = create_app_tabs()
    
    # Fill tab content
    with tab1:
        display_scan_interface()
    
    with tab2:
        display_tag_collection()
    
    with tab3:
        display_series_mosaics()
        
    with tab4:
        display_upgrade_shop()
    
    with tab5:
        display_library_extraction()
            
    with tab6:
        # Display the essence generator in its own tab
        from essence_generator import display_essence_generator
        display_essence_generator()

if __name__ == "__main__":
    main()